You are on page 1of 3

如何连接和编程按钮

了解如何连接和编程按钮以控制 LED。
当您按下按钮或开关时,它们会连接电路中的两个点。此示例在您按下按钮时
打开引脚 13 上的内置 LED。

硬件

 Arduino 板

 瞬时按钮或开关

 10K 欧姆电阻

 连接线

 面包板

电路

将三根电线连接到电路板上。前两个,红色和黑色,连接到面包板侧面的两个
长垂直行,以提供对 5 伏电源和接地的访问。第三根线从数字引脚 2 连接到
按钮的一条腿。按钮的同一条腿通过一个下拉电阻(此处为 10K 欧姆)连接
到地。按钮的另一条腿连接到 5 伏电源。
当按钮打开(未按下)时,按钮的两条腿之间没有连接,因此引脚连接到地
(通过下拉电阻),我们读到低电平。当按钮关闭(按下)时,它会在其两条
腿之间建立连接,将引脚连接到 5 伏,因此我们读取到高电平。

您也可以以相反的方式连接该电路,使用上拉电阻保持输入高电平,并在按下
按钮时变为低电平。如果是这样,草图的行为将被反转,当您按下按钮时,
LED 通常会打开并关闭。

如果您断开数字 I/O 引脚与所有设备的连接,LED 可能会不规律地闪烁。这


是因为输入是“浮动的”——也就是说,它会随机返回 HIGH 或 LOW。这就
是为什么您需要在电路中使用上拉或下拉电阻。

示意图

代码

/*
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 through 220 ohm resistor
- 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.

https://www.arduino.cc/en/Tutorial/BuiltInExamples/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);
}
}

You might also like