Michael Seyoum
Published

Robot leg inverse kinematics and Generic Gait with ESP32

This is a showcase for those who want to build a complex n-legged robotic inverse kinematics and gait sequence but first catch the basics!

BeginnerProtip1 hour175
Robot leg inverse kinematics and Generic Gait with ESP32

Things used in this project

Hardware components

SG 90 servo motor
×1

Software apps and online services

esp32

Story

Read more

Code

Arduino ESP32 Circular Foot Motion Code

Arduino
Generates a circle in X/Y space
Moves the foot smoothly around that circle
Converts each X/Y point into hip and knee angles using IK
Sends angles to servos
#include <Arduino.h>

// Servo pins
const int HIP_PIN  = 14;
const int KNEE_PIN = 27;

// PWM settings (ESP32)
const int HIP_CH  = 0;
const int KNEE_CH = 1;
const int PWM_FREQ = 50;
const int PWM_RES  = 16;

// Leg geometry (mm)
const float L1 = 50.0;
const float L2 = 50.0;

// Circle parameters
float centerX = 60;     // circle center X
float centerY = 0;      // circle center Y
float radius  = 20;     // circle radius
float angle   = 0;      // radians
float step    = 0.05;   // speed of rotation

// Convert angle (deg) to PWM duty
uint32_t angleToDuty(float deg) {
  deg = constrain(deg, 0, 180);
  float us = map(deg, 0, 180, 500, 2500);
  return (uint32_t)((us / 20000.0) * 65535);
}

void setup() {
  ledcSetup(HIP_CH, PWM_FREQ, PWM_RES);
  ledcSetup(KNEE_CH, PWM_FREQ, PWM_RES);

  ledcAttachPin(HIP_PIN, HIP_CH);
  ledcAttachPin(KNEE_PIN, KNEE_CH);
}

void loop() {
  // Generate circular foot position
  float x = centerX + radius * cos(angle);
  float y = centerY + radius * sin(angle);

  applyIK(x, y);

  angle += step;
  if (angle > TWO_PI) angle = 0;

  delay(20);
}

void applyIK(float x, float y) {
  float D = sqrt(x * x + y * y);
  D = constrain(D, 10, L1 + L2 - 5);

  // IK math
  float alpha = atan2(y, x);
  float beta  = acos((L1*L1 + D*D - L2*L2) / (2 * L1 * D));
  float theta1 = alpha + beta;
  float theta2 = acos((L1*L1 + L2*L2 - D*D) / (2 * L1 * L2));

  // Convert to degrees
  float hipDeg  = theta1 * 180.0 / PI;
  float kneeDeg = theta2 * 180.0 / PI;

  // Adjust offsets if needed
  hipDeg  += 90;
  kneeDeg = 180 - kneeDeg;

  ledcWrite(HIP_CH, angleToDuty(hipDeg));
  ledcWrite(KNEE_CH, angleToDuty(kneeDeg));
}

Credits

Michael Seyoum
9 projects • 8 followers
Knack for Tech and Science! Computer scientist!

Comments