Welcome to Raspbot V2 repository
当製品の日本語版マニュアル資料は、こちらからご取得ください。
3.Ultrasonic follow
3. Ultrasonic follow
3. Ultrasonic follow1. Learning objectives2. Experimental preparation3. Implementation principle4. Code analysis5. Experimental results
1. Learning objectives
Use the ultrasonic module to combine with the car to realize the ultrasonic following of the car.
2. Experimental preparation
The car wiring has been installed and installed correctly
3. Implementation principle
We obtain the distance between the car and the obstacle through ultrasound. We set a following distance interval for the car. When the distance between the car and the obstacle is detected in the distance interval we set, the car follows. When the distance detected by the car is greater than the maximum value of the following distance interval we set, the car stops following. When the distance detected by the car is less than the minimum value of the following distance interval we set, the car retreats.
4. Code analysis
Source code path:
/home/pi/project_demo/05.Comprehensive_gameplay/3.ultrasonic_followup.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 = 150 # Define near distance threshold (millimeters)MID_DISTANCE = 300 # Define mid distance threshold (millimeters)FAR_DISTANCE = 500 # Define far distance threshold (millimeters)
def car_follow(): # Read the distance from the ultrasonic sensor diss_H =bot.read_data_array(0x1b,1)[0] diss_L =bot.read_data_array(0x1a,1)[0] dis = diss_H << 8 | diss_L # Print distance #print(f"Ultrasonic Distance: {dis} mm") if dis < NEAR_DISTANCE: print(f"Obstacle is very close, distance : {dis} mm") move_backward(speed) # time.sleep(0.1) elif NEAR_DISTANCE <= dis <= MID_DISTANCE: print(f"Obstacle is at medium distance, distance: {dis} mm") stop_robot() elif MID_DISTANCE < dis < FAR_DISTANCE: print(f"Obstacle is at far distance, distance: {dis} mm")move_forward(speed)elif dis >= FAR_DISTANCE:print(f"No obstacle, distance: {dis} mm")stop_robot()else:print("Unknown situation, stopping")stop_robot()speed = 50 # Set vehicle speedtry:# Turn on ultrasonic ranging functionbot.Ctrl_Ulatist_Switch(1)time.sleep(0.1) # Give the ultrasonic sensor some time to measurewhile True:car_follow()time.sleep(0.1) # Check once every secondexcept KeyboardInterrupt:# When the user interrupts the program, ensure all motors stop stopbot.Ctrl_Ulatist_Switch(0)time.sleep(0.1)stop_robot()print("Ending")5. Experimental results
We put the robot on the ground and run the program. We can use our hands as obstacles. Put our hands in front of the ultrasonic wave. When we get close to the robot, the robot will move backward. When we move away from the robot, the robot will follow us and move slowly. When we take our hands away and there are no other objects within 50cm, the robot will stop following.