KeyboardSerial

はじめに

シリアルポートから受け取った文字の次の文字をタイプします。例えば、‘a’を受け取ると’b’とタイプします。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
  Keyboard test

  For the Arduino Leonardo, Micro or Due

  Reads a byte from the serial port, sends a keystroke back.
  The sent keystroke is one higher than what's received, e.g. if you send a,
  you get b, send A you get B, and so forth.

  The circuit:
  - none

  created 21 Oct 2011
  modified 27 Mar 2012
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/KeyboardSerial
*/

#include "Keyboard.h"
 

Keyboard.hをインクルードします。

setup()

24
25
26
27
28
29
30
void setup() {
  // open the serial port:
  Serial.begin(9600);
  // initialize control over the keyboard:
  Keyboard.begin();
}
 

Serial.begin()でシリアルポートを初期化します。Arduino Leonardoでは、以下のコードを入れるのがより良いと思います。

1
  while (!Serial) ;

次に、Keyboard.begin()で、キーボードの利用を開始します。

loop()

31
32
33
34
35
36
37
38
39
void loop() {
  // check for incoming serial data:
  if (Serial.available() > 0) {
    // read incoming serial data:
    char inChar = Serial.read();
    // Type the next ASCII value from what you received:
    Keyboard.write(inChar + 1);
  }
}

Serial.available()で、シリアルポートにデータがあるかを確認します。データがあれば、Serial.read()で値を読み取り、読み取った値に1を足したものを、Keyboard.write()を使ってタイプします。

バージョン

Hardware:Arduino Leonardo/Arduino Micro/Arduino Due
Software:Arduino 1.8.16

最終更新日

September 11, 2021

inserted by FC2 system