风筝
发表于: 2016-7-4 16:03:17 | 显示全部楼层

按键控制(Button)

当你按下按键或者开关时,电路中的两点连接在一起。本示例展示了如何在按键按下时点亮内置的13脚LED。


所需硬件

-    Arduino或者Genuino开发板

-    按钮开关

-    10K电阻

-    导线

-    面包板


电路连接方式

button.png

将三根导线连接至开发板。前两根导线,红色和绿色,连接到面包板的两侧的长列用于提供5V电源和地。第三根导线将数字引脚2脚连接至按键的一端。同时该端通过下拉电阻连接至地。按键的另一端连接至5V电源。


当按键开路时(未按下),按键的两端没有连接,所以引脚连接到地,读取时为低电平LOW。当按键闭合时(按下),按钮两端连接在一起,并连接到5V,因此读取时为高电平HIGH。


你也可以使用相反的方法搭建电路,使用上拉电阻保持输入是高电平HIGH,当按钮按下时,输入变成低电平LOW。如果是这样,程序的动作就会相反,即正常状态下LED点亮,按下按钮时熄灭。


如果将数字引脚悬空,则LED可能会无规律的闪烁。这是因为输入是悬浮的,也就是随机处于高电平或是低电平。这就是为什么我们需要在电路中添加上拉或者下拉电阻。


原理图

button_schem.png


代码

  1. /*
  2.   Button

  3. Turns on and off a light emitting diode(LED) connected to digital
  4. pin 13, when pressing a pushbutton attached to pin 2.


  5. The circuit:
  6. * LED attached from pin 13 to ground
  7. * pushbutton attached to pin 2 from +5V
  8. * 10K resistor attached to pin 2 from ground

  9. * Note: on most Arduinos there is already an LED on the board
  10. attached to pin 13.


  11. created 2005
  12. by DojoDave <http://www.0j0.org>
  13. modified 30 Aug 2011
  14. by Tom Igoe

  15. This example code is in the public domain.

  16. http://www.arduino.cc/en/Tutorial/Button
  17. */

  18. // constants won't change. They're used here to
  19. // set pin numbers:
  20. const int buttonPin = 2;     // the number of the pushbutton pin
  21. const int ledPin =  13;      // the number of the LED pin

  22. // variables will change:
  23. int buttonState = 0;         // variable for reading the pushbutton status

  24. void setup() {
  25.   // initialize the LED pin as an output:
  26.   pinMode(ledPin, OUTPUT);
  27.   // initialize the pushbutton pin as an input:
  28.   pinMode(buttonPin, INPUT);
  29. }

  30. void loop() {
  31.   // read the state of the pushbutton value:
  32.   buttonState = digitalRead(buttonPin);

  33.   // check if the pushbutton is pressed.
  34.   // if it is, the buttonState is HIGH:
  35.   if (buttonState == HIGH) {
  36.     // turn LED on:
  37.     digitalWrite(ledPin, HIGH);
  38.   } else {
  39.     // turn LED off:
  40.     digitalWrite(ledPin, LOW);
  41.   }
  42. }
复制代码
跳转到指定楼层
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

主题 700 | 回复: 1480



手机版|

GMT+8, 2024-4-18 16:05 , Processed in 0.130935 second(s), 6 queries , Gzip On, MemCache On. Powered by Discuz! X3.5

YiBoard一板网 © 2015-2022 地址:河北省石家庄市长安区高营大街 ( 冀ICP备18020117号 )

快速回复 返回顶部 返回列表