Easy Absolute Orientation: PNI SpacePoint Fusion in Python

SpacePoint Fusion

My college roommate Donnie mentioned the PNI SpacePoint Fusion in comments of the HMC5843 post, and it seemed too good to be true.  A 9 DOF controller (3 axes each of magnetometer, accelerometer, and gyro) with a Kalman filter to calculate a smooth quaternion that interfaces as a USB HID device, all for under $100.  I’d be surprised if PNI is making any profit on it.  I sound more like a shill than I’m normally comfortable with, but I’m truly impressed with this gadget. I have some plans for it involving a Microvision SHOWWX that I’m quite excited about; I’ll write more on that when it’s available in a couple of months.

SpacePoint Fusion Innards

PNI provides some Windows only sample apps that show off how weirdly stable and precise the SpacePoint Fusion is.  Luckily, since its a normal USB HID device (redundant, I know), and PNI provides application notes, it’s easy to use on any platform.  I wrote a Python module that uses libhid via python-hid to make it easy to prototype with in Linux.  The usage is pretty simple, as shown below.  Note that when plugging the device in, you need to keep it still for a few seconds while the gyros are calibrated.  After that, the quaternion, accelerometer, and button data can be updated 62.5 times a second.

>>> import spacepoint
>>> fusion = spacepoint.SpacePoint()
>>> print repr(fusion.quat)
(0.987518310546875, -0.04425048828125, -0.04119873046875, 0.145294189453125)
>>> print repr(fusion.accel)
(-0.054016113354999999, 0.018859863306999999, -0.89648437622400001)
>>> print repr(fusion.buttons)
(0, 0)
>>> fusion.update()
>>> print repr(fusion)
accel: (-0.054016113354999999, 0.018859863306999999, -0.89648437622400001)
 quat: (0.97186279296875, -0.233428955078125, -0.030548095703125, 0.005401611328125)
 buttons: (0, 0)

Update on February 7, 2010: I emailed PNI about a bug in the firmware, and got the following response:

Thank you for submitting the SpacePoint bug regarding libusb, Python, and Linux. You’re right! There is a bug in the SpacePoint FW that prevented opening interface 1 without opening interface 0 when using libusb under Linux. While your work around was effective in allowing the device to operate normally, one should be able to open interface 1 directly without the work around. We were able to use your Python source code to quickly diagnose and repair the bug. Please see the attached for the modified Python script. Please feel free to post this paragraph, the modified code, and all bragging rights on your blog (http://eclecti.cc/).

Units being shipped now have the fix. I modified the Python module to handle units both with and without the firmware fix and bumped the version to 0.2.

Download:
SpacePoint Python Module
or
Standalone spacepoint.py

Setting udev rules to get the permissions right

In most cases, the module will just work properly.  However, if you get the following error, you probably don’t have the right permissions to access the usb device.

>>> import spacepoint
>>> fusion = spacepoint.SpacePoint()
hid_force_open failed with return code 12.

On most modern Linux distros, you can fix this by setting a udev rule for the device. In Ubuntu Karmic Koala, saving the following as /etc/udev/rules.d/45-spacepoint.rules , running sudo service udev restart , and then unplugging and replugging in the device should fix it:

# PNI SpacePoint Fusion
SYSFS{idVendor}=="20ff", SYSFS{idProduct}=="0100", MODE="0664", GROUP="admin"

Sleep Remaining Indicator: A Laser Alarm Clock

Sleep remaining indicator

The chunk of title after the colon intends to serve as an explanation of what a sleep remaining indicator is. However, this project is neither an alarm nor a clock. It is a visual indicator of approximately how much time I have remaining to sleep in the night.

This may not be a problem you need solved. If, however, like me you wear glasses or contacts, the world when you are in bed turns into a blurry mess. Normally I reach over and unlock my phone or lean over and squint at my Chumby One, but those actions make it harder to get back to sleep. What I wanted was a way to instantly know how much longer I could sleep before my alarm would go off.

My solution involves a line laser, a servo, and an Arduino. I set a potentiometer with a number dial to approximately the right length of time in hours and hit the reset button. The servo with the line laser attached will shine the laser line onto the ceiling. The servo will then slowly rotate, moving the laser line underneath a cover made of Lego pieces, making the length of line showing on the ceiling shrink over the hours. It’s a little like an hourglass, but with lasers.

Laser line

Here’s the Arduino sketch. Use it under whatever license you want.

/* Sleep Remaining Indicator v1.0
 * by Nirav Patel <http://eclecti.cc>
 */
 
#include <Servo.h>
#include <math.h>
 
//#define photoPin 1
//#define laserPin 9
#define potPin 0
#define servoPin 10
#define M_PI_4 (M_PI/4.0)
#define MINSERVO 1190 // The laser line is no longer visible
#define MAXSERVO 1810 // The laser line is at its longest
 
unsigned long startTime;
unsigned long totalTime;
unsigned int lastVal;
Servo laserServo;
 
void setup()
{
  Serial.begin(9600);
//  pinMode(photoPin, INPUT);
  pinMode(potPin, INPUT);
 
  // this magic converts the pot value to 0 to 9 hours in milliseconds.
  totalTime = (unsigned long)31641*(unsigned long)(1024-analogRead(potPin));
  Serial.print('Time in hours: ');
  Serial.println((double)totalTime/(double)3600000.0);
 
  laserServo.attach(servoPin);
  startTime = millis();
  lastVal = 0;
}
 
void loop()
{
  // The laser brightness should depend on the ambient light in the room.
  // Unfortunately, my laser dislikes PWM, so I just have it hooked to 3.3v
//  unsigned int light = analogRead(photoPin);
//  analogWrite(laserPin,light>>2);
 
  // calculate the time we've been running (well, sleeping)
  unsigned long time = millis()-startTime;
  // Note that one could use this as an alarm clock by setting off a buzzer or
  // even having the servo rotate loudly
  if (time > totalTime) {
    laserServo.writeMicroseconds(MINSERVO);
    while(1) {}
  }
 
  // This trig makes the line length shrink uniformly over time.
  time = totalTime-time;
  double angle = atan2((double)time,(double)totalTime);
  unsigned int servoVal =  (unsigned int)((angle/M_PI_4)*(double)(MAXSERVO-MINSERVO))+MINSERVO;
 
  servoVal = (servoVal > MAXSERVO? MAXSERVO : (servoVal < MINSERVO ? MINSERVO : servoVal));
  // The servo is imperfect, so don't move unless the value actually changed
  if (servoVal != lastVal) {
    Serial.println(servoVal);
    laserServo.writeMicroseconds(servoVal);
    lastVal = servoVal;
  }
 
  // tick like a clock
  delay(1000);
}

Urban Moonshining: Home Distilling for Fun and (not) Profit

Copper Pot Still
At some point in high school, my friends and I decided to learn the lost craft of home distillation. We started with the best of intentions (well, not really), but were unable to build stills that functioned until we hit college. Since then, we have just about perfected the process of distilling tasty, cheap rum on a stove top. John Martin has chronicled our steps and missteps over the years in a series of blog posts. The first three cover the background story, the basics of fermenting a rum wash, and the general process of distillation. The final post covers the specifics of urban moonshining; that is, plans for a micro still that allows for home distilling within the confines of the average apartment.

Stove Top Still

Soapmaking

Soapmaking
Another rumbling done.

HOWTO: Improvise Jenga

The Players
Precarious
Destuction
A brilliant idea by Meg Blake.

Tetris Gingerbread House

Tetris Gingerbread House

Meg Blake, John Martin, Peter Martin, and I ported Tetris to the medium of sugar. A full build writeup will soon be a rumbling on John’s new site, rumblings.org.

Update: John’s post is up.

HMC5843 Magnetometer Library for Arduino

HMC5843 and Arduino

I (finally) have a project taking up the idle cycles of my brain, the first step of which involves figuring out how to use a magnetometer.  The project will eventually use the digital compass, accelerometers, perhaps a gyro, and maybe absolute forms of positioning like an IR camera.  I’m being slightly vague about this project both because the idea is by far the coolest thing I’ve ever come up with and because it is still somewhat short of half baked.

Anyway, Honeywell recently released a rather reasonably priced three axis magnetometer, the HMC5843, which SparkFun carries a breakout board for.  It interfaces over i2c, which is conveniently supported in hardware by most AVR microcontrollers, including the ones used on Arduino.  Arduino is something of paradox.  On one hard, the hardware is so simple and easy to use, vastly cutting down on the amount of time I need to spend arranging parts on a breadboard.  On the other hand, computations that should take a few operations instead call long functions that get compiled into hundreds, and the IDE makes me want to stab a stick of RAM into my jugular.  Luckily, one can mitigate the downsides by using an external editor, communicating with cutecom/minicom, and using avr-libc instead of the Arduino libraries as much as possible.  Back to the project.

The actual circuit is fairly simple.  Analog pins 4 and 5 on the Arduino serve as i2c’s SDA and SDC lines, respectively.  I’m using a level shifter from SparkFun to get the Arduino’s 5v lines down to the 3.3v that the HMC5843 is looking for.  Note that one can skip this by using a 3.3v Arduino Pro.  The FTDI chip on the Arduino outputs 3.3v, which is brought out on the headers, allowing the level shifter and the magnetometer to be powered off the Arduino.

I tried using the Arduino Wire library for i2c communication, but had no luck.  Atmel made TWI, the i2c implementation on the AVR, fairly easy to use, so I read through the datasheet, looked at some examples, and wrote my own Arduino library specifically for the HMC5843.  The current implementation is absolutely alpha, but it seems to read the x, y, and z values at 10 Hz correctly.  Note that you probably can’t use this library at the same time as Wire or another i2c library, and that it also doesn’t support having multiple i2c devices connected.  Its sole purpose is interfacing the HMC5843.  Here is an example sketch using it:

#include <HMC.h>
 
void setup()
{
  Serial.begin(9600);
  delay(5); // The HMC5843 needs 5ms before it will communicate
  HMC.init();
}
 
void loop()
{
  int x,y,z;
  delay(100); // There will be new values every 100ms
  HMC.getValues(&x,&y,&z);
  Serial.print("x:");
  Serial.print(x);
  Serial.print(" y:");
  Serial.print(y);
  Serial.print(" z:");
  Serial.println(z);
}

Continuing the theme of a different license for each set of code I release, this library is under a two clause BSD style license.  Please feel free to try it out and give me feedback/suggestions/patches/pedantic advice/flames.

Download and extract into the hardware/libraries/ folder of your Arduino directory:
HMC.zip

The Greatest Feeling

Know what the greatest feeling in the world is? It’s when you’re going to throw away an empty pack of Gushers Fruit Snacks and discover that there is one last one hidden in the corner.

August 15, 2009 at 8:00 pm - 1 comments

No Longer Being A Bum

One Infinite Loop

As of today, I am among the ranks of the employed, at a fruit stand in Cupertino.  Two months of doing little but watching Top Gear and playing Xbox games was enough to melt off the last school year of stress and send my mind into hibernation.  I’m going to be doing software development for the forseeable future, but that is about as specific as I can get.
The Bay Area is a strange transition from Pittsburgh or southern Connecticut.  The grocery stores are devoid of italian bread and red potatoes, apparently, and nobody jaywalks.  The sunny skies and In-N-Out Burgers balance it out though.
Work is going to be taking up most of my time, but I’ll finally be able to afford parts for the projects I’ve been stewing on.  A list, with no timelines attached, of what I want to do:
  • Build a laser projector to augment a cloudy night sky.  The plan here was to laser project stars, satellites, and other heavenly bodies onto the clouds in Pittsburgh, since nobody would be able to see them otherwise.  I don’t think the weather will work for that in the Bay Area, but I could still project onto a ceiling or something.
  • Implement a pretty basic portion of Johnny C. Lee’s thesis.
  • Add Windows support to the camera module in Pygame.  Linux support for webcams is finally being released with Pygame 1.9 fairly soon.  Werner Laurensse is working on an OS X implementation for 1.9.1.  It would be a bit strange to leave out perhaps the largest portion of Pygame’s audience.

Star Wars Uncut: Scene 437 in Stop Motion Photography

This is what happens (best case) when geeks have too much free time.  My friend John Martin and I decided to take part in Star Wars Uncut, an experiment to recreate Star Wars: A New Hope in a series of several hundred 15 second chunks, each created by random people across the internet.  I chose a scene with a pleasant blend of dialog and pyrotechnics.

John has an inordinate quantity of Star Wars merchandise, so we went with stop motion animation for the scene, something neither of us was familiar with.  We found the actual action figures for almost every part of the 15 seconds, and really only had to improvise on the explosions, as we would rather not blow up collectibles.

With assistance from Peter Martin and Meg Blake, we fabricated Y-wings out of soda bottles, cardboard tubes, cardboard, and spray paint.  We filled each with a mixture of half potassium nitrate and half sugar, lit it with a fuse, and dragged it with a string as we took pictures.  As you can see by the video above, the results are reasonable for an afternoon of filming and a $0 budget.