Change in code to allow alternate mounting of magnometer

Hi guys,

I’ve built a working digital compass that lights up one of 8 LEDs that is positioned closest to North as the device is rotated. Since I’m a complete beginner I had to utilize a good bit of code I don’t understand to interpret the data my HCM5883L magnometer sends to the Arduino. What I need to do however, is to mount the magnometer board vertically instead of horizontally as it currently is on my breadboard.

I’ve tried editing the code and just swapping the X and Z axises then recalibrating, but that doesn’t seem to have done it. I took on a pretty complex project for my very first project and am surprised I’ve made it this far, but if someone can help me with this last bit I can call this project done! Suggestions? I’ve attached my sketch. Thank you so much!!

compass.cpp (12.9 KB)

compass.h (753 Bytes)

digital_compass_latest.ino (5.76 KB)

Well, your bearing gets calculated in XYZ terms in here:

void compass_heading(){
  compass_scalled_reading();
  
  if (compass_y_scalled>0){
    bearing = 90-atan(compass_x_scalled/compass_y_scalled)*compass_rad2degree;
  }else if (compass_y_scalled<0){
    bearing = 270-atan(compass_x_scalled/compass_y_scalled)*compass_rad2degree;
  }else if (compass_y_scalled==0 & compass_x_scalled<0){
    bearing = 180;
  }else{
    bearing = 0;
  }
}

You say swapping X and Z didn’t “do it”. Did you do it in this function? What did it do then? What happened? Maybe your trig calculations would have to be reconsidered.

Yes, I swapped every X and every Z in the entire code.

When I recalibrate and put it in serial mode to watch the heading, a very small change in rotation results in a rather large change in heading, jumping from 20 degrees to 90 just by rotating 10 degrees or so. Other parts of the 360 degrees are more linear feeling. I think I bit off more than I could chew, I'm stumped!

zakelectric: Yes, I swapped every X and every Z in the entire code.

That doesn't seem wise. You should really only have to do it where the bearing is calculated, in the function shown above.