Cart-pole balance (state feedback)
Balance a 300 mm pole on a belt-driven cart: two quadrature encoders on interrupts, a 2 ms loop, and full state feedback on the pole's angle and rate and the…
Control · Advanced
In a real product: Inverted pendulum (Robotics): A balancing robot, a rocket's gimbal or a crane's anti-sway: an unstable plant held up by fast feedback.
An inverted pendulum falls over on its own: the controller must move the cart under the pole faster than it tips. The rig is a cart on a 600 mm rail, pulled by a 12 V motor through a belt, with a pole on a free pivot. One encoder is on the motor (the cart) and one on the pivot (the pole). Open the World tool's Cart-pole view to watch it.
What you'll learn
- Why an unstable plant needs a fast loop: the pole falls away at about e^(7.4·t), doubling its angle every 0.1 s
- Two quadrature encoders on an Uno's two interrupt pins, counted on A's CHANGE
- Full state feedback: four gains on the angle, its rate, the cart's place and its speed
- Why the cart's gains have the same sign as the pole's (to bring the cart back, first tip the pole towards the middle)
- Wrapping an angle that can go right round, and taking hold again after a fall
How it works
The pole's encoder counts 1200 a turn on D2 (A) and D4 (B), the cart's 200 a motor turn (62.8 mm of belt) on D3 and D12. Both count from where the rig powers up: with the "up" start the pole is held upright (count 0) and tipped 3° by hand before it is let go.
Every 2 ms the loop turns the counts into degrees and millimetres, works out the rates from their changes, and drives the motor at u = kp·angle + kd·rate + kx·x + kv·speed volts through the TB6612FNG. Past 30° the pole is gone, so it lets go (u = 0) until the pole is back within 5° of upright.
The sketch prints angle:, x:, u: and both counts ten times a second, and reads kp=, kd=, kx= and kv=: the Cart-pole view's sliders send them.
Try this
- Run with the Cart-pole view open. Press Nudge the pole: how far does the cart run to catch it?
- Set
kx=0andkv=0: the pole stays up, but the cart drifts until it hits a bumper. - Halve
kd: the pole wobbles. Set it to 0 and the pole falls in under a second. - Change the loop to every 20 ms: why can it no longer hold the pole?
- Knock it over with
kp=0, putkp=1.5back and press Back to the start: it takes hold again.
sketch.ino
// Uno balancing the cart-pole: full state feedback on the pole's angle and rate and the
// cart's position and speed, every 2 ms.
// TB6612FNG: AIN1 D7, AIN2 D8, PWMA D5, STBY D9; the motor on AO1/AO2, VM from a 12 V supply.
// Pole encoder (600 PPR) A on D2, B on D4; cart encoder (100 PPR on the motor) A on D3, B on D12. Both counted on
// A's CHANGE interrupt (two counts a cycle): 1200 a pole turn, 200 a motor turn (62.8 mm of belt).
// u = kp·angle + kd·rate + kx·x + kv·speed (volts, degrees, mm). Past 30° it lets go (the pole has fallen) and
// takes hold again once the pole is back within 5° of upright.
// Every 100 ms: "angle:<deg> x:<mm> u:<V> pole:<counts> cart:<counts>". Over Serial: kp=, kd=, kx=, kv=.
const int AIN1 = 7, AIN2 = 8, PWMA = 5, STBY = 9;
const int POLE_A = 2, POLE_B = 4, CART_A = 3, CART_B = 12;
const float POLE_PER_DEG = 1200.0 / 360.0;
const float CART_PER_MM = 200.0 / 62.83;
const float DT = 0.002;
float kp = 1.5, kd = 0.08, kx = 0.08, kv = 0.02;
volatile long pole = 0, cart = 0;
float lastAngle = 0, lastX = 0, rate = 0, speed = 0, u = 0;
bool holding = true;
unsigned long lastLoop = 0, lastPrint = 0;
String line;
void poleEdge() { pole += (digitalRead(POLE_A) != digitalRead(POLE_B)) ? 1 : -1; }
void cartEdge() { cart += (digitalRead(CART_A) != digitalRead(CART_B)) ? 1 : -1; }
void drive(float volts) {
int duty = constrain((int)(volts / 12.0 * 255.0), -255, 255);
digitalWrite(AIN1, duty > 0);
digitalWrite(AIN2, duty < 0);
analogWrite(PWMA, abs(duty));
}
void command(const String &s) {
float v = s.substring(3).toFloat();
if (s.startsWith("kp=")) kp = v;
else if (s.startsWith("kd=")) kd = v;
else if (s.startsWith("kx=")) kx = v;
else if (s.startsWith("kv=")) kv = v;
}
void setup() {
pinMode(AIN1, OUTPUT); pinMode(AIN2, OUTPUT); pinMode(PWMA, OUTPUT); pinMode(STBY, OUTPUT);
pinMode(POLE_A, INPUT); pinMode(POLE_B, INPUT); pinMode(CART_A, INPUT); pinMode(CART_B, INPUT);
digitalWrite(STBY, HIGH);
attachInterrupt(digitalPinToInterrupt(POLE_A), poleEdge, CHANGE);
attachInterrupt(digitalPinToInterrupt(CART_A), cartEdge, CHANGE);
Serial.begin(115200);
// The rig is zeroed with the pole held upright: count 0 is upright. Two counts a cycle from the 4-count position.
noInterrupts();
pole = 0; cart = 0;
interrupts();
}
void loop() {
while (Serial.available()) {
char c = Serial.read();
if (c == '\n' || c == '\r') { if (line.length()) command(line); line = ""; }
else line += c;
}
unsigned long now = micros();
if (now - lastLoop < 2000) return;
lastLoop = now;
noInterrupts();
long p = pole, c = cart;
interrupts();
// The pole can swing right round: wrap its count to within half a turn of upright.
long turn = (long)(360 * POLE_PER_DEG), wrapped = p % turn;
if (wrapped > turn / 2) wrapped -= turn;
if (wrapped < -turn / 2) wrapped += turn;
float angle = wrapped / POLE_PER_DEG;
float x = c / CART_PER_MM;
// Rates from the counts' differences, lightly filtered (the counts are coarse).
float change = angle - lastAngle;
if (change > 180) change -= 360; // across the wrap at the bottom
if (change < -180) change += 360;
rate += (change / DT - rate) * 0.5;
speed += ((x - lastX) / DT - speed) * 0.3;
lastAngle = angle;
lastX = x;
if (holding && fabs(angle) > 30) holding = false;
if (!holding && fabs(angle) < 5) holding = true;
u = holding ? kp * angle + kd * rate + kx * x + kv * speed : 0;
u = constrain(u, -12, 12);
drive(u);
if (millis() - lastPrint >= 100) {
lastPrint = millis();
Serial.print("angle:"); Serial.print(angle, 2);
Serial.print(" x:"); Serial.print(x, 1);
Serial.print(" u:"); Serial.print(u, 2);
Serial.print(" pole:"); Serial.print(p);
Serial.print(" cart:"); Serial.println(c);
}
}