File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change
1
+ # the sound speed on air (343.2 m/s), that It's equivalent to 0.34320 mm/us that is 1mm each 2.91us
2
+ # pulse_time // 2 // 2.91 -> pulse_time // 5.82 -> pulse_time * 100 // 582
3
+ # echo timeout -> max=4500mm, 4500 * 2.91us -> 0.0131 * 2 -> 0.0262 or 26.2ms
4
+ # echo timeout -> 1000000us or 1s
5
+
6
+ import machine
7
+ from machine import Pin
8
+ import utime
9
+
10
+ class ULTRASONIC_IO :
11
+ def __init__ (self , port , echo_timeout_us = 1000000 ):
12
+ self .echo_timeout_us = echo_timeout_us
13
+ # trigger pin (out)
14
+ self .trigger = Pin (port [1 ], mode = Pin .OUT , pull = None )
15
+ self .trigger .value (0 )
16
+ # echo pin (in)
17
+ self .echo = Pin (port [0 ], mode = Pin .IN , pull = None )
18
+
19
+ def tx_pulse_rx_echo (self ):
20
+
21
+ self .trigger .value (0 )
22
+ utime .sleep_us (5 )
23
+ # Send a 10us pulse.
24
+ self .trigger .value (1 )
25
+ utime .sleep_us (10 )
26
+ self .trigger .value (0 )
27
+ try :
28
+ echo_time = machine .time_pulse_us (self .echo , 1 , self .echo_timeout_us )
29
+ return echo_time
30
+ except :
31
+ pass
32
+
33
+ def get_target_distance (self , mode = 1 ):
34
+ """
35
+ Get the distance in milimeters or centimeters.
36
+ """
37
+ echo_time = self .tx_pulse_rx_echo ()
38
+ utime .sleep_ms (50 )
39
+ if mode == 1 :
40
+ mm = echo_time * 100 // 582
41
+ return mm
42
+ elif mode == 2 :
43
+ cm = (echo_time * 100 // 582 ) / 10
44
+ return cm
45
+
You can’t perform that action at this time.
0 commit comments