pythonsensorsmagnetometer

Compass setting


Compass calibrated correctly. To get the compass angle (360 degrees) I'm using the code

        heading = 180 * math.atan2(yh,xh)/math.pi
        if (yh >= 0):
            return heading
        else:
            return 360 + heading

Its ok. North indicates correctly. The question is what to do to add or leave the result eg. + 20 / -20 degrees (I need to put the compass in one fixed position.)

Thanks for help!


Solution

  • You can add (or subtract) from the heading and use the modulo operator to stay between 0-359 if you like:

    def rotate(heading, degree_change):
        return (heading + degree_change) % 360
    

    In addition, you could use the modulo operator to simplify the code you already have:

    heading = (180 * math.atan2(yh,xh)/math.pi) % 360