树莓派小车
麦克纳姆轮
po一张原理图,安装的时候注意轮子方向。
我把电机控制部分的代码大致封装了一下,后续可以自行添加其他功能。
motor.py
import RPi.GPIO as GPIO
import time
class Motor:
def __init__(self):
# 引脚 1、2 左前 3、4 右前 5、6 右后 7、8 左后
self.in1 = 7
self.in2 = 11
self.in3 = 13
self.in4 = 15
self.in5 = 29
self.in6 = 31
self.in7 = 33
self.in8 = 35
self.speed1 = 40
self.speed2 = 70
# 设置引脚编码模式
GPIO.setmode(GPIO.BOARD)
# 设置引脚模式
GPIO.setup(self.in1, GPIO.OUT)
GPIO.setup(self.in2, GPIO.OUT)
GPIO.setup(self.in3, GPIO.OUT)
GPIO.setup(self.in4, GPIO.OUT)
GPIO.setup(self.in5, GPIO.OUT)
GPIO.setup(self.in6, GPIO.OUT)
GPIO.setup(self.in7, GPIO.OUT)
GPIO.setup(self.in8, GPIO.OUT)
# 初始化PWM
self.pwm1 = GPIO.PWM(self.in1, 50)
self.pwm2 = GPIO.PWM(self.in2, 50)
self.pwm3 = GPIO.PWM(self.in3, 50)
self.pwm4 = GPIO.PWM(self.in4, 50)
self.pwm5 = GPIO.PWM(self.in5, 50)
self.pwm6 = GPIO.PWM(self.in6, 50)
self.pwm7 = GPIO.PWM(self.in7, 50)
self.pwm8 = GPIO.PWM(self.in8, 50)
self.pwm1.start(0)
self.pwm2.start(0)
self.pwm3.start(0)
self.pwm4.start(0)
self.pwm5.start(0)
self.pwm6.start(0)
self.pwm7.start(0)
self.pwm8.start(0)
def Front(self):
self.pwm1.ChangeDutyCycle(0)
self.pwm2.ChangeDutyCycle(self.speed1)
self.pwm3.ChangeDutyCycle(0)
self.pwm4.ChangeDutyCycle(self.speed1)
self.pwm5.ChangeDutyCycle(self.speed1)
self.pwm6.ChangeDutyCycle(0)
self.pwm7.ChangeDutyCycle(self.speed1)
self.pwm8.ChangeDutyCycle(0)
def Rear(self):
self.pwm1.ChangeDutyCycle(self.speed1)
self.pwm2.ChangeDutyCycle(0)
self.pwm3.ChangeDutyCycle(self.speed1)
self.pwm4.ChangeDutyCycle(0)
self.pwm5.ChangeDutyCycle(0)
self.pwm6.ChangeDutyCycle(self.speed1)
self.pwm7.ChangeDutyCycle(0)
self.pwm8.ChangeDutyCycle(self.speed1)
def Left(self):
self.pwm1.ChangeDutyCycle(0)
self.pwm2.ChangeDutyCycle(0)
self.pwm3.ChangeDutyCycle(0)
self.pwm4.ChangeDutyCycle(self.speed2)
self.pwm5.ChangeDutyCycle(self.speed2)
self.pwm6.ChangeDutyCycle(0)
self.pwm7.ChangeDutyCycle(0)
self.pwm8.ChangeDutyCycle(0)
def Right(self):
self.pwm1.ChangeDutyCycle(0)
self.pwm2.ChangeDutyCycle(self.speed2)
self.pwm3.ChangeDutyCycle(0)
self.pwm4.ChangeDutyCycle(0)
self.pwm5.ChangeDutyCycle(0)
self.pwm6.ChangeDutyCycle(0)
self.pwm7.ChangeDutyCycle(self.speed2)
self.pwm8.ChangeDutyCycle(0)
def Stop(self):
self.pwm1.ChangeDutyCycle(0)
self.pwm2.ChangeDutyCycle(0)
self.pwm3.ChangeDutyCycle(0)
self.pwm4.ChangeDutyCycle(0)
self.pwm5.ChangeDutyCycle(0)
self.pwm6.ChangeDutyCycle(0)
self.pwm7.ChangeDutyCycle(0)
self.pwm8.ChangeDutyCycle(0)
main.py
from motor import Motor
import RPi.GPIO as GPIO
import time
GPIO.cleanup()
motor = Motor()
TestPin = 12
GPIO.setmode(GPIO.BOARD)
GPIO.setup(TestPin, GPIO.IN)
while True:
motor.Left()
time.sleep(2)
motor.Right()
time.sleep(2)