我目前正在开发以按钮作为输入的项目,当我们从第一个LED开始点击按钮时它会移动,每隔0.5秒LED就会相互跟随。中断功能工作正常,但问题是中断在循环结束时有效。我点击按钮时想要关闭LED。如何解决这个问题?
int button;
void setup() {
DDRD = B11110000;
attachInterrupt(digitalPinToInterrupt(2), buttonPressed, RISING);
}
void loop() {
if(button) {
PORTD = B00010000;
delay(500);
PORTD = PORTD <<1;
delay(500);
PORTD = PORTD <<1;
delay(500);
PORTD = PORTD <<1;
delay(500);
}
else {
PORTD = B00000000;
}
}
void buttonPressed() {
if(button == 0) {
button = 1;
}else {
button = 0;
}
}
答案 0 :(得分:1)
您可以重写代码来检查每个LED的按钮状态,而不是执行整个循环。这意味着LED将始终保持点亮整个.5秒的时间。
int button;
void setup() {
DDRD = B11110000;
attachInterrupt(digitalPinToInterrupt(2), buttonPressed, RISING);
}
void loop() {
if(button) {
PORTD = PORTD <<1;
if (PORTD == 0) {
PORTD = B00010000;
}
delay(500);
} else {
PORTD = B00000000;
}
}
void buttonPressed() {
button = !button;
}
要立即使LED变暗,不应使用延迟,而是循环最多0.5秒并检查按钮状态;
unsigned long timeout = millis() + 500;
while (button && millis() < timeout);
或者在上下文中更多一点
void loop() {
if(button) {
next_light();
sleep(500);
} else {
PORTD = B00000000;
}
}
void next_light() {
PORTD = PORTD <<1;
if (PORTD == 0) {
PORTD = B00010000;
}
}
void sleep(unsigned long timeout) {
unsigned long end = millis() + timeout;
while (button && millis() < end);
}
void buttonPressed() {
button = !button;
}