int led_pin = 13;
int btn_pin = 7;
int state = 1;
int old_state;
// 1-state: OFF
// 2-stte:a ON
bool btn_val, btn_old_val;
bool isButtonPressed;
unsigned long currentTime, lastTime;
void setup() {
pinMode(led_pin, OUTPUT);
pinMode(btn_pin, INPUT_PULLUP);
}
void loop() {
currentTime = millis();
readButton();
switch (state) {
case 1: // OFF state
if (isButtonPressed) {
state = 2;
}
digitalWrite(led_pin, LOW);
break;
case 2: // ON state
if (isButtonPressed || currentTime-lastTime>3000) {
state = 1;
}
digitalWrite(led_pin, HIGH);
break;
}
if (state != old_state) {
lastTime = currentTime;
}
old_state = state;
}
void readButton() {
btn_val = !digitalRead(btn_pin);
if (btn_val && !btn_old_val) {
isButtonPressed = true;
}
else {
isButtonPressed = false;
delay(50);
}
btn_old_val = btn_val;
}