Skip to content

Class 2 · Fuse it, spin the wheels

Last class you saw the problem: the accelerometer is noisy and the gyro drifts. Today you blend them into one angle you can trust. Then you wire the two gear motors, teach the Uno to count their wheel turns, and make the wheels chase the tilt. It's the first time the sensor moves something.

By the end of class

Your fused angle stays within 2° of a protractor, you know how many encoder counts make one wheel turn, and when you tilt the board the wheels roll toward the tilt, faster the more you tilt.

New parts today

Part What it's for
Two 12 V gear motors with encoders The wheels' motors, and a way to count their turns
TB6612FNG motor driver Direction and push for both motors
100 µF capacitor Smooths the 12 V at the driver
12 V 2 A wall adapter + barrel jack adapter Motor power
Wheels with hubs So you can see which way and how fast

Part 1 · One good angle

Tool: measure the loop time with micros()

micros() is like millis() but counts microseconds. Store the time at the start of each loop and subtract to find how long the last loop took. Even better, make each loop take a fixed time:

unsigned long lastLoop = 0;

void loop() {
  unsigned long now = micros();
  if (now - lastLoop < 5000) return;      // wait until 5 ms have passed
  float dt = (now - lastLoop) / 1000000.0; // seconds, about 0.005
  lastLoop = now;

  // ... the rest of the loop runs 200 times a second
}

return inside loop() just ends this pass; loop() runs again right away. Use the measured dt, not 0.005: if something slows one loop down, the math stays right. The subtraction now - lastLoop works even when micros() rolls over (after about 70 minutes), as long as both are unsigned long.

Serial printing is slow. At 115200 baud, a line of 30 characters takes about 2.6 ms, half your loop. Print every 10th loop (or every 50 ms with millis()), not every loop.

Tool: blend two readings

A noisy reading can be smoothed by keeping most of the old value and adding a little of the new one. Example: a jittery light sensor on A0.

float smooth = 0;

void loop() {
  int raw = analogRead(A0);
  smooth = 0.9 * smooth + 0.1 * raw;   // 90% old, 10% new
  Serial.print(">raw:");    Serial.println(raw);
  Serial.print(">smooth:"); Serial.println(smooth);
  delay(10);
}

The smoothed line is calm but lags behind real changes. The bigger the first number, the calmer and slower it gets.

A complementary filter uses the same trick with two different sensors:

angle = 0.98 * (angle + rate * dt) + 0.02 * accAngle

Each loop, the gyro moves the angle forward (angle + rate * dt): fast, smooth, and it follows every real movement. Then the accelerometer pulls it 2% of the way toward its own answer. Over a fraction of a second the 2% adds up, so the gyro's drift never gets far. But a single bump in the accelerometer only gets 2% say, so the spikes disappear.

Why 0.98?

At 200 loops per second, 0.98 means the accelerometer takes over in roughly a quarter of a second. Closer to 1 (0.995) trusts the gyro longer: smoother, but drift lingers. Smaller (0.95) follows the accelerometer sooner: drift corrected faster, but bumps show through. 0.98 is a common starting point.

Mission 1 · The fused angle

Start from your Class 1 code.

  1. Replace delay(10) with the fixed 5 ms loop and measured dt.
  2. Add the complementary filter, using your calibrated gyro rate and accelerometer angle.
  3. At the end of setup(), set angle = accAngle once, so it starts at the right value instead of 0.
  4. Plot angle with accAngle and watch both while you tap the table and tilt the board.

Done when

Hold the board against a protractor (or use a level app on a phone laid on it) at 0°, 15°, 30° and 45°. Each time, your angle is within 2°, and it holds steady (no creeping) for 30 s. Taps on the table barely show.

Part 2 · Wire the motors

Each gear motor has six wires: two for the motor itself and four for the encoder on its back. Today you wire the motor half to a TB6612 driver and find out how much push it takes to get the wheels moving. In Part 3 you'll wire the encoders.

Before anything else

The 12 V adapter stays unplugged while you wire. Check with Dr. Alvear: look up your motor's stall current on its listing (the current when the shaft is held still at 12 V). The TB6612 handles about 1.2 A per motor continuously and 3.2 A in short peaks. If your motor's stall current is well above that peak, Dr. Alvear will give you a larger dual driver, and its pin names will differ from the table below.

  1. Find the motor and encoder wires. The encoder board on the back of each motor has its pins labeled. Common labels are M1 and M2 (or M+ and M−) for the motor, VCC and GND for the encoder's power, and C1/C2 or A/B for the two encoder signals. Wire colors differ between sellers, so go by the labels or your seller's diagram, not by color.
  2. Place the TB6612 module on the breadboard, straddling the center gap. Read the pin labels printed on your board: modules from different sellers put the pins in different orders. You should find VM, VCC, GND (two or three), AO1, AO2, BO1, BO2, PWMA, AIN1, AIN2, STBY, BIN1, BIN2, PWMB.
  3. Wire it, with the 12 V unplugged:

    From To Why
    Uno pin 9 PWMA Left motor: how hard (PWM)
    Uno pin 7 AIN1 Left motor: direction
    Uno pin 8 AIN2 Left motor: direction
    Uno pin 10 PWMB Right motor: how hard (PWM)
    Uno pin 11 BIN1 Right motor: direction
    Uno pin 12 BIN2 Right motor: direction
    Uno pin 4 STBY HIGH = driver on, LOW = everything off
    Uno 5V VCC The driver's logic power
    Uno GND GND Common ground
    +12 V rail VM Motor power
    12 V ground rail GND Common ground
    Left motor M1, M2 AO1, AO2
    Right motor M1, M2 BO1, BO2
  4. Capacitor: 100 µF across VM and GND, as close to the driver as you can, stripe (−) on ground.

  5. Common ground: the 12 V ground rail connects to the Uno's GND.
  6. Power: the barrel jack adapter's + and − screw terminals to the 12 V rails. Before the driver sees it, check the polarity with the multimeter, and check the voltage: the TB6612 is meant for VM up to about 13.5 V, and some "12 V" adapters read higher with nothing connected. If yours reads more than 13.5 V, ask Dr. Alvear.

12 V goes only to VM. VCC takes 5 V from the Uno; 12 V there destroys the chip.

These pins stay the same for all six classes. The MPU6050 stays on A4/A5, the knobs will go on A0–A2, and the encoders will use pins 2, 3, 5 and 6.

Tool: analogWrite() and an H-bridge

digitalWrite() gives a pin two choices: 0 V or 5 V. analogWrite(pin, level) switches the pin on and off about 500 times a second, and level (0 to 255) sets what fraction of the time it's on. This is PWM (pulse-width modulation). An LED looks dimmer; a motor gets a weaker push. It only works on the pins marked ~ on the Uno: 3, 5, 6, 9, 10, 11.

The TB6612 is an H-bridge: the four-transistor reversing circuit, built into a chip. For each motor, two IN pins choose the direction and the PWM pin sets how hard it pushes. STBY must be HIGH or nothing moves.

IN1 IN2 PWM Motor
HIGH LOW 0–255 Turns one way, that hard
LOW HIGH 0–255 Turns the other way
LOW LOW any Coasts
HIGH HIGH any Brakes

Example, not the project: a desk fan on channel A that runs gently, then hard, then backward (to pull air the other way).

#include <Arduino.h>

const int PWMA = 9;
const int AIN1 = 7;
const int AIN2 = 8;
const int STBY = 4;

void setup() {
  pinMode(PWMA, OUTPUT);
  pinMode(AIN1, OUTPUT);
  pinMode(AIN2, OUTPUT);
  pinMode(STBY, OUTPUT);
  digitalWrite(STBY, HIGH);    // driver on
}

void loop() {
  digitalWrite(AIN1, HIGH);
  digitalWrite(AIN2, LOW);
  analogWrite(PWMA, 100);  delay(2000);   // gentle
  analogWrite(PWMA, 255);  delay(2000);   // full

  digitalWrite(AIN1, LOW);
  digitalWrite(AIN2, HIGH);
  analogWrite(PWMA, 150);  delay(2000);   // backward

  analogWrite(PWMA, 0);    delay(2000);   // off
}

Tool: the dead zone

A gear motor doesn't move at all below some PWM level. Friction in the gears holds it, and the motor just hums. Call that level the dead zone. For a balancing robot it matters: when the robot is almost upright, the controller asks for a small push, and a small push does nothing.

The fix is to start every push from the edge of the dead zone. If the controller asks for u (positive or negative), send

pwm = sign of u × (deadZone + |u|)      then limit it to 255

and send 0 when u is exactly 0. Example, not the project: a conveyor belt whose motor doesn't start below 70.

const int DEAD_ZONE = 70;

// u: -255 (full backward) to 255 (full forward), 0 = stop
int withDeadZone(int u) {
  if (u == 0) return 0;
  int pwm = DEAD_ZONE + abs(u);
  pwm = constrain(pwm, 0, 255);
  if (u < 0) pwm = -pwm;
  return pwm;
}

The answer still has a sign: positive means IN1 HIGH / IN2 LOW, negative the other way, and abs() of it goes to analogWrite.

One more thing to know: at the same PWM, the motor turns more slowly as the battery drains, because PWM is a fraction of whatever voltage the battery has left. The dead zone creeps up a little, too.

Fingers clear

Tape or clamp the motors to the table before you power them, wheels hanging over the edge. A wheel at a few turns per second will grab a finger or a loose wire.

Mission 2 · Find the dead zone

Push the wheels onto the shafts (line up the hub with the flat of the D-shaft and tighten its set screw).

  1. Write a function setMotor(int side, int u) that takes −255 to 255 for one motor and sets its two IN pins and its PWM pin. Don't add the dead zone yet.
  2. Ramp u up slowly from 0 (one step every 200 ms, printed) and write down the smallest value that keeps each wheel turning, both directions. The two motors won't match exactly; use the bigger number.
  3. Add the dead-zone compensation to setMotor(), with your number as a const.
  4. Decide which way is "forward" for the robot. The motors face opposite ways on the robot, so the same IN1/IN2 settings spin them opposite ways on the ground. Make setMotor(side, 100) roll both wheels forward, either by swapping one motor's wires at BO1/BO2 or by flipping the sign in code.

Done when

setMotor() with u = 1 already turns each wheel slowly (no humming), and positive numbers roll both wheels forward. Your dead zone is written in the build log.

Part 3 · Count the turns

The encoder is a small magnet disk on the motor's shaft and two Hall sensors next to it. As the motor turns, each sensor's output goes HIGH and LOW over and over. The two signals, A and B, are a quarter step apart. Count A's pulses and you know how far the wheel turned. Look at B at the moment A rises and you know which way.

The motor's shaft spins many times for each turn of the wheel (that's what the gearbox does), so you get hundreds of pulses per wheel turn. That's too fast to catch by checking a pin in loop(). You need an interrupt.

Tool: counting with interrupts

An interrupt makes the Uno drop what it's doing the instant a pin changes, run a short function, and go back. On the Uno only pins 2 and 3 can do this. That's why the two A signals go there.

Piece What it does
attachInterrupt(digitalPinToInterrupt(2), onPulse, RISING) Run onPulse() every time pin 2 goes from LOW to HIGH. Put it in setup().
void onPulse() { ... } The interrupt function. Keep it tiny: no Serial, no delay.
volatile long count A variable the interrupt function changes. volatile tells the compiler it can change behind loop()'s back.
noInterrupts(); ... interrupts(); Pause interrupts while you copy the count, so you never read half of a number that's being changed. A long is 4 bytes, and the Uno copies it one byte at a time.

Example, not the project: a hand-cranked rope winch with an encoder on its crank. It reports how much rope is let out.

#include <Arduino.h>

const int ENC_A = 2;      // interrupt pin
const int ENC_B = 5;      // plain pin, for direction
const float CM_PER_COUNT = 0.25;   // measured: rope length per count

volatile long count = 0;

void onPulse() {
  if (digitalRead(ENC_B) == LOW) {
    count++;      // one way
  } else {
    count--;      // the other way
  }
}

void setup() {
  Serial.begin(115200);
  pinMode(ENC_A, INPUT_PULLUP);
  pinMode(ENC_B, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(ENC_A), onPulse, RISING);
}

void loop() {
  noInterrupts();
  long c = count;      // copy it safely
  interrupts();

  Serial.print("rope out (cm): ");
  Serial.println(c * CM_PER_COUNT);
  delay(200);
}

If the count goes down when it should go up, swap count++ and count--. INPUT_PULLUP does no harm if the encoder board has its own pull-up resistors, and it helps if it doesn't.

Wire both encoders (12 V unplugged):

From To
Left encoder VCC / GND Uno 5V / GND
Left encoder A (C1) Uno pin 2
Left encoder B (C2) Uno pin 5
Right encoder VCC / GND Uno 5V / GND
Right encoder A (C1) Uno pin 3
Right encoder B (C2) Uno pin 6

Most JGB37-520 listings give the encoder supply as 3.3–5 V. Check yours before you connect it to 5V.

Mission 3 · Counts per wheel turn

Sellers don't agree on how many pulses these encoders give per motor turn (11 and 20 both show up), and the gear ratio depends on the model. So measure it.

  1. Count both encoders with two interrupt functions and two volatile long counters. Print both counts.
  2. Make forward positive for both wheels. Roll the robot's wheels forward by hand: if one count goes down, flip that wheel's ++ and --.
  3. Put a piece of tape on each wheel as a marker. With the 12 V unplugged, turn one wheel 10 full turns by hand, slowly, and read the count. Divide by 10. Do it twice for each wheel.

Done when

Both counts go up when the wheels roll forward, and you have counts per wheel turn for each wheel, within 1–2 % between tries. Write it in the build log as a const.

Tool: speed from counts

Speed is how much the count changed in a fixed time. Every 10 ms, take the count, subtract the count from 10 ms ago, and scale it. For the winch:

long lastCount = 0;
unsigned long lastCheck = 0;
float ropeSpeed = 0;   // cm/s

// in loop():
if (millis() - lastCheck >= 10) {
  lastCheck += 10;
  noInterrupts();
  long c = count;
  interrupts();
  long change = c - lastCount;
  lastCount = c;
  ropeSpeed = change * CM_PER_COUNT / 0.010;   // counts in 10 ms → cm/s
}

In a short window you only catch a few counts, so a slow speed jumps between, say, 0 and 1 count. The blend from Part 1 smooths it.

For a wheel, the distance per count is the wheel's circumference (π × diameter) divided by the counts per wheel turn.

Mission 4 · Measure the speed

  1. In your fixed 5 ms loop, compute each wheel's speed in mm/s every second pass (every 10 ms). Measure your wheel's diameter with a ruler.
  2. Plot both speeds in Teleplot while setMotor() runs both wheels at a fixed u, say 100. Then try 50 and 200.
  3. Grab one wheel gently with a rag for a second. Watch its speed drop while the PWM stays the same.

Done when

Both speeds read positive going forward, match each other within about 10 % at the same u, and a quick check agrees: at a steady speed, count wheel turns for 10 s with a stopwatch, and turns × circumference ÷ 10 s is close to your reading.

Part 4 · Wheels chase the tilt

Mission 5 · Both wheels chase the tilt

Put it together: the fused angle drives the motors.

  1. Hold the IMU breadboard flat, the way it will sit on the robot's middle deck, with the X arrow pointing along the line of the wheel axle.
  2. Make both wheels' push proportional to the angle: u = 8 * angle (PWM per degree), sent with setMotor() to both motors. Limit u to ±255.
  3. If tilting forward rolls the wheels backward, flip the sign of u.
  4. Keep printing the measured wheel speed.

Done when

Tilt the board forward: both wheels roll forward (as if the robot were driving under its fall). Tilt it back: both roll back. More tilt, faster wheels. Level: they stop. Film it for your build log, and write down your counts per wheel turn and dead zone.

If you finish early

  • Try 0.95 and 0.995 in the filter. Plot each against the accelerometer angle while tapping the table. Which would you pick?
  • Run both wheels at u = 150 and plot their speeds. Does one motor run faster than the other? By how much?
  • Quiet the whine. At its normal PWM frequency (about 490 Hz on pins 9 and 10), the motors sing. One line in setup() speeds up Timer 1, the timer behind pins 9 and 10, to about 31 kHz, above what you can hear:

    TCCR1B = (TCCR1B & 0b11111000) | 0b001;   // Timer 1 prescaler = 1: pins 9 and 10 PWM at about 31 kHz
    

    millis() and micros() use a different timer, so they're not affected. Measure the dead zone again afterward: it may change. This is optional; the robot balances either way.

Sign-off with Dr. Alvear

  • Fused angle within 2° of a protractor at four angles, steady for 30 s
  • Motor stall current checked with Dr. Alvear; 12 V only on VM
  • Dead zone and counts per wheel turn measured and in the log
  • Wheel speeds in mm/s, forward positive for both
  • Both wheels chase the tilt in the right direction
  • Build log updated (photo + two sentences)