如何将按钮连接到Arduino板

描述

在本快速入门指南中,您将学习如何将按钮连接到Arduino板,并根据按钮是否被按下来读取HIGH或LOW。您将使用电路板上随附的发光二极管 (LED)
通过按钮打开和关闭,以便验证按钮按下代码是否正常工作。

所需零件

Arduino Uno的

面包板(和一些面包板电线)

电阻 10 kΩ

按钮或开关

电线

Arduino按钮电路

要将按钮连接到Arduino,您需要一个下拉或上拉电阻器。这是为了确保在不按下按钮时,它有一个定义的值。在本例中,我们使用10
kΩ的下拉电阻。

Arduino

在试验板上连接

以下是使用面包板和一些电缆将电位计连接到Arduino的方法:

Arduino

将按钮的一侧连接到Arduino上的5V引脚。并将另一侧连接到Arduino上的数字输入D2。将电阻器从 D2(和按钮)接地。

Arduino按钮代码

以下代码读取按钮状态,然后根据按钮是否被按下来打开或关闭板载 LED。

与所有Arduino代码一样,代码围绕两个主要函数setup()和loop()构建:

在 setup() 中,您需要设置哪些引脚应该是输入和输出。

在 loop() 中,您需要读取按钮输入并根据按钮状态设置 LED 引脚。

查看完整代码:

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);
}
}

代码的工作原理

下面概述了代码的工作原理:

变量和常量:

buttonPin:连接按钮的引脚 2。

ledPin:连接 LED 的引脚 13。

buttonState:存储按钮的状态(HIGH 或 LOW)。

setup():

设置为 OUTPUT 和 INPUT。ledPinbuttonPin

loop():

读取按钮的状态。

如果按下按钮 (HIGH),LED 亮起。

否则,LED 熄灭。

因此,在此代码中,按下引脚 2 上的按钮可切换引脚 13 上的 LED。
审核编辑:陈陈

打开APP阅读更多精彩内容
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉

全部0条评论

快来发表一下你的评论吧 !

×
20
完善资料,
赚取积分