5101+ reviews
Order by 16:00 for same day shipping
14 days return
EN
Individual
Business
In this project, you will learn how to control a stepper motor using a Raspberry Pi. A stepper motor rotates in precise steps, allowing you to accurately control movement. This project uses a 28BYJ-48 stepper motor and a ULN2003 driver.
GPIO | Pin # | Function | Connection |
GPIO 17 | Pin 11 | IN1 | ULN2003 driver |
GPIO 27 | Pin 13 | IN2 | ULN2003 driver |
GPIO 22 | Pin 15 | IN3 | ULN2003 driver |
GPIO 23 | Pin 16 | IN4 | ULN2003 driver |
5V | Pin 2 | Nutrition | ULN2003 driver |
GND | Pin 6 | Earth (Ground) | ULN2003 driver |
Make sure the RPi.GPIO library is installed. This is usually included in Raspberry Pi OS by default.
pip install RPi.GPIO
Open the Thonny Python IDE and enter the following code:
import RPi.GPIO as GPIO
from time import sleep
# GPIO-pinnen koppelen aan ULN2003 IN-pinnen
IN1 = 17
IN2 = 27
IN3 = 22
IN4 = 23
# Pinnen instellen
GPIO.setmode(GPIO.BCM)
GPIO.setup(IN1, GPIO.OUT)
GPIO.setup(IN2, GPIO.OUT)
GPIO.setup(IN3, GPIO.OUT)
GPIO.setup(IN4, GPIO.OUT)
# Stepper motor sequence (4-fase stappen)
step_sequence = [
[1, 0, 0, 0],
[1, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1],
[1, 0, 0, 1]
]
def set_step(w1, w2, w3, w4):
"""Stel de status van de motorpinnen in."""
GPIO.output(IN1, w1)
GPIO.output(IN2, w2)
GPIO.output(IN3, w3)
GPIO.output(IN4, w4)
def step_motor(steps, delay, reverse=False):
"""Draai de motor een aantal stappen."""
if reverse:
sequence = step_sequence[::-1] # Keer de sequentie om
else:
sequence = step_sequence
for _ in range(abs(steps)):
for step in sequence:
# Zorg ervoor dat elke stap 4 waarden bevat
if len(step) == 4:
set_step(*step)
else:
raise ValueError("Step sequence must contain exactly 4 values")
sleep(delay)
try:
print("Stepper motor draait vooruit...")
step_motor(512, 0.002) # Draai 512 stappen vooruit
sleep(1)
print("Stepper motor draait achteruit...")
step_motor(512, 0.002, reverse=True) # Draai 512 stappen achteruit
sleep(1)
except KeyboardInterrupt:
print("\nProgramma gestopt.")
finally:
GPIO.cleanup() # Reset de GPIO-instellingen
Click File > Save As and name the file stepper_motor_intro.py.
Click the greenRun button (▶) at the top the Thonny interface.