Go Down

Topic: HMC5843L Compass Chip simple programing question (Read 1 time) previous topic - next topic

arduinoPi

I have my compass chip with the below code, what happens is when I turn the ship counterclockwise it goes 360 then 359 ,358so on till about 270 then it goes back up to 360

how can I modify the code below to make it go from 0-360 ?


Code: [Select]
#include <Wire.h>
double res = 0;
void setup()
{
Wire.begin();
Serial.begin(9600);
initHMC5843();
delay(100);
}
void loop()
{
readxyz();
}
void initHMC5843()
{
   delay(5);
   Wire.beginTransmission(0x1E);// 7 bits address
   Wire.send(0x02);
   Wire.send(0x00); // continues reading
   Wire.endTransmission();
}

void readxyz()
{
   Wire.beginTransmission(0x1E);
   Wire.send(0x03);
   Wire.endTransmission();
   delay(5);
   Wire.requestFrom(0x1E, 6);
   if(6 <= Wire.available())
   {
       int x,y,z;
       x = Wire.receive() << 8;
       x |= Wire.receive();
       y = Wire.receive() << 8;
       y |= Wire.receive();
       z = Wire.receive() << 8;
       z |= Wire.receive();
       if(x>0)
       {
          res = map(x, 0, 246, 0, 90);
       }
       else if(x<0)
       {
         if(x!=0)
         {
           res = abs(x);
           res = map(res,0,255,90,0);
           res = 270+res;
         }
         else
          res = 0;
       }
       Serial.println(res);
   }
}

el_supremo

#1
Dec 26, 2011, 12:50 am Last Edit: Dec 26, 2011, 01:05 am by el_supremo Reason: 1
The specs that I found for that chip say that it returns a value from -2048 to +2047 inclusive. If 0 is zero degrees then I would replace this:
Code: [Select]

      if(x>0)
      {
         res = map(x, 0, 246, 0, 90);
      }
      else if(x<0)
      {
        if(x!=0)
        {
          res = abs(x);
          res = map(res,0,255,90,0);
          res = 270+res;
        }
        else
         res = 0;
      }


with this:
Code: [Select]

 if(x >= 0)res = map(x,0,2047,0,180);
 else      res = map(x,-1,-2048,360,180);


Pete
P.S. the map function returns an integer so you might as well declare res to be an integer as well.

arduinoPi

how would I incorporate the y axis to return a direction (in degrees)?
with just the x I find it goes from 0 to 270 and back

el_supremo

Do you have a spec sheet for the HMC5843L? It would also help if you could point to some code that works - i.e. code that reads the compass and returns a heading in degrees. I can only find the HMC5843 online and it doesn't seem to work quite the same (or your setup code is wrong).
Also, the values returned by the compass for each axis may not be directions, but a measurement of the magnetic field in which case you have to calibrate your program to what the chip returns.

Pete

arduinoPi


Go Up