Chapter 24 Ultrasonic Ranging
258
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
i m port
RPi
.
GPIO
a s
GPIO
i m 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
d e f
pulseIn
(
pin
,
level
,
timeOut
):
# function pulseIn: obtain pulse time of a pin
t0
=
time
.
time
()
w h ile
(
GPIO
.
input
(
pin
)
! =
level
) :
i f
((
time
.
time
()
-
t0
)
>
timeOut
*
0.000001
):
r e turn
0
;
t0
=
time
.
time
()
w h ile
(
GPIO
.
input
(
pin
)
= =
level
) :
i f
((
time
.
time
()
-
t0
)
>
timeOut
*
0.000001
):
Summary of Contents for Ultimate Starter Kit
Page 1: ...Free your innovation Freenove is an open source electronics platform www freenove com ...
Page 117: ...117 Chapter 9 Potentiometer RGBLED www freenove com support freenove com Hardware connection ...
Page 155: ...155 Chapter 14 Relay Motor www freenove com support freenove com Hardware connection OFF 3 3V ...
Page 173: ...173 Chapter 16 Stepping Motor www freenove com support freenove com Hardware connection ...
Page 239: ...239 Chapter 22 Matrix Keypad www freenove com support freenove com Circuit Schematic diagram ...
Page 240: ...Chapter 22 Matrix Keypad 240 www freenove com support freenove com Hardware connection ...