How to make a Balboa robot balance, part 2: inertial sensors

via Pololu Blog

This is the second post in a series about how to make a Balboa 32U4 robot balance. Last week I talked about selecting mechanical components. In this post I will cover the inertial sensors included on the Balboa’s control board and how to use them in your code.

The key to Balboa’s balancing ability is the built-in ST LSM6DS33 IMU chip, which combines a 3D gyroscope and a 3D accelerometer. The Balboa also includes an ST LIS3MDL 3-axis magnetometer. Both sensors are connected to the AVR via I²C, giving it access to a total of nine sensor channels. These nine channels can be used in software to make an AHRS (attitude and heading reference system), a system that gives the robot a sense of its orientation in three dimensions. AHRS software is particularly important in aviation/drone applications, but for basic balancing, you don’t need anything that complicated. In fact, a single gyro channel is enough to determine the robot’s angle of rotation relative to vertical. The gyroscope’s y-axis channel measures the Balboa’s forward/backward rate of rotation; that is the channel we will be looking at here.

Configuring the gyro

When using the LSM6DS33, the first thing you need to do is configure its angular rate measurement range, which can be set to ±125, ±245, ±500, ±1000, or ±2000 degrees per second. A larger range can support faster motion, but it will have lower resolution. So which range is best for Balboa? If you watch our slow-motion video, you can see it making its quickest movement: popping up 90° from the ground to a balancing position in about a quarter-second, corresponding to an angular speed of around 360°/s. This means that a range of ±1000 is probably enough to cover any normal Balboa motion.

The Pololu LSM6 Arduino library initializes the device with a default setting of ±245°/s, so we have to adjust this in our code. Configuring the LSM6DS33 involves setting some bits in configuration registers, which can be confusing if you have never done it before. You will need to open up the datasheet (1MB pdf), which is also available as a download on the resources tab of the Balboa product page. Let’s look at the table from the datasheet showing the gyro configuration register CTRL2_G:

Table 46 shows that CTRL2_G is a single byte and tells use the names of each of its bits: ODR_G3, ODR_G2, and so on. The last bit is unnamed but must be set to a “0”. In Table 47 we see that two of the bits, FS_G1 and FS_G0, control the range setting: we need to set them to 1 and 0, respectively, to get ±1000°/s. The FS_125 bit should be left at zero except for ±125°/s mode. The rest of the bits control “data rate”, which has a small effect on the power usage and maybe also sensor noise. We will set it to 208 Hz, since that should be fast enough for our measurements. Looking at the appropriate line in Table 48, we can read off the required bits of ODR_G [3:0]: they need to be set to 0101 for 208 Hz.

Putting this all together, we want to set the CTRL2_G register to a binary value of 01011000, which we can represent directly in C++ as 0b01011000. The LSM6 Arduino library gives us a method for writing to a configuration register over the I²C interface and also includes constants for all of the registers listed in the datasheet, so the rest of the initialization code is easy to write:

void setup()
  // Initialize IMU.
  if (!imu.init())
      Serial.println("Failed to detect and initialize IMU!");
  imu.writeReg(LSM6::CTRL2_G, 0b01011000); // 208 Hz, 1000 deg/s

Gyro units

After initialization, the sensor will be ready to take readings, which it returns as sixteen-bit signed integers, one for each axis of rotation. Normally, we would talk about the rate of rotation using familiar units such as degrees per second, but the LSM6DS33 uses a different representation. Page 15 of the datasheet shows the sensitivity at each setting:

LSM6D33 gyro range settings and sensitivity.

What this means is that for our setting of ±1000°/s, you can get the rate of rotation in millidegrees per second by multiplying the sensor value by 35. But don’t do that! Since the measurement is a sixteen-bit signed integer, it has a range of -32,768 to +32,767. Multiplying a relatively large value such as 10,000 by 35 will result in an overflow, giving undesirable and even undefined behavior. We could get around this, but for our purposes it’s good enough and safer to instead convert to degrees per second. Mathematically, you would do this by multiplying by 0.035, but that’s also a bad idea in an Arduino program, since bringing floating-point numbers into your program can dramatically increase program size and slow down computations. Instead, since 1/0.035 is about 29, we can divide by 29 to convert to approximate degrees per second. Dividing by a positive, non-zero integer is always safe and cannot generate an overflow.

Testing and calibration

As a check to make sure we are on the right track, this would be a good time to write a test program that shows us gyro data. Please make sure that you have gone over the sections in the User’s guide on assembling your Balboa and programming it, and that you have tried some of the examples in the Balboa32U4 library, then copy this gyro testing code into your Arduino IDE:

#include <Balboa32U4.h>
#include <Wire.h>
#include <LSM6.h>

LSM6 imu;

void setup()
  // Initialize IMU.
  if (!imu.init())
      Serial.println("Failed to detect and initialize IMU!");
  imu.writeReg(LSM6::CTRL2_G, 0b01011000); // 208 Hz, 1000 deg/s

void loop()
  Serial.println(imu.g.y / 29);

This code reads the gyro ten times per second, displaying the result on the Serial monitor. Here’s some example output for a Balboa that was initially lying down; I rotated it gently up a bit and then back down again:

The first thing you should see is that the numbers look like useful data: even gentle motion is enough to make them jump up and down a lot, since 1 degree per second is very slow. It’s probably fine that we are using units of degrees per second rather than millidegrees per second. Next, notice that when the robot is at rest, unless you are lucky, the gyro reading is not zero. On my Balboa, the value was -5°/s. According to the LSM6DS33 datasheet, this is to be expected, and it comes largely from stresses placed on the chip when it is soldered. We will have to calibrate the sensor to compensate for this offset in our program. In this case, I could just stick a +5 somewhere in my code, but it’s better to check the offset every time, in case it changes with time or temperature, and to do it in the original units for slightly better accuracy. We can assume that the robot begins at rest and average together a series of 100 measurements for calibration, by defining a global variable gYZero and inserting this code at the end of setup():

  // Wait for IMU readings to stabilize.

  // Calibrate the gyro.
  int32_t total = 0;
  for (int i = 0; i < 100; i++)
    total += imu.g.y;
  gYZero = total / 100;


To keep track of the robot’s total rotation angle, you need to integrate the gyro reading: periodically check the sensor and multiply the rate of rotation by the time period. For example, in the Serial monitor output above, when we got a reading of -26, it was rotating at -21°/s during an interval of 0.1 s. A good estimate of the amount of rotation during this interval is -21°/s × 0.1s = -2.1°.

Here is the main gyro-related code from our Balboa Balancer example, which corrects for the offset, converts to degrees, and integrates the angle continuously:

// Call this every 10ms (UPDATE_TIME_MS)
void integrateGyro()
  // Convert from full-scale 1000 deg/s to deg/s.
  angleRate = (imu.g.y - gYZero) / 29;

  angle += angleRate * UPDATE_TIME_MS;

Since we are combining degrees per second and milliseconds here, the variable angle has units of millidegrees. Again, we have to be careful about the range of values on these variables; a value of 90,000 for 90° is beyond the range of a 16-bit integer. For simplicity, we use 32-bit signed integers (int32_t) for almost all of our calculations.

Initial angle and drift

Integrating the gyro reading actually only determines the total change in angle. You still need to pick a good starting value. An easy way to do this is to start the robot in a known position; for example you could initialize angle with a value of zero and start the robot from a vertical position. Our balancer example expects the robot to start lying down on its front side, with the angle initialized to 110 degrees.

Even after you have calibrated the gyro and estimated the starting angle, your angle measurement will tend to drift over time, maybe a few degrees in a minute. In a full AHRS, you use the accelerometer to eliminate drift, but for a balancing robot we can use a simpler trick: if the robot is successfully balancing, we know that on average, it must be close to vertical. So if we constantly, gradually shift the angle variable towards zero, it will not build up any significant error due to gyro drift. In our balancer example, that just takes a single line of code, called whenever the robot is balancing:

  angle = angle * 999 / 1000;

(In a future post, I will talk about how to do this within a complete balancing algorithm, which will have a concept of whether it is currently balancing or lying down.)

Putting this all together, we now have reliable measurements of the robot’s angle and rate of rotation, which will be crucial inputs into our balancing algorithm. Next week I will write about the encoders, another important set of inputs.

Free PCB coupon via Facebook to 2 random commenters

via Dangerous Prototypes


Every Friday we give away some extra PCBs via Facebook. This post was announced on Facebook, and on Monday we’ll send coupon codes to two random commenters. The coupon code usually go to Facebook ‘Other’ Messages Folder . More PCBs via Twitter on Tuesday and the blog every Sunday. Don’t forget there’s free PCBs three times every week:

Some stuff:

  • Yes, we’ll mail it anywhere in the world!
  • We’ll contact you via Facebook with a coupon code for the PCB drawer.
  • Limit one PCB per address per month, please.
  • Like everything else on this site, PCBs are offered without warranty.

We try to stagger free PCB posts so every time zone has a chance to participate, but the best way to see it first is to subscribe to the RSS feed, follow us on Twitter, or like us on Facebook.

Build a motorized gimbal on a budget with Arduino

via Arduino Blog

Tadej Strah, a freshman at Gimnazija Vic in Slovenia, made a motorized gimbal using only $60 worth of parts.

After joining a photo and film club at his university, Strah was inspired by a member with cerebral palsy to build an inexpensive gimbal to keep a small camera level. His project uses an MPU-6050 sensor to detect motion, and an Arduino Mega to process this data and control the device’s two servos. The setup includes a handle from an angle grinder, while the servos are mounted on bent pieces of metal, helping keep the cost down.

Strah believes that with a few upgrades, such as a smaller battery, Bluetooth connectivity, and a 3D-printed frame, it should be able to provide many of the features of those available for $500 or more. Hopefully we’ll see this design become even better in the future!

Until then, you can follow along with Strah’s progress, and perhaps another iteration of his gimbal, on his YouTube channel.


Beefy arms for Balboa balancing robot

via Pololu Blog

If you’re following Paul’s blog series about getting your Balboa robot balancing, you’ll probably want something to protect it when it falls. When I was working with my Balboa, I got a set of prototype arms that our mechanical engineers have been developing, but I felt they were missing a little something. So instead, I took a Beefy Arm Starter Kit from Thingiverse and used OpenSCAD to add adjustable mounting hubs to the arms. I printed two sets of arms with our RigidBot 3D printer and mounted them to the side rails on the Balboa chassis using 25 mm M3 screws and M3 nuts. They’ve been great for keeping obstacles and the floor at arm’s length from my electronics while I drove the robot around with an RC transmitter or through a Raspberry Pi web interface (example code coming soon!).

You can find these beefy arms for the Balboa on Thingiverse if you want to try 3D printing your own. The OpenSCAD script is also available there in case you want to customize your arms.

Pi Wars 2017 is just a few days away!

via Raspberry Pi

On 1-2  April, Cambridge Raspberry Jam will be hosting Pi Wars 2017, the latest iteration of their successful robotics challenge competition.

For those unfamiliar with the setup, Pi Wars contestants use home-brew Raspberry Pi-powered robots to compete across seven challenge courses. There’s also a host of other categories, including prizes for Artistic and Technical Merit, as well as an award for ‘Funniest Robot’!

With only a few days to go until the big weekend, we’ve wrangled Pi Wars 2017 hosts, Mike and Tim, to give us the lowdown on everything you need to know before the main event.

Pi Wars 2015 obstacle course Pi Wars 2017

Crowds gather around the Obstacle Course from the 2015 competition

Pi Wars 2017

This is the third time the competition has been run, and this time we’re running the event over two days:

  • Saturday – School teams.
  • Sunday – Beginner, Intermediate and Pro/Veteran teams.

With teams coming all the way from the USA, Germany, Switzerland, Wales and Scotland as well as England, it truly is an international competition! There are more than 65 teams competing across the weekend. Judging by some of the tweets we’ve been seeing, there’s likely to be some fierce competition!

Special guest and head judge

Doctor Lucy Rogers Pi Wars 2017

Lucy rightly running from House Robot, Sir Killalot, on the set of BBC Robot Wars

We are very fortunate to welcome BBC Robot Wars judge Dr. Lucy Rogers as our special guest and head judge. Away from Robot Wars, Lucy is an independent designer and maker, and famously introduced Raspberry Pi-controlled animatronics to the Blackgang Chine theme park on the Isle of Wight.

Get tickets, come along and watch the action

If you’re in the Cambridge area, or even if you’re further afield, you can come along and watch. Pi Wars 2017 spectator tickets are available from Eventbrite. Children aged 16 and under go free, as do volunteers, and it’s just £5 per day (or £7 for the whole weekend) for everyone else.

What else is happening?

In addition to the competing teams, there will be plenty of show-and-tell tables featuring robotics projects, plus an extensive marketplace featuring your favourite vendors.

Where is it?

The event takes place at the Cambridge Computer Laboratory (William Gates Building). There is free parking a (very) short walk away, and there is catering on site (or bring a packed lunch!). It’s a nice family-friendly day out. You can chat to the stall holders and teams (when they’re not running between challenges!), and generally find out what is possible with the Raspberry Pi, some robotics components, a healthy dose of programming and a maker’s mindset!

The William Gates Building Pi Wars 2017

The William Gates Building

What have we been doing to prepare?

Tim has been hard at work designing and building courses for our seven challenges, which are:

  • Straight-line speed test (autonomous) – get down the course as fast as possible without touching the walls.
  • The minimal maze (autonomous) – get around the maze without touching the walls.
  • The line follower (autonomous) – follow the black line for as many circuits as possible.
  • Slightly deranged golf (remote-controlled) – a beautiful, mystery course that will have a special component added to it by Pi Borg!
  • The obstacle course (remote-controlled) – who knows what’s in store this year?
  • Skittles (remote-controlled) – knock the pins down, score points.
  • Pi Noon – the robot vs robot duel (remote-controlled) – pop the other robot’s balloon before the time runs out.
Pi Wars 2015 Pi Noon competition Pi Wars 2017

2015’s Pi Noon competition

Find out more about the courses and the rules on the Pi Wars 2017 website.

Mike has been fiercely sending out emails to competitors, exhibitors, volunteers, vendors and our wonderful Pi Wars 2017 sponsors, without whom we would be unable to run the event. He’s also busy constructing individual timetables for each team, so everyone knows exactly where they need to be for their challenge runs.

We’re really looking forward to the weekend – it’s all coming together, and with the help of our volunteers, you can be assured of a warm welcome to the venue. So, grab your tickets and prepare for an epic showdown between dozens of robots, all powered by your favourite single-board computer!

The future of Pi Wars

There is an upcoming Pi Wars-style competition in Pennsylvania, USA on 3 June (The MagPi Magazine published a blog about this today), and we’re expecting another USA competition at some point, as well as a possible Pi Wars Scotland. As for the future of the Cambridge-based event? Let’s get this one out of the way first!

Any questions? The best way to contact us is via the Pi Wars 2017 website. Alternatively, give us a shout on Twitter!

Mike and Tim

The post Pi Wars 2017 is just a few days away! appeared first on Raspberry Pi.

Friday Product Post: All’s Well That Means Well

via SparkFun Electronics Blog Posts

Hello, and welcome to another Friday Product Post! Today we have a big treat for you, in the form of new, reliable power supplies from Mean Well! That’s right, four new units with custom-made power cables (sold separately) all available now. These aren’t your regular supplies, either; each provides a great deal of wattage at a great price. Let’s see what Feldi has to say about them!

If all’s well that ends well, then the ends should justify the means.

Mean Well Switching Power Supply - 100W


This is a 100W single output switching power supply from Mean Well. This power supply is extremely reliable and able to output 5VDC at 20A. We’ve been testing this power supply for quite some time and can definitely attest to its durability with its metal casing, short circuit, overload and overvoltage protections.

Inside the metal case that surrounds the power supply you will find a selector switch to change the voltage range between 85VAC to 132VAC and 176VAC to 264VAC, or 248VDC to 373VDC.

But that’s not all…

Mean Well Switching Power Supply - 150W


We also have a 150W version able to output 12VDC at 12.5A…

Mean Well Switching Power Supply - 350W


The large 350W version with 24VDC at 14.6A output…

Mean Well Dual Output Switching Power Supply - 24W


And, for the adventurous, a dual output 24W supply board as well!

However, you are going to need some way to hook these all up to power. Don’t worry; we have you covered!

Adam Tech Wall Adapter Cable (NA)


These Adam Tech Wall Adapter Cables are terminated with a standard North American (NEMA 5–15P) plug at one end and three insulated spade terminal connectors at the other. Each cable is 1m long and provides a safe and appropriate way to hook up our Mean Well power supplies!

Adam Tech Wall Adapter Cable (EU)


We also have a European version available!

Alright, folks, that’s it for today. We know you can get a lot of power out of this Friday’s products. We’ll catch you back here with even more new products next Friday. See you then!

comments | comment feed