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

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

必需的组件

你将需要以下组件:

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

程序

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

草图

在计算机上打开Arduino IDE软件。使用Arduino语言进行编码控制你的电路。通过单击“New”打开一个新的草图文件。

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发送的文本。