Monday, May 23, 2011

Slow Work on the Compass

Last night I tried to do something that I thought would be pretty easy. I was going to take just the horizontal components of the magnetometer (ignoring the large vertical component like a compass does) and output the heading. Unfortunately, I ran into a couple problems.

The big problem was that the outputs weren't working and didn't make much sense to me. It turns out that the problem was related to not being able to output floating point numbers (numbers like 3.14 that are not simple integers) to the computer screen. I thought that when I output float numbers as integers, it just lopped off the numbers after the decimal point. It does do that, but doing so somehow screws up the other outputs. This is becoming a significant problem for debugging, so I think that I might have to use an alternate method for outputting these values. I think I saw online that other people had created custom functions to output float numbers, so hopefully I can just copy their code into mine. That might be my next task.

After I figured out that this was the problem, I was able to change a couple things and output just the numbers I really needed. The code did work reasonably well. I put the sensor flat on a table next to an actual compass, and they read pretty similar. It seemed like the sensor was reading maybe 3 or 4 degrees off from the compass. Not terrible, but not great. I'm wondering if magnetometer readings might need to be recalibrated. There is definately some noise in the readings. It would wander by about +/- 3 degrees as it sat there. That should be ok since I plan on averaging the readings. It was also very sensitive to being tilted. Just 10 degrees or so of tilt would cause the reading to vary by maybe 30 degrees or so. Hopefully the tilt compensation I have planned for it will work well.

There is one more problem I thought of. The heading is calculated simply as arctan(ycomponent/xcomponent), but the arctan function only works from -90 degrees to +90 degrees, so you need to use a couple conditional "if" statements to get from 90 to 270 degrees. That worked, but I realized that there is a discontinuity that will cause a problem for averaging. Right now, it will read 269 degrees, but if you rotate a couple degrees further, it will read -89 degrees. While that is fine in most cases, if the boat is heading towards 270 degrees and is trying to average several compass readings, the average of 269 and -89 is 180 degrees, not 270 degrees! The same problem happens if you shift that discontinuity to zero degrees (or anywhere else). It also happens when using degrees or radians. I'll have to figure out a way to deal with that.

No comments:

Post a Comment