6.Ultrasonic Avoidance Car
Description
The obstacle avoidance function of the car mainly uses the HC-SR04 ultrasonic module. The ultrasonic module is controlled by the servo. The servo rotates to the left, middle and right repeatedly, so that the ultrasonic module measures the distance of obstacles on the left, middle and right directions. And then it controls the car to move according to different distances.
Note
Before running the standalone program, make sure to shut down the main program ccording to the following sections; otherwise, the standalone program will not be able to start. Test Subroutine
Run program
1. You can jump to the project folder directly by running this command:
cd /opt/Code/Pi4/Server or cd /opt/Code/Pi5/Server-pi5
2. Run Light.py:
sudo python Ultrasonic.py
You can press “Ctrl + C” to end the program
Details of the program
1 class Ultrasonic:
2 def __init__(self):
3 GPIO.setwarnings(False)
4 self.trigger_pin = 27
5 self.echo_pin = 22
6 self.MAX_DISTANCE = 300 # define the maximum measuring distance, unit: cm
7 self.timeOut = self.MAX_DISTANCE * 60 # calculate timeout according to the maximum measuring distance
8 GPIO.setmode(GPIO.BCM)
9 GPIO.setup(self.trigger_pin, GPIO.OUT)
10 GPIO.setup(self.echo_pin, GPIO.IN)
11
12 def pulseIn(self, pin, level, timeOut): # obtain pulse time of a pin under timeOut
13 t0 = time.time()
14 while (GPIO.input(pin) != level):
15 if ((time.time() - t0) > timeOut * 0.000001):
16 return 0
17 t0 = time.time()
18 while (GPIO.input(pin) == level):
19 if ((time.time() - t0) > timeOut * 0.000001):
20 return 0
21 pulseTime = (time.time() - t0) * 1000000
22 return pulseTime
23
24 def get_distance(self): # get the measurement results of ultrasonic module,with unit: cm
25 distance_cm = [0, 0, 0, 0, 0]
26 for i in range(5):
27 GPIO.output(self.trigger_pin, GPIO.HIGH) # make trigger_pin output 10us HIGH level
28 time.sleep(0.00001) # 10us
29 GPIO.output(self.trigger_pin, GPIO.LOW) # make trigger_pin output LOW level
30 pingTime = self.pulseIn(self.echo_pin, GPIO.HIGH, self.timeOut) # read pulse time of echo_pin
31 distance_cm[i] = pingTime * 340.0 / 2.0 / 10000.0 # calculate distance with sound speed 340m/s
32 distance_cm = sorted(distance_cm)
33 final_distance = distance_cm[2] # Take the middle value after sorting
34 # If measured value equals 0, convert to 255
35 if final_distance == 0:
36 final_distance = 255
37 return int(final_distance) # Return the processed integer distance value
38
39 def run(self):
40 self.PWM = Motor()
41 while True:
42 M = self.get_distance()
43 if M <= 20: # If obstacle is too close (<=20cm)
44 self.PWM.setMotorModel(-1000, -1000, -1000, -1000) # Move backward
45 time.sleep(0.3)
46 if 50 >= random.randint(1, 100): # Randomly choose turn direction
47 self.PWM.setMotorModel(-2000, -2000, 2000, 2000) # Turn left
48 else:
49 self.PWM.setMotorModel(2000, 2000, -2000, -2000) # Turn right
50 time.sleep(0.3)
51 elif 20 < M <= 30: # If obstacle is at warning distance (20-30cm)
52 self.PWM.setMotorModel(0, 0, 0, 0) # Stop the car
53 time.sleep(0.2)
54 if 50 >= random.randint(1, 100): # Randomly choose turn direction
55 self.PWM.setMotorModel(-2000, -2000, 2000, 2000) # Turn left
56 else:
57 self.PWM.setMotorModel(2000, 2000, -2000, -2000) # Turn right
58 time.sleep(0.3)
59 else: # If no obstacle detected (>30cm)
60 self.PWM.setMotorModel(1000, 1000, 1000, 1000) # Move forward
61
62 ultrasonic = Ultrasonic()
63 # Main program logic follows:
64 if __name__ == '__main__':
65 print('Program is starting ... ')
66 try:
67 ultrasonic.run()
68 except KeyboardInterrupt: # When 'Ctrl+C' is pressed, the child program destroy() will be executed.
69 PWM.setMotorModel(0, 0, 0, 0) # Stop the car when program is interrupted
Result Analysis:
The ultrasonic obstacle avoidance car detects obstacle distances through a single front ultrasonic sensor and performs different avoidance actions based on different distance ranges:
When detected distance > 30cm: - Indicates no obstacles within 30 centimeters in front - The car continues to move forward straight (setMotorModel(1000, 1000, 1000, 1000))
When detected distance ≤ 20cm: - Indicates obstacles are very close with risk of collision - The car first moves backward (setMotorModel(-1000, -1000, -1000, -1000)) - Pauses for 0.3 seconds - Randomly chooses to turn left or right to find a new path - Continues turning motion for 0.3 seconds
When detected distance is between 20-30cm: - Indicates obstacles ahead but still at a safe distance - The car stops first (setMotorModel(0, 0, 0, 0)) - Pauses for 0.2 seconds - Randomly chooses to turn left or right to find a new path - Continues turning motion for 0.3 seconds
Through this control strategy, the car can: - Maintain forward movement within safe distances - Avoid obstacles in time when encountered - Explore new viable paths through random turning - Effectively prevent collisions with obstacles
Need Help?
tech_edu_service@outlook.com