Ben Peoples Speaks

Lots of code
October 17, 2010, 6:55 pm
Filed under: Uncategorized

I spent the last weekend working on an IMU-based control system for an RC airplane.  I came across several bits of code that could be useful to the masses (at least, the programming masses).

First up, interfacing to Pololu’s micro servo controller using a software serial port on an atmega168, this emulates the Orangutan-lib’s servo_set, which sets the value in whole microseconds:

void servo_set(uint8_t servo, uint16_t value)

uint8_t upper, lower;

upper = (value*2) >> 7;
lower = (value*2) & 0x7F;



The software serial code is here:, which uses Timer1 to avoid an overflow on the baudrate. If you need Timer1 for something else, you can probably work out how to change that to an 8-bit timer, but make sure the baud value is then less than 255.

The other handy bit is the code to calculate how far you are off a heading, here using the heading as decidegress (e.g., 1 degree = 10):

heading_error = heading - heading_target;
if(heading_error > 1800)
heading_error -= 3600;
if(heading_error < -1800)
heading_error += 3600;

The trick here is that you have to wrap when your heading is more than 180 degrees off. You get a hard flip-over when you are exactly 180-degrees off, which I initially saw as an error, but turns out to be just a function of the math. You are furthest from your target at 180-off, and you can trigger from ccw to cw as you cross over that point.


Leave a Comment so far
Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: