Mounting HMC5883L magnetometer/compass in vertical orientation, wrong readings

Hello,
I am doing a project where I want to rotate my bot by 180 degrees. So for a feasible solution I thought of a magnetometer HMC5883L for rotation. i don't have to deal with Earth's magnetic field, I just want to know by how much degrees the bot has been rotated. I found this library (Attached) and this code to find the heading.

int heading()
{
    mag.getHeading(&mx, &my, &mz);
    
    // display tab-separated gyro x/y/z values
    Serial.print("mag:\t");
    Serial.print(mx); Serial.print("\t");
    Serial.print(my); Serial.print("\t");
    Serial.print(mz); Serial.print("\t");
 
    float heading = atan2(my, mz);
    if(heading < 0)
      heading += 2 * M_PI;
      heading = heading * 180/M_PI;
      int ihead = (int)heading;
    Serial.print("heading:\t");
    Serial.println(ihead);
    return ihead;
    
    blinkState = !blinkState;
    digitalWrite(LED_PIN, blinkState);
}

The vertical orientation is like the photo attached, its installed in the PCB we designed. (You will see teensy in PCB but need to try magnetometer on arduino first. )

I tried changing the parameter of atan2 filter to my, mz in the code but it is not giving accurate 90 degrees rotation when we rotate the bot by 90 degrees. Problem arising is when we rotate the bot by 90 degrees the readings changes by 140 degrees sometimes and sometimes less. Can anyone know the right code or solution for such kind of orientation of Magnetometer.

Any help will be appreciated.
Thanks

HMC5883L.zip (8.76 KB)

i don't have to deal with Earth's magnetic field,

Yes, you do. That is the very basis for the sensing.

If you are in the northern hemisphere, the Earth's magnetic field points into the ground as well as toward magnetic north.

Look up the details for your locality, because the code won't work properly until this is taken into account. At some point, you will need to study the data sheet to determine exactly where the sensor axes are pointing in your unusual mounting situation, and change the code to suit.

// display tab-separated gyro x/y/z valuesClever comment!