Raspberry PI DC Motor code

DC motors can be controlled by the L298N DC motor driver IC, which is connected to your microcontroller. L298Ns can control up to 2 DC motors. You can easily add motors through the program code. You can set DC motor speed by changing the duty-cycle of each PWM signal. The PWM is a square-wave signal which has two parameters: frequency and duty-cycle. If a PWM signal's duty-cycle is 100% than the motor spins with maximum rpm. In case of 0% the motor will stop. Motor speed and direction in your Ozeki software can be changed on each motor with the motor's own adjustable slide bar from -100% to 100%. If the slide crosses 0 than the motor will change spin direction.

rpi with dc motor controller board
Figure 1 - Raspberry PI with DC Motor Controller Board LM298

Required hardware

  • Raspberry PI
  • DC Motor Controller Board LM298
  • DC Motor(s)

Source code to install on controller


#!/usr/bin/python
import RPi.GPIO as GPIO

GPIO.setmode(GPIO.BCM) 

GPIO.setup(17, GPIO.OUT)
GPIO.setup(27, GPIO.OUT)
GPIO.setup(22, GPIO.OUT)

direction = input('Please define the direction (Left=1 or Right=2): ')
dc = input('Please define the Motor PWM Duty Cycle (0-100): ')
hz = input ('HZ: ')
pwm = GPIO.PWM(17, hz)

if direction == 1:
	GPIO.output(27, 1)
	GPIO.output(22, 0)
elif direction == 2:
	GPIO.output(27, 0)
	GPIO.output(22, 1)

try:
        while True:
                pwm.start(dc)

except KeyboardInterrupt:
        pwm.stop()
        GPIO.cleanup()

More information