13. servoLeft = 180 #Left position of the servo
14. servoRight = 480 #The right position of the servo
15. rangeKeep = 0.3 #Avoidance distance
16.
17. scanDir = 1 #Scan direction, 1 is from left to right, -1 is from right to left
18. scanPos = 1 #Store the current scan position (1 is the left, 2 is the middle, and 3 is the right)
19. scanNum = 3 #The number of scan positions (left, middle, and right, these are three positions)
20.
21. scanList = [0,0,0] #Save scan results
22.
23. GPIO.setmode(GPIO.BCM)
24. GPIO.setup(Tr, GPIO.OUT,initial=GPIO.LOW)
25. GPIO.setup(Ec, GPIO.IN)
Main logic code
1. def checkdist():
2. ''' Refer to the realization of basic functions-ultrasonic module '''
3.
4. while 1:
5. print('Automatic obstacle avoidance mode')
6. if scanPos == 1:
7. pwm.set_pwm(servoPort, 0, servoLeft)
8. time.sleep(0.3)
9. scanList[0] = checkdist()
10. elif scanPos == 2:
11. pwm.set_pwm(servoPort, 0, servoMiddle)
12. time.sleep(0.3)
13. scanList[1] = checkdist()
14. elif scanPos == 3:
15. pwm.set_pwm(servoPort, 0, servoRight)
16. time.sleep(0.3)
17. scanList[2] = checkdist()
18.
19. scanPos = scanPos + scanDir
20.
21. if scanPos > scanNum or scanPos < 1:
22. if scanDir == 1:scanDir = -1
23. elif scanDir == -1:scanDir = 1
24. scanPos = scanPos + scanDir*2
25. print(scanList)
26.