Software

The Setup

We are using the CircuitPython Libraries that are part of adafruit-blinka. See CircuitPython Libraries on Raspberry Pi to get a fresh Raspberry Pi setup.

If you have a running Raspberry Pi with an up to date copy of Raspbian you can simply run the following command to install adafruit-blinka. 

The software is exactly the same on all 40-pin and 20-pin Raspberry Pi models. You can use the L293D or ULN2803 chips without any modification the following code:

Download: file
$ sudo pip3 install adafruit-blinka

The Code

import time
import board
import digitalio

enable_pin = digitalio.DigitalInOut(board.D18)
coil_A_1_pin = digitalio.DigitalInOut(board.D4)
coil_A_2_pin = digitalio.DigitalInOut(board.D17)
coil_B_1_pin = digitalio.DigitalInOut(board.D23)
coil_B_2_pin = digitalio.DigitalInOut(board.D24)

enable_pin.direction = digitalio.Direction.OUTPUT
coil_A_1_pin.direction = digitalio.Direction.OUTPUT
coil_A_2_pin.direction = digitalio.Direction.OUTPUT
coil_B_1_pin.direction = digitalio.Direction.OUTPUT
coil_B_2_pin.direction = digitalio.Direction.OUTPUT

enable_pin.value = True

def forward(delay, steps):
    i = 0
    while i in range(0, steps):
        setStep(1, 0, 1, 0)
        time.sleep(delay)
        setStep(0, 1, 1, 0)
        time.sleep(delay)
        setStep(0, 1, 0, 1)
        time.sleep(delay)
        setStep(1, 0, 0, 1)
        time.sleep(delay)
        i += 1

def backwards(delay, steps):
    i = 0
    while i in range(0, steps):
        setStep(1, 0, 0, 1)
        time.sleep(delay)
        setStep(0, 1, 0, 1)
        time.sleep(delay)
        setStep(0, 1, 1, 0)
        time.sleep(delay)
        setStep(1, 0, 1, 0)
        time.sleep(delay)
        i += 1

def setStep(w1, w2, w3, w4):
    coil_A_1_pin.value = w1
    coil_A_2_pin.value = w2
    coil_B_1_pin.value = w3
    coil_B_2_pin.value = w4

while True:
    user_delay = input("Delay between steps (milliseconds)?")
    user_steps = input("How many steps forward? ")
    forward(int(user_delay) / 1000.0, int(user_steps))
    user_steps = input("How many steps backwards? ")
    backwards(int(user_delay) / 1000.0, int(user_steps))
When the steppers are not moving, they are still 'activated' and hold their position. This draws power. If you don't need the steppers to 'hold' their position, you can call setStep(0,0,0,0) to release the coils. The motor will spin freely and wont draw a lot of current.
This guide was first published on Jan 23, 2013. It was last updated on Jan 23, 2013. This page (Software) was last updated on Sep 20, 2019.