|
按键控制(Button) 当你按下按键或者开关时,电路中的两点连接在一起。本示例展示了如何在按键按下时点亮内置的13脚LED。
所需硬件 - Arduino或者Genuino开发板
- 按钮开关
- 10K电阻
- 导线
- 面包板
电路连接方式
将三根导线连接至开发板。前两根导线,红色和绿色,连接到面包板的两侧的长列用于提供5V电源和地。第三根导线将数字引脚2脚连接至按键的一端。同时该端通过下拉电阻连接至地。按键的另一端连接至5V电源。
当按键开路时(未按下),按键的两端没有连接,所以引脚连接到地,读取时为低电平LOW。当按键闭合时(按下),按钮两端连接在一起,并连接到5V,因此读取时为高电平HIGH。
你也可以使用相反的方法搭建电路,使用上拉电阻保持输入是高电平HIGH,当按钮按下时,输入变成低电平LOW。如果是这样,程序的动作就会相反,即正常状态下LED点亮,按下按钮时熄灭。
如果将数字引脚悬空,则LED可能会无规律的闪烁。这是因为输入是悬浮的,也就是随机处于高电平或是低电平。这就是为什么我们需要在电路中添加上拉或者下拉电阻。
原理图
代码 - /*
- Button
- Turns on and off a light emitting diode(LED) connected to digital
- pin 13, when pressing a pushbutton attached to pin 2.
- The circuit:
- * LED attached from pin 13 to ground
- * pushbutton attached to pin 2 from +5V
- * 10K resistor attached to pin 2 from ground
- * Note: on most Arduinos there is already an LED on the board
- attached to pin 13.
- created 2005
- by DojoDave <http://www.0j0.org>
- modified 30 Aug 2011
- by Tom Igoe
- This example code is in the public domain.
- http://www.arduino.cc/en/Tutorial/Button
- */
- // constants won't change. They're used here to
- // set pin numbers:
- const int buttonPin = 2; // the number of the pushbutton pin
- const int ledPin = 13; // the number of the LED pin
- // variables will change:
- int buttonState = 0; // variable for reading the pushbutton status
- void setup() {
- // initialize the LED pin as an output:
- pinMode(ledPin, OUTPUT);
- // initialize the pushbutton pin as an input:
- pinMode(buttonPin, INPUT);
- }
- void loop() {
- // read the state of the pushbutton value:
- buttonState = digitalRead(buttonPin);
- // check if the pushbutton is pressed.
- // if it is, the buttonState is HIGH:
- if (buttonState == HIGH) {
- // turn LED on:
- digitalWrite(ledPin, HIGH);
- } else {
- // turn LED off:
- digitalWrite(ledPin, LOW);
- }
- }
复制代码 |