I am trying to set a DC motor to work for a fixed amount of time. For example if I will press left, I want it to work for a minute and after that to stop. If I will press right, to work for a minute and than to stop. What do I need to change on this code?



There are two possibilities:

Easy way (but with limitations)

I see a delay of 200 (ms)… So if you want to have it working for a minute, than use 60,000.

If 60,000 is not accepted (maybe the input argument is a signed integer, having a max value of 32,767), than use a for loop and do a delay of a second for 60 times.

This solution will make it not respond within those 60 seconds to another left or right command.

Update: See comment of JRobert, 60,000 can be used without a problem.

Prevent a delay

If you want to respond to a left/right command WHILE the motor moving in these 60 seconds, you have to store the time (with millis) in a variable, and check against the time to know when to switch off the motor.

See command of Duncan C. This is very similar to the 'Blink without Delay' sketch which can be found here.

(Actually, there is a third way using interrupts, but I assume the second solution is best in your case, and is responsive enough considering the tasks you want to do with the Arduino.)

| improve this answer | |
  • 3
    "If 60,000 is not accepted " - Arduino.h defines delay() to take an unsigned long argument, so the compiler will know to allow a long value, or to cast (widen) one that might otherwise require less storage. – JRobert Feb 7 at 13:15
  • 3
    I tend to think using delay() is a dead-end, and rather than telling the OP to update their code with a longer delay we should tell him to rewrite his code following the "blink without delay" pattern. – Duncan C Feb 7 at 13:35
  • 1
    @JRobert Thanks … I updated the answer (and included your name). – Michel Keijzers Feb 7 at 13:46
  • @Duncan C … I think so too, that's why I mentioned both, but I added a reference and your name. Thanks for the update. – Michel Keijzers Feb 7 at 13:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.