自走車方向控制
Last updated
Last updated
建立一個Motor的類別,利用它來完成前進、後退、左轉、右轉等四個方向的移動,做為接續避障、巡跡等功能的基礎。
# 自走車馬達類別
import time
import RPi.GPIO as GPIO
class Motor:
def __init__(self, ena, in1, in2, enb, in3, in4):
self.ENA = ena
self.IN1 = in1
self.IN2 = in2
self.ENB = enb
self.IN3 = in3
self.IN4 = in4
# 設定右輪
GPIO.setup(self.ENA, GPIO.OUT, initial=GPIO.LOW)
# 利用PWN來改變車子馬達轉速(改變車子速度),初始值為全速100
self.ENA_SPEED = GPIO.PWM(self.ENA, 600)
self.ENA_SPEED.start(0)
self.ENA_SPEED.ChangeDutyCycle(100)
GPIO.setup(self.IN1, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(self.IN2, GPIO.OUT, initial=GPIO.LOW)
# 設定左輪
GPIO.setup(self.ENB, GPIO.OUT, initial=GPIO.LOW)
self.ENB_SPEED = GPIO.PWM(self.ENB, 600)
self.ENB_SPEED.start(0)
self.ENB_SPEED.ChangeDutyCycle(100)
GPIO.setup(self.IN3, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(self.IN4, GPIO.OUT, initial=GPIO.LOW)
def right_speed(self, speed):
self.ENA_SPEED.ChangeDutyCycle(speed)
def left_speed(self, speed):
self.ENB_SPEED.ChangeDutyCycle(speed)
def speed(self, speed):
self.right_speed(speed)
self.left_speed(speed)
def forward(self):
GPIO.output(self.ENA, True)
GPIO.output(self.ENB, True)
GPIO.output(self.IN1, True)
GPIO.output(self.IN2, False)
GPIO.output(self.IN3, True)
GPIO.output(self.IN4, False)
def backward(self):
GPIO.output(self.ENA, True)
GPIO.output(self.ENB, True)
GPIO.output(self.IN1, False)
GPIO.output(self.IN2, True)
GPIO.output(self.IN3, False)
GPIO.output(self.IN4, True)
def turn_left(self):
GPIO.output(self.ENA, True)
GPIO.output(self.ENB, True)
GPIO.output(self.IN1, True)
GPIO.output(self.IN2, False)
GPIO.output(self.IN3, False)
GPIO.output(self.IN4, True)
def turn_right(self):
GPIO.output(self.ENA, True)
GPIO.output(self.ENB, True)
GPIO.output(self.IN1, False)
GPIO.output(self.IN2, True)
GPIO.output(self.IN3, True)
GPIO.output(self.IN4, False)
def stop(self):
GPIO.output(self.ENA, True)
GPIO.output(self.ENB, True)
GPIO.output(self.IN1, False)
GPIO.output(self.IN2, False)
GPIO.output(self.IN3, False)
GPIO.output(self.IN4, False)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
motor = Motor(13, 19, 16, 20, 21, 26)
while True:
# motor.speed(50)
motor.forward()
time.sleep(1)
motor.backward()
time.sleep(1)
motor.turn_left()
time.sleep(1)
motor.turn_right()
time.sleep(1)
motor.stop()
time.sleep(5)