The code for the Arduino UNO + W5100 + MPU6050

This is my code for MPU6050.

Cayenne-MPU6050.txt (1.4 KB)

Hi @tad.dvor,

This could be useful. I added some comments and changed variable names. Thx, Craig

#include "Wire.h"
#include "Math.h"
#include "I2Cdev.h"
#include "MPU6050.h"
#include <CayenneEthernet.h>

#define CAYENNE_PRINT Serial  
#define VIRTUAL_PINX V2
#define VIRTUAL_PINY V3   

MPU6050 accelerometer;

const float pi = 3.141592;
const int avg_max = 100;
int16_t ax, ay, az;
float x, y, z;
int avg_count;
float _angle_x, angle_x, _angle_y, angle_y;
long ax_avg, ay_avg, az_avg;

char token[] = "token";

void setup() {

    Serial.begin(38400);   
    Wire.begin();  

    Cayenne.begin(token);
    Serial.println("Cayenne Connected..."); 

    accelerometer.initialize();    
    if (accelerometer.testConnection()) {
        Serial.println("Accelerometer Connected...");  
    }
}
 
void loop() {
    
    //process Cayenne
    Cayenne.run();

    //read accelerometer
    accelerometer.getAcceleration(&ax, &ay, &az);  

    //accumulate averages
    ax_avg = ax_avg + ax;
    ay_avg = ay_avg + ay;
    az_avg = az_avg + az;
    avg_count++;

    //got all the sample?
    if (avg_count == avg_max)
    {
     //calculate averages
     x = ax_avg/avg_max;
     y = ay_avg/avg_max
     z = az_avg/avg_max

     //compute angles
     angle_x = atan2(x, sqrt(square(y) + square(z))      )/(pi/180);
     angle_y = atan2(y, sqrt(square(x) + square(z))      )/(pi/180);

     //initialize for next pass
     avg_count = 0;
     ax_p = 0;
     ay_p = 0;
     az_p = 0;   

    //print results
    Serial.print(angle_x);
    Serial.print("\t"); 
    Serial.println(angle_y);

    }   
}

CAYENNE_OUT(VIRTUAL_PINX)
{
  Cayenne.virtualWrite(VIRTUAL_PINX, angle_x);
}
CAYENNE_OUT(VIRTUAL_PINY)
{
  Cayenne.virtualWrite(VIRTUAL_PINY, angle_y);
}

Thanks, I forgot to translate it from Czech into English :slight_smile:.

Tadeas

No problem. Keep coding, I am happy to translate.

Used to work for a Japanese company, so I have lots of practice :stuck_out_tongue:

Cheers,

Craig

1 Like

Well done sir!

@kreggly is right, this code could be really useful. Thanks for submitting this! Iā€™m ordering MPU6050 sensor now :slight_smile:

-B