Calculating the compass bearing

The XLoBorg library only provides access to the RAW values of the MAG3110 device, which provides a measure of how strong the magnetic field on each of the axes is. To determine the direction of the sensor, we can use the readings from the x and y axes (assuming that we have mounted and calibrated the sensor horizontally). The readings of the x and y axes are proportional to the magnetic field in each direction around the sensor, as shown in the following diagram:

The magnetometer measures the strength of the magnetic field on each axis

The angle at which we turned away from the north can be calculated with the formula shown in the following diagram:

The angle we are pointing towards (that is relative to magnetic north) can be calculated using the measurements Rx and Ry

We can now obtain the compass angle by adding the readCompassAngle() function to our compass class, as follows:

  def readCompassAngle(self,cal=True): 
    if cal==True: 
      read = self.readCompass() 
    else: 
      read = self.readCompassRaw() 
    angle = math.atan2 (read[1],read[0]) # cal angle in radians 
    if (angle < 0): 
      angle += (2 * math.pi) # ensure positive 
    angle = (angle * 360)/(2*math.pi); #report in degrees 
    return angle 

We also need to add the following import with the other import statements:

import math 

We use the math function, math.atan2(), to calculate our angle (atan2 will return with the angle relative to the x axis of the coordinates read[1] and read[2] – the angle we want). The angle is in radians, which means that one full turn is defined as 2Pi, rather than 360 degrees. We convert it back to degrees by multiplying it by 360 and dividing by 2Pi. Since we wish to have our angle between the range of 0 to 360 degrees (rather than -180 to 180 degrees), we must ensure that it is positive by adding the equivalent of a full circle (2Pi) to any negative values.

With the sensor calibrated and the angle calculated, we should now have the proper compass bearing to use on our robot. To compare, you can see the result of using the uncalibrated value in our calculation by calling the function with readCompassAngle (cal=False).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.68.18