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.

A Dutch Designer’s “Comfort Zone”

Check out this amusing workspace submission from Henk Stegeman who lives and works in The Netherlands (which is widely referred to as the land of Elektor). We especially like his Dutch-orange power strips, which stand out in relation to the muted grey, white, and black colors of his IT equipment and furniture. 

Some might call the space busy. Others might say it’s cramped. Stegeman referred to it his “comfort zone.” He must move and shift a lot of objects before he starts to design. But, hey, whatever works, right?

Hi,

Attached you picture of my workspace.
Where ? (you might ask.)
I just move the keyboard aside.
To where ?
Euuh… (good question)

Regards

Henk
The Netherlands

Visit Circuit Cellar‘s Workspace page for more write-ups and photos of engineering workbenches and tools from around the world!

Want to share your space? Email our editorial team pics and info about your spaces!

RL78 Green Energy Design Challenge Deadline Approaches

Attention engineers, programmers, and electronics enthusiasts! The entry deadline of August 31 for the Renesas RL78 Green Energy Challenge is fast approaching. Here are some tips to keep you on schedule.

COMPLETE YOUR DESIGN

The challenge is to design an innovative, energy-efficient application that features the Renesas RL78 MCU, RL78/G13 Renesas Demonstration Kit (RDK), and IAR Toolchain. For information, visit the Eligible Parts page on the design challenge site.

Renesas RDK RL78 board

GATHER YOUR ENTRY FILES

Once you’re done designing your RL78-based project, you need to gather and order your entry materials: project abstract, complete documentation, and code.

Make sure you register for the challenge to obtain a registration number. Label all of your files and documents with your registration number. Don’t put your name on the files and documents.

Consider organizing all of your entry in a ZIP (or RAR) file. Compressing all of your files into one ZIP will keep your entry organized and easier to submit.

FINAL ENTRY CHECKLIST

Before you submit your entry, go through the following checklist one last time to ensure you have everything:

• Abstract (a short project description)
• Complete documentation (a detailed project description)
• Block diagram(s)
• Schematic(s)
• Project photograph(s)
• Source code
• Files are properly labeled (your name doesn’t appear in the entry files)

More details are posted on the challenge’s FAQ webpage.

ENTRY SUBMISSION

Ready to submit your entry? The preferred submission method is to upload your project files via the RL78 Design Challenge Dropbox.

Or send project files to:

RL78 Green Energy Challenge, Circuit Cellar, 4 Park Street, Vernon, CT 06066, USA

Good luck!

DIY Internet-Enabled Home Control System

Why shell out hundreds or thousands of dollars on various home control systems (HCS) when you have the skills and resources to build your own? You can design and implement sophisticated Internet-enabled systems with free tools and some careful planning.

John Breitenbach did just that. He used a microcontroller, free software, and a cloud-based data platform to construct a remote monitoring system for his home’s water heater. The innovative design can email or text status messages and emergency alerts to a smartphone. You can build a similar system to monitor any number of appliances, rooms, or buildings.

An abridged version of Breitenbach’s article, “Internet-Enabled Home Control” (Circuit Cellar 264, July 2012), appears below. (A link to the entire article and an access password are noted at the end of this post.) Breitenbach writes:

Moving from the Northeast to North Carolina, my wife and I were surprised to find that most homes don’t have basements. In the north, the frost line is 36˝–48 ˝ below the surface. To prevent frost heave, foundations must be dug at least that deep. So, digging down an extra few feet to create a basement makes sense. Because the frost line is only 15 ˝ in the Raleigh area, builders rarely excavate the additional 8’ to create basements.

The lack of basements means builders must find unique locations for a home’s mechanical systems including the furnace, AC unit, and water heater. I was shocked to find that my home’s water heater is located in the attic, right above one of the bedrooms (see Photo 1).

Photo 1: My home’s water heater is located in our attic. (Photo courtesy of Michael Thomas)

During my high school summers I worked for my uncle’s plumbing business (“Breitenbach Plumbing—We’re the Best, Don’t Call the Rest”) and saw firsthand the damage water can do to a home. Water heaters can cause some dramatic end-of-life plumbing failures, dumping 40 or more gallons of water at once followed by the steady flow of the supply line.

Having cleaned up the mess of a failed water heater in my own basement up north, I haven’t had a good night’s sleep since I discovered the water heater in my North Carolina attic. For peace of mind, especially when traveling, I instrumented my attic so I could be notified immediately if water started to leak. My goal was to use a microcontroller so I could receive push notifications via e-mails or text messages. In addition to emergency messages, status messages sent on a regular basis reassure me the system is running. I also wanted to use a web browser to check the current status at any time.

MCU & SENSOR

The attic monitor is based on Renesas Electronics’s YRDKRX62N demonstration kit, which features the RX62N 32-bit microcontroller (see Photo 2). Renesas has given away thousands of these boards to promote the RX, and the boards are also widely available through distributors. The YRDK board has a rich feature set including a graphics display, push buttons, and an SD-card slot, plus Ethernet, USB, and serial ports. An Analog Devices ADT7420 digital I2C temperature sensor also enables you to keep an eye on the attic temperature. I plan to use this for a future addition to the project that compares this temperature to the outside air temperature to control an attic fan.

Photo 2: The completed board, which is based on a Renesas Electronics YRDKRX62N demonstration kit. (Photo courtesy of Michael Thomas)

SENSING WATER

Commercial water-detection sensors are typically made from two exposed conductive surfaces in close proximity to each other on a nonconductive surface. Think of a single-sided PCB with no solder mask and tinned traces (see Photo 3).

Photo 3: A leak sensor (Photo courtesy of Michael Thomas)

These sensors rely on the water conductivity to close the circuit between the two conductors. I chose a sensor based on this type of design for its low cost. But, once I received the sensors, I realized I could have saved myself a few bucks by making my own sensor from a couple of wires or a piece of proto-board.

When standing water on the sensor shorts the two contacts, the resistance across the sensor drops to between 400 kΩ and 600 kΩ. The sensor is used as the bottom resistor in a voltage divider with a 1-MΩ resistor up top. The output of the divider is routed to the 12-bit analog inputs on the RX62N microcontroller. Figure 1 shows the sensor interface circuit. When the voltage read by the analog-to-digital converter (ADC) drops below 2 V, it’s time to start bailing. Two sensors are connected: one in the catch pan under the water heater, and a second one just outside the catch pan to detect failures in the small expansion tank.

Figure 1: The sensor interface to the YRDK RX62N board

COMMUNICATIONS CHOICES

One of my project goals was to push notifications to my cell phone because Murphy’s Law says water heaters are likely to fail while you’re away for the weekend. Because I wanted to keep the project costs low, I used my home’s broadband connection as the gateway for the attic monitor. The Renesas RX62N microcontroller includes a 100-Mbps Ethernet controller, so I simply plugged in the cable to connect the board to my home network. The open-source µIP stack supplied by Renesas with the YRDK provides the protocol engine needed to talk to the Internet.

There were a couple of complications with using my home network as the attic monitor’s gateway to the world. It is behind a firewall built into my router and, for security reasons, I don’t want to open up ports to the outside world.

My Internet service provider (ISP) occasionally changes the Internet protocol (IP) address associated with my cable modem. So I would never know what address to point my web browser. I needed a solution that would address both of these problems. Enter Exosite, a company that provides solutions for cloud-based, machine-to-machine (M2M) communications.

TALKING TO THE CLOUD

Exosite provides a number of software components and services that enable M2M communications via the cloud. This is a different philosophy from supervisory control and data acquisition (SCADA) systems I’ve used in the past. The control systems I’ve worked on over the years typically involve a local host polling the hundreds or thousands of connected sensors and actuators that make up a commercial SCADA system. These systems are generally designed to be monitored locally at a single location. In the case of the attic monitor, my goal was to access a limited number of data points from anywhere, and have the system notify me rather than having to continuously poll. Ideally, I’d only hear from the device when there was a problem.

Exosite is the perfect solution: the company publishes a set of simple application programming interfaces (APIs) using standard web protocols that enable smart devices to push data to their servers in the cloud in real time. Once the data is in the cloud, events, alerts, and scripts can be created to do different things with the data—in my case, to send me an e-mail and SMS text alert if there is anything wrong with my water heater. Connected devices can share data with each other or pull data from public data sources, such as public weather stations. Exosite has an industrial-strength platform for large-scale commercial applications. It provides free access to it for the open-source community. I can create a free account that enables me to connect one or two devices to the Exosite platform.

Embedded devices using Exosite are responsible for pushing data to the server and pulling data from it. Devices use simple HTTP requests to accomplish this. This works great in my home setup because the attic monitor can work through my firewall, even when my Internet provider occasionally changes the IP address of my cable modem. Figure 2 shows the network diagram.

Figure 2: The cloud-based network

VIRTUAL USER INTERFACE

Web-based dashboards hosted on Exosite’s servers can be built and configured to show real-time and historical data from connected devices. Controls, such as switches, can be added to the dashboards to push data back down to the device, enabling remote control of embedded devices. Because the user interface is “in the cloud,” there is no need to store all the user interface (UI) widgets and data in the embedded device, which greatly reduces the storage requirements. Photo 4 shows the dashboard for the attic monitor.

Photo 4: Exosite dashboard for the attic monitor

Events and alerts can be added to the dashboard. These are logical evaluations Exosite’s server performs on the incoming data. Events can be triggered based on simple comparisons (e.g., a data value is too high or too low) or complex combinations of a comparison plus a duration (e.g., a data value remains too high for a period of time). Setting up a leak event for one of the sensors is shown in Photo 5.

Photo 5: Creating an event in Exosite

In this case, the event is triggered when the reported ADC voltage is less than 2 V. An event can also be triggered if Exosite doesn’t receive an update from the device for a set period of time. This last feature can be used as a watchdog to ensure the device is still working.

When an event is triggered, an alert can optionally be sent via e-mail. This is the final link that enables an embedded device in my attic to contact me anywhere, anytime, to alert me to a problem. Though I have a smartphone that enables me to access my e-mail account, I can also route the alarm message to my wife’s simpler phone through her cellular provider’s e-mail-to-text-message gateway. Most cellular providers offer this service, which works by sending an e-mail to a special address containing the cell phone number. On the Verizon network, the e-mail address is <yourcellularnumber>@vtext.com. Other providers have similar gateways.

The attic monitor periodically sends heartbeat messages to Exosite to let me know it’s still working. It also sends the status of the water sensors and the current temperature in the attic. I can log in to Exosite at any time to see my attic’s real-time status. I have also configured events and alarms that will notify me if a leak is detected or if the temperature gets too hot…

The complete article includes details such about the Internet engine, reading the cloud, tips for updating the design, and more.  You can read the entire article by typing netenabledcontrol to open the password-protected PDF.

Build a Microcontroller-Based Mail Client

Does the sheer amount of junk mail that fills your Inbox make you hate everything about e-mail? If so, it’s time to have a little fun with electronic mail by building a compact microcontroller-based mail client system. Alexander Mann designed a system that uses an Atmel ATmega32 and a Microchip Technology ENC28J60 Ethernet controller to check continuously for e-mail. When a message arrives, he can immediately read it on the system’s LCD and respond with a standard keyboard.

Mann writes:

My MiniEmail system is a compact microcontroller-based mail client (see Photo 1). The silent, easy-to-use system doesn’t require a lot of power and it is immune to mail worms. Another advantage is the system’s short start-up time. If you want to write a quick e-mail but your PC is off, you can simply switch on the miniature e-mail client and start writing without having to wait for your PC to boot up and load the necessary applications. All you need is an Ethernet connection and the MiniEmail system.

Photo 1: The complete MiniEmail system includes an LCD, a keyboard, and several connections. (A. Mann, Circuit Cellar 204)

HARDWARE

The hardware for the MiniEmail system is inexpensive. It cost me about $50. The LCD is the most expensive part. To keep things simple, I left the system’s power supply, 5- to 3.3-V conversion crystals, and latch out of Figure 1.

Figure 1: This is a block diagram of MiniEmail’s hardware. The arrows indicate the directions of data flow between the devices. The rounded boxes indicate parts that do not sit on the circuit board.

The main components are an Atmel ATmega32 microcontroller and a Microchip Technology ENC28J60 Ethernet controller. Because a mail client is a piece of complex software, you need a fast microcontroller that has a considerable amount of program space. The MiniEmail system uses almost all of the ATmega32’s features, including the SPI, internal EEPROM and SRAM, counters, USART interface, sleep modes, all 32 I/O lines, and most of the 32 KB of program memory. The ENC28J60 is a stand-alone Ethernet controller that provides basic functionality for transmitting frames over an Ethernet connection. It has 8 KB of built-in SRAM, which can be divided into transmit and receive buffers as desired, and it provides several interrupt sources (e.g., when new packets have arrived). The ATmega32 also has 128 KB of external SRAM connected as well as an LCD, which is a standard module with a resolution of 128 × 64 pixels.

Take a look at the ATmega32’s pin connections in Figure 2. Ports A and C are used as 8-bit-wide general I/O ports, one of which is latched using an NXP Semiconductors 74HC573.

Figure 2: Here’s the complete schematic for the MiniEmail. The LF1S022 is the RJ-45 connector for the Ethernet connection.

The two ports provide data connections to the LCD and SRAM (U3). For the SRAM, you need three additional wires: write (*RAM_WR), read strobe (*RAM_RD), and the seventeenth bit of the address (ADDR16). The LCD connector (CON1) uses five additional wires (for the signals CS1, CS2, DI, EN, and RW). CS1 and CS2 are taken from the general I/O port A (DATA6 and DATA7) and determine which of the two halves of the LCD is selected (i.e., the two controllers on the LCD module you are talking to). RW (where you can use ADDR16 again) sets the direction of the LCD access (read or write). DI describes the type of instruction sent to the LCD. EN is the enable signal for read and write cycles. For the keyboard, you need only two pins: KEY_DATA and KEY_CLOCK. The clock signal must be connected to an external interrupt pin, INT1. One additional wire is needed to switch the latch (LE).

You are left with eight I/O pins on the ATmega32’s ports B and D. RXD and TXD are connected to a MAX232, an RS-232 level converter that also provides the negative supply voltage needed for the LCD (LCD_VOUT in Figure 2). The ATmega32’s USART functionality is used as a debugging interface. It isn’t needed for normal operation.

SOFTWARE

The firmware for this project is posted on the Circuit Cellar FTP site. I wrote the firmware in C language with a few small parts of inline assembler. I used the open-source software suite WinAVR, which includes the GNU GCC compiler with special libraries for AVR devices and avrdude, a tool for the in-system programming of AVR microcontrollers…

USER INTERFACE

The user interface consists of three control elements: menus, edit fields, and an elaborate text editor. A special screen (the Mail Menu) enables you to quickly browse through your mailbox. After power-up, the system displays a greeting message. After a short while, the Main menu appears (see Photo 2).

Photo 2: This is a screenshot of MiniEmail’s main menu. In the upper-right corner, a clock shows the current time, which is retrieved from the Internet. An arrow to the left of the menu items indicates the selected item. (A. Mann, Circuit Cellar 204)

The Compose Mail, Check Mailbox, and Configuration submenus form a hierarchical menu structure. When the other items listed beneath the respective menu titles in the diagram are activated (e.g., start the text editor), they enable you to input data, such as a username and password, or retrieve mail from the mail server. “Standby” is the only action that is accessible directly from the main menu. All other actions are grouped by function in the submenus.

WRITING MAIL

With respect to the firmware, sending mail is much easier than reading it, so let’s first focus on the Compose Mail menu. The first item in the menu starts the text editor so you can enter the body of your letter. You then enter the recipient’s mailing address and the subject of your e-mail, just like you would do when sending e-mail from your PC. Additional fields, such as CC or BCC are not included, but since this requires only one more line in the header of the mail, it is not difficult. Your e-mail also needs a reply address, so the recipient knows who sent the mail. The reply address is normally the same for all of the messages you write. The text you enter in this edit field is stored in the ATmega32’s EEPROM, so you don’t have to type it every time you write a letter. After you select the last menu item, “Send” initiates the dispatch of the mail and displays a message that indicates whether or not it was successful.

CHECKING FOR MAIL

What makes this part more sophisticated is the ability to handle not only one e-mail at a time, but also fetch mail from the server. The system can determine which messages are new and which messages have been read. It can also extract data such as the sender, subject, or sent date from the header of the mail and then display the information.

The amount of mail the firmware can handle is limited by the size of the external SRAM. The maximum number of e-mails is currently 1,024. (If you’ve got more mail, you will be so busy answering it that you won’t have time to build your own MiniEmail client—or you should delete some old mail). Note that 1,024 is the number of unique identifiers that the system can remember. The server assigns a unique identifier to each piece of mail. The system uses the identifiers to keep track of which letters are new on the server, which have already been read, and which have been marked for deletion.

All of the header data for all of the 1,024 messages cannot be held in SRAM at once; only the most recent (about 50) mail headers are held. When you want to browse through older e-mails, the firmware automatically reconnects to the server and fetches the headers of the next 50 e-mails.

When you select Check Mailbox in the main menu, you get to a submenu where you can retrieve and read mail. Before you can collect your mail, you must enter your username and password, which can be stored in EEPROM for your convenience. The firmware then retrieves the headers and displays the Mail Menu, where you can browse through your e-mail. Apart from the size and the date, the first 42 characters of the subject and the mail sender are shown. In the first row, additional icons indicate (from left to right) whether a message is new, has been marked for deletion, or has been read. You can view the content of the selected message by pressing Return. When the mail is fetched from the server, it is prepared for viewing. The header and HTML tags, as well as long runs of the same character, are stripped from the mail and base64 decoding (used to encode 8-bit characters) is performed, so the content of the message is as readable as plain text. Binary attachments (e.g., images) can’t be handled. Following this, the mail is viewed in the text editor (with editing disabled).

A similar action is performed when you press “r” in the Mail Menu. In that case, you can edit the text so you can add your reply. Leaving the text editor will bring you back to the Send Mail menu, where the reply address and subject will be filled in so your mail will be clear for take-off. To delete a message, simply press D to mark it for deletion….

OUTLOOK

I hadn’t imagined how many details would need to be considered when I started this project more than a year ago. It has been a very interesting and challenging project. It has also been a lot of fun.

The MiniEmail system provides all of the basics for communicating via email, but such a project is never really finished. There are still dozens of items on my to-do list. Fortunately, the ATmega32 can be replaced with a new member of the AVR family, the Atmel ATmega644, which is pin-compatible to the ATmega32 and has twice the flash memory (and internal SRAM). That will provide enough space for many of my new ideas. I want to get rid of the static IP address, add CC and BCC fields, use a bigger display or a smaller (variable-width) font, improve the filtering and display of mail content and attachments, and add an address book (it would be best in combination with an additional external EEPROM with an SPI, such as the AT25256).

This project proves, rather impressively, that the ATmega32 and the ENC28J60 are a powerful combination. They can be used for many useful Internet applications. My e-mail client system is surely one of the most exciting. I can think of many other interesting possibilities. At the moment, my MiniEmail assembly serves as an online thermometer so I can check my room’s temperature from anywhere in the world…

Mann’s entire article appears in Circuit Cellar 204, 2007. Type “miniemailopen”  to access the password-protected article.