@@ -26,6 +26,10 @@ GY521::GY521(uint8_t address, TwoWire *wire)
2626 _address = address;
2727 _wire = wire;
2828
29+ // initialize errors
30+ // don't do it in reset, as users might want to keep them
31+ axe = aye = aze = 0 ;
32+
2933 reset ();
3034}
3135
@@ -68,12 +72,8 @@ void GY521::reset()
6872}
6973
7074
71- void GY521::calibrate (uint16_t times)
75+ void GY521::calibrate (uint16_t times, float angleX, float angleY, bool inverted )
7276{
73- // disable throttling / caching of read values.
74- bool oldThrottle = _throttle;
75- _throttle = false ;
76-
7777 // set all errors to zero, to get the raw reads.
7878 axe = aye = aze = 0 ;
7979 gxe = gye = gze = 0 ;
@@ -97,20 +97,27 @@ void GY521::calibrate(uint16_t times)
9797 _gze -= getGyroZ ();
9898 }
9999
100- // scale accelerometer calibration errors so read() should get all zero's on average.
101- float factor = _raw2g / times;
102- axe = _axe * factor;
103- aye = _aye * factor;
104- aze = _aze * factor;
105-
106100 // scale gyro calibration errors so read() should get all zero's on average.
107- factor = _raw2dps / times;
101+ float factor = _raw2dps / times;
108102 gxe = _gxe * factor;
109103 gye = _gye * factor;
110104 gze = _gze * factor;
111105
112- // restore throttle state.
113- _throttle = oldThrottle;
106+ // scale accelerometer calibration errors so read() should get all zero's on average.
107+ factor = _raw2g / times;
108+ axe = _axe * factor;
109+ aye = _aye * factor;
110+ aze = _aze * factor;
111+
112+ // remove expected gravity from error
113+ angleX *= GY521_DEGREES2RAD;
114+ angleY *= GY521_DEGREES2RAD;
115+ float _gravx = -sin (angleY) * cos (angleX);
116+ float _gravy = sin (angleX);
117+ float _gravz = cos (angleY) * cos (angleX);
118+ axe -= _gravx;
119+ aye -= _gravy;
120+ aze += inverted ? -_gravz : _gravz;
114121}
115122
116123
0 commit comments