// VERTEBRA firmware outline (Seeed XIAO ESP32-S3). Not built yet.
// Three tendon spools at 90/210/330 deg, each a 28BYJ-48 on a TMC2209. VL53L5CX 8x8 in the bud tip looks down.
// Curl direction phi and amount theta -> tendon length changes dL_i = -r * theta * cos(phi - a_i), r = 13 mm.
#include <AccelStepper.h>
#include <SparkFun_VL53L5CX_Library.h>
AccelStepper t1(AccelStepper::DRIVER, D0, D1), t2(AccelStepper::DRIVER, D2, D3), t3(AccelStepper::DRIVER, D4, D5);
SparkFun_VL53L5CX cam; VL53L5CX_ResultsData z;
const float R_TEND = 13.0, SPOOL_R = 8.0, STEPS_PER_MM = 4096.0 / (2 * PI * SPOOL_R);
const float A[3] = {90, 210, 330};
void pose(float theta_deg, float phi_deg) {
  float th = radians(theta_deg);
  AccelStepper* m[3] = {&t1, &t2, &t3};
  for (int i = 0; i < 3; i++) m[i]->moveTo(-R_TEND * th * cos(radians(phi_deg - A[i])) * STEPS_PER_MM);
}
void setup() { Wire.begin(); cam.begin(); cam.setResolution(64); cam.startRanging();
  AccelStepper* m[3] = {&t1, &t2, &t3}; for (auto s : m) { s->setMaxSpeed(600); s->setAcceleration(300); } }
void loop() {
  if (cam.isDataReady() && cam.getRangingData(&z)) {
    int best = -1, d = 2500;                       // nearest zone under the lamp
    for (int i = 0; i < 64; i++) if (z.distance_mm[i] > 0 && z.distance_mm[i] < d) { d = z.distance_mm[i]; best = i; }
    if (best >= 0) { float x = (best % 8) - 3.5, y = (best / 8) - 3.5; pose(min(120.0, 25.0 * hypot(x, y)), degrees(atan2(y, x))); }
    else pose(0, 0);                               // nobody: hang straight
  }
  t1.run(); t2.run(); t3.run();
}
