Proceed to Your Destination Without Having to Ask Someone
Recalibrate your bearings on electronic compasses as Stuart navigates a journey with an MCU-guided compass module leading the way. He tells us how to avoid magnetoresistive effect, and the difference between magnetic north and true north.
I’ve been writing occasionally about sensors, this article is about electronic compasses. With modern GPS, it’s easy to keep track of where you are, and a GPS can even tell you the direction you are moving – as long as you’re moving. Some handheld hiking GPS units have a built-in electronic compass because GPS gives you your position but can only tell direction if you are moving; I have a hiking GPS with a built-in compass. A lot of cars contain a compass with the direction displayed either on the dashboard or in a corner of the review mirror.
Handheld mechanical compasses have been around for centuries, of course. I still have one in my hiking backpack. A compass can be affected by nearby metal and other interfering items. I had a compass in a car years ago that tended to point to the engine block rather than pointing north. Mechanical compasses are also prone to break and obviously can’t be incorporated into a vehicle dashboard display. Sailing ships with steel hulls and mechanical compasses have historically had steel balls and compensating magnets to adjust for the magnetic effects of the ship’s hull.
Normally a mechanical compass points to the north pole – the magnetic north pole. The magnetic north pole isn’t quite the same as the geographical north pole. Sometimes it doesn’t matter because you are using a compass to navigate between two visible points. Or else you just want a general north/south indication, like the way the compass in a car just gives you a general direction at the 8 points of the compass (N, NE, E, etc.). But sometimes you want to know where true north is, and you want more precision than the 8 compass points. This is especially important in aviation. Of course, modern airplanes use GPS for navigation, but the FAA still requires a compass as a backup instrument.
DECLINATION
As I mentioned, a magnetic compass points to magnetic north, not geographical (true) north. Aviation charts and other maps use true north. A compass can be adjusted to compensate for the difference, but there’s a catch – you have to know where you are geographically. The difference between true north and magnetic north is called declination. Figure 1 shows a chart of the approximate declination for the USA in 2° increments. As you can see, it’s not a straight line, it’s a series of curves. So to calculate true north, you need to know where you are and then calculate the difference using the declination chart (or equivalent software). True north is the magnetic bearing plus the declination for your location (west is negative and east is positive). So if your compass reads 270° and if you are in a location where the declination is 20°W, then true north is at 270-20 or 250°.
Note that the declination lines are marked E on the west side of the USA, and W on the east side. So it’s a little confusing. But E declinations are added to magnetic bearing and W declinations are subtracted. If you are trying to calculate expected magnetic bearing from true north (as indicated on a map, for example) then the math is reversed; E is subtracted from true north and W is added to give the magnetic bearing.
One advantage of an electronic compass is that you can program your software to adjust for declination – but, again, you have to know approximately where you are.
WHAT’S IN AN ELECTRONIC COMPASS?
An electronic compass is a magnetic field sensor that is configured to measure compass heading relative to magnetic north. The most common type of compass uses magneto-resistive sensors. Lord Kelvin discovered magnetoresistance, the change of resistance in iron when placed in a magnetic field, in 1857. But it was a useless curiosity then. Modern electronics can capture the magnetoresistive effect in a useful way. A typical electronic compass has two or three magnetoresistive sensors that are sensed by an analog processing portion and then delivered to a host MCU in some digital form (SPI, I²C, etc.).
Figure 2 and Figure 3 show a schematic for a basic electronic compass demonstration. Figure 2 is a TM4C1233H6PM MCU; connector J3 is for a Honeywell HMC5983 compass module. Connector J2 is a serial port connector for programming the MCU. The MCU circuit is part of a development board; as I usually do with these projects, I deleted from the schematic anything that isn’t used here.
Figure 3 is a 2 line x 16 character LCD module. U3 and U4 provide an interface between the 3.3V MCU and the 5V LCD module; if you used a 3.3V LCD, then U3 and U4 would not be needed.
The HMC5983 is premounted on a module with pins on 0.1” centers. The part is in a 16-pin LPCC package; hard to work with using hand soldering tools, so the module is an easy way to prototype with it. Figure 4 is a photo of the HMC5983 module that I used.
The firmware, available on the Circuit Cellar website, is created in C using the TI Code Composer studio.
Figure 5 is the programming adapter for programming the MCU; it plugs into a PC RS232 serial port, or to a USB-to-RS232 adapter. To program, the MCU, you would short W1 to select programming mode, then reset the MCU with switch S1 (or power-cycle the circuit) then program the MCU using the TI LM Flash Programmer application. Finally, un-short W1 and reset again to run the new software. If you’ve seen my previous articles using the TM4C parts, this is identical to those.
HMC5983: The Honeywell HMC5983 is a 3-axis magnetic field sensor, operating at 3.3V, and with internal temperature and offset compensation. Accuracy is 1° to 2°. The output is selectable as either SPI or I²C interfaces. The device is controlled via a set of internal registers to configure operation modes, take a measurement, and read results. All register reads are 8 bits; 16-bit registers are read as two 8-bit registers (MSB and LSB).
The direction information is provided in X, Y, and Z registers. X and Y values are the magnetic field strength in the X and Y directions (assuming the device is level). Z is the tilt. To calculate magnetic heading, the X and Y results are used (with arctangent calculation) to find magnetic north. The algorithm is described in Honeywell application note AN-203, and implemented in the code. The algorithm is:
If Y = 0 and X > 0, direction = 0°
If Y = 0 and X < 0, direction = 180°
If Y > 0, direction = 90 – (arctan(X/Y)*180/π)
If Y < 0, direction = 270 – (arctan(X/Y)*180/π)
Note that the 180/π term is for converting to degrees; if you try this on a handheld scientific calculator in radians mode, you will need that term. If in degrees mode, that term is not needed since the result of the arctan operation will already be in degrees. The software uses it because the c atan() function returns radians.
The temperature sensor, used for temperature compensation, is also available to the host MCU; the demo software doesn’t use it. However, you could use it if your application needs to know the ambient temperature; it would eliminate the need for an additional temperature sensor. Temperature is not output directly in °C or °F; you have to do some math on the output to get actual temperature. The datasheet has the formula for doing that.
The HMC5983 also has the ability to average up to 8 samples before generating an output; that feature is not used in the demo software. It also allows for adjustable gain to match the sensor to the local field strength.
SOFTWARE
The software for the project reads the HMC5983 and displays the X and Y register values on the first line of the LCD, then the degree heading on the second line, followed by the compass direction (N, NW, W, etc.). Although the HMC5983 produces a tilt value in the Z register, the software doesn’t use it. So the compass reading on this demo depends on holding the sensor level.
Figure 6 shows the LCD display for one reading, X and Y registers are 88 and 76. Using the conversion formula above, this gives a heading of 40°, and a direction of NE. The code calls anything between 22° and 67° NE.
The code does not adjust for declination, so if you wanted to use it as a basis for a real application you would want to add a table for that. The magnetic declination in Colorado, where I live, is about 12°E. So while the magnetic reading shown in Figure 5 is 40°, the true north reading is 40 + 12 or 52°. Of course, the declination varies by where you are in the state (or in any state).
APPLICATIONS
The obvious application for an electronic compass is navigation, whether a handheld compass while hiking or an in-dash compass while driving. GPS can replace a compass in most navigation situations. I’m a fan of GPS, I worked on GPS development when it was an all-DoD program. But GPS does have some limitations. The first is the need to have access to the GPS satellites; inside a building that is sometimes unlikely. Especially if the building has a metal roof or reinforced concrete walls. In addition, GPS can only provide a compass direction while moving. While stationary, GPS can give you a very accurate position, but it has no idea which way you are facing unless it incorporates an electronic compass as previously mentioned. So imagine the following possibilities.
DIRECTION VERIFICATION
Imagine that you have a product that has to operate remotely, say something that turns a solar panel to face the sun to charge a battery, maybe for a gate opener. You can, of course, calibrate the position of the panel and depend on the on-board MCU to adjust the direction. But what if the panel is jammed, or a gear fails or the drive motor fails? How would you know? With an electronic compass, your software would have direct feedback as to the position of the panel; if it’s not moving, the MCU can detect it and call for help. In addition, if a strong wind blows the panel out of position, the MCU can detect and correct it. A similar application would be verifying the position of an antenna rotor, or any application where your system needs to confirm the direction something was commanded to be pointing. You can put a sensor on the motor shaft or the rotor shaft to be sure it is turning, but a compass would give absolute feedback as to the actual position.
GPS is complex: You can get GPS modules cheaply; I did an article about them in Circuit Cellar back in 2018. But GPS doesn’t have inherent navigation capability. The GPS satellites provide very accurate time information, and the GPS receiver uses triangulation to determine location. But a GPS module does not tell you that you are at 340 Main Street, it only reports longitude and latitude. Precise location information that gives you an address is all contained in the maps. In some low-volume applications you may not be able to justify the expense of licensing one of the street or nautical maps for your product. And you may not need that information, you may just need to know, like in the solar panel example, which way something is facing. In a fixed installation, the coordinates may not matter since you know exactly where it is. But direction might.
Indoor: If the product is indoor, you may not be able to get a GPS signal. But unless there is enough metal to confuse the compass, it will still be able to give you directional information. If you need precise location information, GPS is the way to go. But like the outdoor solar panel application, a compass can tell you which way something is facing even when there is too much building to allow a GPS receiver to get a signal.
Startup Orientation: A device such as an industrial robot might need to be oriented on powerup. In most such applications, the controller will know the orientation of the device. But in some scenarios, the orientation may not be known at powerup or after a power outage. A compass can provide an indication of orientation before the controller tries to activate any kind of motion, to prevent damage. Of course, the controller either has to know what the magnetic orientation should be, or else part of initial setup would involve rotating the compass sensor so that it points north when the device is in its rest or initial position.
These examples may be a bit contrived, but illustrate ways you might be able to make use of an electronic compass in applications other than navigation.
OTHER COMPASSES
The HMC5983 is not the only compass IC available, of course. Other devices have additional features. The ST Micro LSM303 includes accelerometers so you can detect motion and direction in one device.
CONCLUSION
An electronic compass can provide directional headings for navigation, positioning, and other applications. This demo shows how one such sensor, the Honeywell HMC5983, can be adapted to an off-the-shelf MCU. Maybe a compass is applicable to your designs.
TI TM4C1233H6PM microcontroller: product page: https://www.ti.com/product/TM4C1233H6PM
RESOURCES
Infenion | www.infineon.com
Texas Instruments | www.ti.com
REFERENCES
[1] Stuart Ball, “START TO FINISH: Stepper Motors: A Primer for When You Need Precise Positioning” Circuit Cellar 401, December 2023, pp. 36.
[2] Stuart Ball, “START TO FINISH: Biometrics: How Do I Know You Are Who You Say You Are?” Circuit Cellar 393, April 2022, pp. 36.
[3] Infineon KP236 datasheet: https://www.infineon.com/dgdl/Infineon-KP236-DS-v01_00-en.
How magnetoresistance works (minus the math)
Lord Kelvin discovered in the 1800s that the electrical resistance of iron is affected by a magnetic field. However, the original discovery was not useful because of the tiny percentage change of resistance. But subsequent work has refined this characteristic to make a usable sensor.
IBM originally used magnetoresistive elements in disk drive read heads and it eventually became the standard for the read elements in spinning hard drives (solid state drives don’t store information on magnetic platters and don’t have read heads, so magnetoresistance is not applicable to that technology). Magnetoresistance is also applicable to other magnetic reader applications such as magnetic employee badge readers.
A typical magnetoresistance application involves a thin (nanometers) strip of magnetoresistive material such as nickel-iron. Even though they are not semiconductors, they can be applied to a semiconductor device, like the HMC5983 used in this demonstration.
A magnetoresistance sensor changes resistance slightly in the presence of a magnetic field, whether it’s a toy magnet or the earth’s magnetic field. The amount of resistance change is a function of the angle of the magnetic field to the magnetoresistive strip (Figure 7). The resistance change is a function of the cosine of the angle shown in the figure. By placing two or more magnetoresistive strips at right angles to each other, you can get a differential measurement.
To get a valid reading, the magnetoresistive strip is normally embedded in one or two legs of a Wheatstone bridge. This nulls out the offset (quiescent) resistance of the strip and helps compensate for temperature. A compass will have two strips mounted orthogonally (at right angles). A sensor such as the HMC5983 has a third magnetoresistive strip for the Z (tilt) measurement.
Distortion: Distortion in an electronic compass is the term for nearby magnetic sources that affect the reading. In a car, that might be the engine block, speakers in the dash, and other sources of magnetic interference. Compensating for this requires calibrating the sensor outputs. I did not implement this in my demo code, but Honeywell has algorithms available to do so. You can compensate for permanent distortion in the sensor platform – where the sensor is mounted, but not for varying distortion. For example, in a car you could compensate for the engine block, speakers, and vehicle frame, but not for buildings you pass as you drive down a street. However, the magnetic field of a source falls off with the square of the distance from the source, so the distortion caused by the vehicle itself is stronger than most buildings due to the proximity.
— ADVERTISMENT—
—Advertise Here—
Types of Magnetoresistive sensors
Anisotropic Magnetoresistive (AMR) Sensors use magnetoresistive strips that change their resistance based on the angle of an applied magnetic field. This is the type of sensor used in the HMC5983.
Giant Magnetoresistive (GMR) Sensors have more magnetoresistive effect (change of resistance for a given magnetic field strength) than AMR. They are built by layering magnetic material with non-magnetic material at nanoscale dimensions.
Tunnel Magnetoresistive (TMR) Sensors are constructed as two magnetic layers separated by a think insulating layer. They use quantum tunneling to produce a larger magnetoresistive effect than either AMR or GMR.
GMR and TMR sensors are typically used in motion sensing, contactless switching, current sensing, and other detection applications There are compass ICs that don’t use AMR; the Bosch BMM350 uses TMR. Hall Effect sensors are also used for sensing magnetic fields, but they aren’t a form of magnetoresistive sensor, so I’ll ignore them here.
PUBLISHED IN CIRCUIT CELLAR MAGAZINE • AUGUST 2024 #409 – Get a PDF of the issue
Sponsor this ArticleStuart Ball recently retired from a 40+ year career as an electrical engineer and engineering manager. His most recent position was as a Principal Engineer at Seagate Technologies.







