Simple Motor Control

Note: The wiring for this is very important. Please double-check your connections before proceeding.


In [1]:
# Import GPIO Libraries
import RPi.GPIO as GPIO
import time

The pin configuration is dependent on the motor and wiring setup. The following code works for my current wiring setup with two motors and controllers (12V stepper motors and L293D H-Bridge driven with an 8 AA battery pack)


In [2]:
GPIO.setmode(GPIO.BCM)

coil_A_1_pin = 4
coil_A_2_pin = 5
coil_B_1_pin = 20
coil_B_2_pin = 21

GPIO.setup(coil_A_1_pin, GPIO.OUT)
GPIO.setup(coil_A_2_pin, GPIO.OUT)
GPIO.setup(coil_B_1_pin, GPIO.OUT)
GPIO.setup(coil_B_2_pin, GPIO.OUT)

reverse_seq = ['1010', '0110', '0101', '1001']
reverse_seq = [ '0101', '0110','1010', '1001']
#reverse_seq = [ '1000','0010', '0100', '0001']
#reverse_seq = ['1100', '1010', '0110', '0101', '0011', '1010', '1001', '0101']
forward_seq = list(reverse_seq) # to copy the list
forward_seq.reverse()

In [4]:
forward_seq


Out[4]:
['1001', '1010', '0110', '0101']

In [ ]:
def motor_forward(delay, steps):
    for i in range(steps):
        for step in forward_seq:
            motor_set_step(step)
            time.sleep(delay)

def motor_backwards(delay, steps):
    for i in range(steps):
        for step in reverse_seq:
            motor_set_step(step)
            time.sleep(delay)


def motor_set_step(step):
    GPIO.output(coil_A_1_pin, step[0] == '1')
    GPIO.output(coil_A_2_pin, step[1] == '1')
    GPIO.output(coil_B_1_pin, step[2] == '1')
    GPIO.output(coil_B_2_pin, step[3] == '1')

In [ ]:
motor_set_step('0000')

delay = 5 # Time Delay (ms)
steps = 50

motor_forward(int(delay) / 1000.0, int(steps))

motor_backwards(int(delay) / 1000.0, int(steps))

# release the motor from a 'hold' position
motor_set_step('0000')

In [ ]:


In [ ]:
GPIO.cleanup()

In [ ]: