9. Motor Driver Truth Table

Motor 1 is controlled by pins PD5 and PD6, and motor 2 is controlled by PD3 and PB3. These pins are connected to the ATmega48/168’s four eight-bit hardware PWM outputs, which allows you to achieve variable motor speeds through hardware timers rather than software. This frees the CPU to perform other tasks while motor speed is automatically maintained.

The suggested procedure for using hardware PWM outputs to control the motors is as follows:

Make the four motor control pins outputs and drive them high; this drives all four motor outputs low.

Configure Timer0 and Timer2 to use a prescaler of 8, which results in a PWM frequency of 20 MHz/8/256 = 9.8 kHz. Set these timers for inverted PWM mode output on both OCxA and OCxB, meaning that these PWM pins are set on timer compare match and cleared on timer overflow. This results in negative PWM pulses with duty cycles determined by registers OCR0A, OCR0B, OCR2A, and OCR2B.

You can command motor 1 to drive “forward” at a speed ranging from 0 – 255 by setting OCR0B = speed and holding fixed OCR0A = 0. You can command motor 1 to drive “reverse” at a speed ranging from 0 – 255 by setting OCR0A = speed and OCR0B = 0. During the period where the two input pins have opposite values, the motor drives at full speed. During the period where the two inputs have the same value (high), the motor brakes. Cycling between drive and brake and high frequency results in variable motor speed that changes as a function of PWM duty cycle. Analogous results can be obtained for motor 2 using OCR2A and OCR2B. (Note that the concept of “forward” is arbitrary as simply flipping the motor leads results in rotation in the opposite direction.)

Using these PWM settings, OCR0B = 255 is equivalent to holding PD5 low while OCR0A = 0 is equivalent to holding PD6 high. As you can see from the truth table above, in this state M1B connects to your battery’s positive terminal and M1A connects to ground. Decreasing OCR0B to something less than 255 decreases the percentage of time PD5 is low, causing M1B to alternate between VIN and GND (and hence causing motor 1 to alternate between drive and brake). Similarly, OCR2B = 255 is equivalent to holding PD3 low while OCR2A = 0 is equivalent to holding PB3 high. In this state, M2B connects to your battery’s positive terminal and M2A connects to ground.