Advertisement
MrLunk

Balancing robot MPU 6050 - gy 521 CALIBARTION

Mar 21st, 2021
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 13.44 KB | None | 0 0
  1. // MPU6050 offset-finder, based on Jeff Rowberg's MPU6050_RAW
  2. // 2016-10-19 by Robert R. Fenichel (bob@fenichel.net)
  3.  
  4. // I2C device class (I2Cdev) demonstration Arduino sketch for MPU6050 class
  5. // 10/7/2011 by Jeff Rowberg <jeff@rowberg.net>
  6. // Updates should (hopefully) always be available at https://github.com/jrowberg/i2cdevlib
  7. //
  8. // Changelog:
  9. // 2019-07-11 - added PID offset generation at begninning Generates first offsets
  10. // - in @ 6 seconds and completes with 4 more sets @ 10 seconds
  11. // - then continues with origional 2016 calibration code.
  12. // 2016-11-25 - added delays to reduce sampling rate to ~200 Hz
  13. // added temporizing printing during long computations
  14. // 2016-10-25 - requires inequality (Low < Target, High > Target) during expansion
  15. // dynamic speed change when closing in
  16. // 2016-10-22 - cosmetic changes
  17. // 2016-10-19 - initial release of IMU_Zero
  18. // 2013-05-08 - added multiple output formats
  19. // - added seamless Fastwire support
  20. // 2011-10-07 - initial release of MPU6050_RAW
  21.  
  22. /* ============================================
  23. I2Cdev device library code is placed under the MIT license
  24. Copyright (c) 2011 Jeff Rowberg
  25.  
  26. Permission is hereby granted, free of charge, to any person obtaining a copy
  27. of this software and associated documentation files (the "Software"), to deal
  28. in the Software without restriction, including without limitation the rights
  29. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  30. copies of the Software, and to permit persons to whom the Software is
  31. furnished to do so, subject to the following conditions:
  32.  
  33. The above copyright notice and this permission notice shall be included in
  34. all copies or substantial portions of the Software.
  35.  
  36. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  37. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  38. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  39. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  40. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  41. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  42. THE SOFTWARE.
  43.  
  44. If an MPU6050
  45. * is an ideal member of its tribe,
  46. * is properly warmed up,
  47. * is at rest in a neutral position,
  48. * is in a location where the pull of gravity is exactly 1g, and
  49. * has been loaded with the best possible offsets,
  50. then it will report 0 for all accelerations and displacements, except for
  51. Z acceleration, for which it will report 16384 (that is, 2^14). Your device
  52. probably won't do quite this well, but good offsets will all get the baseline
  53. outputs close to these target values.
  54.  
  55. Put the MPU6050 on a flat and horizontal surface, and leave it operating for
  56. 5-10 minutes so its temperature gets stabilized.
  57.  
  58. Run this program. A "----- done -----" line will indicate that it has done its best.
  59. With the current accuracy-related constants (NFast = 1000, NSlow = 10000), it will take
  60. a few minutes to get there.
  61.  
  62. Along the way, it will generate a dozen or so lines of output, showing that for each
  63. of the 6 desired offsets, it is
  64. * first, trying to find two estimates, one too low and one too high, and
  65. * then, closing in until the bracket can't be made smaller.
  66.  
  67. The line just above the "done" line will look something like
  68. [567,567] --> [-1,2] [-2223,-2223] --> [0,1] [1131,1132] --> [16374,16404] [155,156] --> [-1,1] [-25,-24] --> [0,3] [5,6] --> [0,4]
  69. As will have been shown in interspersed header lines, the six groups making up this
  70. line describe the optimum offsets for the X acceleration, Y acceleration, Z acceleration,
  71. X gyro, Y gyro, and Z gyro, respectively. In the sample shown just above, the trial showed
  72. that +567 was the best offset for the X acceleration, -2223 was best for Y acceleration,
  73. and so on.
  74.  
  75. The need for the delay between readings (usDelay) was brought to my attention by Nikolaus Doppelhammer.
  76. ===============================================
  77. */
  78.  
  79. // I2Cdev and MPU6050 must be installed as libraries, or else the .cpp/.h files
  80. // for both classes must be in the include path of your project
  81. #include "I2Cdev.h"
  82. #include "MPU6050.h"
  83.  
  84. // Arduino Wire library is required if I2Cdev I2CDEV_ARDUINO_WIRE implementation
  85. // is used in I2Cdev.h
  86. #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  87. #include "Wire.h"
  88. #endif
  89.  
  90. // class default I2C address is 0x68
  91. // specific I2C addresses may be passed as a parameter here
  92. // AD0 low = 0x68 (default for InvenSense evaluation board)
  93. // AD0 high = 0x69
  94. MPU6050 accelgyro;
  95. //MPU6050 accelgyro(0x69); // <-- use for AD0 high
  96.  
  97.  
  98. const char LBRACKET = '[';
  99. const char RBRACKET = ']';
  100. const char COMMA = ',';
  101. const char BLANK = ' ';
  102. const char PERIOD = '.';
  103.  
  104. const int iAx = 0;
  105. const int iAy = 1;
  106. const int iAz = 2;
  107. const int iGx = 3;
  108. const int iGy = 4;
  109. const int iGz = 5;
  110.  
  111. const int usDelay = 3150; // empirical, to hold sampling to 200 Hz
  112. const int NFast = 1000; // the bigger, the better (but slower)
  113. const int NSlow = 10000; // ..
  114. const int LinesBetweenHeaders = 5;
  115. int LowValue[6];
  116. int HighValue[6];
  117. int Smoothed[6];
  118. int LowOffset[6];
  119. int HighOffset[6];
  120. int Target[6];
  121. int LinesOut;
  122. int N;
  123.  
  124. void ForceHeader()
  125. { LinesOut = 99; }
  126.  
  127. void GetSmoothed()
  128. { int16_t RawValue[6];
  129. int i;
  130. long Sums[6];
  131. for (i = iAx; i <= iGz; i++)
  132. { Sums[i] = 0; }
  133. // unsigned long Start = micros();
  134.  
  135. for (i = 1; i <= N; i++)
  136. { // get sums
  137. accelgyro.getMotion6(&RawValue[iAx], &RawValue[iAy], &RawValue[iAz],
  138. &RawValue[iGx], &RawValue[iGy], &RawValue[iGz]);
  139. if ((i % 500) == 0)
  140. Serial.print(PERIOD);
  141. delayMicroseconds(usDelay);
  142. for (int j = iAx; j <= iGz; j++)
  143. Sums[j] = Sums[j] + RawValue[j];
  144. } // get sums
  145. // unsigned long usForN = micros() - Start;
  146. // Serial.print(" reading at ");
  147. // Serial.print(1000000/((usForN+N/2)/N));
  148. // Serial.println(" Hz");
  149. for (i = iAx; i <= iGz; i++)
  150. { Smoothed[i] = (Sums[i] + N/2) / N ; }
  151. } // GetSmoothed
  152.  
  153. void Initialize()
  154. {
  155. // join I2C bus (I2Cdev library doesn't do this automatically)
  156. #if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
  157. Wire.begin();
  158. #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
  159. Fastwire::setup(400, true);
  160. #endif
  161.  
  162. Serial.begin(115200);
  163.  
  164. // initialize device
  165. Serial.println("Initializing I2C devices...");
  166. accelgyro.initialize();
  167.  
  168. // verify connection
  169. Serial.println("Testing device connections...");
  170. Serial.println(accelgyro.testConnection() ? "MPU6050 connection successful" : "MPU6050 connection failed");
  171. Serial.println("PID tuning Each Dot = 100 readings");
  172. /*A tidbit on how PID (PI actually) tuning works.
  173. When we change the offset in the MPU6050 we can get instant results. This allows us to use Proportional and
  174. integral of the PID to discover the ideal offsets. Integral is the key to discovering these offsets, Integral
  175. uses the error from set-point (set-point is zero), it takes a fraction of this error (error * ki) and adds it
  176. to the integral value. Each reading narrows the error down to the desired offset. The greater the error from
  177. set-point, the more we adjust the integral value. The proportional does its part by hiding the noise from the
  178. integral math. The Derivative is not used because of the noise and because the sensor is stationary. With the
  179. noise removed the integral value lands on a solid offset after just 600 readings. At the end of each set of 100
  180. readings, the integral value is used for the actual offsets and the last proportional reading is ignored due to
  181. the fact it reacts to any noise.
  182. */
  183. accelgyro.CalibrateAccel(6);
  184. accelgyro.CalibrateGyro(6);
  185. Serial.println("\nat 600 Readings");
  186. accelgyro.PrintActiveOffsets();
  187. Serial.println();
  188. accelgyro.CalibrateAccel(1);
  189. accelgyro.CalibrateGyro(1);
  190. Serial.println("700 Total Readings");
  191. accelgyro.PrintActiveOffsets();
  192. Serial.println();
  193. accelgyro.CalibrateAccel(1);
  194. accelgyro.CalibrateGyro(1);
  195. Serial.println("800 Total Readings");
  196. accelgyro.PrintActiveOffsets();
  197. Serial.println();
  198. accelgyro.CalibrateAccel(1);
  199. accelgyro.CalibrateGyro(1);
  200. Serial.println("900 Total Readings");
  201. accelgyro.PrintActiveOffsets();
  202. Serial.println();
  203. accelgyro.CalibrateAccel(1);
  204. accelgyro.CalibrateGyro(1);
  205. Serial.println("1000 Total Readings");
  206. accelgyro.PrintActiveOffsets();
  207. Serial.println("\n\n Any of the above offsets will work nice \n\n Lets proof the PID tuning using another method:");
  208. } // Initialize
  209.  
  210. void SetOffsets(int TheOffsets[6])
  211. { accelgyro.setXAccelOffset(TheOffsets [iAx]);
  212. accelgyro.setYAccelOffset(TheOffsets [iAy]);
  213. accelgyro.setZAccelOffset(TheOffsets [iAz]);
  214. accelgyro.setXGyroOffset (TheOffsets [iGx]);
  215. accelgyro.setYGyroOffset (TheOffsets [iGy]);
  216. accelgyro.setZGyroOffset (TheOffsets [iGz]);
  217. } // SetOffsets
  218.  
  219. void ShowProgress()
  220. { if (LinesOut >= LinesBetweenHeaders)
  221. { // show header
  222. Serial.println("\tXAccel\t\t\tYAccel\t\t\t\tZAccel\t\t\tXGyro\t\t\tYGyro\t\t\tZGyro");
  223. LinesOut = 0;
  224. } // show header
  225. Serial.print(BLANK);
  226. for (int i = iAx; i <= iGz; i++)
  227. { Serial.print(LBRACKET);
  228. Serial.print(LowOffset[i]),
  229. Serial.print(COMMA);
  230. Serial.print(HighOffset[i]);
  231. Serial.print("] --> [");
  232. Serial.print(LowValue[i]);
  233. Serial.print(COMMA);
  234. Serial.print(HighValue[i]);
  235. if (i == iGz)
  236. { Serial.println(RBRACKET); }
  237. else
  238. { Serial.print("]\t"); }
  239. }
  240. LinesOut++;
  241. } // ShowProgress
  242.  
  243. void PullBracketsIn()
  244. { boolean AllBracketsNarrow;
  245. boolean StillWorking;
  246. int NewOffset[6];
  247.  
  248. Serial.println("\nclosing in:");
  249. AllBracketsNarrow = false;
  250. ForceHeader();
  251. StillWorking = true;
  252. while (StillWorking)
  253. { StillWorking = false;
  254. if (AllBracketsNarrow && (N == NFast))
  255. { SetAveraging(NSlow); }
  256. else
  257. { AllBracketsNarrow = true; }// tentative
  258. for (int i = iAx; i <= iGz; i++)
  259. { if (HighOffset[i] <= (LowOffset[i]+1))
  260. { NewOffset[i] = LowOffset[i]; }
  261. else
  262. { // binary search
  263. StillWorking = true;
  264. NewOffset[i] = (LowOffset[i] + HighOffset[i]) / 2;
  265. if (HighOffset[i] > (LowOffset[i] + 10))
  266. { AllBracketsNarrow = false; }
  267. } // binary search
  268. }
  269. SetOffsets(NewOffset);
  270. GetSmoothed();
  271. for (int i = iAx; i <= iGz; i++)
  272. { // closing in
  273. if (Smoothed[i] > Target[i])
  274. { // use lower half
  275. HighOffset[i] = NewOffset[i];
  276. HighValue[i] = Smoothed[i];
  277. } // use lower half
  278. else
  279. { // use upper half
  280. LowOffset[i] = NewOffset[i];
  281. LowValue[i] = Smoothed[i];
  282. } // use upper half
  283. } // closing in
  284. ShowProgress();
  285. } // still working
  286.  
  287. } // PullBracketsIn
  288.  
  289. void PullBracketsOut()
  290. { boolean Done = false;
  291. int NextLowOffset[6];
  292. int NextHighOffset[6];
  293.  
  294. Serial.println("expanding:");
  295. ForceHeader();
  296.  
  297. while (!Done)
  298. { Done = true;
  299. SetOffsets(LowOffset);
  300. GetSmoothed();
  301. for (int i = iAx; i <= iGz; i++)
  302. { // got low values
  303. LowValue[i] = Smoothed[i];
  304. if (LowValue[i] >= Target[i])
  305. { Done = false;
  306. NextLowOffset[i] = LowOffset[i] - 1000;
  307. }
  308. else
  309. { NextLowOffset[i] = LowOffset[i]; }
  310. } // got low values
  311.  
  312. SetOffsets(HighOffset);
  313. GetSmoothed();
  314. for (int i = iAx; i <= iGz; i++)
  315. { // got high values
  316. HighValue[i] = Smoothed[i];
  317. if (HighValue[i] <= Target[i])
  318. { Done = false;
  319. NextHighOffset[i] = HighOffset[i] + 1000;
  320. }
  321. else
  322. { NextHighOffset[i] = HighOffset[i]; }
  323. } // got high values
  324. ShowProgress();
  325. for (int i = iAx; i <= iGz; i++)
  326. { LowOffset[i] = NextLowOffset[i]; // had to wait until ShowProgress done
  327. HighOffset[i] = NextHighOffset[i]; // ..
  328. }
  329. } // keep going
  330. } // PullBracketsOut
  331.  
  332. void SetAveraging(int NewN)
  333. { N = NewN;
  334. Serial.print("averaging ");
  335. Serial.print(N);
  336. Serial.println(" readings each time");
  337. } // SetAveraging
  338.  
  339. void setup()
  340. { Initialize();
  341. for (int i = iAx; i <= iGz; i++)
  342. { // set targets and initial guesses
  343. Target[i] = 0; // must fix for ZAccel
  344. HighOffset[i] = 0;
  345. LowOffset[i] = 0;
  346. } // set targets and initial guesses
  347. Target[iAz] = 16384;
  348. SetAveraging(NFast);
  349.  
  350. PullBracketsOut();
  351. PullBracketsIn();
  352.  
  353. Serial.println("-------------- done --------------");
  354. } // setup
  355.  
  356. void loop()
  357. {
  358. } // loop
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement