We are coding to turn on a motor for specified amount of time using the millis function. However our code does not work as it works perfectly in the first 2 iterations however in the third it becomes stuck in the while loop. We are currently using the delay function but we do not want to rely on that. Our code is below.
Any thoughts or solutions?
Thanks
void loop(){
int starttime=millis();
int timeinteger=5000;
while(millis() < starttime + timeinteger)
{
digitalWrite(12, HIGH); //Make Direction of A forward
digitalWrite(9, LOW); // Turn off Brake for A
analogWrite(3, 255); //Turn on Channel A at speed 255
}
Also, your brake after the while loop will only be active for a few microseconds before the loop() gets re-executed and you start up again. I would think this would make this appear to be on continuously. I am surprised that you can tell it works twice.
You could print a serial.println("braking") after the while loop to see if the loop is actually completing.
You can get away with using int rather than long, but then you really really have
to get time tests correct:
int starttime=millis();
int timeinteger=5000;
while(millis() < starttime + timeinteger) // overflows in 32.7 seconds, or 65.5 if unsigned int
{
...
Needs rewriting this way:
int starttime=millis();
int timeinteger=5000;
while (millis() - starttime < timeinteger) // subtract first, then compare.
{
...
The result of the subtraction will be correct so long as the delay isn't greater than
32.7 seconds, due to the way 2's complement works.
But the whole thing is inside-out, you need to test for completion, not for
the duration, otherwise you are stuck in a loop that isn't loop(), so nothing else
can happen.
unsigned long starttime = 0UL ; // use unsigned long so it will work for long delays
const unsigned long timeinteger=5000UL ; // unsigned long constants should have UL
boolean motor_on = false ;
void loop ()
{
if ( // some condition to start the motor such as a button push?
{
digitalWrite(12, HIGH); //Make Direction of A forward
digitalWrite(9, LOW); // Turn off Brake for A
analogWrite(3, 255); //Turn on Channel A at speed 255
motor_on = true ;
starttime = millis () ;
}
if (motor_on && millis() - starttime >= timeinteger) // test for completion, not a while.
{
motor_on = false ;
digitalWrite (9, HIGH) ; // stop it
}
....