11//
22// FILE: GY521.cpp
33// AUTHOR: Rob Tillaart
4- // VERSION: 0.1.4
4+ // VERSION: 0.1.5
55// PURPOSE: Arduino library for I2C GY521 accelerometer-gyroscope sensor
66// URL: https://github.com/RobTillaart/GY521
77//
1010// 0.1.1 2020-07-09 refactor + initial release
1111// 0.1.2 2020-08-06 fix setAccelSensitivity + add getters
1212// 0.1.3 2020-08-07 fix ESP support + pitch roll yaw demo
13- // 0.1.4 2020-09-29 fix #5
13+ // 0.1.4 2020-09-29 fix #5 missing ;
14+ // 0.1.5 2020-09-29 fix #6 fix math for Teensy
1415
1516
1617#include " GY521.h"
@@ -67,7 +68,7 @@ bool GY521::wakeup()
6768 return Wire.endTransmission () == 0 ;
6869}
6970
70- int GY521::read ()
71+ int16_t GY521::read ()
7172{
7273 if (_throttle)
7374 {
@@ -80,20 +81,21 @@ int GY521::read()
8081 // Connected ?
8182 Wire.beginTransmission (_address);
8283 Wire.write (GY521_ACCEL_XOUT_H);
83- if (Wire.endTransmission () != 0 ) return GY521_ERROR_READ ;
84+ if (Wire.endTransmission () != 0 ) return GY521_ERROR_WRITE ;
8485
8586 // Get the data
86- Wire.requestFrom (_address, (uint8_t )14 );
87+ int8_t n = Wire.requestFrom (_address, (uint8_t )14 );
88+ if (n != 14 ) return GY521_ERROR_READ;
8789 // ACCELEROMETER
88- _ax = ( ( (( int )Wire. read ()) << 8 ) | Wire. read () ); // ACCEL_XOUT_H ACCEL_XOUT_L
89- _ay = ( ( (( int )Wire. read ()) << 8 ) | Wire. read () ); // ACCEL_YOUT_H ACCEL_YOUT_L
90- _az = ( ( (( int )Wire. read ()) << 8 ) | Wire. read () ); // ACCEL_ZOUT_H ACCEL_ZOUT_L
90+ _ax = _WireRead2 ( ); // ACCEL_XOUT_H ACCEL_XOUT_L
91+ _ay = _WireRead2 ( ); // ACCEL_YOUT_H ACCEL_YOUT_L
92+ _az = _WireRead2 ( ); // ACCEL_ZOUT_H ACCEL_ZOUT_L
9193 // TEMPERATURE
92- _temperature = ( (( int )Wire. read ()) << 8 ) | Wire. read (); // TEMP_OUT_H TEMP_OUT_L
94+ _temperature = _WireRead2 (); // TEMP_OUT_H TEMP_OUT_L
9395 // GYROSCOPE
94- _gx = (( (( int )Wire. read ()) << 8 ) | Wire. read () ); // GYRO_XOUT_H GYRO_XOUT_L
95- _gy = (( (( int )Wire. read ()) << 8 ) | Wire. read () ); // GYRO_YOUT_H GYRO_YOUT_L
96- _gz = (( (( int )Wire. read ()) << 8 ) | Wire. read () ); // GYRO_ZOUT_H GYRO_ZOUT_L
96+ _gx = _WireRead2 ( ); // GYRO_XOUT_H GYRO_XOUT_L
97+ _gy = _WireRead2 ( ); // GYRO_YOUT_H GYRO_YOUT_L
98+ _gz = _WireRead2 ( ); // GYRO_ZOUT_H GYRO_ZOUT_L
9799
98100 // time interval
99101 uint32_t now = millis ();
@@ -200,9 +202,19 @@ uint8_t GY521::getRegister(uint8_t reg)
200202 Wire.beginTransmission (_address);
201203 Wire.write (reg);
202204 if (Wire.endTransmission () != 0 ) return GY521_ERROR_WRITE;
203- Wire.requestFrom (_address, (uint8_t ) 1 );
205+ uint8_t n = Wire.requestFrom (_address, (uint8_t ) 1 );
206+ if (n != 1 ) return GY521_ERROR_READ;
204207 uint8_t val = Wire.read ();
205208 return val;
206209}
207210
208- // END OF FILE
211+ // to read register of 2 bytes.
212+ int16_t GY521::_WireRead2 ()
213+ {
214+ int16_t tmp = Wire.read ();
215+ tmp <<= 8 ;
216+ tmp |= Wire.read ();
217+ return tmp;
218+ }
219+
220+ // -- END OF FILE --
0 commit comments