Hi!
Recently I've been working with MPU6050 and Madgwick filter. Right now my results are quite alright. I'm reading accelerometer and gyroscope data and then this library GitHub - arduino-libraries/MadgwickAHRS: Arduino implementation of the MadgwickAHRS algorithm gives me quaternion which I made public so I can use it later. Then I visualize orientation using pyOpenGL. I want to improve this project by adding magnetometer but when I used Adafruit HMC5883L library there was a big delay and yaw slowly snaps into specific direction. Can you help me improve my code in any way?
#include "Wire.h"
#include <MPU6050_light.h>
#include <MadgwickAHRS.h>
MPU6050 mpu(Wire);
Madgwick filter;
unsigned long microsPerReading, microsPrevious;
void setup() {
Serial.begin(9600);
Wire.begin();
byte status = mpu.begin();
filter.begin(25);
Serial.print(F("MPU6050 status: "));
Serial.println(status);
while(status!=0){ }
delay(1000);
mpu.calcOffsets(true,true);
microsPerReading = 1000000 / 25;
microsPrevious = micros();
}
void loop() {
float ax, ay, az;
float gx, gy, gz;
unsigned long microsNow;
microsNow = micros();
if (microsNow - microsPrevious >= microsPerReading) {
mpu.update();
ax = mpu.getAccX();
ay = mpu.getAccY();
az = mpu.getAccZ();
gx = mpu.getGyroX();
gy = mpu.getGyroY();
gz = mpu.getGyroZ();
filter.updateIMU(gx, gy, gz, ax, ay, az);
Serial.print(filter.q0);
Serial.print(" ");
Serial.print(filter.q1);
Serial.print(" ");
Serial.print(filter.q2);
Serial.print(" ");
Serial.println(filter.q3);
microsPrevious = microsPrevious + microsPerReading;
}
}
import pygame
from pygame.locals import *
import serial
from OpenGL.GL import *
from OpenGL.GLU import *
class Cube():
def __init__(self):
self.verticies = (
(3, -1, -4),
(3, 1, -4),
(-3, 1, -4),
(-3, -1, -4),
(3, -1, 4),
(3, 1, 4),
(-3, -1, 4),
(-3, 1, 4)
)
self.edges = (
(0, 1),
(0, 3),
(0, 4),
(2, 1),
(2, 3),
(2, 7),
(6, 3),
(6, 4),
(6, 7),
(5, 1),
(5, 4),
(5, 7)
)
def update(self, w, x, y, z):
glPushMatrix()
glRotatef(w*360, y, z, x)
glBegin(GL_LINES)
for edge in self.edges:
for vertex in edge:
glVertex3fv(self.verticies[vertex])
glEnd()
glPopMatrix()
def main():
ser = serial.Serial('COM5', 9600)
pygame.init()
display = (800, 600)
pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
glTranslatef(0.0, 0.0, -20)
cube = Cube()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
data = ser.readline().decode('UTF-8')
data = data.split(' ')
print(data)
try:
cube.update(float(data[0]), float(data[1]), float(data[2]), float(data[3]))
except:
pass
pygame.display.flip()
main()