arduino millis() trick with state machine
This sketch waits until button is pressed ( pin 2 connected with ground ) and if button was pressed - blinks LED 3 times.
#include <Arduino.h>
const int LED_PIN = LED_BUILTIN;
const int BUTTON_PIN = 2;
const long blingTimes = 3;
void setup() {
Serial.begin(9600);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
pinMode(BUTTON_PIN, INPUT_PULLUP);
}
enum {
turn_on,
turn_off,
wait,
};
byte state = wait;
unsigned long prevMillis1 = 0;
const unsigned long delay1 = 1000;
const unsigned long delay2 = 500;
long iteration = 0;
void loop() {
unsigned long currentTime = millis();
if(state == wait) {
if(digitalRead(BUTTON_PIN) == LOW) {
state = turn_on;
iteration=0;
}
}
if (state == turn_on) {
if (millis() - prevMillis1 >= delay1) {
prevMillis1 = currentTime;
digitalWrite(LED_PIN, HIGH);
state = turn_off;
}
}
if (state == turn_off) {
if (millis() - prevMillis1 >= delay2) {
prevMillis1 = currentTime;
digitalWrite(LED_PIN, LOW);
state = turn_on;
iteration++;
if (iteration > blinkTimes) {
state = wait;
}
}
}
}