programming a bidirectional motor

Hey guys,

I'm currently working on a project where a motor must be spun bidirectionally and must be rotated continuously left and right using PWM outputs, ie. it must spin left for 1 second than right for one second and repeated for 60 seconds. I'm using an H-bridge circuit which shouldn't really affect the programming, but i was just wondering on the feasibility of being able to program this?

sorry guys i'm a big noob at this :slight_smile:

Is the PWM setting going to be the same for both directions? If so, the programming is fairly easy:

analogWrite(enablePin, 137); // Set speed
for (int i = 0; i<30, i++)  // Repeat 30 times
    {
    digitalWrite(directionPin, HIGH);  // Run one way...
    delay(1000); // ... for one second.
    digitalWrite(directionPin, LOW);  // Run the other way...
    delay(1000); // ... for one second.
    }
analogWrite(enablePin, 0); // Stop

wow thanks! the websites i was looking seemed to put everything way over my head, but this seems very manageable. I did however have a few questions, in line 1, what does the 137 mean? also, under the for loop, what does directionPin mean? does it need a number?

I think i can figure out the rest of the code, but here's the general lay out i made for the program i want to create.


also, the pwm outputs would be going the left and right logic inputs on my h-bridge, would this cause the motor to spin left and right?

thanks i really appreciate it :slight_smile:

If you haven't already built the h-bridge, you might want to look at a continous rotation servo for an easy setup.

i tried to look up the differences between servo motors and regular motors, and it seems that servomotors will just have a type of feedback control on it whereas regular motors do not? i was just wondering how that would allow for the project to not use an h-bridge anymore

Some youtube videos showing continous rotation servos.

In line 1, what does the 137 mean?

It's a speed I made up. Use a value between 0 (stopped) and 255 (full speed).

what does directionPin mean? does it need a number?

It's the pin of the H-bridge that specified Clockwise or Counter-clockwise. Yes, that would be a pin number.

You didn't provide information about your H-bridge and how it is connected so I just made some guesses.