In order to program a DC motor in python, you will need to use the GPIO library.
Here are some tips to get started on programming a DC motor:
Import the GPIO Library
import RPi.GPIO as GPIO
Figure out which GPIO pins to use for the inputs and EN pins
Set up each input channel and EN pin
GPIO.setup(input,GPIO.OUT)
Use the input channels to control the direction of the DC motor
GPIO.output(input,GPIO.HIGH) or GPIO.output(input,GPIO.LOW)
Use the EN pin to control the speed of the DC motor
Make sure to use the GPIO cleanup command before closing out the program
GPIO.cleanup()
This table is a reference to determine which inputs to turn on and which inputs to turn off
Here is an example code to control 1 DC motor:
import RPi.GPIO as GPIO
#Defines which GPIO pins are being utilized for a channel
in1 = 22
in2 = 27
enA = 25
#Sets up each channel
GPIO.setmode(GPIO.BCM)
GPIO.setup(in1,GPIO.OUT)
GPIO.setup(in2,GPIO.OUT)
GPIO.setup(enA,GPIO.OUT)
#Sets initial output for each channel
GPIO.output(in1,GPIO.LOW)
GPIO.output(in2,GPIO.LOW)
#Sets initial speed for each channel
p=GPIO.PWM(enA,1000)
p.start(100)
print('s-stop f-forward b-backward e-exit')
while(1):
x=input()
if x=='s':
GPIO.output(in1,GPIO.LOW)
GPIO.output(in2,GPIO.LOW)
elif x=='f':
GPIO.output(in1,GPIO.HIGH)
GPIO.output(in2,GPIO.LOW)
elif x=='b':
GPIO.output(in1,GPIO.LOW)
GPIO.output(in2,GPIO.HIGH)
else x=='e':
GPIO.cleanup() #Cleans up each channel
break