Arduino-keyboard-message

提供:Dev Guides
移動先:案内検索

Arduino-キーボードメッセージ

この例では、ボタンが押されると、テキスト文字列がキーボード入力としてコンピューターに送信されます。 文字列は、ボタンが押された回数を報告します。 Leonardoのプログラミングと接続が完了したら、お気に入りのテキストエディターを開いて結果を確認します。

警告-* Keyboard.print()コマンドを使用すると、Arduinoがコンピューターのキーボードを引き継ぎます。 この機能を使用してスケッチを実行しているときにコンピューターの制御が失われないようにするには、 Keyboard.print()*を呼び出す前に、信頼できる制御システムをセットアップします。 このスケッチには、キーボードを切り替えるプッシュボタンが含まれているため、ボタンが押された後にのみ実行されます。

必要なコンポーネント

次のコンポーネントが必要になります-

  • 1×ブレッドボード
  • 1×Arduino Leonardo、Micro、またはDueボード
  • 1×瞬間押しボタン
  • 1×10kオーム抵抗

手順

以下の画像に示すように、回路図に従って、ブレッドボード上のコンポーネントを接続します。

キーボードメッセージブレッドボード

スケッチ

コンピューターでArduino IDEソフトウェアを開きます。 Arduino言語でコーディングすると、回路が制御されます。 [新規]をクリックして、新しいスケッチファイルを開きます。

スケッチ

Arduinoコード

/*
   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
*/

#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

void setup() {
   pinMode(buttonPin, INPUT);//make the pushButton pin an input:
   Keyboard.begin();//initialize control over the keyboard:
}

void loop() {
   int buttonState = digitalRead(buttonPin);//read the pushbutton:
   if ((buttonState != previousButtonState)&& (buttonState == HIGH))//and it's currently pressed: {
     //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;
}

注意すべきコード

プッシュボタンの一方の端子をArduinoのピン4に取り付けます。 もう一方のピンを5Vに接続します。 抵抗をプルダウンとして使用し、ピン4からグランドに接続することにより、グランドへのリファレンスを提供します。

ボードをプログラムしたら、USBケーブルを抜き、テキストエディターを開いて、テキストカーソルを入力領域に置きます。 ボードをもう一度USB経由でコンピューターに接続し、ボタンを押して文書に書き込みます。

結果

任意のテキストエディターを使用して、Arduino経由で送信されたテキストを表示します。