目录

Arduino - 键盘消息( Keyboard Message)

在此示例中,按下按钮时,文本字符串将作为键盘输入发送到计算机。 该字符串报告按下按钮的次数。 一旦你对Leonardo进行了编程和接线,打开你喜欢的文本编辑器来查看结果。

Warning - 使用Keyboard.print()命令时,Arduino将接管计算机的键盘。 为确保在使用此功能运行草图时不会失去对计算机的控制,请在调用Keyboard.print()之前设置可靠的控制系统。 该草图包括一个用于切换键盘的按钮,因此它仅在按下按钮后才会运行。

组件的要求 (Components Required)

您将需要以下组件 -

  • 1 × Breadboard
  • 1×Arduino Leonardo,Micro或Due board
  • 1×瞬时按钮
  • 1×10k欧姆电阻器

过程 (Procedure)

按照电路图并连接面包板上的组件,如下图所示。

键盘消息面包板

草图 (Sketch)

在您的计算机上打开Arduino IDE软件。 用Arduino语言编码将控制你的电路。 单击“新建”打开新的草图文件。

草图

Arduino代码 (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;
}

Code to Note

将按钮的一个端子连接到Arduino上的引脚4。 将另一个引脚连接到5V。 使用电阻作为下拉电阻,通过将引脚4连接到地,提供接地参考。

完成电路板编程后,拔下USB电缆,打开文本编辑器,将文本光标放在打字区域。 再次通过USB将主板连接到计算机,然后按按钮在文档中写入。

结果 (Result)

通过使用任何文本编辑器,它将显示通过Arduino发送的文本。

↑回到顶部↑
WIKI教程 @2018