13.
servoLeft = 180
14.
servoRight = 480
15.
rangeKeep = 0.3
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]
22.
23.
GPIO.setmode(GPIO.BCM)
24.
GPIO.setup(Tr, GPIO.OUT,initial=GPIO.LOW)
25.
GPIO.setup(Ec, GPIO.IN)
Main logic code
def
1.
checkdist():
2.
''' Refer to the realization of basic functions-ultrasonic module '''
3.
4.
while
1:
5.
print('Automatic obstacle avoidance
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.
if
21.
scanPos > scanNum
if
22.
scanDir == 1:scanDir = -1
23.
elif
scanDir == -1:scanDir = 1
24.
scanPos = scanPos + scanDir*2
25.
print(scanList)
26.
#Left position of the servo
#The right position of the servo
#Avoidance distance
#Save scan results
mode')
or
scanPos < 1:
171
Need help?
Do you have a question about the PiCar-Pro and is the answer not in the manual?