ENA IN1 IN2 控制左边的电机A,ENB IN3 IN4控制右边的电机B
以上六个全部接GPIO口,可通过pwm控制ENA ENB实现调速
+12V为外接电源正极接入口
GND为外接电源负极接入口且要和树莓派共地
+5V为5V输出,可悬空
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(12,GPIO.OUT)#这个地方显得不优雅
motorB = GPIO.PWM(12,100)#这一行要写在外面
def motor_prepare(in1,in2,in3):
GPIO.setup(in2,GPIO.OUT)
GPIO.setup(in3,GPIO.OUT)
motorB.start(100)
def motor_run(speed,in1,in2,in3):
if speed>0 :
if speed > 100 :
speed = 100
GPIO.output(in2,0)
GPIO.output(in3,1)
motorB.ChangeDutyCycle(speed)
if speed<0 :
if speed < -100 :
speed = -100
GPIO.output(in2,1)
GPIO.output(in3,0)
motorB.ChangeDutyCycle(-speed)
def motor_stop(in1,in2,in3):
GPIO.output(in2,False)
GPIO.output(in3,False)
motorB = GPIO.PWM(in1,100)
motorB.ChangeDutyCycle(0)
motorB.stop()
motor_prepare(12,20,21)
for i in (50,10,20,30,40,50,60,70,80,90,100):
motor_run(i,12,20,21)
print(i)
time.sleep(2)
motor_stop(12,20,21)
树莓派 3 + L298N模块 驱动直流电机
树莓派通过L298N控制直流电机