Remote-Control Powered Trapdoor Lift

William Wachsmann, a retired electronic technologist from Canada, has more than 35 years of experience working with minicomputers, microcomputers, embedded systems, and programming in industries ranging from nuclear and aerospace to voicemail and transportation systems.

But despite the complexity of the work he has done over the years, when it came to building a remote-controlled, powered trapdoor lift system for his home, he had two priorities: simplicity and price.

“Although it can be fulfilling to design your own hardware, why reinvent the wheel if you don’t have to? Many reasonably priced modules can be wired together,” Wachsmann says in his article about the project, which appears in Circuit Cellar’s May issue. “Add some software to express the functionality required and you can quickly and inexpensively put together a project. Not only is this method useful for a homebuilt one-of-a-kind application, but it can also be used for proof-of-concept prototyping. It leaves you free to concentrate on solving the problems pertinent to your application.”

Wachsmann’s project relies on off-the-shelf modules for the electrical functions of a trapdoor lift system that provides access to his basement.

“Lifting the trapdoor was hard on my wife’s back,” he says. “If her arms were full when she came upstairs and the door was open, she had to twist her body to release the mechanical latching mechanism while simultaneously stopping the door from falling on her head.”

The multidisciplinary project includes mechanical, electronic, and software components. For the full details—including programming of the project’s Freescale Semiconductor FRDM-KL25Z microprocessor using the mbed online IDE—check out the May issue now available for membership download and single-issue purchase.

(And if you’re interested in other articles about remote-control projects, check out Raul Alvarez’s Home Energy Gateway system, which enables users to remotely monitor home energy consumption and monitor household devices. Alvarez’s project won second place in the 2012 DesignSpark chipKIT challenge administered by Circuit Cellar.)

Excerpts from Wachsmann’s article below describe his system’s mechanical and hardware elements.

INS AND OUTS
I used a screw lift from an old treadmill. It has a 48-VDC motor that draws about 1 A under a 100-lb load. The screw mechanism has a 6” travel distance. Built-in limit switches shut off the motor when the screw reaches the end of its travel in each direction. The screw’s length is nominally 30” when closed and 36” when open. The length can be adjusted slightly by rotating the screw by hand, but the overall travel distance is still 6”.

A simple switch would have sufficed to control the screw lift’s DC motor, but I wanted it to be remotely controlled so the trapdoor could be raised and lowered from anywhere upstairs and from the basement. When someone is in the basement with the trapdoor closed there is no visible way for them to know if the door is obstructed. Initially, I was going to install a warning beeper that the door was opening, but that wouldn’t help if an inanimate object (e.g., a bag of groceries) was on top of the door. I needed to incorporate some form of sensing mechanism into the design.

Figure 1: This diagram represents the trapdoor mechanics. The arm’s down position is shown in red; the up position is shown in blue. Vertical red arrows are labeled with the downward force in pounds

Figure 1: This diagram represents the trapdoor mechanics. The arm’s down position is shown in red; the up position is shown in blue. Vertical red arrows are labeled with the downward force in pounds

THE MECHANICS
I needed a levered system design that used a pivoted bar and the motorized screw lift. The lift also had to enable the door to be manually opened in case of a power failure.
I used IMSI/Design’s TurboCAD program for the mechanical design. By using CAD software, I could experiment with the pivot position, moment arms, and torque requirements to meet the mechanical constraints imposed by the screw lift and the trapdoor’s size and weight.

Photo 1: The screw lift and pivot arm mechanism with a spring assist are shown.

Photo 1: The screw lift and pivot arm mechanism with a spring assist are shown.

Figure 1 shows a diagram of the trapdoor, which is hinged on the left. The opposite side of the door exerts a 15.2-lb downward force. This means the torque (force × distance) required to open the door is 509.2 in-lbs. The pivot arm in red is the position when the door is closed. The blue pivot arm shows the position when the door is open to an 80° angle.

To keep within the 6” lift constraint, I used a 4.25” moment arm to pull down on the pivot arm. This left me with the force required to initially lift the door at 119.5 lb. Also this did not include the added torque due to the pivot arm’s weight.

After mulling this over for a couple of days (and nights) I had an idea. I realized that 119.5 lb is only needed when the door is completely closed. As the door opens, the torque requirement lessens. I incorporated a heavy spring (see Photo 1). When the door is closed the spring extension provides an additional downward force of about 35 lb. This is enough to lessen the load on the screw lift and to compensate for the pivot arm’s additional 2.2 lb. Using a screw lift meant the arm would not spring up if the door was manually opened.

I used an angle iron for the pivot arm. It is 28” long because it had to push up on the door to the right of the door’s center of gravity at 16.75” without adding too much additional torque. The roller is the type used as feet on beds. I used an arbor and 0.75”-diameter bolt through the floor joist for the pivot (see Photo 2).

An arbor is used as a bearing with a 0.75” bolt through the floor joist. The lift mechanism pivots at this point.

Photo 2: An arbor is used as a bearing with a 0.75” bolt through the floor joist. The lift mechanism pivots at this point.

THE HARDWARE
I had set an arbitrary $100 limit for the rest of the system and I quickly realized I would easily come in under budget. I used a $24.25 two-channel RF wireless garage door remote-control receiver, which I purchased from eBay (see Photo 3). This controller can be used in a latched or an unlatched mode. The latched mode requires a momentary push of one of the buttons to cause one of the relays to switch and stay in the On position. When the controller is in unlatched mode, you must hold the button down to keep the relay switched.

Photo 3: The two-channel wireless remote control is shown with the cover removed from the receiver. It came with two keychain-style remotes, which I marked with Up and Down arrows.

Photo 3: The two-channel wireless remote control is shown with the cover removed from the receiver. It came with two keychain-style remotes, which I marked with Up and Down arrows.

Unfortunately, this remote control and any similar ones only come with single-pole double-throw (SPDT) relays. What I really wanted were double-pole double-throw (DPDT) relays to switch both sides of the motor to enable current reversal through the motor.
A remote control system with two remotes seemed ideal and was possible to design with SPDT, so I purchased the relays. Figure 2 shows the circuit using two bridge rectifier DC power supplies. It turns out there were problems with this approach.

SW1 and SW2 represent the Up and Down relays. In latched mode, the door would open when SW1 was energized using the A button on a remote. Pressing the A button again would stop the motor while the door was opening. So would pressing the B button, but then to continue opening the door you needed to press the B button again. Pressing the A  button in this state would cause the door to close because SW2 was still energized. Added to this confusion was the necessity of pressing the A button again when the door was fully opened and stopped due to the internal limit switches. If you didn’t do this, then pressing the B button to close the door wouldn’t work because SW1 was still energized.

Figure 2: It would be theoretically possible to use dual-power supplies and single-pole double-throw (SPDT) switches to control a motor in two directions. When SW1 (b,c) is connected, current flows through D2. When SW2 (b,c) is connected, current flows through D1 in the opposite direction.

Figure 2: It would be theoretically possible to use dual-power supplies and single-pole double-throw (SPDT) switches to control a motor in two directions. When SW1 (b,c) is connected, current flows through D2. When SW2 (b,c) is connected, current flows through D1 in the opposite direction.

I decided to just use the door in unlatched mode and continuously hold down the A button until the door was fully open. What was the problem with this? Noise! Interference from the motor was getting back into the control and causing the relay to frequently switch on and off. This is not good for mechanical relays that have a finite contact life.

After playing around for a while with both operation modes, I noticed that even in the latched mode the motor would sometimes stop and it would occasionally even reverse itself. This was really bad and it became worse.

If both SW1 and SW2 happened to switch at the same time and if the current was at a maximum and there was arcing at the terminal, there could conceivably be a momentary short through a diode in each of the bridge rectifiers that would burn them out. Arc suppression devices wouldn’t help because when active at high voltages, they would almost look like a short between the switch’s terminals A,C. I needed to step back and rethink this.

I found an $8.84 two-channel DPDT relay switch board module on eBay. The module enabled me to use a single-power supply and isolated the motor current from the remote-control board. These relays boards have TTL inputs, so it is tricky to use relays on the remote control board to control the relays on the second relay board. You have to contend with contact bounce. Even if I incorporated debounce circuits, I still didn’t have a way stop the door from opening if it was obstructed.

It was time to get with the 21st century. I needed to use a microcontroller and handle all the debounce and logic functions in firmware.

I bought a $12.95 Freescale Semiconductor FRDM-KL25Z development board, which uses the Kinetis L series of microcontrollers. The FRDM-KL25Z is built on the ARM Cortex-M0+ core. This board comes with multiple I/O pins, most of which can be programmed as required. It also has two micro-USB ports, one of which is used for downloading your program onto the microcontroller and for debugging (see Figure 3).

Figure 3: This is the system’s complete wiring diagram. On the left is a 48-V AC supply and an unregulated 12-V DC motor. A 2.7-Ω, 5-W resistor, which is used for current sensing, is in series with the motor.

Figure 3: This is the system’s complete wiring diagram. On the left is a 48-V AC supply and an unregulated 12-V DC motor. A 2.7-Ω, 5-W resistor, which is used for current sensing, is in series with the motor.

High-Tech Halloween

Still contemplating Halloween ideas? Do you have a costume yet? Is your house trick-or-treat ready? Perhaps some of these high-tech costumes and decorations will help get you in the spirit.

Recent Circuit Cellar interviewee Jeremy Blum designed a creative and high-tech costume that includes 12 individually addressable LEDs, an Adafruit microcontroller, and 3-D printing.

Skull_Side_Full_IMG_0067

Custom animatronic skull

RavenSide2Armature_IMG_0015

Animatronic talking raven

Looking for Halloween decoration inspiration? Peter Montgomery designed some programmable servo animation controllers built around a Freescale Semiconductor 68HC11 microcontroller and a Parallax SX28 configurable controller.

Peter’s Windows-based plastic skull is animated with RC servos controlled via a custom system. It moves at 24 or 30 frames per second over a custom RS-485 network.
This animatronic talking raven features a machined aluminum armature and moves via RC servos. The servos are controlled by a custom system using Windows and embedded controllers.

Peter’s Halloween projects were originally featured in “Servo Animation Controller” (Circuit Cellar 188, 2006). He displays the Halloween projects every year.

Feeling inspired? Share your tech-based Halloween projects with us.

MCU-Based Prosthetic Arm with Kinect

James Kim—a biomedical student at Ryerson University in Toronto, Canada—recently submitted an update on the status of an interesting prosthetic arm design project. The design features a Freescale 9S12 microcontroller and a Microsoft Kinect, which tracks arm movements that are then reproduced on the prosthetic arm.

He also submitted a block diagram.

Overview of the prosthetic arm system (Source: J. Kim)

Kim explains:

The 9S12 microcontroller board we use is Arduino form-factor compatible and was coded in C using Codewarrior.  The Kinect was coded in C# using Visual Studio using the latest version of Microsoft Kinect SDK 1.5.  In the article, I plan to discuss how the microcontroller was set up to do deterministic control of the motors (including the timer setup and the PID code used), how the control was implemented to compensate for gravitational effects on the arm, and how we interfaced the microcontroller to the PC.  This last part will involve a discussion of data logging as well as interfacing with the Kinect.

The Kinect tracks a user’s movement and the prosthetic arm replicates it. (Source: J. Kim, YouTube)

The system includes:

Circuit Cellar intends to publish an article about the project in an upcoming issue.

2012 ESC Boston: Tech from Microchip, Fujitsu, & More

The 2012 Embedded Systems Conference in Boston started September 17 and ends today. Here’s a wrap-up of the most interesting news and products.

MICROCHIP TECHNOLOGY

Microchip Technology announced Monday morning the addition of 15 new USB PIC microcontrollers to its line of full-speed USB 2.0 Device PIC MCUs. In a short presentation, Microchip product marketing manager Wayne Freeman introduced the three new 8-bit, crystal-free USB PIC families.

The PIC16F145x family (three devices) features the Microchip’s lowest-cost MCUs. The devices are available in 14- and 20-pin packages, support full-speed USB communication, don’t require external crystals, include PWM with complement generation, and more. They’re suitable for applications requiring USB connectivity and cap sense capabilities.

Microchip’s three PIC18F2x/4xK50 devices (available in 28- and 40/44-pins) enable “easy migration” from legacy PIC18 USB devices. In addition to 1.8- to 5-V operation, they feature a Charge Time Measurement Unit (CTMU) for cap-touch sensing, which makes them handy for data logging systems for tasks such as temperature and humidity measurement.

The nine devices in the PIC18F97J94 family are available in 64-, 80-, and 100-pin packages. Each device includes a 60 × 8 LCD controller and also integrates a real-time clock/calendar (RTCC) with battery back-up. Systems such as hand-held scanners and home automation panels are excellent candidates for these devices.

Several interesting designs were on display at the Microchip booth.

  • The M2M PICtail module was used in an SMS texting system.

This SMS text messaging system was featured at Microchip’s Machine-to-Machine (M2M) station. The M2M PICtail module (located on the bottom left) costs around $200.

  • Microchip featured its PIC MCU iPod Accessory Kit in glucose meter design. It was one of several healthcare-related systems that exhibitors displayed at the conference.

The interface can be an iPhone, iPad, or iPod Touch.

Visit www.microchip.com for more information.

RENESAS

As most of you know, the entry period for the Renesas RL78 Green Energy Challenge ended on August 31 and the judges are now reviewing the entries. Two particular demos on display at the Renesas booth caught my attention.

  • A lemon powering an RL78 L12 MCU:

Lemon power and the RL78

  • An R8C capacitive touch system:

Cap touch technology is on the minds of countless electrical engineers.

Go to www.am.renesas.com.

FREESCALE

I was pleased to see a reprint of Mark Pedley’s recent Circuit Cellar article, “eCompass” (August 2012), on display at Freescale’s booth. The article covers the topics of building and calibrating a tilt‐compensating electronic compass.

A Circuit Cellar reprint for attendees

Two of the more interesting projects were:

  • An Xtrinsic sensor demo:

Xtrinsic and e-compass

  • A Tower-based medical suitcase, which included a variety of boards: MED-BPM (a dev board for blood pressure monitor applications), MED-EKG (an aux board for EKG and heart rate monitoring applications), and more.

Tower System-based medical suitcase

STMicro

I stopped by the STMicro booth for a look at the STM32F3DISCOVERY kit, but I quickly became interested in the Dual Interface EEPROM station. It was the smartphone that caught my attention (again). Like other exhibitors, STMicro had a smartphone-related application on hand.

  • The Dual EEPROMs enable you to access memory via either  wired or RF interfaces. Energy harvesting is the new function STMicro is promoting. According to the documentation, “It also features an energy harvesting and RF status function.”

The Dual Interface EEPROM family has an RF and I2C interface

  • According to STMicro’s website, the DATALOG-M24LR-A PCB (the green board, top left) “features an M24LR64-R Dual Interface EEPROM IC connected to an STM8L101K3 8-bit microcontroller through an I2C bus on one side, and to a 20 mm x 40 mm 13.56 MHz etched RF antenna on the other one side. The STM8L101K3 is also interfaced with an STTS75 temperature sensor and a CR2330 coin cell battery.”

FUJITSU

I’m glad I spend a few moments at the Fujitsu booth. We rarely see Circuit Cellar authors using Fujitsu parts, so I wanted to see if there was something you’d find intriguing. Perhaps the following images will pique your interest in Fujitsu technologies.

The FM3 family, which features the ARM Cortext-M3 core, is worth checking out. FM3 connectivity demonstration

Connectivity demo

Check out Fujitsu’s System Memory site and document ion to see if its memory products and solutions suit your needs. Access speed comparison: FRAM vs. SRAM vs. EEPROM

Access speed comparison

The ESC conference site has details about the other exhibitors that had booths in the exhibition hall.

 

 

 

 

 

 

Implement a Tilt and Interference-Compensated Electronic Compass

Would you like to incorporate an electronic compass in a consumer product you’re designing or a personal device you’re constructing? If so, you’ll do well to understand as much as possible about the differences between various sensors and how certain forms of interference can affect their accuracies.

Mark Pedley of Freescale Semiconductor has an article in Circuit Cellar 265 (August 2012) on these topics. An abridged version of his article follows. Pedley writes:

 Whenever a new high-volume consumer electronics market develops, the semiconductor companies are never far behind, providing excellent components at surprisingly low prices. The market for sensors in consumer products is a recent example. It all started with an accelerometer used to select between portrait and landscape display orientations and then, with the addition of a magnetometer, evolved into the electronic compass (eCompass) used to align street maps to the smartphone’s geographic heading or to enable augmented reality overlays. As a result, high-volume pricing for smartphone accelerometer and magnetometer sensors is now less than $1 each.

A magnetometer sensor alone cannot provide an accurate compass heading for two reasons. First, the magnetic field measured at the magnetometer varies significantly with tilt angle. Second, the magnetometer requires calibrating not only for its own offset but also against spurious magnetic fields resulting from any nearby ferromagnetic components on the circuit board. This article describes how the accelerometer is used to compensate the magnetometer for tilt and includes a simple technique for calibrating the magnetometer.

SENSOR SELECTION

The accelerometer should be three axis and capable of operating in the ±2-g range with a minimum of 10 bits of resolution. The output of a 10-bit accelerometer operating in the ±2-g range will change by 512 counts as the accelerometer is rotated 180° from pointing downward to upward, giving an average sensitivity of one count per 0.35° change in tilt. This is more than adequate for tilt-compensation purposes.

It is important to check the accelerometer datasheet for the “0-g offset accuracy” which is the output when the accelerometer is in 0-g freefall. Since this value is a constant additive error on each accelerometer channel, it adds a bias in the calculated tilt angles, so look for accelerometers where this parameter does not exceed 50 mg.

The magnitude of the earth’s geomagnetic field is typically about 50 µT with a horizontal component that varies over the earth’s surface, from a maximum of about 40 µT down to 0 at the geomagnetic poles. If an eCompass is required to operate in horizontal geomagnetic fields down to 10 µT (in arctic Canada, for example) with a noise jitter of ±3°, then a back-of-the-envelope calculation indicates that a magnetometer with a maximum noise level of 0.5 µT is needed.

Most of my projects have used Freescale’s MMA8451Q Xtrinsic three-axis, 14-bit accelerometer and MAG3110 three-axis magnetometer. The MMA8451Q is supplied in a 3-mm × 3-mm × 1-mm, 16-pin QFN package and provides a 14-bit data output with ±30-mg, 0-g offset accuracy. The MAG3110 magnetometer is supplied in a 2-mm × 2-mm × 0.85 mm, 10-pin DFN package and provides a measurement range of ±1,000 µT with 0.1-µT resolution and a noise level down to 0.25 µT. Both parts operate with a supply voltage between 1.95 V and 3.6 V.

Similar sensors are supplied by Asahi Kasei (AKM), Kionix, STMicroelectronics, and other manufacturers. Your best strategy is to go to the manufacturers’ websites and make a list of those that provide samples in single units or low-volume packs of up to five devices. With a bit of luck, you may be able to get both the accelerometer and magnetometer sensors for free. Add a handful of decoupling capacitors and pull-up resistors and you should be well within the $5 component cost.

Each reader has a preferred microcontroller to read the raw data from the two sensors and implement the eCompass. This article assumes the microcontroller provides an I2C bus to interface to the sensors, supports floating-point operations whether natively or through software emulation libraries, and has a few spare bytes of program and data memory…

LAYOUT & BOARD BRING-UP

Once you’ve selected your sensors, the next step is to design the accelerometer and magnetometer daughterboard with I2C bus connection to the microcontroller. Reference schematics for the MMA8451Q and MAG3110 are provided in the sensor datasheets and reproduced in Figure 1.

Figure 1: Schematics for (a) MMA8451Q and (b) MAG3110 sensors (Source: M. Pedley, Circuit Cellar 265)

Don’t waste any time rotating the accelerometer or magnetometer packages to align their x-, y-, and z-sensing directions to each other since this will be  fixed later in software. But do ensure the sensor board will not be mounted in the immediate vicinity of any ferromagnetic materials since these will produce a constant additive magnetic field termed the “hard-iron field.” The most common ferromagnetic materials are iron, steel, ferrite, nickel, and cobalt. Non-ferromagnetic materials are all safe to use (e.g., aluminum, copper, brass, tin, silver, and gold).

The calibration process described later enables the estimation and software subtraction of any hard-iron field, but it’s good practice to minimize hard iron interference at the design stage. Remember, a current trace will create a cylindrical magnetic field that falls off relatively slowly with the inverse of distance, so place the magnetometer as far away from high current traces as possible. A 0.1-A current trace at 10-mm distance will produce a 2-µT magnetic field, four times our 0.5-µT error budget, only reducing to 0.5 µT at a 40-mm distance. More detailed layout guidance is provided in Freescale Semiconductor’s application note AN4247: “Layout Recommendations for PCBs Using a Magnetometer Sensor.”

You’ll be surprised at the number of features implemented in the latest consumer sensors (i.e., freefall detection, high- and low-pass filtering options, automatic portrait and landscape detection, etc.), but disable all these since you simply want the raw accelerometer and magnetometer data. Configure the accelerometer into a 2-g range and check that you can read the x, y, and z accelerometer and magnetometer data (in units of bit counts) from the sensors’ internal registers at a sampling rate of between 10 Hz and 50 Hz. Smartphones commonly use IDH3 to minimize power consumption while anything above 50 Hz is overkill. Check the accelerometer datasheet for the conversion factor between counts and g (4,096 counts per g for the MMA8451Q in ±2-g mode) and use this to scale the x, y, z accelerometer readings into units of g. Do the same for the x, y, z magnetometer data again taking the conversion factor from the magnetometer datasheet (10 counts per µT for the MAG3110).

COORDINATE SYSTEM

The equations and C software in Listing 1 use the “aerospace,” or “x-North y-East z-Down,” coordinate system depicted in Photo 1.

Listing 1: C source code for the tilt-compensated eCompass (Source: M. Pedley, Circuit Cellar 265)

This defines the initial eCompass orientation to be where the x-axis points north, the y-axis points east, and the z-axis points downwards. The three orientation angles, roll (ϕ), pitch (θ), and compass heading, or yaw (ψ)—are defined as clockwise rotations about the positive x, y, and z axes— respectively. Photo 1 also shows the earth’s gravitational vector which points downward with magnitude of 1 g or 9.81 ms-2 and the earth’s geomagnetic field vector, which points downward from horizontal (in the northern hemisphere) by the inclination angle δ to give a horizontal component B0cosδ and a downward component B0sinδ.

Photo 1: The aerospace noth-east-down coordinate system (Source: M. Pedley, Circuit Cellar 265)

Based on how your eCompass housing will be held, you should be able to assign the compass-pointing direction or x-axis, the downward or z-axis, and the y-axis, which should point to the right to complete a right-handed coordinate system.

AXIS ALIGNMENT & MAGNETIC CALIBRATION

You now need to align the sensor data to the aerospace coordinate system. As with all work with magnetometers, this should be performed on a wooden table well away from any laboratory power supplies or steel furniture. Place the eCompass flat and upright so the z-axis points downward and is aligned with gravity. Check that the accelerometer z-axis reads approximately 1 g and the x- and y-axes are near 0. Invert the eCompass so its z-axis points upward and check that the z-axis now reads approximately –1 g. Repeat with the x- and y-axes pointing downward and then upward and check that the x- and  y-axis accelerometer readings are near 1 g and –1 g, respectively. It’s not important if the accelerometer readings are a few tens of mg away from the required reading since all you’re doing here is correcting for gross rotations of the sensor packages and the sensor daughterboard in multiples of 90°. Any needed correction will be unique for your board layout and mounting orientation but will be no more complicated than “swap the x- and y-accelerometer channels and negate the z-channel reading.” Code this accelerometer axis mapping into your software and don’t touch it again.

Figure 2 may help explain this visually. The accelerometer sensor measures both gravity and linear acceleration and, in the absence of any linear acceleration (as is the case when sitting on a desk), the magnitude of the accelerometer reading will always equal 1 g, and therefore, lie on the surface of a 1-g sphere, irrespective of the orientation.

Figure 2: Accelerometer axis alignment points (Source: M. Pedley, Circuit Cellar 265)

The six measurements  lie on the vertices of an octahedron inscribed within the 1-g sphere and the axis mapping simply rotates and reflects the octahedron as needed until the accelerometer channels are correctly aligned.

The magnetometer axis alignment is similar to that of the accelerometer, but makes use of the geomagnetic field vector. Place the eCompass flat, upright, and pointing northward and then rotate in yaw angle by 270° to the east, south, and finally west. The x-channel magnetometer reading should be a maximum when the eCompass is pointed north and a minimum when pointed south. The y-channel magnetometer reading should be a minimum when the eCompass is pointed east and a maximum when pointed west. The z-channel reading should be approximately constant since the vertical component of the geomagnetic field is constant irrespective of rotation in yaw.

Then invert the eCompass on the desk and repeat the process. As before, the magnetometer x-axis reading should be a maximum when the eCompass is pointed north and a minimum when pointed south. But now, because of the inverted position, the magnetometer y-axis should be a maximum when the eCompass is pointed east and a minimum when pointed west. The magnetometer z-axis reading should still be constant but, in the northern hemisphere, lower than the previous upright readings since the magnetometer z-axis is now aligned against the downward component of the geomagnetic field vector.

Figure 3 shows upright and inverted magnetometer measurements taken in the northern hemisphere with a 270o compass rotation.

Figure 3: The upright (a) and inverted (b) magnetometer measurements (Source: M. Pedley, Circuit Cellar 265)

The maximum and minimum of the x- and y-axis magnetometer measurements occur at the expected angles and the z-axis measurement is less when inverted than when upright. These magnetometer axes are therefore correctly aligned but, as with the accelerometer correction, swap and negate the measurements from your three magnetometer channels as needed until correctly aligned and then lock down this part of your code.

A lot can be learned by closely looking at the measurements in Figure 3. The x- and y-magnetometer measurements lie on a circle with radius of approximately 25 µT enabling us to deduce that the horizontal geomagnetic field is approximately 25 µT. But the measurements are offset from zero by the magnetic “hard iron” interfering field, which results from both permanently magnetized ferromagnetic materials on the circuit board and from a zero-field offset in the magnetometer sensor itself. Consumer sensor manufacturers long ago realized it was pointless to accurately calibrate their magnetometers when their target market is smartphones, each with a different hard-iron interfering field. The magnetometer sensor offset is, therefore, calibrated together with the circuit board hard-iron magnetic field. For now, simply note that the x and y components of the hard iron offset have values of approximately 215 µT and 185 µT. A simple method to determine all three hard-iron components is described later.

Refer to the complete article for information about calculating the roll and pitch angles and determining the compass heading angle.

Mark Pedley has a Physics degree from Oxford University and now works on sensor fusion algorithms for Freescale Semiconductor in Tempe, Arizona.