Calibrating the compass

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() ...

Get Raspberry Pi 3 Cookbook for Python Programmers - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.