/* https://forum.arduino.cc/t/help-millis-function/1115289/16
switch on/off outputs in a sequence
by noiasca
2023-04-15
code in thread
*/
const uint8_t outputPin[3] {6, 5, 3}; // an array with all output pins
struct Sequence { // one Sequence holds the interval an the state of the 3 outputs
uint32_t interval; // how long should this line be active
int stateA; // output 0
int stateB; // output 1
int stateC; // output 2
};
Sequence sequence[] { // several sequences in an array
{1000, HIGH, LOW, LOW}, // interval, stateA, stateB, stateC
{1000, HIGH, LOW, HIGH},
{1000, LOW, HIGH, HIGH},
{1000, HIGH, HIGH, LOW}
};
const uint8_t noOfSequence = sizeof(sequence) / sizeof(sequence[0]); // calculate the number of sequences
// a non blocking function to activate/deactivate outputs by an defined sequence
void sequenceRun() {
static uint8_t current = noOfSequence - 1; // we start in the last sequence
static uint32_t previousMillis = -5000; // make the timestamp already outdated
if (millis() - previousMillis > sequence[current].interval) {
previousMillis = millis(); // remember current timestamp for next runt
current++; // increase current sequence
if (current >= noOfSequence) { // handle rollover
current = 0;
}
Serial.println(current); // debut print to follow what the program is doing
digitalWrite(outputPin[0], sequence[current].stateA); // set the output according to the table line
digitalWrite(outputPin[1], sequence[current].stateB);
digitalWrite(outputPin[2], sequence[current].stateC);
}
}
void setup() {
Serial.begin(115200);
for (auto &i : outputPin) pinMode(i, OUTPUT); // call pinMode for each output pin
}
void loop() {
sequenceRun();
}