Raspberry Pi Program to Control DC Motor
RPi.GPIO library to control a DC motor by setting GPIO pins high or low; for example, import RPi.GPIO as GPIO, set pin mode, and use GPIO.output(pin, GPIO.HIGH) to run the motor.Examples
How to Think About It
Algorithm
Code
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) motor_pin1 = 17 motor_pin2 = 18 GPIO.setup(motor_pin1, GPIO.OUT) GPIO.setup(motor_pin2, GPIO.OUT) print("Motor running forward") GPIO.output(motor_pin1, GPIO.HIGH) GPIO.output(motor_pin2, GPIO.LOW) time.sleep(5) print("Motor stopped") GPIO.output(motor_pin1, GPIO.LOW) GPIO.output(motor_pin2, GPIO.LOW) GPIO.cleanup()
Dry Run
Let's trace running the motor forward for 5 seconds then stopping it.
Setup GPIO mode
GPIO mode set to BCM numbering
Setup motor pins
Pins 17 and 18 set as output
Run motor forward
Pin 17 = HIGH, Pin 18 = LOW; motor spins forward
Wait 5 seconds
Program pauses for 5 seconds
Stop motor
Pin 17 = LOW, Pin 18 = LOW; motor stops
Cleanup GPIO
GPIO pins reset to default state
| Step | Pin 17 | Pin 18 | Motor State |
|---|---|---|---|
| Setup | N/A | N/A | Pins configured |
| Run forward | HIGH | LOW | Spinning forward |
| Wait | HIGH | LOW | Spinning forward |
| Stop | LOW | LOW | Stopped |
| Cleanup | N/A | N/A | GPIO reset |
Why This Works
Step 1: GPIO Setup
We use GPIO.setmode(GPIO.BCM) to select the pin numbering system and set the motor pins as outputs to control voltage signals.
Step 2: Motor Direction Control
Setting one pin HIGH and the other LOW makes the motor spin in one direction; reversing these signals spins it the other way.
Step 3: Stopping the Motor
Setting both pins LOW cuts power to the motor, stopping it safely.
Step 4: Cleaning Up
Calling GPIO.cleanup() resets the pins so they don't stay active after the program ends.
Alternative Approaches
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) motor_pin = 17 GPIO.setup(motor_pin, GPIO.OUT) pwm = GPIO.PWM(motor_pin, 100) # 100 Hz pwm.start(0) print("Motor speed ramp up") for speed in range(0, 101, 20): pwm.ChangeDutyCycle(speed) time.sleep(1) print("Motor stop") pwm.ChangeDutyCycle(0) pwm.stop() GPIO.cleanup()
from gpiozero import Motor from time import sleep motor = Motor(forward=17, backward=18) print("Motor forward") motor.forward() sleep(5) print("Motor stop") motor.stop()
Complexity: O(1) time, O(1) space
Time Complexity
The program runs a fixed sequence of commands without loops that depend on input size, so it runs in constant time.
Space Complexity
Uses a fixed number of variables and GPIO pins, so memory use is constant.
Which Approach is Fastest?
All approaches run quickly; using GPIO Zero adds abstraction but simplifies code, while PWM adds complexity for speed control.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Basic GPIO control | O(1) | O(1) | Simple on/off motor control |
| PWM speed control | O(1) | O(1) | Controlling motor speed smoothly |
| GPIO Zero library | O(1) | O(1) | Easy and readable motor control |