What I'm trying to do: when I push a button once, it makes an LED blink for 3 times, with each blink and pause lasting for 500 ms. So, basically the whole action takes 3 seconds to last (or actually 2,5 s?), then it stops until the next push. I've successfully done this using delay but since I need my program to run while the LED's blinking I can't use this anymore.
So, the millis() works perfectly when I hold the button to start the LED to blink (and it blinks continuosly as I hold the button, this is the basic BWoD code). But I can't figure out how to make the LED blink (even continuosly) with a push. I hope you guys can give me an advice how to solve the problem. My current code is below (tried to use the while function, didn't work correctly as well as if etc). Thanks!
#define led1 12
#define btn 2
int led1state = LOW;
int btnstate;
unsigned long prevmls = 0;
const long interval = 500;
void setup() {
pinMode(led1, OUTPUT);
pinMode(btn, INPUT_PULLUP);
}
void loop() {
unsigned long crntmls = millis();
unsigned long CBmls = millis();
btnstate = digitalRead(btn);
digitalWrite(led1, led1state);
while(digitalRead(btn) == HIGH);
if (crntmls - prevmls >= interval){
prevmls = crntmls;
if(btnstate == LOW){
if (led1state == LOW){
led1state = HIGH;
}else{
led1state = LOW;
}
}
}
}