How to Control DC Motor Using Embedded C: Simple Guide
To control a DC motor using
Embedded C, use GPIO pins to set the motor direction and PWM (Pulse Width Modulation) to control speed. Write code to set output pins high or low for direction and generate PWM signals to adjust motor speed smoothly.Syntax
To control a DC motor, you typically use two GPIO pins for direction and one PWM pin for speed control.
GPIO_SetPinHigh(pin): Sets the pin to high voltage (motor direction forward).GPIO_SetPinLow(pin): Sets the pin to low voltage (motor direction reverse).PWM_SetDutyCycle(channel, duty): Sets PWM duty cycle (0-100%) to control motor speed.
c
void setMotorDirectionForward() { GPIO_SetPinHigh(DIR_PIN1); GPIO_SetPinLow(DIR_PIN2); } void setMotorDirectionReverse() { GPIO_SetPinLow(DIR_PIN1); GPIO_SetPinHigh(DIR_PIN2); } void setMotorSpeed(int speedPercent) { PWM_SetDutyCycle(PWM_CHANNEL, speedPercent); // speedPercent: 0 to 100 }
Example
This example shows how to initialize pins, set motor direction forward, and run the motor at 75% speed using PWM.
c
#include <stdint.h> #include "gpio.h" // hypothetical GPIO library #include "pwm.h" // hypothetical PWM library #define DIR_PIN1 1 #define DIR_PIN2 2 #define PWM_CHANNEL 0 void setMotorDirectionForward() { GPIO_SetPinHigh(DIR_PIN1); GPIO_SetPinLow(DIR_PIN2); } void setMotorSpeed(int speedPercent) { PWM_SetDutyCycle(PWM_CHANNEL, speedPercent); } int main() { GPIO_InitPin(DIR_PIN1, OUTPUT); GPIO_InitPin(DIR_PIN2, OUTPUT); PWM_Init(PWM_CHANNEL, 1000); // 1kHz frequency setMotorDirectionForward(); setMotorSpeed(75); // 75% speed while(1) { // Motor runs continuously } return 0; }
Output
Motor runs forward at 75% speed (no console output, hardware action only)
Common Pitfalls
- Not initializing GPIO or PWM pins properly causes motor not to run.
- Setting both direction pins high or low can short the motor driver.
- Using PWM duty cycle values outside 0-100% range leads to unexpected behavior.
- Forgetting to configure PWM frequency can cause motor noise or poor speed control.
c
/* Wrong: Both direction pins high - can damage motor driver */ GPIO_SetPinHigh(DIR_PIN1); GPIO_SetPinHigh(DIR_PIN2); /* Right: One pin high, one pin low for direction */ GPIO_SetPinHigh(DIR_PIN1); GPIO_SetPinLow(DIR_PIN2);
Quick Reference
Summary tips for controlling DC motor with Embedded C:
- Use two GPIO pins for direction control.
- Use PWM to control motor speed smoothly.
- Initialize all pins and PWM before use.
- Keep PWM frequency around 1kHz for quiet operation.
- Never set both direction pins to the same level.
Key Takeaways
Use GPIO pins to set motor direction by setting one pin high and the other low.
Control motor speed by adjusting PWM duty cycle between 0% and 100%.
Always initialize GPIO and PWM modules before controlling the motor.
Avoid setting both direction pins high or low to prevent hardware damage.
Set PWM frequency around 1kHz for smooth and quiet motor operation.