EasyManua.ls Logo

Freenove Ultimate Starter Kit

Freenove Ultimate Starter Kit
286 pages
To Next Page IconTo Next Page
To Next Page IconTo Next Page
To Previous Page IconTo Previous Page
To Previous Page IconTo Previous Page
Loading...
Chapter 24 Ultrasonic Ranging
258
www.freenove.com
support@freenove.com
Finally, in the while loop of main function, get the measurement distance and print it out constantly.
while(1){
distance = getSonar();
printf("The distance is : %.2f cm\n",distance);
delay(1000);
}
About function p u lseIn():
int pulseIn(int pin, int level, int timeout);
Return the length of the pulse (in microseconds) or 0 if no pulse is completed before the timeout (unsigned
long).
Python Code 24.1.1 UltrasonicRanging
First observe the project result, and then analyze the code.
1. Use cd command to enter 24.1.1_UltrasonicRanging directory of Python code.
cd ~/Freenove_Ultimate_Starter_Kit_for_Raspberry_Pi/Code/Python_Code/24.1.1_UltrasonicRanging
2. Use python command to execute code "UltrasonicRanging.py".
python UltrasonicRanging.py
After the program is executed, make the detector of ultrasonic ranging module aim at the plane of an object,
then the distance between the ultrasonic module and the object will be displayed in the terminal. As is shown
below:
The following is the program code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
im port RPi. GPIO as GPIO
im port time
trigPin = 16
echoPin = 18
MAX_DISTANCE = 220 #define the maximum measured distance(cm)
timeOut = MAX_DISTANCE*60 #calculate timeout(μs) according to the maximum measured
distance
def pulseIn(pin,level,timeOut): # function pulseIn: obtain pulse time of a pin
t0 = time. time()
w hile(GPIO.input(pin) != level):
if((time.time() - t0) > timeOut*0.000001):
return 0;
t0 = time. time()
w hile(GPIO.input(pin) == level):
if((time.time() - t0) > timeOut*0.000001):

Table of Contents