一、硬件
- 树莓派
- 12V直流电机
- L298N电机驱动器
- 220V转12V变压器
二、连线
- 树莓派与L298N需要共地
- L298N驱动模块
![L298N](https://i-blog.csdnimg.cn/blog_migrate/98052d669d850992f7d2ec4cb7df661b.png)
- 树莓派接线
![树莓派](https://i-blog.csdnimg.cn/blog_migrate/13e37240c650b0bf93bc3dadd1db3dfa.png)
三、树莓派python库配置
- 安装GPIO库
sudo apt-get install python3-rpi.gpio
- 电机控制程序
import time
import RPi.GPIO as GPIO
Motor_A_EN = 16
Motor_A_Pin1 = 20
Motor_A_Pin2 = 21
def setup():
global pwm_A
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(Motor_A_EN, GPIO.OUT)
GPIO.setup(Motor_A_Pin1, GPIO.OUT)
GPIO.setup(Motor_A_Pin2, GPIO.OUT)
motorStop()
try:
pwm_A = GPIO.PWM(Motor_A_EN, 1000)
except:
pass
def motorStop():
GPIO.output(Motor_A_Pin1, GPIO.LOW)
GPIO.output(Motor_A_Pin2, GPIO.LOW)
GPIO.output(Motor_A_EN, GPIO.LOW)
def motor_A(direction,speed):
if direction == 1:
GPIO.output(Motor_A_Pin1,GPIO.LOW)
GPIO.output(Motor_A_Pin2, GPIO.HIGH)
pwm_A.start(0)
pwm_A.ChangeDutyCycle(speed)
elif direction == 0:
GPIO.output(Motor_A_Pin1, GPIO.HIGH)
GPIO.output(Motor_A_Pin2, GPIO.LOW)
pwm_A.start(0)
pwm_A.ChangeDutyCycle(speed)
else:
GPIO.output(Motor_A_Pin1, GPIO.LOW)
GPIO.output(Motor_A_Pin2, GPIO.LOW)
setup()
motor_A(1,100)
time.sleep(3)
motorStop()
time.sleep(3)
motor_A(0,100)
time.sleep(3)
motorStop()
GPIO.cleanup()