#include "I2Cdev.h"
#include "MPU6050.h"
#include "Wire.h"
#include "Kalman.h"
//MPU
MPU6050 MPU6050;
int16_t accx, accy, accz, gyrox, gyroy, gyroz;
int16_t gyrox_rate, gyroy_rate, gyroz_rate;
int16_t accy_euler, accx_angle, accy_angle;
bool MPU6050_state;
//Kalman
Kalman kalmanX;
Kalman kalmanY;
uint32_t timer;
float kalman_anglex, kalman_angley;
void setup()
{
pinMode(3, OUTPUT);
pinMode(9, OUTPUT);
pinMode(10, OUTPUT);
pinMode(11, OUTPUT);
TCCR1A = 0;
TCCR1B = 0;
TCCR2A = 0;
TCCR2B = 0;
TCCR1A |= _BV(COM1A1) | _BV(COM1B1) | _BV(WGM10);
TCCR1B |= _BV(CS10) | _BV(CS11);
TCCR2A |= _BV(COM2A1) | _BV(COM2B1) | _BV(WGM20);
TCCR2B |= _BV(CS22);
//OCR1A = PIN 9
//OCR1B = PIN 10
//OCR2A = PIN 11
//OCR2B = PIN 3
OCR1A = 900>>3;
OCR1B = 900>>3;
OCR2A = 900>>3;
OCR2B = 900>>3;
delay(1000);
Wire.begin();
Serial.begin(9600);
MPU6050.initialize();
MPU6050_state = MPU6050.testConnection();
while(MPU6050_state == 0)
{
Serial.println("Keine Verbindung zu MPU");
delay(10000);
MPU6050_state = MPU6050.testConnection();
}
if(MPU6050_state == 1)
{
Serial.println("Verbindung zu MPU");
}
accy_euler = atan2(accy, accz);
accx_angle = (atan2(-accx, (accy*sin(accy_euler)+accz*cos(accy_euler)))) * 180 / 3.14;
accy_angle = (atan2(accy, accz)) * 180 / 3.14;
kalmanX.setAngle(accx_angle);
kalmanY.setAngle(accy_angle);
timer = micros();
}
void loop()
{
float dt = (float)(micros() - timer) / 1000000;
timer = micros();
MPU6050.setFullScaleGyroRange(MPU6050_GYRO_FS_2000); //Muss in void loop() sein
MPU6050.getMotion6(&accx, &accy, &accz, &gyrox, &gyroy, &gyroz);
accy_euler = atan2(accy, accz);
accx_angle = (atan2(-accx, (accy*sin(accy_euler)+accz*cos(accy_euler)))) * 180 / 3.14;
accy_angle = (atan2(accy, accz)) * 180 / 3.14;
gyrox_rate = (gyrox + 12) / 16.4;
gyroy_rate = (gyroy - 29) / 16.4;
gyroz_rate = (gyroz + 17) / 16.4;
kalmanX.setAngle(accx_angle);
kalmanY.setAngle(accy_angle);
kalman_anglex = kalmanX.getAngle(accx_angle, gyrox_rate, dt);
kalman_angley = kalmanY.getAngle(accy_angle, gyroy_rate, dt);
//RC
static int16_t throttle = 1300;
//PID Setup
float PC = 0.00;
float IC = 0.00;
float DC = 0.00;
//PID
float error = 0.00 - kalman_angley;
static float error_summe = 0;
static float error_old = 0;
int16_t P = (int16_t)(error * PC);
error_summe += (error * dt);
int16_t I = (int16_t)(error_summe * IC);
int16_t D = (int16_t)((error - error_old) * DC);
error_old = error;
//Motor
OCR1A = (throttle + P + D + I)>>3;
OCR1B = (throttle - P - D - I)>>3;
OCR2A = (throttle - P - D - I)>>3;
OCR2B = (throttle + P + D + I)>>3;
}