小车综合玩法--5.画地为牢
一、实验准备
前面我们利用四路巡线模块巡线,现在我们利用这个特性,用黑线将小车围起来,让小车一直在我们围的圈内运动。
1.小车接线已安装,且安装正确
2.调试四路巡线模块遇黑线时指示灯亮。不是黑线时指示灯灭。
二、实验原理
红外传感器巡线的基本原理是利用物体的反射性质,我们本次实验是巡白底黑线行驶,当红外线发射到黑线上时会被黑线吸收掉,发射到其他的颜色的材料上会有反射回到红外的接收管上。
通过四路巡线模块,我们让小车遇到黑色线就左转或者右转,只有全部都是白色的才可以直走。也可以把其想象为一种避障,障碍为黑线。
三、实验源码
import sys
import time
sys.path.append('/home/pi/project_demo/lib')
# 导入麦克纳姆小车驱动库 Import Mecanum Car Driver Library
from McLumk_Wheel_Sports import *
speed = 25#25
try:
while True:
# 从I2C读取巡线传感器数据 Read line sensor data from I2C
track_data = bot.read_data_array(0x0a, 1)
track = int(track_data[0])
# 解析巡线传感器的状态 Analyze the status of the line patrol sensor
x1 = (track >> 3) & 0x01
x2 = (track >> 2) & 0x01
x3 = (track >> 1) & 0x01
x4 = track & 0x01
"""
X2 X1 X3 X4
| | | |
L1 L2 R1 R2
"""
lineL1 = x2
lineL2 = x1
lineR1 = x3
lineR2 = x4
# 0000
if not lineL1 and not lineL2 and not lineR1 and not lineR2:
rotate_right(speed)
time.sleep(1)
# 1X00
elif lineL1 and not lineR1 and not lineR2:
rotate_left(speed-10)
time.sleep(1)
# 00X1
elif not lineL1 and not lineL2 and lineR2:
rotate_right(speed-10)
time.sleep(1)
# 10X1
elif lineL1 and not lineL2 and lineR2:
rotate_right(speed-10)
time.sleep(1)
# 1X01
elif lineL1 and not lineR1 and lineR2:
rotate_right(speed-10)
time.sleep(1)
# 0110
elif not lineL1 and lineL2 and lineR1 and not lineR2:
rotate_right(speed-10)
time.sleep(1)
# 0111
elif not lineL1 and lineL2 and lineR1 and lineR2:
rotate_right(speed-20)
time.sleep(1)
# 1110
elif lineL1 and lineL2 and lineR1 and not lineR2:
rotate_left(speed-20)
time.sleep(1)
# 1111
elif lineL1 and lineL2 and lineR1 and lineR2:
move_forward(speed)
# 等待一段时间再进行下一次检测 Wait for a while before the next test
time.sleep(0.01)
except KeyboardInterrupt:
# 当用户中断程序时,确保所有电机停止 Ensure that all motors stop when the user interrupts the program
stop_robot()
print("Ending")
stop_robot()
# 清理资源 Cleaning up resources
del bot
四、实验现象
我们把小车放在有围了黑线的地图上,确保小车的四路巡线模块已经调成遇黑线时,指示灯亮,不是黑线时,指示灯灭后,运行程序。运行程序后,我们会看到小车在白底的地图上没有遇到黑线时,小车直走;遇到地图边缘的黑线时,小车会右转或者左转,始终在黑圈范围内运动。