用按钮控制LED的点亮和熄灭
基础练习
按下按钮,LED点亮,松开按钮LED熄灭
接线图
电路图
练习代码
// 设置各引脚别名
const int buttonPin = 2;
const int ledPin = 13;
int buttonState = 0;
void setup()
{
// 初始化LED引脚为输出
pinMode(ledPin, OUTPUT);
// 初始化按键引脚为输入
pinMode(buttonPin, INPUT);
}
void loop()
{
// 读取引脚状态
buttonState = digitalRead(buttonPin);
// 判断引脚是否被按下
if (buttonState == HIGH)
{
/* 点亮LED */
digitalWrite(ledPin, HIGH);
}
else
{
//熄灭
digitalWrite(ledPin, LOW);
}
}
扩展练习
按下按钮后,LED点亮,再次按下按钮LED熄灭
接线图
电路图
需要的配件
代码
// 设置各引脚别名
const int buttonPin = 2;
const int ledPin = 13;
// led 状态
boolean ledState = false;
void setup()
{
// 初始化LED引脚为输出
pinMode(ledPin, OUTPUT);
//将引脚2设置为输入上拉模式
//引脚2与外部按钮连接
pinMode(buttonPin, INPUT_PULLUP);
}
void loop()
{
while (digitalRead(buttonPin) == HIGH)
{
}
/* 如果当前LED未打开状态 */
if (ledState == true)
{
/* 则关闭LED */
digitalWrite(ledPin, LOW);
}
else
{
/* 否则打开LED */
digitalWrite(ledPin, HIGH);
}
// led 状态取反
ledState = !ledState;
delay(500);
}