# Reverse DC motor direction every second automatically

I have the Arduino Starter Kit and I'm on project 10 Zoetrope. I've removed the switch that changes the direction as I don't want the reverse to happen when I press a switch. I want the reverse to happen based on time.

For example using code, I want the reverse to happen every second (the motor moves clockwise for the first second, counterclockwise for the next second, clockwise for the third second etc.)

I've search for solutions but I haven't found anything yet. I had no luck with the `millis` function as well.

Consider code of the following form.

``````// Declare some globals
byte direction=0, second, prev=0;

void loop() {
second = millis()/1000;
if (prev != second) {
prev = second;
direction = second & 1; // Direction is 0 or 1
OutputTheNewDirection(direction);
}
``````

More generally, suppose you want to make a pattern of clockwise for j time units, alternating with counterclockwise for k time units. Suppose a time unit is m milliseconds long. You can use code as in the following example, where m is 500, j is 10, and k is 1.

``````// Declare some globals and constants
byte direction=0, tunit, prev=0;
enum { m=500, j=10, k=1 };

void loop() {
tunit = (millis()/m) % (j+k);
if (prev != tunit) {
prev = tunit;
direction = tunit < j; // Direction is 0 or 1
OutputTheNewDirection(direction);
}
``````
• As my coding skills are not the best i think i can figure this out. What if i want to change the direction as the time passes by. For example i want the direction to be clockwise when i press the on/off switch then after 5 seconds change it to counterclockwise then after half a second change to clockwise etc. – paul Sep 4 '16 at 19:03
• @paul, see edited answer for 5 seconds CW alternating with half a second CCW – James Waldby - jwpat7 Sep 4 '16 at 22:45