// XBOT Motion Controller — XBOTNOW
// Board: ESP32-DevKitC V4 · Core: esp32 v3.x · Library: Adafruit MPU6050
// Output: JSON lines @ 115200 baud, 50 Hz
#include <Adafruit_MPU6050.h>

const int BTN[4] = {25, 27, 32, 33};
const float ALPHA = 0.96;        // complementary filter: trust gyro short-term
Adafruit_MPU6050 mpu;
float pitch = 0, roll = 0, gxBias = 0, gyBias = 0, gzBias = 0;
unsigned long last = 0;

void setup() {
  Serial.begin(115200);
  for (int i = 0; i < 4; i++) pinMode(BTN[i], INPUT_PULLUP);
  if (!mpu.begin()) { Serial.println("{\"err\":\"mpu\"}"); while (1) delay(500); }
  mpu.setFilterBandwidth(MPU6050_BAND_21_HZ);
  sensors_event_t a, g, t;
  for (int i = 0; i < 200; i++) {            // keep still: gyro bias
    mpu.getEvent(&a, &g, &t);
    gxBias += g.gyro.x; gyBias += g.gyro.y; gzBias += g.gyro.z; delay(5);
  }
  gxBias /= 200; gyBias /= 200; gzBias /= 200;
  last = micros();
}

void loop() {
  sensors_event_t a, g, t; mpu.getEvent(&a, &g, &t);
  float dt = (micros() - last) / 1e6; last = micros();
  float accPitch = atan2(-a.acceleration.x, sqrt(sq(a.acceleration.y) + sq(a.acceleration.z))) * 57.2958;
  float accRoll  = atan2(a.acceleration.y, a.acceleration.z) * 57.2958;
  pitch = ALPHA * (pitch + (g.gyro.y - gyBias) * 57.2958 * dt) + (1 - ALPHA) * accPitch;
  roll  = ALPHA * (roll  + (g.gyro.x - gxBias) * 57.2958 * dt) + (1 - ALPHA) * accRoll;

  int b = 0;
  for (int i = 0; i < 4; i++) if (digitalRead(BTN[i]) == LOW) b |= (1 << i);
  Serial.printf("{\"p\":%.1f,\"r\":%.1f,\"gz\":%.2f,\"b\":%d,\"t\":%lu}\n",
                pitch, roll, g.gyro.z - gzBias, b, millis());
  delay(20);                                 // ~50 Hz
}
