/* The sensor outputs provided by the library are the raw 16-bit values obtained by concatenating the 8-bit high and low accelerometer and magnetometer data registers. They can be converted to units of g and gauss using the conversion factors specified in the datasheet for your particular device and full scale setting (gain). Example: An LSM303D gives a magnetometer X axis reading of 1982 with its default full scale setting of +/- 4 gauss. The M_GN specification in the LSM303D datasheet (page 10) states a conversion factor of 0.160 mgauss/LSB (least significant bit) at this FS setting, so the raw reading of -1982 corresponds to 1982 * 0.160 = 317.1 mgauss = 0.3171 gauss. In the LSM303DLHC, LSM303DLM, and LSM303DLH, the acceleration data registers actually contain a left-aligned 12-bit number, so the lowest 4 bits are always 0, and the values should be shifted right by 4 bits (divided by 16) to be consistent with the conversion factors specified in the datasheets. Example: An LSM303DLH gives an accelerometer Z axis reading of -16144 with its default full scale setting of +/- 2 g. Dropping the lowest 4 bits gives a 12-bit raw value of -1009. The LA_So specification in the LSM303DLH datasheet (page 11) states a conversion factor of 1 mg/digit at this FS setting, so the value of -1009 corresponds to -1009 * 1 = 1009 mg = 1.009 g. */ #include #include LSM303 compass; char report[80]; //uint8_t teapotPacket[14] = { '$', 0x02, 0,0, 0,0, 0,0, 0,0, 0x00, 0x00, '\r', '\n' }; float heading, headingDegrees, headingFiltered, declination; void setup() { Serial.begin(9600); Wire.begin(); compass.init(); compass.enableDefault(); } void loop() { compass.read(); /* teapotPacket[2] = compass.a.x; teapotPacket[3] = compass.a.y; teapotPacket[4] = compass.a.z; Serial.write(teapotPacket, 14); snprintf(report, sizeof(report), "Acc: %6d %6d %6d Mag: %6d %6d %6d", compass.a.x, compass.a.y, compass.a.z, compass.m.x, compass.m.y, compass.m.z); Serial.println(report);*/ //Calculating Heading heading = atan2(compass.m.y, compass.m.x); // Correcting the heading with the declination angle depending on your location // You can find your declination angle at: http://www.ngdc.noaa.gov/geomag-web/ // At my location it's 4.2 degrees => 0.073 rad declination = 0.073; heading += declination; // Correcting when signs are reveresed if(heading <0) heading += 2*PI; // Correcting due to the addition of the declination angle if(heading > 2*PI)heading -= 2*PI; headingDegrees = heading * 180/PI; // The heading in Degrees unit // Smoothing the output angle / Low pass filter headingFiltered = headingFiltered*0.85 + headingDegrees*0.15; //Sending the heading value through the Serial Port to Processing IDE Serial.println(headingFiltered); delay(50); }