Solving angular measurements.

Hello..
This is my first post on Project Guidance.
I use Arduino MEGA 2560, a button (pin2) and a LSM303 connected via I2C.
Results are monitored via Serial Port.
Before I post the code, i´l explain the purpouse of the sketch.
Having Magnetic data from LSM "Magnetic North" monitored on Serial Port window (Acceleration not used yet), by pressing the button a line on Serial Port shows "Stored Heading" (the value displayed is stored in memory).
The inmediate next line "Change since last save", shows the difference (+/-) in degrees acording with angular rotation of LSM303 (if any change)...
After that, the Serial Port continues updating "Magnetic Heading".
Pressing the buton again, the above sequence repeats, replacing "Stored Heading" with new one (if LSM rotates).
The nex line, as mentioned, shows the "Change since las save" with the appropiate +/- sign ...
Example: With 150º stored, rotating LSM303 CW to 160º the "Change since last save" reads +10º. Or...
If I go back with 160º stored, to 150º, the reading is -10º. All is OK except..
When changes occur near Magnetig North.
With 355º stored, if the LSM303 crosses the North (CW) to 005º, the "Change since last save" reads -350º
With 005º stored, rotating LSM303 CCW to 355º, the reading at "Change since last save" is +350º
My programming skills are seriously basic... Too old to learn.
But I´ve been working with programmers before I retired and remember "trouble" each time angular measures was the project.
I would appreciate very much if someone reads the next CODE and finds what´s missing (or should be added)

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_LSM303_U.h>

/* Assign a unique ID to these sensors */
Adafruit_LSM303_Accel_Unified accel = Adafruit_LSM303_Accel_Unified(54321);
Adafruit_LSM303_Mag_Unified mag = Adafruit_LSM303_Mag_Unified(12345);

const int buttonPin = 2;//Your button Pin
int lastButtonState;
float storedHeading [2];
float lastHeading;
boolean timerExpired;
boolean updateDelta;
unsigned long startTime;

void setup(void) 
{
  Serial.begin(9600);
  /* Initialize the sensor */
  if(!mag.begin())
  {
    /* There was a problem detecting the LSM303 ... check your connections */
    Serial.println("Ooops, no LSM303 detected ... Check your wiring!");
    while(1);
  }
}

void loop(void) 
{
  int buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH)
  {
    if (lastButtonState == LOW)
    {
      storedHeading[0] = storedHeading[1];
      storedHeading[1] = lastHeading;
      Serial.print(F("Stored Heading = "));
      Serial.println(storedHeading[1]);
      updateDelta = true;
    }
  }
  lastButtonState = buttonState;
  //
  if (updateDelta)
  {
    Serial.println(F("Change since last save: "));
    Serial.println(storedHeading[1] - storedHeading[0]);
    updateDelta = false;
  }
  //
  sensors_event_t event; /* Get a new sensor event */
  mag.getEvent(&event);
  float Pi = 3.14159;
  float heading = (atan2(event.magnetic.y,event.magnetic.x) * 180) / Pi;// Calculate the angle of the vector y,x
  if (heading < 0)// Normalize to 0-360
  {
    heading = 360 + heading;
  }
  if ((heading != lastHeading) && (timerExpired))// update display on a change only
  {
    Serial.print("Magnetic North: ");
    Serial.println(heading);
    startTime = millis();
  }
  lastHeading = heading;
  if (millis() - startTime >= 500UL)
  {
    timerExpired = true;
  }
  else
  {
    timerExpired = false;
  }
}

The problem you are having is because of this line:
Serial.println(storedHeading[1] - storedHeading[0]);

You are not taking into account the direction of rotation, only the two positions where measurements are taken.
If you know you will never rotate your device for more than 179° at a time you can assume that it was rotated along the shorter direction, but that's not very nice way to do it.
Better, solution would be to check intermediate positions. You can accomplish that not by checking only when the button is pressed but continuously, and using that stream of information as a clue in which direction you are rotating your device.

I think this may be the code you are looking for.

I found it here mathematics - Comparing angles and working out the difference - Game Development Stack Exchange

angle = 180 - abs(abs(a1 - a2) - 180);

As far as I can tell it does what you want, i.e tell you the difference between 2 angles

Note it doesn't tell you if you have moved clockwise or anticlockwise

alternative code

angle = new - old;
if (angle < -180) angle += 360;
else if (angle > +180) angle -= 360;

keeps the angle between -180 and +180 so you can see which direction it rotated

assumption the rotation is never more than 180
rotate 350 degrees to the right will be seen as -10 to the left
no formula can detect that diff.

Thanks a lot for suggestions. I really apreciate your advice..
I heard years ago that angles are kind o tricky things to solve in programs.
Going back to the sketch I posted.. when I wrote
float Pi = 3.14159;
__ float heading = (atan2(event.magnetic.y,event.magnetic.x) * 180) / Pi;// Calculate the angle of the vector y,x__
** if (heading < 0)// Normalize to 0-360**
** {**
** heading = 360 + heading;**

And the code robtillaart posted, which lines should be deleted / added (or mixed)..
Sorry guys... As a technician on fluids/electronics I worked for almost 40 years side by side with good programmers but never had time to learn. I gave it a try in the late 70´s and early 80´s with Basic / Pascal /and some others but all of that is history..

one note:
float heading = (atan2(event.magnetic.y,event.magnetic.x) * 180) / Pi;
would be faster

float heading = atan2(event.magnetic.y,event.magnetic.x) * (180 / 3.14159265);

as the compiler could optimize the division away