Welcome to Raspbot V2 repository
当製品の日本語版マニュアル資料は、こちらからご取得ください。
2.Ultrasonic avoid
2.Ultrasonic avoid
2.Ultrasonic avoid1. Learning objectives2. Experimental preparation3. Implementation principle4. Code analysis5. Experimental results
1. Learning objectives
Use the ultrasonic module to combine with the car to achieve ultrasonic obstacle avoidance.
2. Experimental preparation
The car wiring has been installed and installed correctly
3. Implementation principle
Use ultrasound to obtain the distance between the car and the obstacle. When the distance between the car and the obstacle is less than the distance we set, the car turns left to avoid the obstacle.
4. Code analysis
Source code path:
/home/pi/project_demo/05.Comprehensive_gameplay/2.ultrasonic_obstacle_avoidance.ipynb
x#!/usr/bin/python3# -*- coding: UTF-8 -*-import syssys.path.append('/home/pi/project_demo/lib')#Import Mecanum Car Driver Libraryfrom McLumk_Wheel_Sports import *
# Constants related to the ultrasonic sensorNEAR_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) # 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")
5. Experimental results
We put the car on the ground and run the program. The car will keep moving forward. When there is an obstacle in front and the distance is less than the set distance, the car will turn left to avoid the obstacle.