Index>Robot Kit>Mars Rover PiCar-B Smart Robot Car Kit for RPi>Lesson 4 Introduction to the Ultrasonic Scanning Function

Lesson 4 Introduction to the Ultrasonic Scanning Function

455

Lesson 4 Introduction to the Ultrasonic Scanning Function

 

4.1 Function introduction

Ultrasonic scanning function refers to that when running the program, PiCar-b will turn the servo to rotate the ultrasonic module, detect the surroundings via the ultrasonic module, test the distance between the robot and surrounding objects, and display the corresponding distance in the WEB control interface.

4.2 Turn on the ultrasonic scanning function

Run the ultrasonic scanning program

1. Start up Raspberry Pi robot for about 30s-60s.

2. When PiCar-b is started up, enter the IP address of your Raspberry Pi on the Google browser of your mobile phone or computer, and access Port 5000, for example: 192.168.3.44:5000. Then the web controller will be displayed on the browser.

image.png 

3. Place the trolley at the position to be detected.

4. Click the pattern "scan" , and PiCar-b will rotate and detect the surroundings. The scanning results will be displayed in the pattern "scan" .

image.png 

4.2 The main code program

Please see the complete code in findline.py.

Import dependency and initialize

1. import time  

2. import RPi.GPIO as GPIO  

3. import Adafruit_PCA9685  

4.   

5. Ultrasonic module pin

6. UPin1 = 11   

7. Upin2 = 8  

8.   

9. Servo pin. Set the servo pin of your product that controls the left and right rotation of the ultrasonic module.

10. servoPin = 1  

11.   

12. GPIO.setmode(GPIO.BCM)  

13. GPIO.setup(UPin1, GPIO.OUT,initial=GPIO.LOW)  

14. GPIO.setup(Upin2, GPIO.IN)  

15.   

16. pwm = Adafruit_PCA9685.PCA9685()  

17. pwm.set_pwm_freq(50)  

18.   

19. pwm0_init = 300   

20. pwm0_max  = 450 # Set the maximum scanning angle

21. pwm0_min  = 150 # Set the minimum scanning angle

22. pwm0_pos  = pwm0_init  

 

Define the scanning function

 

1. def checkdist():  

2.     ''' Reference basic module control ultra.Py  '''

3.   

4. def radarScan(): Main function of ultrasonic scanning function

5.     global pwm0_pos  

6.     scan_speed = 3 Scanning speed

7.   

8.     Move the servo to the maximum angle

9.     pwm0_pos = pwm0_max  

10.     pwm.set_pwm(servoPin, 0, pwm0_pos)  

11.     time.sleep(0.5)  

12.   

13.     # Rotate the servo and measure the distance continuously to reach the minimum angle  

14.     print(str(checkdist()), 'm')  

15.     while pwm0_pos>pwm0_min:  

16.         pwm0_pos-=scan_speed  

17.         pwm.set_pwm(servoPin, 0, pwm0_pos)  

18.         print(str(checkdist()), 'm')  

19.   

20.     Returning

21.     pwm.set_pwm(servoPin, 0, pwm0_init)  

 

Execute the function

1. if __name__ == '__main__':  

2.     radar_scan()  

3.     GPIO.cleanup()