KeyboardMessage

はじめに

ボタンを押したときに文字列を送信します。

プログラム

定義等

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

  For the Arduino Leonardo and Micro.

  Sends a text string when a button is pressed.

  The circuit:
  - pushbutton attached from pin 4 to +5V
  - 10 kilohm resistor attached from pin 4 to ground

  created 24 Oct 2011
  modified 27 Mar 2012
  by Tom Igoe
  modified 11 Nov 2013
  by Scott Fitzgerald

  This example code is in the public domain.

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

#include "Keyboard.h"

const int buttonPin = 4;          // input pin for pushbutton
int previousButtonState = HIGH;   // for checking the state of a pushButton
int counter = 0;                  // button push counter
 

buttonPinとpreviousButtonState、counterという変数を定義します。buttonPinは、constと指定されているので、プログラム内での変更はできません。

setup()

29
30
31
32
33
34
35
void setup() {
  // make the pushButton pin an input:
  pinMode(buttonPin, INPUT);
  // initialize control over the keyboard:
  Keyboard.begin();
}
 

デジタルのbuttonPin(2番ピン)をpinMode()を使って入力モードにします。次に、Keyboard.begin()で、キーボードの利用を開始します。

loop()

36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
void loop() {
  // read the pushbutton:
  int buttonState = digitalRead(buttonPin);
  // if the button state has changed,
  if ((buttonState != previousButtonState)
      // and it's currently pressed:
      && (buttonState == HIGH)) {
    // increment the button counter
    counter++;
    // type out a message
    Keyboard.print("You pressed the button ");
    Keyboard.print(counter);
    Keyboard.println(" times.");
  }
  // save the current button state for comparison next time:
  previousButtonState = buttonState;
}

digitalRead()を使ってputtonPinの状態を確認し、以前の状態と変わっていて、かつ、HIGH(=ボタンが押されている)ときに、counterをインクリメントし、Keyboard.print()Keyboard.println()を使ってメッセージを送信します。最後に、buttonStateを保存します。

バージョン

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

最終更新日

September 11, 2021

inserted by FC2 system