I am using an MPU6050 gyro to move some RGB leds. All works fine.
But, the MPU6050 will once in a moment return a spurious value that triggers part of my code (basically if the X or Y move more than a certain amount of degrees.
It sits there lovely returning 0,0,0,0,0,0,0,0,0,0 and then suddenly it will throw in a random -7 or something.
Power supply is nice and smooth and I think it's just part of the way gyro are.
I wrote some ropey sampling code that kinda works (I'll await the horror gasps because it has a delay(5) in it.... ).
But, it does smooth the results nicely.
Any more sampling than 10 times slows the loop (and therefore the movement) of the RGBs too much (they move left and right with the Gyro).
void getGYRO() { // Sample the gyro data multiple times
for (i = 0; i <= 10; i++) {
mpu.update();
delay(5);
angleXsum = angleXsum + mpu.getAngleX();
angleYsum = angleYsum + mpu.getAngleY();
angleX = (angleXsum / 10);
angleY = (angleYsum / 10);
if (angleX < -20) { // Confine the tilt extremes
angleX = -20;
}
if (angleX > 20) {
angleX = 20;
}
if (angleY < -20) {
angleY = -20;
}
if (angleY > 20) {
angleY = 20;
}
angleXsum = 0;
angleYsum = 0;
Serial.print("X Sum: "); Serial.println(angleX);
Serial.print("Y Sum: "); Serial.println(angleY);
}
}
Also, the Serial prints are usually commented out. So they don't slow the loop.
My guess is the loop allows x and y to change enough to undo the smoothing. Will a counter work?
int a, aa;
void setup() {
Serial.begin(115200);
randomSeed(analogRead(A0));
}
void loop() {
a++;
if (a > 10) {
a = 0;
Serial.println(aa / 10.0);
aa = 0;
}
aa += random(100);
}