// MuTech Robotics - BIP1 Two-Legged Walking Robot with 8 Servos (Arduino Uno)
// 16-channel servo driver (PCA9685-type): VCC -> Arduino 5V, GND -> GND, SDA -> A4, SCL -> A5
// Servo power: battery pack -> driver V+ terminal (servos are NOT powered from the Arduino). All grounds joined.
// Channels: 0 L hip, 1 L thigh, 2 L knee, 3 L ankle, 4 R hip, 5 R thigh, 6 R knee, 7 R ankle
// Library: Adafruit PWM Servo Driver
//
// Start with TRIM all zero, stand the robot up, and adjust TRIM until it stands straight. Then let it walk.
// Strictly follow the description given with this video.
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver driver;
const int SERVOS = 8;
int TRIM[SERVOS] = {0, 0, 0, 0, 0, 0, 0, 0};          // degrees, to make the stand pose straight
int DIR[SERVOS] = {1, 1, 1, 1, -1, -1, -1, -1};       // right leg servos are mirrored
float now[SERVOS];

void setServo(int ch, float offset) {                  // offset from standing, in degrees
  float deg = constrain(90 + DIR[ch] * offset + TRIM[ch], 0, 180);
  driver.setPWM(ch, 0, map((long)(deg * 10), 0, 1800, 110, 510));   // ~0.5 to 2.5 ms at 50 Hz
  now[ch] = offset;
}

// Moves smoothly from the current pose to the target pose.
void pose(const int8_t target[SERVOS], int ms) {
  float from[SERVOS];
  for (int i = 0; i < SERVOS; i++) from[i] = now[i];
  const int steps = ms / 20;
  for (int s = 1; s <= steps; s++) {
    float k = (1 - cos(PI * s / steps)) / 2;          // ease in and out
    for (int i = 0; i < SERVOS; i++) setServo(i, from[i] + (target[i] - from[i]) * k);
    delay(20);
  }
}

//                        Lhip Lthi Lkne Lank Rhip Rthi Rkne Rank
const int8_t STAND[8]    = {  0,   0,   0,   0,   0,   0,   0,   0};
const int8_t LEAN_R[8]   = {  0,   0,   0, -12,   0,   0,   0, -12};   // weight onto the right foot
const int8_t LIFT_L[8]   = {  0,  25,  35, -12,   0,   0,   0, -12};   // left knee up
const int8_t STEP_L[8]   = {  0,  15,  10,  -5,   0, -10,  -5,  -5};   // left foot forward, down
const int8_t LEAN_L[8]   = {  0,   0,   0,  12,   0,   0,   0,  12};
const int8_t LIFT_R[8]   = {  0,   0,   0,  12,   0,  25,  35,  12};
const int8_t STEP_R[8]   = {  0, -10,  -5,   5,   0,  15,  10,   5};

void setup() {
  Serial.begin(9600);
  driver.begin();
  driver.setPWMFreq(50);
  for (int i = 0; i < SERVOS; i++) setServo(i, 0);
  delay(2000);                                         // time to set it on the floor
}

void loop() {
  pose(LEAN_R, 400); pose(LIFT_L, 300); pose(STEP_L, 300);
  pose(LEAN_L, 400); pose(LIFT_R, 300); pose(STEP_R, 300);
}
