实现功能
按一次按钮,蜂鸣器响一次,点亮或熄灭LED
有源蜂鸣器:引脚一长一短,一般带有贴纸
Arduino代码
#define LED 13 //LED的引脚,因为Arduino的13引脚与板载的LED连接在一起,所以LED定义为13
#define BTN 12 //按钮引脚
#define BUZZER 11 //有源蜂鸣器引脚
boolean buttonState=false; //设定LED的状态。false代表要将LED熄灭
void setup() {
// put your setup code here, to run once:
pinMode(BTN,INPUT_PULLUP); //为避免读取按钮是“悬空”,在按钮引脚上加一个上拉电阻
pinMode(BUZZER,OUTPUT);
pinMode(LED,OUTPUT);
//将有源蜂鸣器和LED都设为输出
digitalWrite(BUZZER,LOW); //给有源蜂鸣器低电平,不让其发声
}
void loop() {
// put your main code here, to run repeatedly:
if(digitalRead(BTN)==LOW){ //如果按钮按下
delay(20);
if(digitalRead(BTN)==LOW){ //检测到按钮按下,延时20ms后再检测一次,实现软件消抖
digitalWrite(BUZZER,HIGH);
delay(500);
digitalWrite(BUZZER,LOW);
//使蜂鸣器发声500ms
buttonState=!buttonState;
//按钮按下,改变LED状态
if(buttonState){
digitalWrite(13,HIGH);
}
else{
digitalWrite(13,LOW);
}
//如果LED状态为真,点亮LED,否则,熄灭。
}
}
}