Arduino 简明教程
Arduino - Keyboard Message
在此示例中,当按下按钮时,一个文本字符串将作为键盘输入被发送到计算机。该字符串报告按钮被按下的次数。一旦对 Leonardo 进行了编程并将其连接好,打开您最喜欢的文本编辑器查看结果。
Warning − 在您使用 Keyboard.print() 命令时,Arduino 接管了您的电脑键盘。为了确保在使用此功能运行草图时不丢失对您电脑的控制,在调用 Keyboard.print() 之前设置一个可靠的控制系统。此草图包含一个按钮,用于切换键盘,因此只有在按下按钮后才运行此草图。
Components Required
您将需要以下组件:
-
1 × Breadboard
-
1 × Arduino Leonardo、Micro 或 Due 电路板
-
1 × momentary pushbutton
-
1 × 10k 欧姆电阻
Arduino Code
/*
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;
}