Articles on: Learning & FAQ

How to Connect Stepper Motor with Raspberry Pi?


Raspberry Pi Raspberry Pi is the first embedded Linux board that became popular in various circles. It is essentially a small computer about the size of a credit card. the Raspberry Pi is widely used in various projects. Among them, using the Raspberry Pi to control the rotation of the stepper motor is a common task. In this article, you will learn how to use the Python programming language and the GPIO library to implement this function, and introduce the corresponding wiring methods.

Required materials

1 ) Raspberry Pi (Raspberry Pi 3B+ or a newer version is recommended)
2) Stepper motor (e.g. model NEMA 17)
3) Motor driver board (e.g. DRV8825 or A4988)
4) Several DuPont leads
5) 12V DC power adapter
6) Breadboard (optional)

Wiring method

1 ) Connect the four wires of the stepper motor to the A1, A2, B1 and B2 interfaces of the motor driver board.
2) Connect the positive pole of the power supply to the VMOT interface of the motor driver board, and connect the negative pole to the GND interface
3) Connect the 5V pin of the Raspberry Pi (such as GPIO 2) to the VCC interface of the motor driver board, and connect the GND pin of the Raspberry Pi (such as GPIO 6) to the GND interface of the motor driver board.
4) Connect the GPIO pins of the Raspberry Pi (such as GPIO 17, 18, 27 and 22) to the DIR, STEP, MS1 and MS2 interfaces of the motor driver board respectively.

Python code implementation

Firstly, install the Raspberry Pi GPIO library. Enter the following command in the terminal:
sudo apt-get update
sudo apt-get install python3-gpiozero

Secondly, create a Python file named and enter the following code
import timeimport RPi.GPIO as GPIO
# define pins
DIR = 17
STEP = 18
MS1 = 27
MS2 = 22
# set pin mode
# Set rotation direction and stepping mode
GPIO.output(DIR, GPIO.HIGH)  # clockwise rotation
GPIO.output(MS1, GPIO.LOW) # Set to 1/4 stepping mode
# Control stepper motor rotation
steps = 200  # Set the number of rotation steps
delay = 0.01  # set delay
for i in range(steps):
      GPIO.output(STEP, GPIO.HIGH)
      GPIO.output(STEP, GPIO.LOW)
# Clean up GPIO and exit

Lastly, save the file and run in terminal:


This article introduces you to how to use Raspberry Pi to control stepper motor rotation and provides the corresponding wiring methods. You can achieve this easily with the Python programming language and GPIO library. Please adjust the parameters in the code according to actual needs to meet your project requirements.

Updated on: 31/10/2023

Was this article helpful?

Share your feedback


Thank you!