Hardware Reference
In-Depth Information
Operating an H-bridge Circuit
Next up, you write a program to control the motor's direction and speed using
the potentiometer and the H-bridge. Setting the potentiometer in a middle range
stops the motor, setting the potentiometer in a range above the middle increases
the speed forward, and setting the potentiometer in a range below the middle
increases the speed backward. This is another perfect opportunity to employ
functions in your Arduino program. You can write a function to stop the motor,
one to cause it spin forward at a set speed, and one to cause it to spin backward
at a set speed. Ensure that you correctly disable the H-bridge at the beginning of
the function before changing the motor mode; doing so reduces the probability
that you will make a mistake and accidentally short out the H-bridge.
Following the logic diagram from Figure 4-6, you can quickly figure out how
you need to control the pins to achieve the desired results:
To stop current low through the device, set the enable pin low.
To set the switches for rotation in one direction, set one high, the other low.
To set switches for rotation in the opposite direction, swap which is high
and which is low.
To cause the motor to stop immediately, set both switches low.
NOTE Alwaysdisablethecurrentflowbeforechangingthestateoftheswitches
toensurethatamomentaryshortcannotbecreatedastheswitchesflip.
First, you should devise the functions that safely execute the previously
described motions. Create a new Arduino sketch and start by writing your
new functions:
//Motor goes forward at given rate (from 0-255)
void forward (int rate)
{
digitalWrite(EN, LOW);
digitalWrite(MC1, HIGH);
digitalWrite(MC2, LOW);
analogWrite(EN, rate);
}
//Motor goes backward at given rate (from 0-255)
void reverse (int rate)
{
digitalWrite(EN, LOW);
digitalWrite(MC1, LOW);
digitalWrite(MC2, HIGH);
analogWrite(EN, rate);
Search WWH ::




Custom Search