问题描述
我正在编写一个交通灯程序,并且正在尝试合并一个按钮,当按下该按钮时,上面的灯会变成红色,下面的灯会变成绿色(见图)。我无法让它结束当时正在运行的循环和函数。我需要它在按下按钮的循环中的任何一点改变灯光,但我无法找到如何使其工作。也许有人可以帮我解决这个问题? (对不起,如果这不是问这个问题的合适地方,我愿意接受我能得到的任何反馈)
这是接线的图像:
这是目前为止的代码:
// Check WiFi connection status
if (WiFi.status () == WL_CONNECTED) {
HTTPClient http;
http.begin (serverName);
// If you need an HTTP request with a content type: text / plain
http.addHeader ("Content-Type","text / plain");
int httpResponseCode = http.POST ("**** The new data for the server ****");
if (httpResponseCode> 0) {
Serial.print ("HTTP Response code:");
Serial.println (httpResponseCode);
String payload = http.getString ();
Serial.println (payload);
}
else {
Serial.print ("Error code:");
Serial.println (httpResponseCode);
}
// Free resources
http.end ();
}
解决方法
我有 3 个小窍门给你:
-
为按钮使用中断。您可以在 Arduino Reference 找到
attachInterrupt()
它是如何工作的。关于 Arduino Uno 中断的一个问题是,它只有 2 个引脚。这意味着您只能使用此方法实现 2 个按钮。 -
你应该避免在你的代码中使用长时间的延迟,因为程序在延迟期间什么都不做。这意味着在 1 个红绿灯延迟期间,您不能切换第二个红绿灯。 相反,您可以使用
millis()
函数和计时变量来计算时间。 -
了解有限状态机的工作原理。有了这个概念并且不使用延迟,您可以连接任意数量的按钮,只要您有可用的可用引脚。