I am trying to make a code whereby the relay and led turns on only at certain delays but I am trying to use millis. However, when I try to create the interval between the first and second time the components "ON", it does not delay and the second "ON" just starts straight away. Here is my code
const byte BUTTON = 2;
const byte LED = 12;
const byte relay = 3;
unsigned long relayTurnedOnAt; // when led was turned on
unsigned long firstroundstart; // when button was released
unsigned long firstrounddone;
unsigned long relayTurnedOnAt2;
unsigned long secondroundstart;
unsigned long secondrounddone;
unsigned long turnOnDelay = 50; // wait to turn on LED
unsigned long turnOffDelay = 2000; // turn off LED after this time
unsigned long betweenrounds = 6000;
bool relayReady = false; // flag for when button is let go
bool relayState = false; // for LED is on or not.
bool relayReady2 = false;
bool relayState2 = false;
int buttonState = 0;
void setup() {
pinMode(BUTTON, INPUT_PULLUP);
pinMode(LED, OUTPUT);
pinMode(relay, OUTPUT);
digitalWrite(LED, LOW);
}
void loop() {
unsigned long currentMillis = millis();
buttonState = digitalRead(BUTTON);
//first round
if (buttonState == LOW) {
firstroundstart = currentMillis;
relayReady = true;
}
//}
if (relayReady) {
if ((unsigned long)(currentMillis - firstroundstart) >= turnOnDelay) {
digitalWrite(relay, HIGH);
digitalWrite(LED, HIGH);
relayState = true;
relayTurnedOnAt = currentMillis;
relayReady = false;
}
}
if (relayState) {
if ((unsigned long)(currentMillis - relayTurnedOnAt) >= turnOffDelay) {
relayState = false;
digitalWrite(relay, LOW);
digitalWrite(LED, LOW);
firstrounddone = currentMillis;
}
}
//first round done
//between rounds
if ((unsigned long) (currentMillis - firstrounddone) >= betweenrounds) {
secondroundstart = currentMillis;
relayReady2 = true;
}
//second round start
if (relayReady2) {
if ((unsigned long)(currentMillis - secondroundstart) >= turnOnDelay) {
digitalWrite(relay, HIGH);
digitalWrite(LED, HIGH);
relayState2 = true;
relayTurnedOnAt2 = currentMillis;
relayReady2 = false;
}
}
if (relayState2) {
if ((unsigned long)(currentMillis - relayTurnedOnAt2) >= turnOffDelay) {
relayState2 = false;
digitalWrite(relay, LOW);
digitalWrite(LED, LOW);
secondrounddone = currentMillis;
}
}
}