crawling-panther

crawling-panther

A 363 g quadruped that walks on eight hobby servos and an Arduino Uno. It measures the distance ahead, backs away from obstacles, turns left and walks on. The diagram below runs the same gaits as the sketches, with the same angles.

  • Gait v3 runs on the real robot: it walks toward its distance sensor, avoids obstacles and does push-ups.
  • Gaits v1 (by hand) and v2 (learned in simulation) are the earlier versions. Each keeps the robot drawing of its time.
  • 363gtotal weight
  • 8servosMG90S, two per leg
  • 500candidatesgaits tried in simulation
  • 175cmsimulated in 40 cycles
Robot model (live)
Starting
R1 + L2 R2 + L1 on the ground knee lifted

Hardware

The body and legs are 3D printed. Each leg has a hip servo that swings it forward and back, and a knee servo that lifts it.

Controller
Arduino Uno with a Sensor Shield v5.0
Actuators
8 TowerPro MG90S micro servos, 2 per leg
Structure
3D-printed body and legs
Weight
363 g, ready to walk
Sensors
HC-SR04 ultrasonic distance sensor, MPU6050 gyroscope and accelerometer

Parts

PartQtyJob
Arduino Uno1Runs the gait and generates the servo signals
Sensor Shield v5.01Breaks out signal, power and ground pins for each servo
TowerPro MG90S servo84 hips and 4 knees
External battery17.4 V. Powers the servos and the Arduino
5 V voltage regulator module1Turns the battery voltage into 5 V for the servos and, through its USB port, for the Arduino. Its own capacitors smooth the supply
Rocker switch1Cuts the power from the battery
HC-SR04 ultrasonic sensor1Sits at the front end of the body and measures the distance ahead. The robot turns away below 10 cm
MPU6050 module1Gyroscope and accelerometer, mounted upright on the body and wired to the Arduino's I²C pins. The sketches do not read it
3D-printed body and legs1 setFrame and four two-joint legs

Power and signal

Eight servos draw far more current than the Arduino's own 5 V pin can supply. So the battery feeds a 5 V regulator through a switch, and the regulator powers two things: the servo rail on the shield, and the Arduino through the regulator's USB port. The Arduino only sends the control signals. When all servos start at once the supply dips, which is why the sketches start them one by one.

Servos
  1. Battery
  2. Rocker switch
  3. 5 V regulator
  4. Servo rail on the shield
  5. 8 servos
Arduino
  1. 5 V regulator
  2. USB port
  3. Arduino Uno
Signal
  1. Arduino Uno
  2. Sensor Shield v5.0
  3. 8 servo signal pins

Sensor wiring

Both sensors share the Arduino's 5 V and ground. Only the signal pins are listed.

SensorSignalArduino pin
HC-SR04TRIGA3
HC-SR04ECHOA2
MPU6050SDAA4
MPU6050SCLA5

A4 and A5 are the Uno's I²C pins, so the distance sensor uses A3 and A2 instead. An I²C scanner sketch finds the MPU6050 at address 0x68.

Servo map

The scale shows each neutral angle on the servo's 0 to 180 degree range. These are the angles of the current robot (sketch v3). When the robot was rebuilt, R1 moved from pin 4 to pin 2 and R1 and L2 were calibrated again.

ServoPinJointNeutral angle
R12Hip80°
R26Hip110°
R35Knee170°
R47Knee30°
L18Hip110°
L210Hip42°
L39Knee70°
L411Knee145°

Software

Calibration

Servo horns never sit at exactly the same angle, so 90° is a different pose on every leg. We calibrated each servo by hand with a small calibration sketch:

  1. Power the servos from the battery and pick one servo on the serial monitor.
  2. Nudge it up or down until the leg stands neutral: hip pointing straight out, knee at its resting height.
  3. Write that angle into the neutral table shown in the servo map. The sketch prints the finished arrays, ready to paste.
  4. Describe every movement as an offset from the neutral angle, never as an absolute angle.

Trot gait

The legs move as two diagonal pairs, R1 + L2 and R2 + L1. While one pair steps, the other stays on the ground and pushes the body forward. In gait v1 the hips swing 20° and the knees lift 45°. Every move is split into 20 small sub-steps so the servos glide instead of jumping.

In gait v1, one full step is six moves:

  1. Lift the knees of R3 and L4.
  2. Swing R1 and L2 forward, and R2 and L1 back.
  3. Lower the knees of R3 and L4.
  4. Lift the knees of R4 and L3.
  5. Swing R2 and L1 forward, and R1 and L2 back.
  6. Lower the knees of R4 and L3.

The v1 test routine does five steps forward, rests in the neutral pose, then does five steps backward.

Obstacle avoidance (v3)

An HC-SR04 ultrasonic sensor at the front end of the body looks ahead. It sends a 10 µs pulse, and the length of the echo in microseconds divided by 58 is the distance in centimetres. The robot checks it after every half cycle of the gait:

  1. Two readings in a row below 10 cm count as an obstacle, so one noisy reading does not stop the robot.
  2. It backs up for 2 cycles: the same gait with every hip swing reversed.
  3. It turns left on the spot for 6 cycles, about 90°. The legs on the left side swing backward and the legs on the right side swing forward.
  4. It walks on in the new direction.

Small differences between the legs made the robot veer to the left. Two keys on the serial monitor, z and x, move one degree of hip swing from one side to the other, and the value that walks straight goes into the trim variable at the top of the sketch. The same serial monitor starts and stops the robot (g, s), prints the distance (d) and tests the left turn (l).

Three versions of the sketch

Gait v2 keeps the structure of v1 and takes its numbers from the simulation (see below). Gait v3 keeps the structure of v2, walks toward the distance sensor and adds obstacle avoidance:

v1 manualv2 learnedv3 obstacle
RobotFirst robotFirst robotRebuilt robot with sensors, 363 g
Walks towardR1 and L1, the old frontR1 and L1, the old frontThe distance sensor. R2 and L2 are the front legs
Hip swing20°, both sidesRight 17°, left 25°21°, both sides, plus a trim key
Knee lift45°45°45°, one value per knee
Sub-steps per move202222
Delay per sub-step12 ms8 ms8 ms
Moves per cycle6: lift, swing, lower for each pair4: lift and swing together, then lower, for each pair4, as in v2
Behaviour5 steps forward, rest, 5 steps backwardForward only, until powered offForward until an obstacle is closer than 10 cm, then back up, turn left and walk on
Serial commandsNoneNoneg, s, d, l, z, x

The hips swing by different amounts on the two sides in v2 because that is what the search found. In v3 both sides use 21°, because in our tests the uneven pair made the robot veer when it walked toward the other end. The remaining drift is trimmed with the z and x keys.

// crawling-panther: trot gait v3
//   * walks the learned gait toward the sensor end (old rear legs R2/L2 are the front)
//   * HC-SR04 on A3 (trig) and A2 (echo): when something is closer than OBSTACLE_CM the robot
//     backs up BACK_CYCLES cycles, turns left about 90 degrees and walks on
//
// Serial monitor (115200 baud, newline):
//   g walk   s stop   d print distance   l left-turn test   z / x steer more right / left
#include <Servo.h>

enum { R1, R2, R3, R4, L1, L2, L3, L4, N };

const int pins[N]    = {2,   6,   5,   7,  8,   10, 9,  11};
const int neutral[N] = {80, 110, 170, 30, 110, 42, 70, 145};   // calibrated angles
const int sign[N]    = {1,   1,  -1,   1, -1,  -1,  1,  -1};   // mounting direction

const int HIP_SWING_R  = 21;    // degrees
const int HIP_SWING_L  = 21;
//                                R1 R2 R3  R4  L1 L2 L3  L4      (only the knees R3, R4, L3, L4 are used)
const int kneeLift[N]         = {0, 0, 45, 45, 0, 0, 45, 45};
int trim = 0;                   // drift trim: robot veers left -> press z. Copy the final value here.

const int INTERP_STEPS = 22;    // sub-steps per movement
const int STEP_DELAY   = 8;     // ms between sub-steps
const int FORWARD      = -1;    // old rear legs (R2, L2) are the front

const uint8_t TRIG_PIN = A3;    // if you never get a reading, swap these two
const uint8_t ECHO_PIN = A2;
const int OBSTACLE_CM    = 10;  // turn when closer than this (an HC-SR04 cannot read below ~2 cm)
const int NO_ECHO        = 999; // nothing heard
const int BACK_CYCLES    = 2;   // how far to back off before turning
const int TURN_CYCLES_90 = 6;   // gait cycles for a ~90 degree left turn: tune with the 'l' key

Servo servos[N];
int cur[N], target[N];
bool walking = true;
int sideDirR = 1, sideDirL = 1;  // -1 = this side's hips swing the other way (turning)
int walkDir = 1;                 // -1 while backing up

// Move all servos smoothly from cur[] to target[]
void apply() {
  int start[N];
  for (int i = 0; i < N; i++) start[i] = cur[i];
  for (int s = 1; s <= INTERP_STEPS; s++) {
    for (int i = 0; i < N; i++) {
      cur[i] = start[i] + (long)(target[i] - start[i]) * s / INTERP_STEPS;
      servos[i].write(cur[i]);
    }
    delay(STEP_DELAY);
  }
}

// d = +1 swings the leg toward the sensor, d = -1 the other way
void hip(int i, int d) {
  bool right = (i == R1 || i == R2);
  int swing = right ? HIP_SWING_R + trim : HIP_SWING_L - trim;
  if (swing < 0) swing = 0;
  int side = right ? sideDirR : sideDirL;
  target[i] = neutral[i] + sign[i] * swing * d * FORWARD * side * walkDir;
}

void knee(int i, bool lifted) {
  target[i] = neutral[i] + (lifted ? sign[i] * kneeLift[i] : 0);
}

void halfCycleA() {
  knee(R3, true); knee(L4, true);
  hip(R1, +1); hip(L2, +1); hip(R2, -1); hip(L1, -1);
  apply();
  knee(R3, false); knee(L4, false); apply();
}

void halfCycleB() {
  knee(R4, true); knee(L3, true);
  hip(R2, +1); hip(L1, +1); hip(R1, -1); hip(L2, -1);
  apply();
  knee(R4, false); knee(L3, false); apply();
}

// ---------- distance ----------
int readOnce() {
  digitalWrite(TRIG_PIN, LOW);  delayMicroseconds(2);
  digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);
  unsigned long t = pulseIn(ECHO_PIN, HIGH, 25000UL);   // 25 ms is about 4 m
  delay(10);                                            // let the echo die out
  if (t == 0) return NO_ECHO;
  return (int)(t / 58);                                 // microseconds to cm
}

bool blocked() {                                        // two close readings in a row
  return readOnce() < OBSTACLE_CM && readOnce() < OBSTACLE_CM;
}

// ---------- avoiding ----------
void backUp(int cycles) {
  walkDir = -1;
  for (int c = 0; c < cycles; c++) { halfCycleA(); halfCycleB(); }
  walkDir = 1;
}

// The robot's front is now the old rear, so its LEFT side carries the R servos:
// turning left = R servos swing backward, L servos swing forward.
void turnLeft(int cycles) {
  sideDirR = -1; sideDirL = 1;
  for (int c = 0; c < cycles; c++) { halfCycleA(); halfCycleB(); }
  sideDirR = sideDirL = 1;
}

void avoidObstacle() {
  Serial.println(F("Obstacle: backing up, turning left"));
  backUp(BACK_CYCLES);
  turnLeft(TURN_CYCLES_90);
}

void setup() {
  Serial.begin(115200);
  pinMode(TRIG_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  for (int i = 0; i < N; i++) {
    cur[i] = target[i] = neutral[i];
    servos[i].write(cur[i]);
    servos[i].attach(pins[i]);
    delay(500);                 // start servos one by one (protects the regulator)
  }
  Serial.println(F("g walk  s stop  d distance  l left turn  z / x steer"));
  delay(2000);                  // wait 2 s before walking
}

void handleSerial() {
  while (Serial.available()) {
    char c = Serial.read();
    if (c == 'g') walking = true;
    else if (c == 's') walking = false;
    else if (c == 'd') { Serial.print(F("distance: ")); Serial.println(readOnce()); }
    else if (c == 'l') turnLeft(TURN_CYCLES_90);
    else if (c == 'z') { trim = min(trim + 1, 20);  Serial.print(F("trim ")); Serial.println(trim); }
    else if (c == 'x') { trim = max(trim - 1, -20); Serial.print(F("trim ")); Serial.println(trim); }
  }
}

void loop() {
  handleSerial();
  if (!walking) return;
  halfCycleA();
  if (blocked()) { avoidObstacle(); return; }
  halfCycleB();
  if (blocked()) { avoidObstacle(); return; }
}

Other sketches

Simulation

We built a physics model of the robot, let a search algorithm find a walking gait in it, and wrote that gait into the Arduino sketch v2. Everything labelled "simulation" on this page comes from the model, and the real robot's angles are compared with it in Results.

01URDF modelBody, legs and servo limits
02PyBulletPhysics simulation, 4 ms steps
03Search25 generations of 20 gaits
04Sketch v2Learned angles written into the Arduino code
05Real robotSketch v3 runs the angles, tuned on the robot

Robot model

The robot is described in a URDF file: a body, four hips and four legs, joined by eight revolute joints. Each joint is limited like an MG90S servo: 0.2 N·m of torque, 8 rad/s and a range of ±1 rad. The model weighs 342 g in total. The finished robot, with its sensors, weighs 363 g.

crawling-panther_v1.urdf is Rodi's first model. crawling-panther_v2.urdf is the corrected one, with the right weight, the servo limits and a fix for the root mass (see Challenges).

The physics engine is PyBullet. Floor friction and motor strength are estimates, so the simulation shows what is plausible, not exactly what the real robot does.

How the gait was learned

We used an evolutionary search. It needs no extra libraries and runs in a few minutes.

  1. A candidate gait is six numbers: right and left hip swing, right and left knee lift, speed, and a heading-correction gain.
  2. Every candidate walks 40 cycles in PyBullet.
  3. It receives a score (below).
  4. The five best candidates of a generation are averaged. The next 20 candidates are random variations around that average, and the variation shrinks a little each generation.
  5. This repeats for 25 generations of 20 candidates, which is 500 walks.
score = forward distance (cm) − sideways drift (cm) − 0.3 × heading change (°) − 60 if the body tilts more than 35°

The search ranges were chosen to suit the real robot: hip swing 5° to 25°, knee lift 20° to 45°, 15 to 60 sub-steps per move, gain 0 to 1.5. Bigger swings make the legs collide, and the MG90S knee is limited.

What it learned

The search ends with six numbers. The table shows each one next to the number that went into sketch v2. They differ slightly for two reasons. The search uses decimals, but an Arduino servo only moves in whole degrees, so the values are rounded. And the sketch waits 8 ms between sub-steps while the simulation steps every 4 ms, so on the real robot the gait runs at about half the simulated speed.

ParameterWhat it controlsSimulation's answerNumber in sketch v2
Right hip swingHow far the right hips swing the legs forward and back17.4°17°
Left hip swingThe same for the left hips24.8°25°
Knee liftHow high the knees raise a foot (both sides)45°45°
SpeedHow many small steps one leg movement is split into. More steps is slower22.3 steps22 steps, 8 ms each
Heading-correction gainHow strongly the heading error steers the robot back on course0.64Not used on the robot. A hand-set trim key corrects the drift instead

Two values sit at the edge of the allowed range: the knee lift (45°) and the left hip (24.8° of 25°). A wider range might score higher, but it would ask more from the real servos.

Show the data as a table
GenerationScoreForward (cm)Sideways (cm)Heading change (°)Max tilt (°)Hips R / L (°)

Learning curve in simulation: the best score in each generation. It climbed from 32.5 to 167.5. The best single candidate scored 170.4 in generation 24.

Heading correction

A walking robot drifts off its line. In the simulation the heading comes straight from the physics engine, so the search could learn a correction: when the heading error grows, the stride on one side gets longer and on the other side shorter, in proportion to the error. The strength of the correction is the learned gain.

The real robot does not do this. The MPU6050 is mounted but the sketches do not read it, and the drift is trimmed by hand with the z and x keys. A gyroscope loop is one of the ideas under Future work.

Files

Results

The search found its angles in simulation. The sketch that runs on the robot uses angles we set and tuned on the real robot. The table puts them side by side.

Learned in simulationReal robot (v3)
Right hip swing17.4°21°
Left hip swing24.8°21°
Knee lift45°45°
Sub-steps per move22.322
Delay per sub-step4 ms (one physics step)8 ms
Heading correctionLearned gain 0.64None. A trim key shifts the swing between the two sides

The knee lift and the number of sub-steps came out almost the same. The hips did not: the search preferred 17° on the right and 25° on the left, while the robot walks with 21° on both sides. In our tests the uneven pair made the real robot veer, so the real robot walks with equal hips and a trim key instead.

What the simulation predicted for its own gait in 40 cycles: 175 cm forward, −0.3 cm sideways, a heading change of 14.5° and a maximum tilt of 5.8°. We did not measure distance or drift on the real robot, so this page compares angles only.

Challenges

What went wrong, and what we know so far.

On the robot

Regulator protection

The voltage regulator went into protection and blinked when all 8 servos started at once. We now start the servos one at a time in code and added a power switch. The regulator module has its own capacitors that smooth the supply.

Fixed

A leg that did not touch the ground

The robot veered to the left because one leg did not reach the floor. Moving the knee's neutral angle was not enough, since R3 was already at 170° of its 180° range. We adjusted the leg and calibrated every angle again, and the trim key covers what is left.

Fixed

MPU6050 not found

The gyroscope returned only zeros and the I²C scanner found nothing. SDA was connected to ground, and SDA and SCL were swapped. After rewiring them to A4 and A5 the scanner found the MPU6050 at 0x68.

Fixed

Obstacle not detected

The robot walked straight into obstacles because it only reacted below 3 cm, and an HC-SR04 is unreliable that close. The limit is now 10 cm, and two readings in a row must agree.

Fixed

Limited torque

The MG90S has little torque for a 363 g robot, so the gait needs careful tuning of angles and timing. Small changes decide whether a step lifts the body or stalls.

Managed by tuning

In the simulation

A heavy root link

PyBullet gave the first (root) link of the URDF a default mass of 1 kg. On top of the robot's 342 g, the model looked about four times too heavy, and its servos could not lift the legs. We added a tiny root mass (0.1 g) to the URDF, which fixed it. Lesson: add up the masses the simulator really uses and compare them with the scale.

Fixed

A gait that looked good for 15 cycles

Our first learning runs scored every candidate on 15 cycles. The winner looked good for 15 cycles, then started to turn, because its small heading error kept adding up. A short test rewarded gaits that only look good briefly. We made the test 40 cycles long and turned the heading-correction gain into a learned parameter.

Fixed in simulation

Different servo directions

In the simulation, each joint turns in the direction set by the URDF. On the real robot, the direction depends on how each servo horn was mounted. The two sets of signs differ, so a gait from the simulation can move a real leg the wrong way. We added a command that moves each servo on its own, so every direction can be checked one by one.

Managed by testing

Future work

Ideas for later. None of them is part of the robot yet.

Heading hold with the gyroscope

The MPU6050 is already mounted upright on the body. Reading its rotation rate would let the robot correct its own heading while it walks, the way the simulation does with its learned gain.

Straighter walking, tested in simulation first

Put the real robot's quirks into the model, such as a leg that does not quite reach the floor, and let the search find angles that compensate. Then compare the result with the trim we set by hand.

Measuring the real robot

Walk a fixed number of cycles on a marked floor and measure the distance, the drift and the heading change, so the real robot can be compared with the simulation number by number.

Team

Rodi Ercan

3D printing and mechanical assembly. Servo calibration and Arduino code, together with Boran. Simulation work.

Boran Akgün

Servo calibration and Arduino code, together with Rodi. Simulation work.

github.com/spiderbot-project/crawling-panther