In this lesson, you will learn how to combine Pulse Width Modulation (PWM) signals with H-Bridge logic to gain complete command over a DC motor's speed and direction.
An H-Bridge is a circuit configuration of four transistors that allows current to flow through a motor in either direction. When transistors on the top-left and bottom-right are closed, the motor spins forward; swapping to the top-right and bottom-left reverses the polarity and the rotation. Because driving these transistors directly from a microcontroller pin would exceed current limits, we use an H-bridge driver integrated circuit (IC) to handle the power.
Controlling Speed and Direction
To control the motor, we connect two types of signals from our microcontroller to the driver’s inputs:
- Directional Logic: Standard GPIO pins are set to either
0or1to toggle the internal transistor states (forward/reverse). - Speed (PWM): We route a PWM signal to the "Enable" pin of the H-bridge. By adjusting the duty cycle, we effectively chop the power delivered to the motor.
Consider this logic for a simple motor driver interface:
// Setting pins for Forward Direction
GPIO_Write(DIR_PIN_A, HIGH);
GPIO_Write(DIR_PIN_B, LOW);
// Adjusting Speed via PWM Duty Cycle (e.g., 50% speed)
// Assuming Timer-based PWM is pre-configured
Timer_SetCompare(PWM_CHANNEL, 500);
Critical Safety Considerations
When shifting directions, never change the logic states of your direction pins while the PWM signal is at a high duty cycle. Doing so can cause a "shoot-through" condition, where transistors briefly short the power supply directly to ground. Always implement a small software delay or use your timer interrupts to set the PWM duty cycle to 0 (stopping the motor) before toggling the directional GPIO pins. By synchronizing your timer-based PWM generation with simple GPIO logic states, you transform a basic digital signal into a robust, variable-speed motion control system.
Key Takeaway: By feeding a PWM signal into the H-bridge "Enable" pin while using standard GPIOs to toggle direction, you decouple the motor's power regulation from its rotational polarity.