The compass needs to be calibrated in order to report values that are centered and equalized. This is needed because there are magnetic fields all around; by calibrating the sensor, we can cancel out the effect of any localized fields.
By measuring the readings of the compass on all axes, we can determine the minimum and maximum values for each axis. This will allow us to calculate the mid-point of the readings, and also the scaling, so that each axis will read the same value whenever it is facing the same way.
Add the following code at the top of the file (after the import statements):
CAL=100 #take CAL samples
Add the following code to __init__(self) of the compass class:
self.offset,self.scaling=self.calibrateCompass() ...