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...
259
Chapter 24 Ultrasonic Ranging
www.freenove.com
support@freenove.com
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
return 0;
pulseTime = ( time.time() - t0)*0.000001
r eturn pulseTime
def 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 eturn distance
def setup():
p rint ('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
def loop():
w hile(True):
distance = getSonar()
print ("The distance is : %.2f cm"%(distance))
time.sleep(1)
if __name__ == '__main__': #program start from here
setup()
try:
loop()
e xcept 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

Table of Contents