课程表

Arduino 基础

Arduino 函数库

Arduino 进阶

Arduino 项目

Arduino 传感器

Arduino 电机控制

Arduino 声音

工具箱
速查手册

Arduino 键盘消息

当前位置:免费教程 » 程序设计 » Arduino

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

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

 

必需的组件

您将需要以下组件 -

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

 

程序

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

 

面包板

 

草图

在计算机上打开Arduino IDE软件。 在Arduino语言编码将控制你的电路。 通过单击新建打开一个新的草图文件。

 

Sketch

 

Arduino代码

  1. /*
  2. Keyboard Message test For the Arduino Leonardo and Micro,
  3. Sends a text string when a button is pressed.
  4. The circuit:
  5. * pushbutton attached from pin 4 to +5V
  6. * 10-kilohm resistor attached from pin 4 to ground
  7. */
  8.  
  9. #include "Keyboard.h"
  10. const int buttonPin = 4; // input pin for pushbutton
  11. int previousButtonState = HIGH; // for checking the state of a pushButton
  12. int counter = 0; // button push counter
  13.  
  14. void setup() {
  15. pinMode(buttonPin, INPUT); // make the pushButton pin an input:
  16. Keyboard.begin(); // initialize control over the keyboard:
  17. }
  18.  
  19. void loop() {
  20. int buttonState = digitalRead(buttonPin); // read the pushbutton:
  21. if ((buttonState != previousButtonState)&& (buttonState == HIGH)) // and it's currently pressed: {
  22. // increment the button counter
  23. counter++;
  24. // type out a message
  25. Keyboard.print("You pressed the button ");
  26. Keyboard.print(counter);
  27. Keyboard.println(" times.");
  28. }
  29. // save the current button state for comparison next time:
  30. previousButtonState = buttonState;
  31. }

 

代码说明

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

一旦你编写了电路板,拔下USB电缆,打开一个文本编辑器,并将文本光标放在打字区域。 通过USB再次将板连接到计算机,然后按按钮写入文档。

 

结果

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

转载本站内容时,请务必注明来自W3xue,违者必究。
 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号