Reputation: 31
This is what I am trying to achieve:
User inputs time using a rotary encoder.
The Arduino Serial Monitor must display real-time values of time as the user keeps rotating the encoder.
The user then hits a physical switch (push switch) to initiate the countdown.
Initially, my code worked perfectly with delay()
function.
But my application also requires me to run a motor as long as the timer lasts. For this, I need a non-blocking delay. I am having a hard time with that. Please help. Here is my code:
unsigned long previousMillis = 0; // will store last time LED was updated
// constants won't change:
const long interval = 1000; // interval at which to blink (milliseconds)
#define outputA 6
#define outputB 7
int i;
int button=5;
int counter = 0;
int aState;
int aLastState;
void setup() {
pinMode (outputA,INPUT);
pinMode (outputB,INPUT);
pinMode (button,INPUT);
Serial.begin (9600);
// Reads the initial state of the outputA
aLastState = digitalRead(outputA);
}
void loop() {
// here is where you'd put code that needs to be running all the time.
aState = digitalRead(outputA); // Reads the "current" state of the outputA
// If the previous and the current state of the outputA are different, that means a Pulse has occured
if (aState != aLastState) {
// If the outputB state is different to the outputA state, that means the encoder is rotating clockwise
if (digitalRead(outputB) != aState) {
counter = counter+1;
} else {
counter = counter-1;
}
Serial.print("Time (secs): ");
Serial.println(counter);
i = counter;
if (digitalRead(button) == HIGH) {
while (i != 0) {
unsigned long currentMillis = millis();
if (currentMillis - previousMillis == interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
i--;
Serial.println(i);
}
}
}
aLastState = aState;
}
}
Upvotes: 0
Views: 1026
Reputation: 303
If I understand well you are decrementing i
only when entering if (currentMillis - previousMillis == interval)
. It means you are decrementing very slowly, and not millisecond by milliseconds…
To correct this I'm suggesting:
unsigned long startMillis = millis();
while (millis() - startMillis() < counter){ //check if your time has elapsed
unsigned long currentMillis = millis();
if (currentMillis - previousMillis == interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
Serial.println((int) counter - (millis() - startMillis()));
}
}
Hope it helps!
Upvotes: 0