Compass Equations HELP

Hey everyone

I am currently building a robot, and i decided to put a compass in it. I want to get the robot to take a reading then subtract or add 90 degrees and turn to that heading.

My problem is what if the heading it takes is 350 degrees. It will then add 90 and get 440. which doesn't work.

I have not made a code for this yet as i want to work this out first.
Thanks
JBoy_529

heading = heading % 360;
or
heading %=360;

look here:http://arduino.cc/en/Reference/Modulo

heading = heading % 360;

Still not quite there:

int heading = 45;  // heading NE
int turn = -90; // turn 90 degrees to port
....later
heading = (heading + turn) % 360;

Oops.

Add a dash of

heading = (heading < 0) ? 360 + heading : heading;

maybe?

Yes, unfortunately because the % operator is not a modular-arithmetic operator for negative values (a hangover from the early days of C compilers) I would recommend coding things this way:

  heading += change_in_heading ;
  if (heading < 0)
    heading += 360 ;
  else if (heading >= 360)
    heading -= 360 ;

Partly because on a microcontroller this will run much faster than the % operator too!

still room for improvement - try change = 1000? then one subtraction is not enough :wink:

 heading += change_in_heading ;
  while (heading < 0) heading += 360 ;
  while (heading >= 360) heading -= 360 ;