在此示例中,当按下按钮时,会将文本字符串作为键盘输入发送到计算机。
您将需要以下组件-
遵循电路图,并将面包板上的组件连接起来,如下图所示。
链接:https://www.learnfk.comhttps://www.learnfk.com/arduino/arduino-keyboard-message.html
来源:LearnFk无涯教程网
/* 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; //按钮输入引脚 int previousButtonState=HIGH; //用于检查按钮的状态 int counter=0; //按钮推计数器 void setup() { pinMode(buttonPin, INPUT); //使按钮引脚成为输入: Keyboard.begin(); //初始化对键盘的控制: } void loop() { int buttonState=digitalRead(buttonPin); //阅读按钮: if ((buttonState != previousButtonState)&& (buttonState == HIGH)) //目前已按下: //增加按钮计数器 counter++; //打出一条消息 Keyboard.print("You pressed the button "); Keyboard.print(counter); Keyboard.println(" times."); } //保存当前按钮状态以供下次比较: previousButtonState=buttonState; }
将按钮的一个端子连接到Arduino的引脚4,将另一个引脚连接到5V,通过将电阻从引脚4接地,可将其用作下拉电阻,为接地提供参考。
对电路板进行编程后,拔下USB电缆,打开文本编辑器,然后将文本光标置于键入区域,再次通过USB将开发板连接到计算机,然后按按钮写入文档。
通过使用任何文本编辑器,它将显示通过Arduino发送的文本。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)