执行动作:
采用一个按钮控制,当按下按钮并松手时,led灯亮;当再次按下按钮并松手时,led灯灭。
比较上次写的判断语句,这次我们使用中断函数(attachInterrupt),使代码更简洁易懂。
中断函数(attachInterrupt):attachInterrupt(interrupt,function,mode)
interrupt:中断源(在Arduino中,中断源可选值为0或1,一般分别对应2号和3号引脚)
function:需要中断的函数名
mode:LOW(低电平触发)、CHANGE(变化时触发)、
RISING(低电平变为高电平触发)、FALLING(高电平变为低电平触发)
注意:在写代码时,interrupt处要写成0或1,不能写成2或3
#define led 4
#define button 0
int state = LOW;
void setup() {
// put your setup code here, to run once:
pinMode(led, OUTPUT);
attachInterrupt(button, use, RISING);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(led, state);
}
void use() {
state = !state;
}