259
Chapter 24 Ultrasonic Ranging
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
r e turn
0
;
pulseTime
=
(
time
.
time
()
-
t0
) *
0.000001
r e turn
pulseTime
d e f
getSonar
():
#get the measurement results of ultrasonic module,with unit: cm
GPIO
.
output
(
trigPin
,
GPIO
.
HIGH
)
#make trigPin send 10us high level
time
.
sleep
(
0.00001
)
#10us
GPIO
.
output
(
trigPin
,
GPIO
.
LOW
)
pingTime
=
pulseIn
(
echoPin
,
GPIO
.
HIGH
,
timeOut
)
#read plus time of echoPin
distance
=
pingTime
*
340.0
/
2.0
/
10000.0
# the sound speed is 340m/s, and
calculate distance (cm)
r e turn
distance
d e f
setup
( ):
p r int
(
'Program is starting...'
)
GPIO
.
setmode
(
GPIO
.
BOARD
)
#numbers GPIOs by physical location
GPIO
.
setup
(
trigPin
,
GPIO
.
OUT
)
# set trigPin to output mode
GPIO
.
setup
(
echoPin
,
GPIO
.
IN
)
# set echoPin to input mode
d e f
loop
( ):
w h ile
(
True
):
distance
=
getSonar
()
p r int
(
"The distance is : %.2f cm"
% (
distance
))
time
.
sleep
(
1
)
i f
__name__
= =
'__main__'
:
#program start from here
setup
()
t r y
:
loop
( )
e x cept
KeyboardInterrupt
:
#when 'Ctrl+C' is pressed, the program will exit
GPIO
.
cleanup
()
#release resource
First, define the pins and the maximum measurement distance.
trigPin
=
16
echoPin
=
18
MAX_DISTANCE
=
220
# define the maximum measured distance
If the module does not return high level, we can not wait forever. So we need to calculate the lasting time
over maximum distance, that is, timeOut( μ s) .
timeOut= 2*MAX_DISTANCE/100/340*1000000
. The
constant part behind is approximately equal to 58.8.
timeOut
=
MAX_DISTANCE
*
60
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 ...