Skip to content

Commit 15bb72b

Browse files
committed
Fix signed integer parsing.
1 parent b3981e7 commit 15bb72b

File tree

1 file changed

+13
-20
lines changed

1 file changed

+13
-20
lines changed

adafruit_fxas21002c.py

+13-20
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
* Author(s): Tony DiCola
3333
"""
3434
import time
35+
import ustruct
3536

3637
import adafruit_bus_device.i2c_device as i2c_device
3738

@@ -98,41 +99,33 @@ def __init__(self, i2c, address=_FXAS21002C_ADDRESS,
9899

99100
def _read_u8(self, address):
100101
# Read an 8-bit unsigned value from the specified 8-bit address.
101-
with self._device:
102+
with self._device as i2c:
102103
self._BUFFER[0] = address & 0xFF
103-
self._device.write(self._BUFFER, end=1, stop=False)
104-
self._device.readinto(self._BUFFER, end=1)
104+
i2c.write(self._BUFFER, end=1, stop=False)
105+
i2c.readinto(self._BUFFER, end=1)
105106
return self._BUFFER[0]
106107

107108
def _write_u8(self, address, val):
108109
# Write an 8-bit unsigned value to the specified 8-bit address.
109-
with self._device:
110+
with self._device as i2c:
110111
self._BUFFER[0] = address & 0xFF
111112
self._BUFFER[1] = val & 0xFF
112-
self._device.write(self._BUFFER, end=2)
113+
i2c.write(self._BUFFER, end=2)
113114

114115
def read_raw(self):
115116
"""Read the raw gyroscope readings. Returns a 3-tuple of X, Y, Z axis
116-
16-bit unsigned values. If you want the gyroscope values in friendly
117+
16-bit signed values. If you want the gyroscope values in friendly
117118
units consider using the gyroscope property!
118119
"""
119-
# Read 7 bytes from the sensor.
120+
# Read gyro data from the sensor.
120121
with self._device:
121-
self._BUFFER[0] = _GYRO_REGISTER_STATUS | 0x80
122+
self._BUFFER[0] = _GYRO_REGISTER_OUT_X_MSB
122123
self._device.write(self._BUFFER, end=1, stop=False)
123124
self._device.readinto(self._BUFFER)
124-
# Parse out the gyroscope data.
125-
status = self._BUFFER[0]
126-
xhi = self._BUFFER[1]
127-
xlo = self._BUFFER[2]
128-
yhi = self._BUFFER[3]
129-
ylo = self._BUFFER[4]
130-
zhi = self._BUFFER[5]
131-
zlo = self._BUFFER[6]
132-
# Shift values to create properly formed integers
133-
raw_x = ((xhi << 8) | xlo) & 0xFFFF
134-
raw_y = ((yhi << 8) | ylo) & 0xFFFF
135-
raw_z = ((zhi << 8) | zlo) & 0xFFFF
125+
# Parse out the gyroscope data as 16-bit signed data.
126+
raw_x = ustruct.unpack_from('>h', self._BUFFER[0:2])[0]
127+
raw_y = ustruct.unpack_from('>h', self._BUFFER[2:4])[0]
128+
raw_z = ustruct.unpack_from('>h', self._BUFFER[4:6])[0]
136129
return (raw_x, raw_y, raw_z)
137130

138131
@property

0 commit comments

Comments
 (0)