int ledRED = 13;
int ledGREEN = 12;
int pushbuttonRED = 5;
int pushbuttonGREEN = 4;
bool redState = false;
bool greenState = false;
unsigned long redStartTime = 0;
unsigned long greenStartTime = 0;
const long blinkDuration = 1000; // LED 点亮时间
void setup() {
// put your setup code here, to run once:
pinMode(ledRED, OUTPUT);
pinMode(ledGREEN, OUTPUT);
pinMode(pushbuttonRED, INPUT_PULLUP);
pinMode(pushbuttonGREEN, INPUT_PULLUP);
}
void loop() {
// put your main code here, to run repeatedly:
/*
if(1) //simulate push and holding
{
digitalWrite(ledRED, HIGH);
delay(1000);
digitalWrite(ledRED, LOW);
delay(1000);
}
else
{
digitalWrite(ledRED, LOW);
}
if(digitalRead(pushbuttonGREEN) == LOW)
{
digitalWrite(ledGREEN, HIGH);
delay(1000);
digitalWrite(ledGREEN, LOW);
delay(1000);
}
else
{
digitalWrite(ledGREEN, LOW);
}
*/
/*
在这种阻塞式的场景中,each pushbutton control one LED, it seem operating in a good way
but if you holding one pushbutton then push and hold another, you will find both of
LEDs running in a incorrect period that is doubled by before. Because you had to
run one control then run another.
*/
/*----------------------------------------------------------------------------*/
unsigned long currentMillis = millis();
// 读取按钮状态(按下时为 LOW)
if (digitalRead(pushbuttonRED) == LOW) {
redState = true;
redStartTime = currentMillis; // 记录按下时的时间
digitalWrite(ledRED, HIGH);
}
if (digitalRead(pushbuttonGREEN) == LOW) {
greenState = true;
greenStartTime = currentMillis;
digitalWrite(ledGREEN, HIGH);
}
// 检查是否超过亮灯时间
if (redState && currentMillis - redStartTime >= blinkDuration) {
digitalWrite(ledRED, LOW);
redState = false;
}
if (greenState && currentMillis - greenStartTime >= blinkDuration) {
digitalWrite(ledGREEN, LOW);
greenState = false;
}
/*----------------------------------------------------------------------------*/
}