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.
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.
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.
| Part | Qty | Job |
|---|---|---|
| Arduino Uno | 1 | Runs the gait and generates the servo signals |
| Sensor Shield v5.0 | 1 | Breaks out signal, power and ground pins for each servo |
| TowerPro MG90S servo | 8 | 4 hips and 4 knees |
| External battery | 1 | 7.4 V. Powers the servos and the Arduino |
| 5 V voltage regulator module | 1 | Turns the battery voltage into 5 V for the servos and, through its USB port, for the Arduino. Its own capacitors smooth the supply |
| Rocker switch | 1 | Cuts the power from the battery |
| HC-SR04 ultrasonic sensor | 1 | Sits at the front end of the body and measures the distance ahead. The robot turns away below 10 cm |
| MPU6050 module | 1 | Gyroscope 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 legs | 1 set | Frame and four two-joint legs |
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.
Both sensors share the Arduino's 5 V and ground. Only the signal pins are listed.
| Sensor | Signal | Arduino pin |
|---|---|---|
| HC-SR04 | TRIG | A3 |
| HC-SR04 | ECHO | A2 |
| MPU6050 | SDA | A4 |
| MPU6050 | SCL | A5 |
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.
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.
| Servo | Pin | Joint | Neutral angle |
|---|---|---|---|
| R1 | 2 | Hip | 80° |
| R2 | 6 | Hip | 110° |
| R3 | 5 | Knee | 170° |
| R4 | 7 | Knee | 30° |
| L1 | 8 | Hip | 110° |
| L2 | 10 | Hip | 42° |
| L3 | 9 | Knee | 70° |
| L4 | 11 | Knee | 145° |
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:
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:
The v1 test routine does five steps forward, rests in the neutral pose, then does five steps backward.
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:
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).
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 manual | v2 learned | v3 obstacle | |
|---|---|---|---|
| Robot | First robot | First robot | Rebuilt robot with sensors, 363 g |
| Walks toward | R1 and L1, the old front | R1 and L1, the old front | The distance sensor. R2 and L2 are the front legs |
| Hip swing | 20°, both sides | Right 17°, left 25° | 21°, both sides, plus a trim key |
| Knee lift | 45° | 45° | 45°, one value per knee |
| Sub-steps per move | 20 | 22 | 22 |
| Delay per sub-step | 12 ms | 8 ms | 8 ms |
| Moves per cycle | 6: lift, swing, lower for each pair | 4: lift and swing together, then lower, for each pair | 4, as in v2 |
| Behaviour | 5 steps forward, rest, 5 steps backward | Forward only, until powered off | Forward until an obstacle is closer than 10 cm, then back up, turn left and walk on |
| Serial commands | None | None | g, 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.
#include <Servo.h> enum { R1, R2, R3, R4, L1, L2, L3, L4, N }; const int pins[N] = {4, 6, 5, 7, 8, 10, 9, 11}; const int neutral[N] = {85, 110, 170, 30, 110, 40, 70, 145}; // calibrated angles const int sign[N] = {1, 1, -1, 1, -1, -1, 1, -1}; // mounting direction const int HIP_SWING = 20; const int KNEE_LIFT = 45; const int STEPS = 5; // steps forward, then backward const int INTERP_STEPS = 20; // sub-steps per movement const int STEP_DELAY = 12; // ms between sub-steps // If the robot walks backward instead of forward, swap these two values const int FORWARD = 1; const int BACKWARD = -1; Servo servos[N]; int cur[N]; // current angles int target[N]; // target angles int moveDir = FORWARD; // 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); } } void hip(int i, int d) { target[i] = neutral[i] + sign[i] * HIP_SWING * d * moveDir; } void knee(int i, bool lifted) { target[i] = neutral[i] + (lifted ? sign[i] * KNEE_LIFT : 0); } // One full step: both diagonal groups move once void gaitStep() { // Group R1+L2 knee(R3, true); knee(L4, true); apply(); // lift hip(R1, +1); hip(L2, +1); hip(R2, -1); hip(L1, -1); apply(); // swing knee(R3, false); knee(L4, false); apply(); // lower // Group R2+L1 knee(R4, true); knee(L3, true); apply(); hip(R2, +1); hip(L1, +1); hip(R1, -1); hip(L2, -1); apply(); knee(R4, false); knee(L3, false); apply(); } void rest() { for (int i = 0; i < N; i++) target[i] = neutral[i]; apply(); } void setup() { 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) } delay(2000); // wait 2 s before walking } void loop() { moveDir = FORWARD; for (int k = 0; k < STEPS; k++) gaitStep(); rest(); delay(1000); moveDir = BACKWARD; for (int k = 0; k < STEPS; k++) gaitStep(); rest(); delay(1000); }
// crawling-panther: trot gait v2 (parameters learned in simulation), walks forward only. // Same structure as v1; differences: // * left and right hips swing by different amounts (found by simulation) // * knee lift and hip swing happen together, then the knees come down (4 moves per cycle) // * slower than the simulation on purpose (STEP_DELAY) #include <Servo.h> enum { R1, R2, R3, R4, L1, L2, L3, L4, N }; const int pins[N] = {4, 6, 5, 7, 8, 10, 9, 11}; const int neutral[N] = {85, 110, 170, 30, 110, 40, 70, 145}; // calibrated angles const int sign[N] = {1, 1, -1, 1, -1, -1, 1, -1}; // mounting direction // Learned in simulation (simulation/best_gait_v2.json): right 17.4, left 24.8, knee 45 const int HIP_SWING_R = 17; const int HIP_SWING_L = 25; const int KNEE_LIFT = 45; const int INTERP_STEPS = 22; // sub-steps per movement (same as simulation) const int STEP_DELAY = 8; // ms between sub-steps (simulation is ~4 ms; 8 ms = about half speed) // If the robot walks backward instead of forward, change to -1 const int FORWARD = 1; Servo servos[N]; int cur[N]; // current angles int target[N]; // target angles // 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 forward, d = -1 backward void hip(int i, int d) { int swing = (i == R1 || i == R2) ? HIP_SWING_R : HIP_SWING_L; target[i] = neutral[i] + sign[i] * swing * d * FORWARD; } void knee(int i, bool lifted) { target[i] = neutral[i] + (lifted ? sign[i] * KNEE_LIFT : 0); } // One full cycle: both diagonal groups move once void gaitCycle() { // Group R1+L2: lift knees R3, L4 while R1, L2 swing forward and R2, L1 push back 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(); // Group R2+L1: lift knees R4, L3 while R2, L1 swing forward and R1, L2 push back 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(); } void setup() { 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) } delay(2000); // wait 2 s before walking } void loop() { gaitCycle(); // walks forward until powered off }
// 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; } }
The robot can also stand up from a crouch and do push-ups. A push-up uses all four knees at once: folding them lowers the body, straightening them pushes it back up. The hips stay at their neutral angles the whole time.
p starts and stops the push-ups. + and − change the depth in steps of 5°, from 5° to 45°. f and v change the speed.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.
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.
record_video.py.We used an evolutionary search. It needs no extra libraries and runs in a few minutes.
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.
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.
| Parameter | What it controls | Simulation's answer | Number in sketch v2 |
|---|---|---|---|
| Right hip swing | How far the right hips swing the legs forward and back | 17.4° | 17° |
| Left hip swing | The same for the left hips | 24.8° | 25° |
| Knee lift | How high the knees raise a foot (both sides) | 45° | 45° |
| Speed | How many small steps one leg movement is split into. More steps is slower | 22.3 steps | 22 steps, 8 ms each |
| Heading-correction gain | How strongly the heading error steers the robot back on course | 0.64 | Not 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.
| Generation | Score | Forward (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.
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.
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 simulation | Real robot (v3) | |
|---|---|---|
| Right hip swing | 17.4° | 21° |
| Left hip swing | 24.8° | 21° |
| Knee lift | 45° | 45° |
| Sub-steps per move | 22.3 | 22 |
| Delay per sub-step | 4 ms (one physics step) | 8 ms |
| Heading correction | Learned gain 0.64 | None. 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.
What went wrong, and what we know so far.
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.
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.
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.
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.
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.
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.
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.
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.
Ideas for later. None of them is part of the robot yet.
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.
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.
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.
3D printing and mechanical assembly. Servo calibration and Arduino code, together with Boran. Simulation work.