Advertisement
Guest User

Untitled

a guest
Jul 28th, 2015
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 23.44 KB | None | 0 0
  1. #include "MPU6050.h"
  2.  
  3.  
  4. const float MPU6050::PI = 3.14159265358979323846f;
  5. const float MPU6050::GyroMeasError = PI * (60.0f / 180.0f); // gyroscope measurement error in rads/s (start at 60 deg/s), then reduce after ~10 s to 3
  6. const float MPU6050::beta = sqrt(3.0f / 4.0f) * GyroMeasError; // compute beta
  7. const float MPU6050::GyroMeasDrift = PI * (1.0f / 180.0f); // gyroscope measurement drift in rad/s/s (start at 0.0 deg/s/s)
  8. const float MPU6050::zeta = sqrt(3.0f / 4.0f) * GyroMeasDrift; // compute zeta, the other free parameter in the Madgwick scheme usually set to a small or zero value
  9.  
  10. MPU6050::MPU6050(SoftwareI2C *iic, PinName ad0pin)
  11. {
  12. i2c = iic;
  13. ad0 = new DigitalOut(ad0pin);
  14.  
  15. *ad0 = true;
  16. q[0] = 1.0f;
  17.  
  18. gScale = GFS_250DPS;
  19. aScale = AFS_2G;
  20.  
  21. for(int i = 0 ; i < 3; i++)
  22. {
  23. q[i+1] = 0.0f;
  24. gyroBias[i] = 0.0f;
  25. accelBias[i] = 0.0f;
  26. }
  27.  
  28. lastUpdate = 0;
  29. firstUpdate = 0;
  30. }
  31.  
  32. void MPU6050::create(SoftwareI2C *iic, PinName ad0pin)
  33. {
  34. i2c = iic;
  35. ad0 = new DigitalOut(ad0pin);
  36.  
  37. *ad0 = 1;
  38.  
  39. q[0] = 1.0f;
  40.  
  41. gScale = GFS_250DPS;
  42. aScale = AFS_2G;
  43.  
  44. for(int i = 0 ; i < 3; i++)
  45. {
  46. q[i+1] = 0.0f;
  47. gyroBias[i] = 0.0f;
  48. accelBias[i] = 0.0f;
  49. }
  50.  
  51. lastUpdate = 0;
  52. firstUpdate = 0;
  53. dt = -1;
  54. }
  55.  
  56. void MPU6050::writeByte(uint8_t address, uint8_t subAddress, uint8_t data)
  57. {
  58. *ad0 = 0;
  59. uint8_t data_write[2];
  60. data_write[0] = subAddress;
  61. data_write[1] = data;
  62. i2c->write(address, data_write, 2);
  63. *ad0 = 1;
  64. }
  65.  
  66. uint8_t MPU6050::readByte(uint8_t address, uint8_t subAddress)
  67. {
  68. *ad0 = 0;
  69. uint8_t data[1]; // data will store the register data
  70. uint8_t data_write[1];
  71. data_write[0] = subAddress;
  72. i2c->write(address, data_write, 1); // no stop
  73. i2c->read(address, data, 1);
  74. *ad0 = 1;
  75. return data[0];
  76. }
  77.  
  78. void MPU6050::readBytes(uint8_t address, uint8_t subAddress, uint8_t count, uint8_t * dest)
  79. {
  80. *ad0 = 0;
  81. uint8_t data[14];
  82. uint8_t data_write[1];
  83. data_write[0] = subAddress;
  84. i2c->write(address, data_write, 1); // no stop
  85. i2c->read(address, data, count);
  86. for(int i = 0; i < count; i++)
  87. {
  88. dest[i] = data[i];
  89. }
  90. *ad0 = 1;
  91. }
  92.  
  93. void MPU6050::getGres() {
  94. switch (gScale)
  95. {
  96. // Possible gyro scales (and their register bit settings) are:
  97. // 250 DPS (00), 500 DPS (01), 1000 DPS (10), and 2000 DPS (11).
  98. // Here's a bit of an algorith to calculate DPS/(ADC tick) based on that 2-bit value:
  99. case GFS_250DPS:
  100. gRes = 250.0/32768.0;
  101. break;
  102. case GFS_500DPS:
  103. gRes = 500.0/32768.0;
  104. break;
  105. case GFS_1000DPS:
  106. gRes = 1000.0/32768.0;
  107. break;
  108. case GFS_2000DPS:
  109. gRes = 2000.0/32768.0;
  110. break;
  111. }
  112. }
  113.  
  114. void MPU6050::getAres() {
  115. switch (aScale)
  116. {
  117. // Possible accelerometer scales (and their register bit settings) are:
  118. // 2 Gs (00), 4 Gs (01), 8 Gs (10), and 16 Gs (11).
  119. // Here's a bit of an algorith to calculate DPS/(ADC tick) based on that 2-bit value:
  120. case AFS_2G:
  121. aRes = 2.0/32768.0;
  122. break;
  123. case AFS_4G:
  124. aRes = 4.0/32768.0;
  125. break;
  126. case AFS_8G:
  127. aRes = 8.0/32768.0;
  128. break;
  129. case AFS_16G:
  130. aRes = 16.0/32768.0;
  131. break;
  132. }
  133. }
  134.  
  135.  
  136. void MPU6050::readAccelData(int16_t * destination)
  137. {
  138. uint8_t rawData[6]; // x/y/z accel register data stored here
  139. readBytes(MPU6050_ADDRESS, ACCEL_XOUT_H, 6, &rawData[0]); // Read the six raw data registers into data array
  140. destination[0] = (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value
  141. destination[1] = (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;
  142. destination[2] = (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ;
  143. }
  144.  
  145. void MPU6050::readGyroData(int16_t * destination)
  146. {
  147. uint8_t rawData[6]; // x/y/z gyro register data stored here
  148. readBytes(MPU6050_ADDRESS, GYRO_XOUT_H, 6, &rawData[0]); // Read the six raw data registers sequentially into data array
  149. destination[0] = (int16_t)(((int16_t)rawData[0] << 8) | rawData[1]) ; // Turn the MSB and LSB into a signed 16-bit value
  150. destination[1] = (int16_t)(((int16_t)rawData[2] << 8) | rawData[3]) ;
  151. destination[2] = (int16_t)(((int16_t)rawData[4] << 8) | rawData[5]) ;
  152. }
  153.  
  154. int16_t MPU6050::readTempData()
  155. {
  156. uint8_t rawData[2]; // x/y/z gyro register data stored here
  157. readBytes(MPU6050_ADDRESS, TEMP_OUT_H, 2, &rawData[0]); // Read the two raw data registers sequentially into data array
  158. return (int16_t)(((int16_t)rawData[0]) << 8 | rawData[1]) ; // Turn the MSB and LSB into a 16-bit value
  159. }
  160.  
  161. void MPU6050::init()
  162. {
  163. // Initialize MPU6050 device
  164. // wake up device
  165. writeByte(MPU6050_ADDRESS, PWR_MGMT_1, 0x00); // Clear sleep mode bit (6), enable all sensors
  166. wait(0.1); // Delay 100 ms for PLL to get established on x-axis gyro; should check for PLL ready interrupt
  167.  
  168. // get stable time source
  169. writeByte(MPU6050_ADDRESS, PWR_MGMT_1, 0x01); // Set clock source to be PLL with x-axis gyroscope reference, bits 2:0 = 001
  170.  
  171. // Configure Gyro and Accelerometer
  172. // Disable FSYNC and set accelerometer and gyro bandwidth to 44 and 42 Hz, respectively;
  173. // DLPF_CFG = bits 2:0 = 010; this sets the sample rate at 1 kHz for both
  174. // Maximum delay is 4.9 ms which is just over a 200 Hz maximum rate
  175. writeByte(MPU6050_ADDRESS, CONFIG, 0x03);
  176.  
  177. // Set sample rate = gyroscope output rate/(1 + SMPLRT_DIV)
  178. writeByte(MPU6050_ADDRESS, SMPLRT_DIV, 0x04); // Use a 200 Hz rate; the same rate set in CONFIG above
  179.  
  180. // Set gyroscope full scale range
  181. // Range selects FS_SEL and AFS_SEL are 0 - 3, so 2-bit values are left-shifted into positions 4:3
  182. uint8_t c = readByte(MPU6050_ADDRESS, GYRO_CONFIG);
  183. writeByte(MPU6050_ADDRESS, GYRO_CONFIG, c & ~0xE0); // Clear self-test bits [7:5]
  184. writeByte(MPU6050_ADDRESS, GYRO_CONFIG, c & ~0x18); // Clear AFS bits [4:3]
  185. writeByte(MPU6050_ADDRESS, GYRO_CONFIG, c | gScale << 3); // Set full scale range for the gyro
  186.  
  187. // Set accelerometer configuration
  188. c = readByte(MPU6050_ADDRESS, ACCEL_CONFIG);
  189. writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, c & ~0xE0); // Clear self-test bits [7:5]
  190. writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, c & ~0x18); // Clear AFS bits [4:3]
  191. writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, c | aScale << 3); // Set full scale range for the accelerometer
  192.  
  193. // Configure Interrupts and Bypass Enable
  194. // Set interrupt pin active high, push-pull, and clear on read of INT_STATUS, enable I2C_BYPASS_EN so additional chips
  195. // can join the I2C bus and all can be controlled by the Arduino as master
  196. writeByte(MPU6050_ADDRESS, INT_PIN_CFG, 0x22);
  197. writeByte(MPU6050_ADDRESS, INT_ENABLE, 0x01); // Enable data ready (bit 0) interrupt
  198. }
  199.  
  200. void MPU6050::reset() {
  201. // reset device
  202. writeByte(MPU6050_ADDRESS, PWR_MGMT_1, 0x80); // Write a one to bit 7 reset bit; toggle reset device
  203. wait(0.1);
  204. }
  205.  
  206. // Function which accumulates gyro and accelerometer data after device initialization. It calculates the average
  207. // of the at-rest readings and then loads the resulting offsets into accelerometer and gyro bias registers.
  208. void MPU6050::calibrate(float * dest1, float * dest2)
  209. {
  210. uint8_t data[12]; // data array to hold accelerometer and gyro x, y, z, data
  211. uint16_t ii, packet_count, fifo_count;
  212. int32_t gyro_bias[3] = {
  213. 0, 0, 0 }
  214. , accel_bias[3] = {
  215. 0, 0, 0 };
  216.  
  217. // reset device, reset all registers, clear gyro and accelerometer bias registers
  218. writeByte(MPU6050_ADDRESS, PWR_MGMT_1, 0x80); // Write a one to bit 7 reset bit; toggle reset device
  219. wait(0.1);
  220.  
  221. // get stable time source
  222. // Set clock source to be PLL with x-axis gyroscope reference, bits 2:0 = 001
  223. writeByte(MPU6050_ADDRESS, PWR_MGMT_1, 0x01);
  224. writeByte(MPU6050_ADDRESS, PWR_MGMT_2, 0x00);
  225. wait(0.2);
  226.  
  227. // Configure device for bias calculation
  228. writeByte(MPU6050_ADDRESS, INT_ENABLE, 0x00); // Disable all interrupts
  229. writeByte(MPU6050_ADDRESS, FIFO_EN, 0x00); // Disable FIFO
  230. writeByte(MPU6050_ADDRESS, PWR_MGMT_1, 0x00); // Turn on internal clock source
  231. writeByte(MPU6050_ADDRESS, I2C_MST_CTRL, 0x00); // Disable I2C master
  232. writeByte(MPU6050_ADDRESS, USER_CTRL, 0x00); // Disable FIFO and I2C master modes
  233. writeByte(MPU6050_ADDRESS, USER_CTRL, 0x0C); // Reset FIFO and DMP
  234. wait(0.015);
  235.  
  236. // Configure MPU6050 gyro and accelerometer for bias calculation
  237. writeByte(MPU6050_ADDRESS, CONFIG, 0x01); // Set low-pass filter to 188 Hz
  238. writeByte(MPU6050_ADDRESS, SMPLRT_DIV, 0x00); // Set sample rate to 1 kHz
  239. writeByte(MPU6050_ADDRESS, GYRO_CONFIG, 0x00); // Set gyro full-scale to 250 degrees per second, maximum sensitivity
  240. writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, 0x00); // Set accelerometer full-scale to 2 g, maximum sensitivity
  241.  
  242. uint16_t gyrosensitivity = 131; // = 131 LSB/degrees/sec
  243. uint16_t accelsensitivity = 16384; // = 16384 LSB/g
  244.  
  245. // Configure FIFO to capture accelerometer and gyro data for bias calculation
  246. writeByte(MPU6050_ADDRESS, USER_CTRL, 0x40); // Enable FIFO
  247. writeByte(MPU6050_ADDRESS, FIFO_EN, 0x78); // Enable gyro and accelerometer sensors for FIFO (max size 1024 bytes in MPU-6050)
  248. wait(0.08); // accumulate 80 samples in 80 milliseconds = 960 bytes
  249.  
  250. // At end of sample accumulation, turn off FIFO sensor read
  251. writeByte(MPU6050_ADDRESS, FIFO_EN, 0x00); // Disable gyro and accelerometer sensors for FIFO
  252. readBytes(MPU6050_ADDRESS, FIFO_COUNTH, 2, &data[0]); // read FIFO sample count
  253. fifo_count = ((uint16_t)data[0] << 8) | data[1];
  254. packet_count = fifo_count/12;// How many sets of full gyro and accelerometer data for averaging
  255.  
  256. for (ii = 0; ii < packet_count; ii++) {
  257. int16_t accel_temp[3] = {
  258. 0, 0, 0 }
  259. , gyro_temp[3] = {
  260. 0, 0, 0 };
  261. readBytes(MPU6050_ADDRESS, FIFO_R_W, 12, &data[0]); // read data for averaging
  262. accel_temp[0] = (int16_t) (((int16_t)data[0] << 8) | data[1] ) ; // Form signed 16-bit integer for each sample in FIFO
  263. accel_temp[1] = (int16_t) (((int16_t)data[2] << 8) | data[3] ) ;
  264. accel_temp[2] = (int16_t) (((int16_t)data[4] << 8) | data[5] ) ;
  265. gyro_temp[0] = (int16_t) (((int16_t)data[6] << 8) | data[7] ) ;
  266. gyro_temp[1] = (int16_t) (((int16_t)data[8] << 8) | data[9] ) ;
  267. gyro_temp[2] = (int16_t) (((int16_t)data[10] << 8) | data[11]) ;
  268.  
  269. accel_bias[0] += (int32_t) accel_temp[0]; // Sum individual signed 16-bit biases to get accumulated signed 32-bit biases
  270. accel_bias[1] += (int32_t) accel_temp[1];
  271. accel_bias[2] += (int32_t) accel_temp[2];
  272. gyro_bias[0] += (int32_t) gyro_temp[0];
  273. gyro_bias[1] += (int32_t) gyro_temp[1];
  274. gyro_bias[2] += (int32_t) gyro_temp[2];
  275.  
  276. }
  277. accel_bias[0] /= (int32_t) packet_count; // Normalize sums to get average count biases
  278. accel_bias[1] /= (int32_t) packet_count;
  279. accel_bias[2] /= (int32_t) packet_count;
  280. gyro_bias[0] /= (int32_t) packet_count;
  281. gyro_bias[1] /= (int32_t) packet_count;
  282. gyro_bias[2] /= (int32_t) packet_count;
  283.  
  284. if(accel_bias[2] > 0L) {
  285. accel_bias[2] -= (int32_t) accelsensitivity;
  286. } // Remove gravity from the z-axis accelerometer bias calculation
  287. else {
  288. accel_bias[2] += (int32_t) accelsensitivity;
  289. }
  290.  
  291. // Construct the gyro biases for push to the hardware gyro bias registers, which are reset to zero upon device startup
  292. data[0] = (-gyro_bias[0]/4 >> 8) & 0xFF; // Divide by 4 to get 32.9 LSB per deg/s to conform to expected bias input format
  293. data[1] = (-gyro_bias[0]/4) & 0xFF; // Biases are additive, so change sign on calculated average gyro biases
  294. data[2] = (-gyro_bias[1]/4 >> 8) & 0xFF;
  295. data[3] = (-gyro_bias[1]/4) & 0xFF;
  296. data[4] = (-gyro_bias[2]/4 >> 8) & 0xFF;
  297. data[5] = (-gyro_bias[2]/4) & 0xFF;
  298.  
  299. // Push gyro biases to hardware registers
  300. writeByte(MPU6050_ADDRESS, XG_OFFS_USRH, data[0]);
  301. writeByte(MPU6050_ADDRESS, XG_OFFS_USRL, data[1]);
  302. writeByte(MPU6050_ADDRESS, YG_OFFS_USRH, data[2]);
  303. writeByte(MPU6050_ADDRESS, YG_OFFS_USRL, data[3]);
  304. writeByte(MPU6050_ADDRESS, ZG_OFFS_USRH, data[4]);
  305. writeByte(MPU6050_ADDRESS, ZG_OFFS_USRL, data[5]);
  306.  
  307. dest1[0] = (float) gyro_bias[0]/(float) gyrosensitivity; // construct gyro bias in deg/s for later manual subtraction
  308. dest1[1] = (float) gyro_bias[1]/(float) gyrosensitivity;
  309. dest1[2] = (float) gyro_bias[2]/(float) gyrosensitivity;
  310.  
  311. // Construct the accelerometer biases for push to the hardware accelerometer bias registers. These registers contain
  312. // factory trim values which must be added to the calculated accelerometer biases; on boot up these registers will hold
  313. // non-zero values. In addition, bit 0 of the lower byte must be preserved since it is used for temperature
  314. // compensation calculations. Accelerometer bias registers expect bias input as 2048 LSB per g, so that
  315. // the accelerometer biases calculated above must be divided by 8.
  316.  
  317. int32_t accel_bias_reg[3] = {
  318. 0, 0, 0 }; // A place to hold the factory accelerometer trim biases
  319. readBytes(MPU6050_ADDRESS, XA_OFFSET_H, 2, &data[0]); // Read factory accelerometer trim values
  320. accel_bias_reg[0] = (int16_t) ((int16_t)data[0] << 8) | data[1];
  321. readBytes(MPU6050_ADDRESS, YA_OFFSET_H, 2, &data[0]);
  322. accel_bias_reg[1] = (int16_t) ((int16_t)data[0] << 8) | data[1];
  323. readBytes(MPU6050_ADDRESS, ZA_OFFSET_H, 2, &data[0]);
  324. accel_bias_reg[2] = (int16_t) ((int16_t)data[0] << 8) | data[1];
  325.  
  326. uint32_t mask = 1uL; // Define mask for temperature compensation bit 0 of lower byte of accelerometer bias registers
  327. uint8_t mask_bit[3] = {
  328. 0, 0, 0 }; // Define array to hold mask bit for each accelerometer bias axis
  329.  
  330. for(ii = 0; ii < 3; ii++) {
  331. if(accel_bias_reg[ii] & mask) mask_bit[ii] = 0x01; // If temperature compensation bit is set, record that fact in mask_bit
  332. }
  333.  
  334. // Construct total accelerometer bias, including calculated average accelerometer bias from above
  335. accel_bias_reg[0] -= (accel_bias[0]/8); // Subtract calculated averaged accelerometer bias scaled to 2048 LSB/g (16 g full scale)
  336. accel_bias_reg[1] -= (accel_bias[1]/8);
  337. accel_bias_reg[2] -= (accel_bias[2]/8);
  338.  
  339. data[0] = (accel_bias_reg[0] >> 8) & 0xFF;
  340. data[1] = (accel_bias_reg[0]) & 0xFF;
  341. data[1] = data[1] | mask_bit[0]; // preserve temperature compensation bit when writing back to accelerometer bias registers
  342. data[2] = (accel_bias_reg[1] >> 8) & 0xFF;
  343. data[3] = (accel_bias_reg[1]) & 0xFF;
  344. data[3] = data[3] | mask_bit[1]; // preserve temperature compensation bit when writing back to accelerometer bias registers
  345. data[4] = (accel_bias_reg[2] >> 8) & 0xFF;
  346. data[5] = (accel_bias_reg[2]) & 0xFF;
  347. data[5] = data[5] | mask_bit[2]; // preserve temperature compensation bit when writing back to accelerometer bias registers
  348.  
  349. // Push accelerometer biases to hardware registers
  350. // writeByte(MPU6050_ADDRESS, XA_OFFSET_H, data[0]);
  351. // writeByte(MPU6050_ADDRESS, XA_OFFSET_L_TC, data[1]);
  352. // writeByte(MPU6050_ADDRESS, YA_OFFSET_H, data[2]);
  353. // writeByte(MPU6050_ADDRESS, YA_OFFSET_L_TC, data[3]);
  354. // writeByte(MPU6050_ADDRESS, ZA_OFFSET_H, data[4]);
  355. // writeByte(MPU6050_ADDRESS, ZA_OFFSET_L_TC, data[5]);
  356.  
  357. // Output scaled accelerometer biases for manual subtraction in the main program
  358. dest2[0] = (float)accel_bias[0]/(float)accelsensitivity;
  359. dest2[1] = (float)accel_bias[1]/(float)accelsensitivity;
  360. dest2[2] = (float)accel_bias[2]/(float)accelsensitivity;
  361. }
  362.  
  363.  
  364. // Accelerometer and gyroscope self test; check calibration wrt factory settings
  365. void MPU6050::selfTest(float * destination) // Should return percent deviation from factory trim values, +/- 14 or less deviation is a pass
  366. {
  367. uint8_t rawData[4] = {
  368. 0, 0, 0, 0 };
  369. uint8_t selfTest[6];
  370. float factoryTrim[6];
  371.  
  372. // Configure the accelerometer for self-test
  373. writeByte(MPU6050_ADDRESS, ACCEL_CONFIG, 0xF0); // Enable self test on all three axes and set accelerometer range to +/- 8 g
  374. writeByte(MPU6050_ADDRESS, GYRO_CONFIG, 0xE0); // Enable self test on all three axes and set gyro range to +/- 250 degrees/s
  375. wait(0.25); // Delay a while to let the device execute the self-test
  376. rawData[0] = readByte(MPU6050_ADDRESS, SELF_TEST_X); // X-axis self-test results
  377. rawData[1] = readByte(MPU6050_ADDRESS, SELF_TEST_Y); // Y-axis self-test results
  378. rawData[2] = readByte(MPU6050_ADDRESS, SELF_TEST_Z); // Z-axis self-test results
  379. rawData[3] = readByte(MPU6050_ADDRESS, SELF_TEST_A); // Mixed-axis self-test results
  380. // Extract the acceleration test results first
  381. selfTest[0] = (rawData[0] >> 3) | (rawData[3] & 0x30) >> 4 ; // XA_TEST result is a five-bit unsigned integer
  382. selfTest[1] = (rawData[1] >> 3) | (rawData[3] & 0x0C) >> 4 ; // YA_TEST result is a five-bit unsigned integer
  383. selfTest[2] = (rawData[2] >> 3) | (rawData[3] & 0x03) >> 4 ; // ZA_TEST result is a five-bit unsigned integer
  384. // Extract the gyration test results first
  385. selfTest[3] = rawData[0] & 0x1F ; // XG_TEST result is a five-bit unsigned integer
  386. selfTest[4] = rawData[1] & 0x1F ; // YG_TEST result is a five-bit unsigned integer
  387. selfTest[5] = rawData[2] & 0x1F ; // ZG_TEST result is a five-bit unsigned integer
  388. // Process results to allow final comparison with factory set values
  389. factoryTrim[0] = (4096.0f*0.34f)*(pow( (0.92f/0.34f) , ((selfTest[0] - 1.0f)/30.0f))); // FT[Xa] factory trim calculation
  390. factoryTrim[1] = (4096.0f*0.34f)*(pow( (0.92f/0.34f) , ((selfTest[1] - 1.0f)/30.0f))); // FT[Ya] factory trim calculation
  391. factoryTrim[2] = (4096.0f*0.34f)*(pow( (0.92f/0.34f) , ((selfTest[2] - 1.0f)/30.0f))); // FT[Za] factory trim calculation
  392. factoryTrim[3] = ( 25.0f*131.0f)*(pow( 1.046f , (selfTest[3] - 1.0f) )); // FT[Xg] factory trim calculation
  393. factoryTrim[4] = (-25.0f*131.0f)*(pow( 1.046f , (selfTest[4] - 1.0f) )); // FT[Yg] factory trim calculation
  394. factoryTrim[5] = ( 25.0f*131.0f)*(pow( 1.046f , (selfTest[5] - 1.0f) )); // FT[Zg] factory trim calculation
  395.  
  396. // Output self-test results and factory trim calculation if desired
  397. // Serial.println(selfTest[0]); Serial.println(selfTest[1]); Serial.println(selfTest[2]);
  398. // Serial.println(selfTest[3]); Serial.println(selfTest[4]); Serial.println(selfTest[5]);
  399. // Serial.println(factoryTrim[0]); Serial.println(factoryTrim[1]); Serial.println(factoryTrim[2]);
  400. // Serial.println(factoryTrim[3]); Serial.println(factoryTrim[4]); Serial.println(factoryTrim[5]);
  401.  
  402. // Report results as a ratio of (STR - FT)/FT; the change from Factory Trim of the Self-Test Response
  403. // To get to percent, must multiply by 100 and subtract result from 100
  404. for (int i = 0; i < 6; i++) {
  405. destination[i] = 100.0f + 100.0f*(selfTest[i] - factoryTrim[i])/factoryTrim[i]; // Report percent differences
  406. }
  407.  
  408. }
  409.  
  410.  
  411. void MPU6050::updateDt()
  412. {
  413. long tmp = millis();
  414. if(dt < 0) dt = 0.01f;
  415. else
  416. {
  417. dt = ((float)(tmp - lastUpdate)) / 1000.0f;
  418. if(dt == 0.0f)
  419. dt = 0.01f;
  420. }
  421.  
  422. lastUpdate = tmp;
  423. }
  424.  
  425. // Implementation of Sebastian Madgwick's "...efficient orientation filter for... inertial/magnetic sensor arrays"
  426. // (see http://www.x-io.co.uk/category/open-source/ for examples and more details)
  427. // which fuses acceleration and rotation rate to produce a quaternion-based estimate of relative
  428. // device orientation -- which can be converted to yaw, pitch, and roll. Useful for stabilizing quadcopters, etc.
  429. // The performance of the orientation filter is at least as good as conventional Kalman-based filtering algorithms
  430. // but is much less computationally intensive---it can be performed on a 3.3 V Pro Mini operating at 8 MHz!
  431. void MPU6050::updateQuaternion(float gx, float gy, float gz, float ax, float ay, float az) {
  432. float q1 = q[0], q2 = q[1], q3 = q[2], q4 = q[3]; // short name local variable for readability
  433. float norm; // vector norm
  434. float f1, f2, f3; // objective funcyion elements
  435. float J_11or24, J_12or23, J_13or22, J_14or21, J_32, J_33; // objective function Jacobian elements
  436. float qDot1, qDot2, qDot3, qDot4;
  437. float hatDot1, hatDot2, hatDot3, hatDot4;
  438. float gerrx, gerry, gerrz, gbiasx, gbiasy, gbiasz; // gyro bias error
  439.  
  440. // Auxiliary variables to avoid repeated arithmetic
  441. float _halfq1 = 0.5f * q1;
  442. float _halfq2 = 0.5f * q2;
  443. float _halfq3 = 0.5f * q3;
  444. float _halfq4 = 0.5f * q4;
  445. float _2q1 = 2.0f * q1;
  446. float _2q2 = 2.0f * q2;
  447. float _2q3 = 2.0f * q3;
  448. float _2q4 = 2.0f * q4;
  449. // float _2q1q3 = 2.0f * q1 * q3;
  450. // float _2q3q4 = 2.0f * q3 * q4;
  451.  
  452. // Normalise accelerometer measurement
  453. norm = sqrt(ax * ax + ay * ay + az * az);
  454. if (norm == 0.0f) return; // handle NaN
  455. norm = 1.0f/norm;
  456. ax *= norm;
  457. ay *= norm;
  458. az *= norm;
  459.  
  460. // Compute the objective function and Jacobian
  461. f1 = _2q2 * q4 - _2q1 * q3 - ax;
  462. f2 = _2q1 * q2 + _2q3 * q4 - ay;
  463. f3 = 1.0f - _2q2 * q2 - _2q3 * q3 - az;
  464. J_11or24 = _2q3;
  465. J_12or23 = _2q4;
  466. J_13or22 = _2q1;
  467. J_14or21 = _2q2;
  468. J_32 = 2.0f * J_14or21;
  469. J_33 = 2.0f * J_11or24;
  470.  
  471. // Compute the gradient (matrix multiplication)
  472. hatDot1 = J_14or21 * f2 - J_11or24 * f1;
  473. hatDot2 = J_12or23 * f1 + J_13or22 * f2 - J_32 * f3;
  474. hatDot3 = J_12or23 * f2 - J_33 *f3 - J_13or22 * f1;
  475. hatDot4 = J_14or21 * f1 + J_11or24 * f2;
  476.  
  477. // Normalize the gradient
  478. norm = sqrt(hatDot1 * hatDot1 + hatDot2 * hatDot2 + hatDot3 * hatDot3 + hatDot4 * hatDot4);
  479. hatDot1 /= norm;
  480. hatDot2 /= norm;
  481. hatDot3 /= norm;
  482. hatDot4 /= norm;
  483.  
  484. // Compute estimated gyroscope biases
  485. gerrx = _2q1 * hatDot2 - _2q2 * hatDot1 - _2q3 * hatDot4 + _2q4 * hatDot3;
  486. gerry = _2q1 * hatDot3 + _2q2 * hatDot4 - _2q3 * hatDot1 - _2q4 * hatDot2;
  487. gerrz = _2q1 * hatDot4 - _2q2 * hatDot3 + _2q3 * hatDot2 - _2q4 * hatDot1;
  488.  
  489. // Compute and remove gyroscope biases
  490. gbiasx += gerrx * dt * zeta;
  491. gbiasy += gerry * dt * zeta;
  492. gbiasz += gerrz * dt * zeta;
  493. // gx -= gbiasx;
  494. // gy -= gbiasy;
  495. // gz -= gbiasz;
  496.  
  497. // Compute the quaternion derivative
  498. qDot1 = -_halfq2 * gx - _halfq3 * gy - _halfq4 * gz;
  499. qDot2 = _halfq1 * gx + _halfq3 * gz - _halfq4 * gy;
  500. qDot3 = _halfq1 * gy - _halfq2 * gz + _halfq4 * gx;
  501. qDot4 = _halfq1 * gz + _halfq2 * gy - _halfq3 * gx;
  502.  
  503. // Compute then integrate estimated quaternion derivative
  504. q1 += (qDot1 -(beta * hatDot1)) * dt;
  505. q2 += (qDot2 -(beta * hatDot2)) * dt;
  506. q3 += (qDot3 -(beta * hatDot3)) * dt;
  507. q4 += (qDot4 -(beta * hatDot4)) * dt;
  508.  
  509. // Normalize the quaternion
  510. norm = sqrt(q1 * q1 + q2 * q2 + q3 * q3 + q4 * q4); // normalise quaternion
  511. norm = 1.0f/norm;
  512. q[0] = q1 * norm;
  513. q[1] = q2 * norm;
  514. q[2] = q3 * norm;
  515. q[3] = q4 * norm;
  516.  
  517. }
  518.  
  519.  
  520. float MPU6050::invSqrt(float x)
  521. {
  522. float xhalf = 0.5f * x;
  523. int i = *(int*)&x; // evil floating point bit level hacking
  524. i = 0x5f3759df - (i >> 1); // what the fuck?
  525. x = *(float*)&i;
  526. x = x*(1.5f-(xhalf*x*x));
  527.  
  528. return x;
  529. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement