一、实验准备
通过超声波模块与小车结合,实现小车超声波避障。小车接线已安装,且安装正确
二、实验原理
通过超声波我们获取小车与障碍物的距离。当检测到小车与障碍物的距离小于我们的设置的距离时,小车左旋避开障碍物。
三、实验源码
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import sys
sys.path.append('/home/pi/project_demo/lib')
#导入麦克纳姆小车驱动库 Import Mecanum Car Driver Library
from McLumk_Wheel_Sports import *
# Constants related to the ultrasonic sensor
NEAR_DISTANCE = 200 # Define near distance threshold (millimeters)
FAR_DISTANCE = 425 # Define far distance threshold (millimeters)
def car_avoid():
# 读取超声波传感器的距离 Reading distance from ultrasonic sensordiss_H =bot.read_data_array(0x1b,1)[0]diss_L =bot.read_data_array(0x1a,1)[0]dis = diss_H << 8 | diss_L
# 打印距离 Printing distance#print(f"Ultrasonic Distance: {dis} mm")time.sleep(0.05) # 每隔1秒读取一次距离 Read the distance every 1 second
if dis < NEAR_DISTANCE:print(f"Obstacle is very close, distance: {dis} mm")move_backward(speed)time.sleep(0.1)elif NEAR_DISTANCE <= dis <= FAR_DISTANCE:print(f"Obstacle is at medium distance, distance: {dis} mm")stop_robot()time.sleep(0.2)rotate_left(speed)time.sleep(0.15)elif FAR_DISTANCE < dis:print(f"No obstacle, distance: {dis} mm")move_forward(speed)
else:print("Unknown situation, stopping")stop_robot()time.sleep(0.2)
speed = 20 # Set vehicle speed
try:# 打开超声波测距功能 Turn on the ultrasonic ranging functionbot.Ctrl_Ulatist_Switch(1)time.sleep(0.1) # 给超声波传感器一点时间来测量 Give the ultrasonic sensor some time to measurewhile True:car_avoid()
except KeyboardInterrupt:# When the user interrupts the program, ensure all motors stopbot.Ctrl_Ulatist_Switch(0)time.sleep(0.1)stop_robot()print("Ending")
四、实验现象
我们把小车放在地上,运行程序,小车会一直前进。
1)当遇到前方有障碍物时,小于设置的最小距离时,小车会后退。
2)当遇到前方有障碍物时,大于设置的最小距离且小于最远距离时,小车会左旋避开障碍物。
3)当遇到前方有障碍物大于最远距离时,小车前进。
小车显示屏上会打印障碍物的距离,同时程序运行打印小车距离障碍物的距离。