lsm303dlh compass

Hi there
Im using the LSM303DLH compass module with an arduino Uno I’ve got the three example sketches serial calibrate and heading all to run and have ouput to touch screen and logged data to sd all is good.
However I now wish to extend what the compass displays. my application requires not only a current heading that is sampled displayed and updated every 2 second but additional displays for an average heading that is say sampled calculated and updated every two minutes . further calculation is made on this average heading(mean direction) to establish trend ie is the mean persistently shifting in one direction say from north toward east or is the mean oscillating ie swinging from north toward east and then returning back to ward north. If its not clear we are talking about tracking the nature of wind shifts
During a sailboat race. A tactical compass. You may ask how can a compass fixed on a boat give wind direction don’t worry it can, at least on one point of sailing, effectively the whole boat becomes the
Wind direction indicator.

So What I believe I need to do is write code for the arduino & compass that
Will sample the heading every 2 seconds ,store that sum into an array then after 2minutes of sampling add up the sum total of all readings and divide by 60 (total number of readings) to get a mean heading for that two minute period which is then parsed to the display and logged to sd card and also parsed into another array and stored for later (15 minutes ) calculation .the process is then repeated for another 2 minutes displayed and logged after some predetermined time say 15 minutes
Further calculation is made on the second array to compare elements for difference ie a persistent increment/decrement (shift from north to west) or an oscillation (swinging back and forth) this trend
Is then parsed to display, and logged.
I believe the logic of my thinking is about right here is one thing I’m doubtful about but I will come to that in a moment.My reason for this post is that im very new to electronics, arduino and programming only a few monthsI’m really lost to make a start .if I can insert &modify the supplied code below with if, and ,or statements. How to write the code to build and initialize an array how to analyze these arrays looking for increments/decrements etc.I have one reference the arduino cook book which is a help but im finding it really difficult to make that initial start I would really appreciate some pointers a bit of code to get me started would be fantastic. Returning to my doubt – I’m not sure that a simple addition on the heading samples is correct, that that would produce a true mean reading my math is really quite poor but I think because headings range from 0-360 deg if the direction swings around 0 deg say + - 15 deg could this throw up an error in what is display –not accurate hopefully some one may be able to help
Many thanks ken b

#include <Wire.h>
#include <LSM303DLH.h>

LSM303DLH compass;

void setup() {
  // Calibration values. Use the Calibrate example program to get the values for
  // your compass.
  compass.m_min.x = -520; compass.m_min.y = -570; compass.m_min.z = -770;
  compass.m_max.x = +540; compass.m_max.y = +500; compass.m_max.z = 180;

void loop() {;
  int heading = compass.heading((LSM303DLH::vector){0,-1,0});


This sounds like an exciting project, and we would be really interested to hear any updates, especially if you can post pictures or videos of what you are doing! And yes, I am surprised to hear that you can use the whole boat as a wind indicator, but I will take your word for it for now.

It sounds like you mostly just need to learn C programming, and there are numerous tutorials out on the web for that. You can also search for specific things you want to do. For example, if I search Google for “average heading of a sailboat”, the first result includes example C code. Some other things to search for are “moving average” and “exponential smoothing”.

I do have one suggestion about how to get your average heading (different from the one I found on Google). As you pointed out, you can’t really average numbers that loop back to zero. So instead you should try to straighten them out to be more like normal number - one that can get arbitrarily high or low. To do that, I recommend thinking about the way we measure turns. If you spin around twice, we say that you have done a 720° turn, not a 0° turn, right? The only way to do that is to track the turn step-by-step as it progresses. For example, if you see a sequence of angles like this:

340, 350, 0, 10, 20, …

you should adjust the last three to be 360° and higher, rewriting it like this:

340, 350, 360, 370, 380, …

After that adjustment you should be able to average the angles together in a reasonable way. So the only math that you need to figure out is how to rewrite each angle. What I would do is to add or subtract 360 until it is within 180° of the previous angle, but there are a few different ways you could do it.

I hope that little suggestion helps. Good luck with your project,


Many thanks for your speedy responses that is really important to me well not so much the speedy but the service.You have really helped both with your suggestions re searches and the math I was thinking conversion to a percentage but your solution makes better sense .
re the project the compass is just one part of the application .as you may realize its about sailing
my background is dinghy sailboat racing about 30 years racing and coaching is my passion.
high level competitive sailing is a very complex sport .in a nut shell if you have say 10 boats racing
the leading group might not necessarily have the fastest boat speed .things like how they maneuver the boat ,sailing in more wind or a more advantageous wind direction localized to them.unlike say a track race where the winner is clearly the fastest.on a sail boat winning is not always a true measure of a boats performance.
so where does the hardware fit in.Historically it has been notoriously difficult to measure the actual speed of a racing boat.we rely on feel and experience . but even after 30 years its nearly impossible to feel the difference between fast and slow. the hardware for the first time offers the prospect of providing solid evidence. it allows us to focus on the things that really adds a far greater level of confidence in the decision making process ,when confidence is high we relax and naturally sail faster for it.A tactical compass doesn’t provide evidence for boat speed .however it offers the prospect of even greater gains
in my experience the area of greatest potential gains and losses are to do with wind strategy.
The boat as a wind indicator . A sailing boat cannot sail directly toward the wind. Sails would flap just like a flag on a mast.A boat that is only blown along down wind is not much use. however we can make progress toward the wind at an angle of about 45 degrees by following a zig zag path we can effectively sail directly against the wind .when we follow this 45 degree path the boat becomes the wind indicator.
the wind is not constant it moves around a mean direction shifting ±10 or 15 degrees .
we race around two fixed points Bouys that are laid directly in line with the mean wind direction
lets say this mean direction is north 0 deg when the marks are layed . If it stays constantly at 0`
our closest angles to the wind will be 315` or 45` in this situation the distances to the mark are equal but and this is where the money is the wind is not constant the bouys are fixed when the wind shifts say 15` to the left the right hand coarse moves closer to the bouy and the lefthand coarse moves further away. because we are always try to keep to the 45` optimum angle to the wind the boat responds to the shifts it becomes a wind indicator.
what the compass tells us is weather left or right is favored it can therefore deliver great advantage.
This is a very simplified version of what actually happens .changes can be very sublte as ive said earlier
wind can swing back and forth or it can slowly move in one direction .
coding that will establish a mean direction and test for trends is a very powerful tool.
this is just the tip of the iceburg the full application integrates gps logging and display, tilt compensation
is another vital part of the kit it offers measurement of the mast tip movement in waves which effects
flow of air over the sails which can have a massive impact on performance.
also use of vectors to determine best tacking angles for volicity made good and coarse made good
all features that will use the LSM303DLH
integration of video for coaching again is a major feature
finally Ive been talking about the equipping one boat my intention is to equip three identical boats
this dramatically increases the coaching potential of the system

hope this gives an outline of what im working toward it doe sent cover everything in the app
but it covers the basics.
Ive got the concept just need the the skills and knowledge and a bit of time to make it happen

your help and support is most appreciated and valued
as the project develops i will gladly upload my progress

ken brown