@@ -144,32 +144,36 @@ def __init__(self, i2c_bus, address=0x0C, gain=GAIN_1X, debug=False):
144
144
self .gain = self ._gain_current
145
145
146
146
147
- def _transceive (self , payload , rxlen = 0 , delay = 0.01 ):
147
+ def _transceive (self , payload , rxlen = 0 ):
148
148
"""
149
149
Writes the specified 'payload' to the sensor
150
150
Returns the results of the write attempt.
151
151
:param bytearray payload: The byte array to write to the sensor
152
152
:param rxlen: (optional) The numbers of bytes to read back (default=0)
153
153
"""
154
- # Write 'value' to the specified register
155
- with self .i2c_device as i2c :
156
- i2c .write (payload )
157
-
158
- # Insert a delay since we aren't using INTs for DRDY
159
- time .sleep (delay )
160
-
161
154
# Read the response (+1 to account for the mandatory status byte!)
162
155
data = bytearray (rxlen + 1 )
163
- while True :
164
- # While busy, the sensor doesn't respond to reads.
165
- try :
166
- with self .i2c_device as i2c :
167
- i2c .readinto (data )
168
- # Make sure we have something in the response
169
- if data [0 ]:
170
- break
171
- except OSError :
172
- pass
156
+
157
+ if len (payload ) == 1 :
158
+ # Transceive with repeated start
159
+ with self .i2c_device as i2c :
160
+ i2c .write_then_readinto (payload , data , stop = False )
161
+ else :
162
+ # Write 'value' to the specified register
163
+ with self .i2c_device as i2c :
164
+ i2c .write (payload , stop = False )
165
+
166
+ while True :
167
+ # While busy, the sensor doesn't respond to reads.
168
+ try :
169
+ with self .i2c_device as i2c :
170
+ i2c .readinto (data )
171
+ # Make sure we have something in the response
172
+ if data [0 ]:
173
+ break
174
+ except OSError :
175
+ pass
176
+
173
177
# Track status byte
174
178
self ._status_last = data [0 ]
175
179
# Unpack data (status byte, big-endian 16-bit register value)
@@ -262,17 +266,25 @@ def reset(self):
262
266
print ("Resetting sensor" )
263
267
time .sleep (2 )
264
268
self ._status_last = self ._transceive (bytes ([_CMD_RT ]))
269
+ # burn a read post reset
270
+ try :
271
+ self .magnetic
272
+ except OSError :
273
+ pass
265
274
return self ._status_last
266
275
267
276
268
277
@property
269
- def read_data (self ):
278
+ def read_data (self , delay = 0.01 ):
270
279
"""
271
280
Reads a single X/Y/Z sample from the magnetometer.
272
281
"""
273
282
# Set the device to single measurement mode
274
283
self ._transceive (bytes ([_CMD_SM | _CMD_AXIS_ALL ]))
275
284
285
+ # Insert a delay since we aren't using INTs for DRDY
286
+ time .sleep (delay )
287
+
276
288
# Read the 'XYZ' data as three signed 16-bit integers
277
289
data = self ._transceive (bytes ([_CMD_RM | _CMD_AXIS_ALL ]), 6 )
278
290
self ._status_last , m_x , m_y , m_z = struct .unpack (">Bhhh" , data )
0 commit comments