Hi, I'm using non-blocking delay in a switch() case and the delay is not looping?
In the example below I would expect the serial monitor to switch between YES / NO every 5000 milliseconds. But it just switches from YES to NO once. Do I need a while statement of have I made a mistake in the code?
The switch(newPos) case is selected using a rotary encoder.
void loop() {
// State machine
preset();
// delay between changing presets
delay(10);
} // loop
void preset() {
unsigned long previousMillis = 0;
const long interval = 5000;
// State machine
switch (newPos) {
case 1:
// Preset 1
// ...
break;
case 2: {
// Preset 2
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
previousMillis = currentMillis;
Serial.println("YES");
} else {
Serial.println("NO");
}
}
break;
} // state machine
} // preset
Well there's your problem.
/Users/john/Documents/Arduino/sketch_oct12a/sketch_oct12a.ino: In function 'void preset()':
sketch_oct12a:16:11: error: 'newPos' was not declared in this scope
switch (newPos)
^~~~~~
exit status 1
'newPos' was not declared in this scope
I added some to get it to compile. As I did I noticed that your 'previousMillis' veriable is not static or global so it gets set to 0 each time you enter preset().
Hi John,
Excellent, thanks.
The 'unsigned' previousMillis seems to be the issue. I changed it to 'static' and inserted the Blink Without Delay code to test and the LED flashes when I select the switch(newPos) case using the rotary encoder.
I'm controlling a DC motor so what I've done for the moment is to insert the start / stop commands in the 'blink' code. What would be the more elegant way of doing this and removing the LED from the circuit?
// if the LED is off turn it on and vice-versa:
if (ledState == LOW) {
ledState = HIGH;
myMotor->run(FORWARD);
myMotor->setSpeed(blower * newPos);
} else {
ledState = LOW;
myMotor->run(RELEASE);
}
// set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState);
... actually having the LED in the circuit will be useful as I'm creating a random delay and the visual feedback will be valuable.