// Motion Controller — XBOTNOW
// Board: ESP32-DevKitC V4 · Core: esp32 v3.x · Library: Adafruit MPU6050
#include <WiFi.h>
#include <esp_now.h>
#include <esp_wifi.h>
#include <Adafruit_MPU6050.h>

uint8_t CAR_MAC[] = {0x24, 0x6F, 0x28, 0x00, 0x00, 0x00};  // from car Serial Monitor
const int DRIVE_BTN = 27;
const float DEADZONE = 5;      // degrees
const float MAX_TILT = 35;     // degrees for full speed

struct DrivePacket { int16_t left; int16_t right; uint8_t seq; };
Adafruit_MPU6050 mpu;
float pitch0 = 0, roll0 = 0, pitchF = 0, rollF = 0;
uint8_t seq = 0;

void readTilt(float& pitch, float& roll) {
  sensors_event_t a, g, t; mpu.getEvent(&a, &g, &t);
  pitch = atan2(a.acceleration.x, sqrt(sq(a.acceleration.y) + sq(a.acceleration.z))) * 57.3;
  roll  = atan2(a.acceleration.y, a.acceleration.z) * 57.3;
}

float axis(float deg) {           // degrees -> -1..1 with deadzone
  if (fabs(deg) < DEADZONE) return 0;
  return constrain((deg - copysign(DEADZONE, deg)) / (MAX_TILT - DEADZONE), -1, 1);
}

void setup() {
  Serial.begin(115200);
  pinMode(DRIVE_BTN, INPUT_PULLUP);
  if (!mpu.begin()) { Serial.println("MPU6050 not found"); while (1) delay(10); }
  float p, r, sp = 0, sr = 0;
  for (int i = 0; i < 50; i++) { readTilt(p, r); sp += p; sr += r; delay(20); }
  pitch0 = sp / 50; roll0 = sr / 50;          // "level" = how you hold it now

  WiFi.mode(WIFI_STA);
  esp_wifi_set_channel(1, WIFI_SECOND_CHAN_NONE);
  esp_now_init();
  esp_now_peer_info_t peer = {};
  memcpy(peer.peer_addr, CAR_MAC, 6);
  peer.channel = 1;
  esp_now_add_peer(&peer);
}

void loop() {
  float p, r; readTilt(p, r);
  pitchF = 0.8 * pitchF + 0.2 * (p - pitch0);   // smoothing
  rollF  = 0.8 * rollF  + 0.2 * (r - roll0);

  float throttle = -axis(pitchF);   // tilt forward = forward (flip sign if needed)
  float steer = axis(rollF);
  int left = 0, right = 0;
  if (digitalRead(DRIVE_BTN) == LOW) {
    left  = constrain((throttle + steer) * 255, -255, 255);
    right = constrain((throttle - steer) * 255, -255, 255);
  }
  DrivePacket pkt = {(int16_t)left, (int16_t)right, seq++};
  esp_now_send(CAR_MAC, (uint8_t*)&pkt, sizeof(pkt));
  delay(50);                        // 20 packets per second
}
