57
57
class TFmini :
58
58
"""TF mini communication module, use with just RX or TX+RX for advanced
59
59
command & control.
60
+ :param uart: the pyseral or busio.uart compatible uart device
61
+ :param timeout: how long we'll wait for valid data or response, in seconds. Default is 1
60
62
"""
61
-
62
- def __init__ (self , uart , * , timeout = 3 ):
63
+
64
+ def __init__ (self , uart , * , timeout = 1 ):
63
65
self ._uart = uart
64
66
self ._uart .baudrate = 115200
65
67
self .timeout = timeout
@@ -73,31 +75,33 @@ def distance(self):
73
75
stamp = time .monotonic ()
74
76
while time .monotonic () - stamp < self .timeout :
75
77
# look for the header start
76
- c = self ._uart .read (1 )
77
- if c [0 ] != 0x59 :
78
+ x = self ._uart .read (1 )
79
+ if x is None or x [0 ] != 0x59 :
78
80
continue
79
81
# get remaining packet
80
82
data = self ._uart .read (8 )
81
83
# check first byte is magicbyte
82
- framebyte , distance , self ._strength , self ._mode , _ , checksum = struct .unpack ("<BHHBBB" ,data )
84
+ frame , dist , self ._strength , self ._mode , _ , checksum = struct .unpack ("<BHHBBB" , data )
83
85
# look for second 0x59 frame indicator
84
- if framebyte != 0x59 :
86
+ if frame != 0x59 :
85
87
continue
86
88
# calculate and check sum
87
89
mysum = (sum (data [0 :7 ]) + 0x59 ) & 0xFF
88
90
if mysum != checksum :
89
91
continue
90
- return distance
92
+ return dist
91
93
raise RuntimeError ("Timed out looking for valid data" )
92
94
93
95
@property
94
96
def strength (self ):
95
- self .distance
97
+ """The signal validity, higher value means better measurement"""
98
+ _ = self .distance # trigger distance measurement
96
99
return self ._strength
97
100
98
101
@property
99
102
def mode (self ):
100
- self .distance
103
+ """The measurement mode can be MODE_SHORT (2) or MODE_LONG (7)"""
104
+ _ = self .distance # trigger distance measurement
101
105
return self ._mode
102
106
103
107
@mode .setter
@@ -107,13 +111,15 @@ def mode(self, newmode):
107
111
self ._set_config (_CONFIGPARAM + bytes ([0 , 0 , newmode , 0x11 ]))
108
112
109
113
def _set_config (self , command ):
114
+ """Manager for sending commands, put sensor into config mode, config,
115
+ then exit configuration mode!"""
110
116
self ._uart .write (_STARTCONFIG )
111
117
stamp = time .monotonic ()
112
118
while (time .monotonic () - stamp ) < self .timeout :
113
119
# look for the header start
114
- c = self ._uart .read (1 )
115
- if c is None or c [0 ] != 0x42 :
116
- continue
120
+ x = self ._uart .read (1 )
121
+ if x is None or x [0 ] != 0x42 :
122
+ continue
117
123
echo = self ._uart .read (len (_STARTREPLY ))
118
124
#print("start ", [hex(i) for i in echo])
119
125
if echo != _STARTREPLY :
0 commit comments