Skip to content

Instantly share code, notes, and snippets.

@imneonizer
Last active March 1, 2022 08:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imneonizer/2afd15100ff016524a3347ff133ae3cd to your computer and use it in GitHub Desktop.
Save imneonizer/2afd15100ff016524a3347ff133ae3cd to your computer and use it in GitHub Desktop.
MPU6050_esp8266
#include <Wire.h>
#include <ESP8266WiFi.h>
const int MPU_addr = 0x68; // I2C address of the MPU-6050
int16_t AcX, AcY, AcZ, Tmp, GyX, GyY, GyZ;
float ax = 0, ay = 0, az = 0, gx = 0, gy = 0, gz = 0, Amp=0;
// SCL -> D1
// SDA -> D2
void setup()
{
Serial.begin(115200);
Wire.begin();
Wire.beginTransmission(MPU_addr);
Wire.write(0x6B); // PWR_MGMT_1 register
Wire.write(0); // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
}
void loop(){
// create an array to store sampling data for inferencing
// 19Hz * 5 sec -> 95 samples, for 7 axis input
float buffer[95][7];
// fill data into the buffer
for (int i=0; i<=95; i++){
mpu_read();
buffer[i][0] = ax;
buffer[i][1] = ay;
buffer[i][2] = az;
buffer[i][3] = gx;
buffer[i][4] = gy;
buffer[i][5] = gz;
buffer[i][6] = Amp;
Serial.print(ax);
Serial.print(",");
Serial.print(ay);
Serial.print(",");
Serial.print(az);
Serial.print(",");
Serial.print(gx);
Serial.print(",");
Serial.print(gy);
Serial.print(",");
Serial.print(gz);
Serial.print(",");
Serial.println(Amp);
delay(50); // to maintain the 19Hz frequency
}
}
void mpu_read(){
// read sensor data
Wire.beginTransmission(MPU_addr);
Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU_addr, 14, true); // request a total of 14 registers
AcX = Wire.read() << 8 | Wire.read(); // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
AcY = Wire.read() << 8 | Wire.read(); // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ = Wire.read() << 8 | Wire.read(); // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp = Wire.read() << 8 | Wire.read(); // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX = Wire.read() << 8 | Wire.read(); // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY = Wire.read() << 8 | Wire.read(); // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ = Wire.read() << 8 | Wire.read(); // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
// scale the readings
ax = (AcX - 2050) / 16384.00;
ay = (AcY - 77) / 16384.00;
az = (AcZ - 1947) / 16384.00;
gx = (GyX + 270) / 131.07;
gy = (GyY - 351) / 131.07;
gz = (GyZ + 136) / 131.07;
// calculating Amplitute vactor for 3 axis
float Raw_Amp = pow(pow(ax, 2) + pow(ay, 2) + pow(az, 2), 0.5);
Amp = Raw_Amp * 10; // Mulitiplied by 10 bcz values are between 0 to 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment