Arduino - 鍵盤訊息



在這個例子中,當按下按鈕時,一個文字字串將作為鍵盤輸入傳送到電腦。字串報告按鈕被按下的次數。一旦你將程式寫入Leonardo並連線好電路,開啟你喜歡的文字編輯器檢視結果。

警告 − 當你使用 Keyboard.print() 命令時,Arduino 將接管你的電腦鍵盤。為了確保在執行包含此函式的程式時不會失去對電腦的控制,請在呼叫 Keyboard.print() 之前設定可靠的控制系統。此程式包含一個按鈕來切換鍵盤,以便它僅在按下按鈕後執行。

所需元件

你需要以下元件:

  • 1 個 麵包板
  • 1 個 Arduino Leonardo、Micro 或 Due 開發板
  • 1 個 瞬時按鈕
  • 1 個 10k 歐姆電阻

步驟

按照電路圖,將元件連線到麵包板,如下圖所示。

Keyboard Message Breadboard

程式

在你的電腦上開啟 Arduino IDE 軟體。使用 Arduino 語言進行程式設計來控制你的電路。點選“新建”開啟一個新的程式檔案。

Sketch

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 傳送的文字。

廣告