小车循迹代码
以下是一个简单的小车循迹代码示例:
import RPi.GPIO as GPIO
# 设置引脚号
left_sensor_pin = 11
middle_sensor_pin = 13
right_sensor_pin = 15
left_motor_pin1 = 16
left_motor_pin2 = 18
right_motor_pin1 = 21
right_motor_pin2 = 23
# 初始化GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(left_sensor_pin, GPIO.IN)
GPIO.setup(middle_sensor_pin, GPIO.IN)
GPIO.setup(right_sensor_pin, GPIO.IN)
GPIO.setup(left_motor_pin1, GPIO.OUT)
GPIO.setup(left_motor_pin2, GPIO.OUT)
GPIO.setup(right_motor_pin1, GPIO.OUT)
GPIO.setup(right_motor_pin2, GPIO.OUT)
# 循迹函数
def follow_track():
left_sensor = GPIO.input(left_sensor_pin)
middle_sensor = GPIO.input(middle_sensor_pin)
right_sensor = GPIO.input(right_sensor_pin)
if left_sensor == 1 and middle_sensor == 0 and right_sensor == 1:
# 左右传感器都在黑线上,中间传感器不在黑线上,向前直行
GPIO.output(left_motor_pin1, GPIO.HIGH)
GPIO.output(left_motor_pin2, GPIO.LOW)
GPIO.output(right_motor_pin1, GPIO.HIGH)
GPIO.output(right_motor_pin2, GPIO.LOW)
elif left_sensor == 0 and middle_sensor == 1 and right_sensor == 0:
# 左右传感器都不在黑线上,中间传感器在黑线上,向前直行
GPIO.output(left_motor_pin1, GPIO.HIGH)
GPIO.output(left_motor_pin2, GPIO.LOW)
GPIO.output(right_motor_pin1, GPIO.HIGH)
GPIO.output(right_motor_pin2, GPIO.LOW)
elif left_sensor == 1 and middle_sensor == 1 and right_sensor == 0:
# 左右传感器都在黑线上,中间传感器在黑线外,向右转弯
GPIO.output(left_motor_pin1, GPIO.HIGH)
GPIO.output(left_motor_pin2, GPIO.LOW)
GPIO.output(right_motor_pin1, GPIO.LOW)
GPIO.output(right_motor_pin2, GPIO.HIGH)
elif left_sensor == 0 and middle_sensor == 1 and right_sensor == 1:
# 左右传感器都在黑线上,中间传感器在黑线外,向左转弯
GPIO.output(left_motor_pin1, GPIO.LOW)
GPIO.output(left_motor_pin2, GPIO.HIGH)
GPIO.output(right_motor_pin1, GPIO.HIGH)
GPIO.output(right_motor_pin2, GPIO.LOW)
else:
# 其他情况停止
GPIO.output(left_motor_pin1, GPIO.LOW)
GPIO.output(left_motor_pin2, GPIO.LOW)
GPIO.output(right_motor_pin1, GPIO.LOW)
GPIO.output(right_motor_pin2, GPIO.LOW)
# 主循环
try:
while True:
follow_track()
finally:
GPIO.cleanup()
这是一个基于树莓派的循迹小车代码示例,使用了RPi.GPIO库来控制GPIO引脚。代码中定义了引脚号以及初始化GPIO设置。循迹函数follow_track()根据传感器的状态来控制小车的行动,通过设置电机的引脚状态来控制小车的前进、转弯或停止。在主循环中不断调用follow_track()函数来实现循迹行驶。最后通过GPIO.cleanup()来清理GPIO设置
原文地址: https://www.cveoy.top/t/topic/imkK 著作权归作者所有。请勿转载和采集!