Software

Since we need to control pins (connected to pin 4 and 17 of the GPIO) we also need to use the GPIO library. For details of this, see Lesson 4.

There are lots of ways to get the sketch from the listing below onto your Raspberry Pi. Perhaps the easiest is to connect to your Pi using SSH (See Lesson 6) opening an editor using the command below:

nano motor.py

and then pasting in the code below, before saving the files using CTRL-x.

Here is the code:

import RPi.GPIO as io
io.setmode(io.BCM)

in1_pin = 4
in2_pin = 17

io.setup(in1_pin, io.OUT)
io.setup(in2_pin, io.OUT)

def set(property, value):
    try:
        f = open("/sys/class/rpi-pwm/pwm0/" + property, 'w')
        f.write(value)
        f.close()	
    except:
        print("Error writing to: " + property + " value: " + value)
 
set("delayed", "0")
set("mode", "pwm")
set("frequency", "500")
set("active", "1")

def clockwise():
    io.output(in1_pin, True)    
    io.output(in2_pin, False)

def counter_clockwise():
    io.output(in1_pin, False)
    io.output(in2_pin, True)

clockwise()

while True:
    cmd = raw_input("Command, f/r 0..9, E.g. f5 :")
    direction = cmd[0]
    if direction == "f":
        clockwise()
    else: 
        counter_clockwise()
    speed = int(cmd[1]) * 11
    set("duty", str(speed))

The Python program first sets-up the two GPIO pins to be outputs. It then defines the same convenience function (“set”) that we used in Lesson 8, to write to the PWM Kernel Module. This is then used to set the parameters for PWM.

There are two other functions defined, “clockwise” and “counter_clockwise”, that control the direction of the motor by changing the two input pins.

If both control pins are HIGH, or both LOW then the motor will be stopped. But if IN1 is HIGH and IN2 LOW it rotates in one direction, reversing in direction if the values of IN1 and IN2 are reversed.

The main loop of the program waits for you to enter commands in the format of a letter (“f” or “r”) and a digit between 0 and 9. The letter sets the direction of the motor and the digit the speed, by multiplying the digit by 11 to give a value between 0 and 99 that the PWM library expects.

This guide was first published on Jan 14, 2013. It was last updated on Nov 20, 2018. This page (Software) was last updated on Mar 02, 2018.