Building a Balancing Scooter
Two wheels are more than you need! See my
self-balancing electric unicycle.
Also see Version 2 of the scooter.

Short MPEG Video [1.0 MB]




Self-balancing scooters, like the Segway™ are often thought to be technological miracles, but it is not actually very hard to build one. I built the one described here in about a week using off-the-shelf parts. I spent another week tweaking the high-speed stability, improving the steering control, and writing about it.

Although the Segway has several exotic components, mine is built from common low-tech parts like wheelchair motors and RC car batteries. The parts, even at small quantity retail prices, cost less than half of a genuine Segway. It also doesn't need complex or high-performance software. The first version was written in Python and used serial ports to talk to the gyroscope and motor controller. The current software, now in C running in an onboard 8-bit microcontroller, is only 500 lines of code.

Riding the scooter is definitely fun. Things I like about it are:

Things I don't like are:

Rolls Royce vs Model T

The Segway is made with quite high-quality, high-tech, and expensive components. Overall, the components I used are a lot lower-tech and cheaper than the ones in the Segway. Yet, mine seems to ride just fine. It suggests that there's room for a Henry Ford of balancing scooters to develop and sell a low-cost everyman's version. Here's a quick comparison. Quotes below are from segway.com.

SegwayMy Scooter
MotorsBrushless servo motors with neodymium magnets. "The highest-power motors for their size and weight ever put into mass production".Conventional DC motors with gearbox, widely used in powered wheelchairs.$286each from National Power Chair or from Robot MarketPlace.
Gearbox"Like a precision Swiss watch". Engineers designed the "meshes in the gearbox to produce sound exactly two musical octaves apart."Part of the wheelchair motor above. When going up a ramp, they sound kind of like the starter motor on my old Dodge Dart. Rrrrr-rrrr-rrrr-rrrr.
Batteries2, 60-cell custom-designed NiMH packs producing 72 volts. "the highest power of any currently available chemistry".20, 6-cell NiMH packs made for RC cars. They have "IDEAL SOLUTION FOR RC TOY" printed on them. $15 each from Powerizer.
WheelsWheels are "sophisticated engineering-grade thermoplastic." Tires by Michelin, with a "unique tread compound (a silica-based compound instead of traditional carbon-based materials)".Wheels are stamped steel. I think they're made for utility trailers. Tires made by Cheng Shin tire works. They make startlingly loud squelching sounds on tile floors. Tire and wheel are$79 each from NPC, and hubs are $20 each.
Controller"Sophisticated controller boards from Delphi Electronics" with "Texas Instruments digital signal processor, monitoring the entire Segway HT system and checking 100 times per second."An 8-bit microcontroller from Atmel, running code written in C using floating point arithmetic. It sends speed control commands out the serial port at 9600 baud in ASCII to the motor driver.$10 from Digikey.
Motor Driver"a set of 12 high-power, high-voltage field-effect transistors (FETs)".The controller has 16 MOSFETs and can handle way more current than my batteries can supply. Made byRoboteQ, it's $485 from Robot MarketPlace. It's a popular part for use in Battlebots.
Gyroscope"packed with five solid-state, vibrating-ring, angular-rate sensors"One ceramic rate gyro, of the same kind that's in your camcorder (to detect your hand jiggling and stabilize the video) or RC helicopter (to stabilize the tail), and a 2-axis accelerometer to correct for drift.$149 from Rotomotion complete with the Atmel microcontroller.
StructurePlastic and aluminum in smooth swooping shapes. "Chassis withstands 7 tons of force."Two pieces of aluminum plate with holes drilled in them, and a standard aluminum extrusion for the handle.
Safety featuresEverything is dual redundant. For example, "in the unlikely event of a battery failure, the system is designed to use the second battery to operate the machine and allow it to continue balancing until it is brought to a safe stop."There is no redundancy or backup system. It is not even robustly made. Loose wires literally dangle out the bottom. In the fairly likely event of the software crashing, a wire coming loose, a component failing, or the batteries running low, the wheels will stop and the entire kinetic energy of the system will be used to accelerate my head toward the ground.

Despite being able to build my own, I'm still impressed with the Segway™ and with the courage it takes to bring such a product to market. Like with cars, it's pretty easy to put together a motor and wheels and make it go. But building a safe, comfortable vehicle is a serious effort.

Warning

There is one very important difference between what can be built as an experiment and the commercial Segway: The commercial one has a lot of safety features, redundancy and fool-proofing. Mine has none whatsoever (Well, it does have a kill switch so it doesn't go zooming away if I fall off, and it does shut down if it finds itself tipped more than 45 degrees.) Those details are kind of important, and you should think about them carefully before considering building such a thing yourself. With a scooter like this, if it stops working for any reason (software crash, hardware failure, low battery) you will fall, hard, and probably on your face. Imagine zipping along at 10 MPH, and suddenly the platform you're standing on stops dead. Oh, and there's a T-bar in front of you to trip you up if you start to run. So you really shouldn't try to replicate this experiment, and I can't be responsible for what happens if you read this and try to build something.

A scooter that you ride on is not the best place to learn how to build a two-wheeled balancing device. Getting them working properly is quite subtle, so you should really start with atwo-wheeled balancing robot and then scale up. See my notes on safety if you're considering trying to build something.

Construction

The mechanical construction is incredibly simple. Just a plate to stand on bolted to the tops of the motors, a support across the bottom, and a handle. Hanging from the foot plate are two pieces of hand-bent sheet metal to support the batteries. The batteries are just taped and cable-tied to the sheet metal.

Mechanically it's much simpler than any other kind of vehicle. With only two wheels side-by-side, there is very little structure. With no steering it doesn't need complicated pivots and linkages. It is literally just two motors bolted to a frame and a stick to hold.


The electronics and footrest all fit entirely within the 14" wheel diameter. Without the handle, it can roll end over end. But the ground clearance is pretty small. I should go up to 16" wheels, hopefully a bit lighter than the big tires I've got now. Currently it weighs about 90 lbs with its full load of batteries. The wheels alone must account for 20 lbs of this.

Dashboard

The dashboard is an electronics chassis box with knobs for steering and balance feedback loop gain. This shows the early version of the dead man's switch, which really is not adequate. I found this out when I fell off, but the wire pulled apart instead of yanking out the connector. When it pulled apart, the exposed strands ended up touching to complete the circuit and keep it going. Fortunately, a safety feature in the software shut it down before it ran over my head.


Power

The motors I used are made for wheelchairs where they are driven from a 24 volt battery. I want a little more speed, so I drive them from 36 volts. My wheels are also a bit larger than the wheelchair's. It should reach 15 MPH flat out. I got 36 volts by putting 5 standard 7.2 volt RC car battery packs in series. The batteries are rated for 30 amps discharge and I wanted over 100, so I put 4 strings of 5 in parallel for a total of 20 packs or 120 cells.

There is a a complication with multiple NiMH batteries in parallel. You want to avoid current flowing between them when their voltages are a bit different. So there is a bridge rectifier for every pair of batteries, with both + and - terminals connected to the motor driver. That way the voltage on the 4 strings of batteries can differ by up to 1.5 volts without current flowing.

The batteries can be disconnected by the 4-way connector for safety, and for charging. I use anAstroflight model 112 charger, which delivers 5 amps charge current at the 40 volt charging voltage. See schematic diagram.

'

The system pumps energy back into the batteries when it's decelerating or doing downhill. I had worried about the frequent current reversals harming the batteries, but I'm assured by a number of people who've had experience doing this with NiMH batteries that it works well. There might be some extreme case, like starting at the top of Pike's Peak and riding all the way down, where it could overcharge and destroy the batteries.

' + '

Balance and Control

Balancing is easy. Just keep the wheels under the center of gravity. It's just like when you pick up a stick and balance it resting on the palm of your hand.

Actually, there are some complications. You don't know where the center of gravity is. You don't know exactly which way up is. And you may not be able to move the wheels fast enough to keep under it.

I discuss knowing which way is up under "Gyroscope" below, but for now assume it's known. Technically what it knows is the angle between the scooter's chassis and the direction of gravity. And instead of keeping the wheels below the center of gravity, it keeps the stick vertical (ie, the angle equal to zero.)

With the stick vertical, if you stand in just the right position, the center of gravity will be right over the wheels and the scooter will be stable. But if you lean forward, the center of gravity will be in front of the wheels and the scooter will start tipping forward. The computer senses this and moves the wheels to keep the stick vertical. But by then it has fallen some more, and it needs to move the wheels faster.

The net result is that when you lean forward, the scooter accelerates forward and when you lean back it accelerates back. It's surprisingly intuitive. Most people find they can control it within seconds of getting on it. If you're used to riding busses or subways, you're used to leaning forward when the bus is about to accelerate. Well, this scooter follows your lean instead of you having to follow it.

There is another complication. What happens if you keep leaning forward until the scooter is going so fast that the wheels can't keep up? It has to change the tilt of the scooter so instead of keeping the bar vertical, it tilts back. The bar is at waist level, so it pushes you back until the center of gravity is no longer in front of the wheels and it stops accelerating. If you lean farther forward it keeps tilting back in order to keep the speed down. In order to be able to tilt the scooter back it needs to speed up the wheels and get them out in front, so the speed limiter needs to kick in before the motors are maxed out. I currently have the limit set to 50% of maximum speed.

Keeping the Stick Vertical

Keeping the stick vertical is easy. If it tilts forward, it runs the wheels forward until the bottom of the stick is under the top.

Here too there are complications. It has to move the wheels just the right amount forward. Too much and it'll have to move them back, then forth, until the thing is bucking widly. This is pretty much the default thing that happens until you get it tuned just right.

It needs to know both the angle of the stick and how fast it's changing. Knowing how fast it's changing lets it slow down before it overshoots the mark. Technically this is known as a PD loop. The amount of drive it sends to the wheels is proportional (P) to the error in angle, and also to the derivative (D) of the error.

I mentioned above that when it's going too fast it needs to tilt the stick back. This is tricky to do, because in order to tilt back it needs to accelerate the wheels forward to get them a few inches out in front. It then seems like it's going even faster, and it tries to tilt even farther back. This is called "positive feedback" and it's a recipe for uncontrollable oscillation. Making this stable was the trickiest part of the whole project, and the fact that it can only be tested at high speed resulted in several moments of terror and a few bruises before I got it right.

Wheels and Steering

Steering is done by making one wheel go faster than the other. Because all the mass is centered between the wheels, it can spin around quite quickly.

When not moving, maximum turning corresponds to having one wheel at about 10% forward and the other at 10% reverse. This spins it around pretty fast. You wouldn't want to turn this fast at high speed because it would tip sideways, so it reduces the maximum turning speed as the forward speed increases.

The wheels have 0.5 degrees of toe-in, meaning that they are both angled slightly inwards. The front wheels of most cars have a similar amount of toe-in. Pneumatic tires are inherently flexible sideways, and it makes it more stable to have them always flexed slightly. I don't know if 0.5 degrees is the right amount and I haven't tested any alternatives. But the steering is quite stable despite not having any active correction in software.

Putting it all together

What takes many paragraphs to explain is surprisingly simple to code. Here is the basic pseudocode of the balance algorithm, complete with the numbers which made my scooter feel stable and responsive.

Inputs
angle, angle_rate: the tilt angle of the scooter in radians and its derivative in radians/sec
steer_knob: the reading from the steering knob, between -1 and +1.
Balance
balance_torque = 5.0 * (angle - rest_angle) + 0.4 * angle_rate
Limit top speed by tilting back
overspeed = max(0, cur_speed - 0.5)
if (overspeed > 0) {
  overspeed_integral = min(0.4, overspeed_integral + min(0.2, overspeed+0.05) * dt)
}
else {
  overspeed_integral = max(0, overspeed_integral - 0.04*dt)
}
rest_angle = 0.4*overspeed + 0.7*overspeed_integral
Steer. Decrease steering rate at high speed
steer_cmd = 0.07/(0.3+abs(cur_speed)) * steer_knob
Track current speed
cur_speed += 1.2 * balance_torque * dt
Differential steering
left_motor_pwm = balance_torque + cur_speed + steer_cmd
right_motor_pwm = balance_torque + cur_speed - steer_cmd
Outputs
left_motor_pwm and right_motor_pwm directly set the duty cycle of the pulse width modulator for the wheel controller, and range from -1 to +1 (+1 is 100% forward, -1 is 100% reverse.)

Gyroscope

In order to keep the handle vertical, it needs to know which way is up. Humans, other mammals, and even lobsters have a nifty little sensor in the inner ear which does this, and it's possible to do something similar mechanically. The simplest way to know which way is up is with a pendulum. A pendulum at rest points down.

Unfortunately, the scooter is not at rest. If it's accelerating forwards a pendulum will swing backwards. It may also get swinging back and forth. It needs a much more stable notion of up.

A gyroscope made from a spinning wheel is the classical solution to keeping a vertical reference. They are still used in airplanes to remind pilots which way is up when they're in the clouds. But having an actual spinning flywheel is clumsy. They take time to spin up, they need expensive precision bearings and lubrication and use a lot of power, and occasionally the flywheel explodes (they have to spin pretty fast) and sends little bits of shrapnel into the rest of the system.

Although it's hard to visualize, it turns out that if you have a tuning fork vibrating and rotate it, it will cause a measurable vibration in the perpendicular direction. By measuring the vibration you can tell which way it is rotating and how fast. The scooter uses a very small ceramic tuning fork in just this way. They are a standard electronic product called a piezoelectric rate gyro, used in handheld camcorders to detect your hand jiggling and subtract out the motion from the picture to make it stable. One of the first successful applications of nanotechnology, they're a vital enabling technology for TV shows like C.O.P.S.

Unfortunately, these rate gyros are not perfect. They tend to report a small rate of rotation even when they're perfectly still. And if the balancing software integrates this small rate for long enough, it'll think it has rotated a lot. So it needs to compensate for that, and it does it with a pendulum. While a pendulum may swing around and wobble back and forth in the short term, the long-term average of its position is straight down.

Again, it doesn't use an actual pendulum. It uses a "micromachined silicon accelerometer", a silicon chip with a sort of diving board etched into it. This diving board bends a tiny amount in the direction of gravity, and some electronics detect how much it bends. With two of these arranged perpendicular to each other, it can compute the angle of gravity by computing the arctangent of the ratio of the bending measurements. And unlike a pendulum they don't get swinging around.

So now it has to combine the short-term reading of the rate gyro and the long-term reading of the pendulum. There is a theoretically optimal way to combine these pieces of information into a good estimate of actual tilt angle. This is called a Kalman filter. Such a filter was a good place to start, but I found I got better results with a hand-tuned feedback loop.

Sound complicated? It's not as bad as it sounds. In fact, the whole code, including stuff to read ADCs and manage serial communication is about 500 lines.

Microcontrollers

All the software needs somewhere to run. Not so long ago this task would have required more computer than you could lift, but now it runs in a tiny chip costing $10. The one I used is fromAtmel. They're fast and very easy to write software for; I wrote the code in C using floating point arithmetic and trigonometric functions, and it has plenty of speed for this kind of application.

The Atmel chip I'm using has built in analog data converters to interface with the gyroscopes and steering controls so it's a nearly complete solution. There are only about 5 chips in the whole scooter.

Motor driver

The software needs to exert precise control over the speed and torque of the motors. Under worst-case conditions, like going fast up a steep ramp, the motors need to work very hard to keep up and can consume a tremendous amount of power doing so, as much as 5000 watts.

The torque generated by the motor is directly related to the current flowing through the motor. The current is controlled by alternately switching the motor across the full battery voltage, then short circuiting it. If it did this slowly it would do just what you'd think: alternate full speed, then full stop. But it alternates very fast, about 4000 times per second, and this produces a smooth output from the motor. If it spends 37% of the time with the motor connected to the battery, the motor runs about 37% of full speed.

The scooter uses a device made by RoboteQ to switch all this power around. It's a popular unit among Battlebot builders since it's small and handles a lot of power. It receives commands from the microcontroller over a serial port, such as "left motor 37% forward, right motor 35% forward" (but in a compact binary format) and it gives the motors that much power. This command would correspond to going about 5 mph in a gentle right turn.

Limits

In theory, balancing is quite simple. Just keep the support under the center of gravity. Where it gets complicated is in handing the limitations of the motor & battery system. The simple control strategy may require much more power than the motors and battery can deliver. If it lets the scooter get into a situation where the wheels can't keep up with the center of gravity, the rider will be thrown.

If you're going fast and then run into something like a ramp or speed bump, it may require a lot of power for a short time to keep the wheels going up the ramp. As batteries get low and motors get warm, the amount of available power goes down. It's hard to predict exactly when it doesn't have enough to run safely. There's certainly a large gap between when it couldn't handle hitting a speed bump at 10 MPH and when the batteries actually run down.

I plan to experiment with using a bank of capacitors to provide enough short-term oomph to handle hitting a major bump at high speed. It's much easier to calculate the amount of energy needed to handle a bump safely than the maximum speed for a given battery condition. It just needs enough to get the wheels out ahead of the center of gravity, so it can slow down. My back-of-the-envelope calculations suggest about 2500 Joules delivered in 0.5 seconds. The new carbon aerogel ultracapacitors (not to be confused with mere supercapacitors) can store this much power in small 4" x 4" x 2" package costing about $250.

Or, I could just stick a wheel in front of it. But that would seem like something of a compromise.

Performance and Testing

When I first built this, I had never been on a Segway or even seen one close up. You'd think with all my geeky friends I'd know someone with one, but I didn't. I tuned the system according to how I thought it should work. A few days after I put up this page, I got to try a genuine Segway and I realized two things: it felt better to have a stiffer feedback loop so the handle didn't move back and forth so much, and that it should limit maximum speed by tilting back. I changed both, and it feels much better now. These videos are from the original version:

Current Problems

These are the things that are currently bad about my prototype.

Things Learned

' + '

Future Work

Things I'd like to try, if I had more time:

Links

Ben Smither's self-balancing one-wheeled scooter.

nBot, a 2-wheel balancing robot. A much better place to start if you want to build something that balances. Good collection of links.

Ted Larson's balancing robot. Mesmerizing to watch.

LegWay, a balancing robot made from Lego.

A Japanese version of the Segway. Smaller and more fuel-efficient.

Equibot, a balancing robot without gyroscopes. Probably the easiest and lowest-cost balancing machine you can build if you want to build something. The disadvantage is that it only works on flat floors.

A simple and elegant experiment in dynamic balance

Francisco Lobo built a balancing robot using similar technology.

Some students in British Columbia built one. Their report includes working code and schematics.

The Brilliant Pebbles project has a useful wiki for programming Atmel microcontrollers.

Bay Area Segway Enthusiasts Group, who let me try a genuine Segway.

Steve Wozniak's Segway Page.

The Robot Marketplace sells most of the parts I used; they also sell higher quality battery packs.

Ugh. You knew it had to happen.

Maddox has an even simpler idea for making your own.

A FIRST robotics team built a balancing scooter in 2002.

Segway LLC.

Self-balancing Skateboard by the UBC Electric Bike Club.