Doing the Robot, 21st-Century Style

Growing up in the 1970s, the first robot I remember was Rosie from The Jetsons. In the 1980s, I discovered Transformers, which were touted as “robots in disguise,” I imitated Michael Jackson’s version of “the robot,” and (unbeknownst to me) the Arthrobot surgical robot was first developed. This was years before Honda debuted ASIMO, the first humanoid robot, in 2004.

“In the 1970s, microprocessors gave me hope that real robots would eventually become part of our future,” RobotBASIC codeveloper John Blankenship told me in a 2013 interview. It appears that the “future” may already be here.

Honda's ASIMO humanoid robot

Honda’s ASIMO humanoid robot

Welcome to the 21st century. Technology is becoming “smarter,“ as evidenced at the Consumer Electronics Show (CES) 2014, which took place in January. The show unveiled a variety of smartphone-controlled robots and drones as well as wireless tracking devices.

Circuit Cellar’s columnists and contributors have been busy with their own developments. Steve Lubbers wondered if robots could be programmed to influence each other’s behavior. He used Texas Instruments’s LaunchPad hardware and a low-cost radio link to build a group of robots to test his theory. The results are on p. 18.

RobotBASIC’s Blankenship wanted to program robots more quickly. His article explains how he uses robot simulation to decrease development time (p. 30).

The Internet of Things (IoT), which relies on embedded technology for communication, is also making advancements. According to information technology research and advisory company Gartner, by 2020, there will be close to 26 billion devices on the IoT.

With the IoT, nothing is out of the realm of a designer’s imagination. For instance, if you’re not at home, you can use IoT-based platforms (such as the one columnist Jeff Bachiochi writes about on p. 58) to preheat your oven or turn off your sprinklers when it starts to rain.

Meanwhile, I will program my crockpot and try to explain to my 8-year-old how I survived childhood without the Internet.

Electrostatic Cleaning Robot Project

How do you clean a clean-energy generating system? With a microcontroller (and a few other parts, of course). An excellent example is US designer Scott Potter’s award-winning, Renesas RL78 microcontroller-based Electrostatic Cleaning Robot system that cleans heliostats (i.e., solar-tracking mirrors) used in solar energy-harvesting systems. Renesas and Circuit Cellar magazine announced this week at DevCon 2012 in Garden Grove, CA, that Potter’s design won First Prize in the RL78 Green Energy Challenge.

This image depicts two Electrostatic Cleaning Robots set up on two heliostats. (Source: S. Potter)

The nearby image depicts two Electrostatic Cleaning Robots set up vertically in order to clean the two heliostats in a horizontal left-to-right (and vice versa) fashion.

The Electrostatic Cleaning Robot in place to clean

Potter’s design can quickly clean heliostats in Concentrating Solar Power (CSP) plants. The heliostats must be clean in order to maximize steam production, which generates power.

The robot cleaner prototype

Built around an RL78 microcontroller, the Electrostatic Cleaning Robot provides a reliable cleaning solution that’s powered entirely by photovoltaic cells. The robot traverses the surface of the mirror and uses a high-voltage AC electric field to sweep away dust and debris.

Parts and circuitry inside the robot cleaner

Object oriented C++ software, developed with the IAR Embedded Workbench and the RL78 Demonstration Kit, controls the device.

IAR Embedded Workbench IDE

The RL78 microcontroller uses the following for system control:

• 20 Digital I/Os used as system control lines

• 1 ADC monitors solar cell voltage

• 1 Interval timer provides controller time tick

• Timer array unit: 4 timers capture the width of sensor pulses

• Watchdog timer for system reliability

• Low voltage detection for reliable operation in intermittent solar conditions

• RTC used in diagnostic logs

• 1 UART used for diagnostics

• Flash memory for storing diagnostic logs

The complete project (description, schematics, diagrams, and code) is now available on the Challenge website.

 

Pi-Face: A New Raspberry Pi Accessory

Ready for the Pi-Face Digital? What’s that? you ask.

Pi-Face at Electronica 2012 (Source: Elektor.tv)

Pi Interface Digital, or Pi-Face Digital, is a Raspberry Pi accessory board Premier Farnell will begin distributing in early 2013. You can plug it into a Raspberry Pi and start designing immediately. Plus, you can connect sensors to Pi-Face Digital for a variety of purposes, such as temperature- or pressure-monitoring applications.

The following useful information is posted at the University of Manchester’s School of Computer Science site.

Pi-Face Digital is the first of a range of interfaces to allow the Raspberry Pi to control and manipulate the real world. It allows the Raspberry Pi to read switches connected to it – a door sensor or pressure pad perhaps, a microswitch or reed switch, or a hand held button. With appropriate easy to write code, the Raspberry Pi then drives outputs, powering motors, actuator, LEDs, light bulbs or anything you can imagine to respond to the inputs… The hardware provides an easy and consistent programming interface, in Scratch (as shown running on a Raspberry Pi in the photograph) and Python with good observability to promote easy development, and reduce technology barriers.

It will cost approximately €20 to €30. You can register at element14.

Want to see Pi-Face in action? Check it out on Elektor.tv!

CircuitCellar.com is an Elektor International Media publication.

Microcontroller-Based Markov Music Box

Check out the spectrogram for two FM notes produced by FM modulation. Red indicates higher energy at a given time and frequency.

Cornell University senior lecturer Bruce Land had two reasons for developing an Atmel AVR micrcontroller-based music box. One, he wanted to present synthesis/sequencing algorithms to his students. And two, he wanted the challenge of creating an interactive music box. Interactive audio is becoming an increasingly popular topic among engineers and designers, as we recently reported.

Land writes:

Traditional music boxes play one or two tunes very well, but are not very interactive. Put differently, they have a high quality of synthesis, but a fixed-pattern note sequencer and fixed tonal quality. I wanted to build a device which would play an interesting music-like note sequence, which constantly changed and evolved, with settable timbre, tempo, and beat… To synthesize nice sounding musical notes you need to control spectral content of the note, the rise time (attack), fall time (decay), and the change in spectral content during attack and decay.  Also it is nice to have at least two independent musical voices. And all of this has to be done using the modest arithmetic capability of an 8-bit microcontroller.

Land’s students subsequently used the music box for other projects, such as an auto-composing piano, as shown in the following video.

In early 2013 Circuit Cellar will run Land’s in-depth article on the Markov music box project. Stay tuned for more information.

Principles of Embedded System Design (CC 25th Anniversary Preview)

You have an idea an idea for an innovative microcontroller-based design? Once you start start soldering and wiring, you might want to keep an eye on Bob Japenga’s checklist of essential embedded system design principle. His complete list will appear in Circuit Cellar‘s 25th Anniversary issue, which will be available in early 2013. But since many of you will be attempting to complete projects before January 1, we’re giving you a sneak peek.

Japenga writes:

We all know that old adage: “If you don’t have time to do it right the first time, where do you find the time to do it right the second?” But this is the nature of developing robust embedded systems. There are literally thousands of little decisions that we make even in the simplest of projects. How can we minimize repeating mistakes?

So my goal in this article is twofold: to celebrate with Circuit Cellar 25 years of great service to us engineers and to hammer home some of those principles that we so often forget. I will divide the essentials into four categories: general essentials, essentials that exist because things (i.e., us and our designs) fail, essentials about testing, and essentials about memory use.

General Essentials

KISS & No Simpler“Keep it simple stupid (KISS).” How often do I need to hear this? I like the saying about KISS that’s often attributed to Albert Einstein but was actually Roger Session’s paraphrase: “Make things as simple as possible, but no simpler.” I am counting these as our first and second essentials.  Keep it simple is number one and no simpler is the second. I find this an immense challenge. When we are faced with schedule deadlines and tight budgets, it is costly to make a design simple. Some people have a gift at taking a problem and abstracting an elegant and simple solution. I remember giving a design specification to one of my employees a number of years ago when I worked for an aerospace company. After several days he came back with over 20 pages of algorithms and charts defining how the specification should be met in software. I wasn’t smart enough to know why it was too complex, but my gut feeling was: “This is too complex. Make it simpler.” Later, I turned it over to another young man who returned with an elegant two-page algorithm that worked perfectly.

How do we do that? “As simple as possible” can get us in trouble if we make it too simple. For example, just recently we were designing a multi-drop serial interface to be incorporated into a medical device. A strong case could be made for the simplicity of using a single-ended interface. But experience tells us that a differential interface will be more robust in the face of defibrillators and all the various noisy electronic instruments it will to play with. Which meets the KISS principle? The same tough decision comes when you’re trying to decide whether to go with a two-wire or a four-wire interface. Two wires has less cabling, but it’s more complex in the interface and forces single-duplex operation. Again, which meets the principle?

Sometimes the trade-off can come down to what you already have in the house. If you have well-debugged libraries for handling the two-wire 485 protocols, the reduced number of wires reduces the overall system complexity even though the software will in fact be more complex.

Sometimes when dealing with algorithm development, the KISS principle can also present ambiguous alternatives. At times, a straightforward linear programming approach can be many times more lines of code and more complex than an elegant algorithm. But the elegant algorithm may be obscure, difficult to maintain, or take too long to come up with. Therein lies the challenge to Keep It Simple Stupid but No Simpler.

Define the Problem/Create Clear SpecsHaving a clear set of specs is essential to every part of a design. We all know this and we always belly ache about how we don’t have perfect specifications. But get with it. You won’t always have perfect specs from your customer. But it is essential that you make them as good as possible. And in writing. If your customer is willing, keep pushing back and keep writing it down and refining it as you go.

I’ve found that essential for every phase of a project. Whether it is hardware or software, writing out the spec (on the schematic or in the code) is a wonderful act of discipline. Write out the spec for the module. Write out the spec for the algorithm. Write out the spec for the circuit. Writing it out forces you to think it through. End the belly-aching about the lack of good specs. Start creating them.

Don’t Skimp on the ToolsTools are our life blood. If you are a manager and your designers don’t have the best tools, you are wasting your money on their salaries. That said, we are not talking about buying tools you don’t use, tools that don’t pay for themselves, or tools that you can rent more cost effectively. Last week we were discussing a problem where one of our cell modem designs exceeded the limit for the second harmonic in spurious emissions. In talking over the problem with the test lab, I discovered that they had a tool that they brought inside the anechoic chamber that could tell the cell modem to transmit on such and such a frequency at maximum power. Naively, I asked, “Shouldn’t we have such a tool?” Someone responded: “Yes, but they cost almost a million dollars.” Oh. But we found we could rent one for $1,000 a day. So, I am not talking about being unwise with our money.

Many years ago while at the aerospace company, I was recommending an HP64000 system that appeared to be a very powerful tool for our software development team. I wrote up the proposal and presented it to the vice president of engineering. His question has haunted me ever since. “Would you buy it if it were your money?” I said then, and continue to say now, “Get the best tools that will allow you to do the job as quickly as possible. If a 200-man-hour job can be done for 100 hours with a $10,000 instrument, is it worth it. Absolutely.”

Read the DocumentationLast year we had a problem that showed up only after we started making the product in 1,000-piece runs. The problem was that some builds of the system took a very long time to power up. We had built about 10 prototypes, tested the design over thousands of power ups, and it tested just fine (thanks to POC-IT). Then the 1,000-piece run uncovered about a half-dozen units that had variable power-up times—ranging from a few seconds to more than an hour! Replacing the watchdog chip that controlled the RESET line to an ARM9 processor fixed the problem. But why did these half dozen fail? Many hours into the analysis we discovered that the RESET line out of the watchdog chip on the failed units would pulse but stay low for long periods of time. A shot of cold air instantly caused the chip to release the RESET. Was it a faulty chip lot? Nope. Upon a closer read of the documentation, we found that you cannot have a pull-up resister on the RESET line. For years we always had pull-ups on RESET lines. We’d missed that in the documentation.

Like it or not, we have to pour over the documentation of the chips and software library calls we use. We have to digest the content carefully. We cannot rely on what is intuitive.

Finally, and this is much more necessary than in years past, we have to pour over the errata sheets. And we need to do it before we commit the design. A number of years ago, a customer designed a major new product line around an Atmel ARM9. This ARM9 had the capability of directly addressing NOR memory up to 128 MB.  Except for the fact that the errata said that due to a bug it could only address 16 MB.  Ouch! Later we had problems with the I2C bus in the same chip. At times, the bus would lock up and nothing except a power cycle would unlock it. Enter the errata. Under some unmentioned conditions the I2C state machine can lock up. Ouch! In this case, we were able to use a bit-bang algorithm rather than the built-in I2C—but obviously at the cost of money, scheduling, and real time.

If You Can’t Explain it to Mom, It Ain’t ClearThat’s another way to say: “Assume no one reads the user manual.” I recently read a blog post about the City of Boston’s electronic parking meters (http://usabilitylessons.wordpress.com/category/general/). Truly, one wonders who reviewed that user interface. If you want to make robust embedded systems with a user interface, they need to have intuitive interfaces, or you may be surprised at what the user comes up with. This takes time and effort, but it’s well worth it. Try it out on the uninitiated. Engineers are the worst kind of people for testing user interfaces. Try it on kids. My business partner’s one-year-old son found the first bug in our first product.

Be sure to get your hands on the upcoming anniversary issue to learn about the reset of the principles. He covers “Things Fail Essentials,” “Testing Essentials,” “Memory Management Essentials,” and more. Consider using it to create your own design principles checklist that you can keep at your workbench.

Autonomous Mobile Robot (Part 2): Software & Operation

I designed a microcontroller-based mobile robot that can cruise on its own, avoid obstacles, escape from inadvertent collisions, and track a light source. In the first part of this series, I introduced my TOMBOT robot’s hardware. Now I’ll describe its software and how to achieve autonomous robot behavior.

Autonomous Behavior Model Overview
The TOMBOT is a minimalist system with just enough components to demonstrate some simple autonomous behaviors: Cruise, Escape, Avoid, and Home behaviors (see Figure 1). All the behaviors require left and right servos for maneuverability. In general, “Cruise” just keeps the robot in motion in lieu of any stimulus. “Escape” uses the bumper to sense a collision and then 180 spin with reverse. “Avoid” makes use of continuous forward looking IR sensors to veer left or right upon approaching a close obstacle. Finally “Home” utilizes the front optical photocells to provide robot self-guidance to a strong light highly directional source.

Figure 1: High-level autonomous behavior flow

Figure 2 shows more details. The diagram captures the interaction of TOMBOT hardware and software. On the left side of the diagram are the sensors, power sources, and command override (the XBee radio command input). All analog sensor inputs and bumper switches are sampled (every 100 ms automatically) during the Microchip Technology PIC32 Timer 1 interrupt. The bumper left and right switches undergo debounce using 100 ms as a timer increment. The analog sensors inputs are digitized using the PIC32’s 10-bit ADC. Each sensor is assigned its own ADC channel input. The collected data is averaged in some cases and then made available for use by the different behaviors. Processing other than averaging is done within the behavior itself.

Figure 2: Detailed TOMBOT autonomous model

All behaviors are implemented as state machines. If a behavior requests motor control, it will be internally arbitrated against all other behaviors before motor action is taken. Escape has the highest priority (the power behavior is not yet implemented) and will dominate with its state machine over all the other behaviors. If escape is not active, then avoid will dominate as a result of its IR detectors are sensing an object in front of the TOMBOT less than 8″ away. If escape and avoid are not active, then home will overtake robot steering to sense track a light source that is immediately in front of TOMBOT. Finally cruise assumes command, and takes the TOMBOT in a forward direction temporarily.

A received command from the XBee RF module can stop and start autonomous operation remotely. This is very handy for system debugging. Complete values of all sensors and battery power can be viewed on graphics display using remote command, with LEDs and buzzer, announcing remote command acceptance and execution.

Currently, the green LED is used to signal that the TOMBOT is ready to accept a command. Red is used to indicate that the TOMBOT is executing a command. The buzzer indicates that the remote command has been completed coincident with the red led turning on.

With behavior programming, there are a lot of considerations. For successful autonomous operation, calibration of the photocells and IR sensors and servos is required. The good news is that each of these behaviors can be isolated (selectively comment out prior to compile time what is not needed), so that phenomena can be isolated and the proper calibrations made. We will discuss this as we get a little bit deeper into the library API, but in general, behavior modeling itself does not require accurate modeling and is fairly robust under less than ideal conditions.

TOMBOT Software Library
The TOMBOT robot library is modular. Some experience with C programming is required to use it (see Figure 3).

Figure 3: TOMBOT Library

The entire library is written using Microchip’s PIC32 C compiler. Both the compiler and Microchip’s 8.xx IDE are available as free downloads at www.microchip.com. The overall library structure is shown. At a highest level library has three main sections: Motor, I/O and Behavior. We cover these areas in some detail.

TOMBOT Motor Library
All functions controlling the servos’ (left and right wheel) operation is contained in this part of the library (see Listing1 Motor.h). In addition the Microchip PIC32 peripheral library is also used. Motor initialization is required before any other library functions. Motor initialization starts up both left and right servo in idle position using PIC32 PWM peripherals OC3 and OC4 and the dual Timer34 (32 bits) for period setting. C Define statements are used to set pulse period and duty cycle for both left and right wheels. These defines provide PWM varies from 1 to 2 ms for different speed CCW rotation over a 20-ms period and from 1.5 ms to 1 ms for CC rotation.

Listing 1: All functions controlling the servos are in this part of the library.

V_LEFT and V_RIGHT (velocity left and right) use the PIC32 peripheral library function to set duty cycle. The other motor functions, in turn, use V_LEFT and V_RIGHT with the define statements. See FORWARD and BACKWARD functions as an example (see Listing 2).

Listing 2: Motor function code examples

In idle setting both PWM set to 1-ms center positions should cause the servos not to turn. A servo calibration process is required to ensure center position does not result in any rotation. For the servos we have a set screw that can be used to adjust motor idle to no spin activity with a small Philips screwdriver.

TOMBOT I/O Library

This is a collection of different low level library functions. Let’s deal with these by examining their files and describing the function set starting with timer (see Listing 3). It uses Timer45 combination (full 32 bits) for precision timer for behaviors. The C defines statements set the different time values. The routine is noninterrupt at this time and simply waits on timer timeout to return.

Listing 3: Low-level library functions

The next I/O library function is ADC. There are a total of five analog inputs all defined below. Each sensor definition corresponds to an integer (32-bit number) designating the specific input channel to which a sensor is connected. The five are: Right IR, Left IR, Battery, Left Photo Cell, Right Photo Cell.

The initialization function initializes the ADC peripheral for the specific channel. The read function performs a 10-bit ADC conversion and returns the result. To faciliate operation across the five sensors we use SCAN_SENSORS function. This does an initialization and conversion of each sensor in turn. The results are placed in global memory where the behavior functions can access . SCAN_SENOR also performs a running average of the last eight samples of photo cell left and right (see Listing 4).

Listing 4: SCAN_SENOR also performs a running average of the last eight samples

The next I/O library function is Graphics (see Listing 5). TOMBOT uses a 102 × 64 monchrome graphics display module that has both red and green LED backlights. There are also red and green LEDs on the module that are independently controlled. The module is driven by the PIC32 SPI2 interface and has several control lines CS –chip select, A0 –command /data.

Listing 5: The Graphics I/O library function

The Graphics display relies on the use of an 8 × 8 font stored in as a project file for character generation. Within the library there are also cursor position macros, functions to write characters or text strings, and functions to draw 32 × 32 bit maps. The library graphic primitives are shown for intialization, module control, and writing to the module. The library writes to a RAM Vmap memory area. And then from this RAM area the screen is updated using dumpVmap function. The LED and backlight controls included within these graphics library.

The next part of I/O library function is delay (see Listing 6). It is just a series of different software delays that can be used by other library function. They were only included because of legacy use with the graphics library.

Listing 6: Series of different software delays

The next I/O library function is UART-XBEE (see Listing 7). This is the serial driver to configure and transfer data through the XBee radio on the robot side. The library is fairly straightforward. It has an initialize function to set up the UART1B for 9600 8N1, transmit and receive.

Listing 7: XBee library functions

Transmission is done one character at a time. Reception is done via interrupt service routine, where the received character is retrieved and a semaphore flag is set. For this communication, I use a Sparkfun XBee Dongle configured through USB as a COM port and then run HyperTerminal or an equivalent application on PC. The default setting for XBee is all that is required (see Photo 1).

Photo 1: XBee PC to TOMBOT communications

The next I/O library function is buzzer (see Listing 8). It uses a simple digital output (Port F bit 1) to control a buzzer. The functions are initializing buzzer control and then the on/off buzzer.

Listing 8: The functions initialize buzzer control

TOMBOT Behavior Library
The Behavior library is the heart of the autonomous TOMBOT and where integrated behavior happens. All of these behaviors require the use of left and right servos for autonomous maneuverability. Each behavior is a finite state machine that interacts with the environment (every 0.1 s). All behaviors have a designated priority relative to the wheel operation. These priorities are resolved by the arbiter for final wheel activation. Listing 9 shows the API for the entire Behavior Library.

Listing 9: The API for the entire behavior library

Let’s briefly cover the specifics.

  • “Cruise” just keeps the robot in motion in lieu of any stimulus.
  • “Escape” uses the bumper to sense a collision and then 180° spin with reverse.
  • “Avoid” makes use of continuous forward looking IR sensors to veer left or right upon approaching a close obstacle.
  • “Home” utilizes the front optical photocells to provide robot self-guidance to a strong light highly directional source.
  • “Remote operation” allows for the TOMBOT to respond to the PC via XBee communications to enter/exit autonomous mode, report status, or execute a predetermined motion scenario (i.e., Spin X times, run back and forth X times, etc.).
  • “Dump” is an internal function that is used within Remote.
  • “Arbiter” is an internal function that is an intrinsic part of the behavior library that resolves different behavior priorities for wheel activation.

Here’s an example of the Main function-invoking different Behavior using API (see Listing 10). Note that this is part of a main loop. Behaviors can be called within a main loop or “Stacked Up”. You can remove or stack up behaviors as you choose ( simply comment out what you don’t need and recompile). Keep in mind that remote is a way for a remote operator to control operation or view status.

Listing 10: TOMBOT API Example

Let’s now examine the detailed state machine associated with each behavior to gain a better understanding of behavior operation (see Listing 11).

Listing 11:The TOMBOT’s arbiter

The arbiter is simple for TOMBOT. It is a fixed arbiter. If either during escape or avoid, it abdicates to those behaviors and lets them resolve motor control internally. Home or cruise motor control requests are handled directly by the arbiter (see Listing 12).

Listing 12: Home behavior

Home is still being debugged and is not yet a final product. The goal is for the TOMBOT during Home is to steer the robot toward a strong light source when not engaged in higher priority behaviors.

The Cruise behavior sets motor to forward operation for one second if no other higher priority behaviors are active (see Listing 13).

Listing 13: Cruise behavior

The Escape behavior tests the bumper switch state to determine if a bump is detected (see Listing 14). Once detected it runs through a series of states. The first is an immediate backup, and then it turns around and moves away from obstacle.

Listing 14: Escape behavior

This function is a response to the remote C or capture command that formats and dumps (see Listing 15) to the graphics display The IR left and right, Photo left and Right, and battery in floating point format.

Listing 15: The dump function

This behavior uses the IR sensors and determines if an object is within 8″ of the front of TOMBOT (see Listing 16).

Listing 16: Avoid behavior

If both sensors detect a target within 8″ then it just turns around and moves away (pretty much like escape). If only the right sensor detects an object in range spins away from right side else if on left spins away on left side (see Listing 17).

Listing 17: Remote part 1

Remote behavior is fairly comprehensive (see Listing 18). There are 14 different cases. Each case is driven by a different XBee received radio character. Once a character is received the red LED is turned on. Once the behavior is complete, the red LED is turned off and a buzzer is sounded.

Listing 18: Remote part 2

The first case toggles Autonomous mode on and off. The other 13 are prescribed actions. Seven of these 13 were written to demonstrate TOMBOT mobile agility with multiple spins, back and forwards. The final six of the 13 are standard single step debug like stop, backward, and capture. Capture dumps all sensor output to the display screen (see Table 1).

Table 1: TOMBOT remote commands

Early Findings & Implementation
Implementation always presents a choice. In my particular case, I was interested in rapid development. At that time, I selected to using non interrupt code and just have linear flow of code for easy debug. This amounts to “blocking code.” Block code is used throughout the behavior implementation and causes the robot to be nonresponsive when blocking occurs. All blocking is identified when timeout functions occur. Here the robot is “blind” to outside environmental conditions. Using a real-time operating system (e.g., Free RTOS) to eliminate this problem is recommended.

The TOMBOT also uses photocells for homing. These sensitive devices have different responses and need to be calibrated to ensure correct response. A photocell calibration is needed within the baseline and used prior to operation.

TOMBOT Demo

The TOMBOT was successfully demoed to a large first-grade class in southern California as part of a Science, Technology, Engineering and Mathematics (STEM) program. The main behaviors were limited to Remote, Avoid, and Escape. With autonomous operation off, the robot demonstrated mobility and maneuverability. With autonomous operation on, the robot could interact with a student to demo avoid and escape behavior.

Tom Kibalo holds a BSEE from City College of New York and an MSEE from the University of Maryland. He as 39 years of engineering experience with a number of companies in the Washington, DC area. Tom is an adjunct EE facility member for local community college, and he is president of Kibacorp, a Microchip Design Partner.

From the IBM PC AT to AVRs & Arduinos (CC 25th Anniversary Preview)

During the last 25 years, hundreds of the world’s most brilliant electrical engineers and embedded developers have published articles in Circuit Cellar magazine. But only a choice few had the skill, focus, creativity, and stamina to consistently publish six or more articles per year. Ed Nisley is a member of that select group. Since Issue 1, Nisley has covered topics ranging from a video hand scanner project to X10 powerline control to Arduino-based designs to crystal characterization.

In the upcoming Circuit Cellar 25th Anniversary Issue—which is slated for publication in early 2013—Nisley describes some of his most memorable projects, such as his hand Scanner design from Issue #1. He writes:

The cable in the upper-left corner went to the serial port of my Genuine IBM PC AT. The hand-wired circuit board in front came from an earlier project: an 8031-based video digitizer that captured single frames and produced, believe it or not, RS-232 serial data. It wasn’t fast, but it worked surprisingly well and, best of all, the board was relatively inexpensive. Having built the board and written the firmware, I modified it to output compressed data from hand images, then wrote a PC program to display the results.

Combining a TV camera, a prototype 8031-based video digitizer, and an IBM PC with custom firmware and software produced a digital hand scanner for Circuit Cellar Issue 1. The aluminum case came from an external 8″ floppy drive!

The robust aluminum case originally housed an external 8″ floppy drive for one of my earlier DIY “home computers” (they sure don’t make ‘em like they used to!) and I assembled the rest of the hardware in my shop. With hardware and software in hand, I hauled everything to Circuit Cellar Galactic HQ for a demo.

Some of the work Nisley details is much more modern. For instance, the photo below shows the Arduino microcontroller boards he has been using in many of his recent projects. Nisley writes:

The processors, from the Atmel AVR microcontroller family, date to the mid-1990s, with a compiler-friendly architecture producing good performance with high-level languages. Barely more than breakout boards wrapped around the microcontrollers, Arduinos provide a convenient way to mount and wire to the microcontroller chips. The hardware may be too expensive to incorporate in a product, but it’s ideal for prototypes and demonstrations.

The Arduino microcontroller project provides a convenient basis for small-scale projects like this NiMH cell tester. Simple interconnections work well with low-speed signals and lowcurrent hardware, but analog gotchas always lie in wait.

Even better, a single person can still comprehend all of a project’s hardware and software, if only because the projects tend to be human scaled. The Arduino’s open-source licensing model fits well with my column’s readily available hardware and firmware: you can reproduce everything from scratch, then extend it to suit your needs.

Circuit Cellar’s Circuit Cellar 25th Anniversary Issue will be available in early 2013. Stay tuned for more updates on the issue’s content.

Elektor & element14 Partner for Embedded Linux Webinar at Electronica 2012

Want to learn more about Embedded Linux? You’re in luck. On Wednesday, November 14, Elektor and Farnell/element14 will partner to run an informative webinar on the topic at Electronica 2012 in Munich, Germany. If you’re at the show, you can attend the recordings for free. Register before October 31 to get free Electronica entry tickets from Farnell/element14.

Attendees should go to the Farnell/element14 stand (Hall 5, Stand 558) for the Elektor Academy seminar, which will focus on the latest developments on the innovative Embedded Linux board. You can watch the presentation and ask the experts questions. The webinar will be recorded and webcast a bit later.

  • Presenter: Embedded Linux expert Benedict Sauter, the board’s designer
  • Description: Benedict Sauter will take you through the design and update us on the latest applications.
  • When: Wed, November 14, 2012
  • Time: 11:30 CET
  • Where: Farnell element14 stand (Messe München, Hall 5, Booth 558)
  • Language: English

Visit the element14 page about the Elektor Academy event for more information and to register for a free entry ticket.

CircuitCellar.com is an Elektor International Media publication.

CC268: The History of Embedded Tech

At the end of September 2012, an enthusiastic crew of electrical engineers and journalists (and significant others) traveled to Portsmouth, NH, from locations as far apart as San Luis Obispo, CA,  and Paris, France, to celebrate Circuit Cellar’s 25th anniversary. Attendees included Don Akkermans (Director, Elektor International Media), Steve Ciarcia (Founder, Circuit Cellar), the current magazine staff, and several well-known engineers, editors, and columnists. The event marked the beginning of the next chapter in the history of this long-revered publication. As you’d expect, contributors and staffers both reminisced about the past and shared ideas about its future. And in many instances, the conversations turned to the content in this issue, which was at that time entering the final phase of production. Why? We purposely designed this issue (and next month’s) to feature a diversity of content that would represent the breadth of coverage we’ve come to deliver during the past quarter century. A quick look at this issue’s topics gives you an idea of how far embedded technology has come. The topics also point to the fact that some of the most popular ’80s-era engineering concerns are as relevant as ever. Let’s review.

In the earliest issues of Circuit Cellar, home control was one of the hottest topics. Today, inventive DIY home control projects are highly coveted by professional engineers and newbies alike. On page 16, Scott Weber presents an interesting GPS-based time server for lighting control applications. An MCU extracts time from GPS data and transmits it to networked devices.

The time-broadcasting device includes a circuit board that’s attached to a GPS module. (Source: S. Weber, CC268)

Thiadmer Riemersma’s DIY automated component dispenser is a contemporary solution to a problem that has frustrated engineers for decades (p. 26). The MCU-based design simplifies component management and will be a welcome addition to any workbench.

The DIY automated component dispenser. (Source: T. Riemersma, CC268)

USB technology started becoming relevant in the mid-to-late 1990s, and since then has become the go-to connection option for designers and end users alike. Turn to page 30 for Jan Axelson’s  tips about debugging USB firmware. Axelson covers controller architectures and details devices such as the FTDI FT232R USB UART controller and Microchip Technology’s PIC18F4550 microcontroller.

Debugging USB firmware (Source: J. Axelson, CC268)

Electrical engineers have been trying to “control time” in various ways since the earliest innovators began studying and experimenting with electric charge. Contemporary timing control systems are implemented in a amazing ways. For instance, Richard Lord built a digital camera controller that enables him to photograph the movement of high-speed objects (p. 36).

Security and product reliability are topics that have been on the minds of engineers for decades. Whether you’re working on aerospace electronics or a compact embedded system for your workbench (p. 52), you’ll want to ensure your data is protected and that you’ve gone through the necessary steps to predict your project’s likely reliability (p. 60).

The issue’s last two articles detail how to use contemporary electronics to improve older mechanical systems. On page 64 George Martin presents a tachometer design you can implement immediately in a machine shop. And lastly, on page 70, Jeff Bachiochi wraps up his series “Mechanical Gyroscope Replacement.” The goal is to transmit reliable data to motor controllers. The photo below shows the Pololu MinIMU-9.

The Pololu MinIMU-9’s sensor axes are aligned with the mechanical gyro so the x and y output pitch and roll, respectively. (Source: J. Bachiochi, CC268)

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.

 

 

 

 

 

 

One-Time Passwords from Your Watch

Passwords establish the identity of a user, and they are an essential component of modern information technology. In this article, I describe one-time passwords: passwords that you use once and then never again. Because they’re used only once, you don’t have to remember them. I describe how to implement one-time passwords with a Texas Instruments (TI) eZ430-Chronos wireless development tool in a watch and how to use them to log in to existing web services such as Google Gmail (see Photo 1).

Photo 1—The Texas Instruments eZ430 Chronos watch displays a unique code that enables logging into Google Gmail. The code is derived from the current time and a secret value embedded in the watch.

To help me get around on the Internet, I use a list of about 80 passwords (at the latest count). Almost any online service I use requires a password: reading e-mail, banking, shopping, checking reservations, and so on. Many of these Internet-based services have Draconian password rules. For example, some sites require a password of at least eight characters with at least two capitals or numbers and two punctuation characters. The sheer number of passwords, and their complexity, makes it impossible to remember all of them.

What are the alternatives? There are three different ways of verifying the identity of a remote user. The most prevailing one, the password, tests something that a user knows. A second method tests something that the user has, such as a secure token. Finally, we can make use of biometrics, testing a unique user property, such as a fingerprint or an eye iris pattern.

Each of these three methods comes with advantages and disadvantages. The first method (passwords) is inexpensive, but it relies on the user’s memory. The second method (secure token) replaces the password with a small amount of embedded hardware. To help the user to log on, the token provides a unique code. Since it’s possible for a secure token to get lost, it must be possible to revoke the token. The third method (biometrics) requires the user to enroll a biometric, such as a fingerprint. Upon login, the user’s fingerprint is measured again and tested against the enrolled fingerprint. The enrollment has potential privacy issues. And, unlike a secure token, it’s not possible to revoke something that is biometric.

The one-time password design in this article belongs to the second category. A compelling motivation for this choice is that a standard, open proposal for one-time passwords is available. The Initiative for Open Authentication (OATH) is an industry consortium that works on a universal authentication mechanism for Internet users. They have developed several proposals for user authentication methods, and they have submitted these to the Internet Engineering Task Force (IETF). I’ll be relying on these proposals to demonstrate one-time passwords using a eZ430-Chronos watch. The eZ430-Chronos watch, which I’ll be using as a secure token, is a wearable embedded development platform with a 16-bit Texas Instruments MSP430 microcontroller.

ONE-TIME PASSWORD LOGON

Figure 1 demonstrates how one-time passwords work. Let’s assume a user—let’s call him Frank—is about to log on to a server. Frank will generate a one-time password using two pieces of information: a secret value unique to Frank and a counter value that increments after each authentication. The secret, as well as the counter, is stored in a secure token. To transform the counter and the secret into a one-time password, a cryptographic hash algorithm is used. Meanwhile, the server will generate the one-time password it is expecting to see from Frank. The server has a user table that keeps track of Frank’s secret and his counter value. When both the server and Frank obtain the same output, the server will authenticate Frank. Because Frank will use each password only once, it’s not a problem if an attacker intercepts the communication between Frank and the server.

Figure 1—A one-time password is formed by passing the value of a personal secret and a counter through a cryptographic hash (1). The server obtains Frank’s secret and counter value from a user table and generates the same one-time password (2). The two passwords must match to authenticate Frank (3). After each authentication, Frank’s counter is incremented, ensuring a different password the next time (4).

After each logon attempt, Frank will update his copy of the counter in the secure token. The server, however, will only update Frank’s counter in the user table when the logon was successful. This will intercept false logon attempts. Of course, it is possible that Frank’s counter value in the secure token gets out of sync with Frank’s counter value in the server. To adjust for that possibility, the server will use a synchronization algorithm. The server will attempt a window of counter values before rejecting Frank’s logon. The window chosen should be small (i.e., five). It should only cover for the occasional failed logon performed by Frank. As an alternate mechanism to counter synchronization, Frank could also send the value of his counter directly to the server. This is safe because of the properties of a cryptographic hash: the secret value cannot be computed from the one-time password, even if one knows the counter value.

You see that, similar to the classic password, the one-time password scheme still relies on a shared secret between Frank and the server. However, the shared secret is not communicated directly from the user to the server, it is only tested indirectly through the use of a cryptographic hash. The security of a one-time password therefore stands or falls with the security of the cryptographic hash, so it’s worthwhile to look further into this operation.

CRYPTOGRAPHIC HASH

A cryptographic hash is a one-way function that calculates a fixed-length output, called the digest, from an arbitrary-length input, called the message. The one-way property means that, given the message, it’s easy to calculate the digest. But, given the digest, one cannot find back the message.

The one-way property of a good cryptographic hash implies that no information is leaked from the message into the digest. For example, a small change in the input message may cause a large and seemingly random change in the digest. For the one-time password system, this property is important. It ensures that each one-time password will look very different from one authentication to the next.

The one-time password algorithm makes use of the SHA-1 cryptographic hash algorithm. This algorithm produces a digest of 160 bits. By today’s Internet standards, SHA-1 is considered old. It was developed by Ronald L. Rivest and published as a standard in 1995.

Is SHA-1 still adequate to create one-time passwords? Let’s consider the problem that an attacker must solve to break the one-time password system. Assume an attacker knows the SHA-1 digest of Frank’s last logon attempt. The attacker could now try to find a message that matches the observed digest. Indeed, knowing the message implies knowing a value of Frank’s secret and the counter. Such an attack is called a pre-image attack.

Fortunately, for SHA-1, there are no known (published) pre-image attacks that are more efficient than brute force trying all possible messages. It’s easy to see that this requires an astronomical number of messages values. For a 160-bit digest, the attacker can expect to test on the order of 2160 messages. Therefore it’s reasonable to conclude that SHA-1 is adequate for the one-time password algorithm. Note, however, that this does not imply that SHA-1 is adequate for any application. In another attack model, cryptographers worry about collisions, the possibility of an attacker finding a pair of messages that generate the same digest. For such attacks on SHA-1, significant progress has been made in recent years.

The one-time password scheme in Figure 1 combines two inputs into a single digest: a secret key and a counter value. To combine a static, secret key with a variable message, cryptographers use a keyed hash. The digest of a keyed hash is called a message authentication code (MAC). It can be used to verify the identity of the message sender.

Figure 2 shows how SHA-1 is used in a hash-based message authentication code (HMAC) construction. SHA-1 is applied twice. The first SHA-1 input is a combination of the secret key and the input message. The resulting digest is combined again with the secret key, and SHA-1 is then used to compute the final MAC. Each time, the secret key is mapped into a block of 512 bits. The first time, it is XORed with a constant array of 64 copies of the value 0x36. The second time, it is XORed with a constant array of 64 copies of the value 0x5C.

Figure 2—The SHA-1 algorithm on the left is a one-way function that transforms an arbitrary-length message into a 160-bit fixed digest. The Hash-based message authentication code (HMAC) on the right uses SHA-1 to combine a secret value with an arbitrary-length message to produce a 160-bit message authentication code (MAC).

THE HOTP ALGORITHM

With the HMAC construction, the one-time password algorithm can now be implemented. In fact, the HMAC can almost be used as is. The problem with using the MAC itself as the one-time password is that it contains too many bits. The secure token used by Frank does not directly communicate with the server. Rather, it shows a one-time password Frank needs to type in. A 160-bit number requires 48 decimal digits, which is far too long for a human.

OATH has proposed the Hash-based one-time password (HOTP) algorithm. HOTP uses a key (K) and a counter (C). The output of HOTP is a six-digit, one-time password called the HOTP value. It is obtained as follows. First, compute a 160-bit HMAC value using K and C. Store this result in an array of 20 bytes, hmac, such that hmac[0] contains the 8 leftmost bits of the 160-bit HMAC string and hmac[19] contains the 8 rightmost bits. The HOTP value is then computed with a snippet of C code (see Listing 1).

Listing 1—C code used to compute the HTOP value

There is now an algorithm that will compute a six-digit code starting from a K value and a C value. HOTP is described in IETF RFC 4226. A typical HOTP implementation would use a 32-bit C and an 80-bit K.

An interesting variant of HOTP, which I will be using in my implementation, is the time-based one-time password (TOTP) algorithm. The TOTP value is computed in the same way as the HOTP value. However, the C is replaced with a timestamp value. Rather than synchronizing a C between the secure token and the server, TOTP simply relies on the time, which is the same for the server and the token. Of course, this requires the secure token to have access to a stable and synchronized time source, but for a watch, this is a requirement that is easily met.

The timestamp value chosen for TOTP is the current Unix time, divided by a factor d. The current Unix time is the number of seconds that have elapsed since midnight January 1, 1970, Coordinated Universal Time. The factor d compensates for small synchronization differences between the server and the token. For example, a value of 30 will enable a 30-s window for each one-time password. The 30-s window also gives a user sufficient time to type in the one-time password before it expires.

IMPLEMENTATION IN THE eZ430-CHRONOS WATCH

I implemented the TOTP algorithm on the eZ430-Chronos watch. This watch contains a CC430F6137 microcontroller, which has 32 KB of flash memory for programs and 4,096 bytes of RAM for data. The watch comes with a set of software applications to demonstrate its capabilities. Software for the watch can be written in C using TI’s Code Composer Studio (CCStudio) or in IAR Systems’s IAR Embedded Workbench.

The software for the eZ430-Chronos watch is structured as an event-driven system that ties activities performed by software to events such as alarms and button presses. In addition, the overall operation of the watch is driven through several modes, corresponding to a particular function executed on the watch. These modes are driven through a menu system.

Photo 2 shows the watch with its 96-segment liquid crystal display (LCD) and four buttons to control its operation. The left buttons select the mode. The watch has two independent menu systems, one to control the top line of the display and one to control the bottom line. Hence, the overall mode of the watch is determined by a combination of a menu-1 entry and a menu-2 entry.

Photo 2—With the watch in TOTP mode, one-time passwords are shown on the second line of the display. In this photo, I am using the one-time password 854410. The watch display cycles through the strings “totP,” “854,” and “410.”

Listing 2 illustrates the code relevant to the TOTP implementation. When the watch is in TOTP mode, the sx button is tied to the function set_totp(). This function initializes the TOTP timestamp value.

Listing 2—Code relevant to the TOTP implementation

The function retrieves the current time from the watch and converts it into elapsed seconds using the standard library function mktime. Two adjustments are made to the output of mktime, on line 11 and line 12. The first factor, 2208988800, takes into account that the mktime in the TI library returns the number of seconds since January 1, 1900, while the TOTP standard sets zero time at January 1, 1970. The second factor, 18000, takes into account that my watch is set to Eastern Standard Time (EST), while the TOTP standard assumes the UTC time zone—five hours ahead of EST. Finally, on line 14, the number of seconds is divided by 30 to obtain the standard TOTP timestamp. The TOTP timestamp is further updated every 30 s, through the function tick_totp().

The one-time password is calculated by compute_totp on line 33. Rather than writing a SHA1-HMAC from scratch, I ported the open-source implementation from Google Authenticator to the TI MSP 430. Lines 39 through 50 show how a six-digit TOTP code is calculated from the 160-bit digest output of the SHA1-HMAC.

The display menu function is display_totp on line 52. The function is called when the watch first enters TOTP mode and every second after that. First, the watch will recompute the one-time password code at the start of each 30-s interval. Next, the TOTP code is displayed. The six digits of the TOTP code are more than can be shown on the bottom line of the watch. Therefore, the watch will cycle between showing “totP,” the first three digits of the one-time password, and the next three digits of the one-time password. The transitions each take 1 s, which is sufficient for a user to read all digits.

There is one element missing to display TOTP codes: I did not explain how the unique secret value is loaded into the watch. I use Google Authenticator to generate this secret value and to maintain a copy of it on Google’s servers so that I can use it to log on with TOTP.

LOGGING ONTO GMAIL

Google Authenticator is an implementation of TOTP developed by Google. It provides an implementation for Android, Blackberry, and IOS so you can use a smartphone as a secure token. In addition, it also enables you to extend your login procedure with a one-time password. You cannot replace your standard password with a one-time password, but you can enable both at the same time. Such a solution is called a two-factor authentication procedure. You need to provide a password and a one-time password to complete the login.

As part of setting up the two-factor authentication with Google (through Account Settings – Using Two-Step Verification), you will receive a secret key. The secret key is presented as a 16-character string made up of a 32-character alphabet. The alphabet consists of the letters A through Z and the digits 2, 3, 4, 5, 6, and 7. This clever choice avoids numbers that can confused with letters (8 and B, for example). The 16-character string thus represents an 80-bit key.

I program this string in the TOTP design for the eZ430-Chronos watch to initialize the secret. In the current implementation, the key is loaded in the function reset_totp().

base32_decode((const u8 *)
      ”4RGXVQI7YVY4LBPC”, stotp.key, 16);

Of course, entering the key as a constant string in the firmware is an obvious vulnerability. An attacker who has access to a copy of the firmware also has the secret key used by the TOTP implementation! It’s possible to protect or obfuscate the key from the watch firmware, but these techniques are beyond the scope of this article. Once the key is programmed into the watch and the time is correctly set, you can display TOTP codes that help you complete the logon process of Google. Photo 1 shows a demonstration of logging onto Google’s two-step verification with a one-time password.

OTHER USES OF TOTP

There are other possibilities for one-time passwords. If you are using Linux as your host PC, you can install the OATH Toolkit, which implements the HOTP and TOTP mechanisms for logon. This toolkit enables you to install authentication modules on your PC that can replace the normal login passwords. This enables you to effectively replace the password you need to remember with a password generated from your watch.

Incidentally, several recent articles—which I have included in the resources section of this article—point to the limits of conventional passwords. New technologies, including one-time passwords and biometrics, provide an interesting alternative. With standards such as those from OATH around the corner, the future may become more secure and user-friendly at the same time.

[Editor’s note: This article originally appeared in Circuit Cellar 262, May 2012.]

Patrick Schaumont writes the Embedded Security column for Circuit Cellar magazine. He is an Associate Professor in the Bradley Department of Electrical and Computer Engineering at Virginia Tech. Patrick works with his students on research projects in embedded security, covering hardware, firmware, and software.

PROJECT FILES

To download the code, go to ftp://ftp.circuitcellar.com/pub/Circuit_Cellar/2012/262.

RESOURCES

Google Authenticator, http://code.google.com/p/google-authenticator.

Initiative for Open Authentication (OATH), www.openauthentication.org.

Internet Engineering Task Force (IETF), www.ietf.org.

D. M’Raihi, et al, “TOTP: Time-Based One-Time Password Algorithm,” IETF RFC 6238, 2011.

—, “HOTP: An HMAC-Based One-Time Password Algorithm,” IETF RFC 4226, 2005.

OATH Toolkit, www.nongnu.org/oath-toolkit.

K. Schaffer, “Are Password Requirements Too Difficult?,” IEEE Computer Magazine, 2011.

S. Sengupta, “Logging in With a Touch or a Phrase (Anything but a Password),” New York Times, 2011.

SOURCES

IAR Embedded Workbench – IAR Systems

eZ430-Chronos Wireless development system and Code Composer Studio (CCStudio) IDE – Texas Instruments, Inc.

 

DIY 10.1˝ Touchscreen Home Control System

Domotics (home automation) control systems are among the most innovative and rewarding design projects creative electrical engineers can undertake. Let’s take a look at an innovative Beagle Board-based control system that enables a user to control lights with a 10.1˝ capacitive touchscreen.

Domotics control system

The design features the following modules:

• An I/O board for testing purposes
• An LED strip board for controlling an RGB LED strip
• A relay board for switching 230-VAC devices
• An energy meter for measuring on/off (and also for logging)

ELektor editor and engineer Clemens Valens recently interviewed Koen van Dongen about the design. Van Dongen describes the system’s electronics and then demonstrates how to use the touchscreen to control a light and LED strip.

As Valens explains suggests, it would be a worthwhile endeavor to incorporate a Wi-Fi connection to enable cellphone and tablet control. If you build such system, be sure to share it with our staff. Good luck!

CircuitCellar.com is an Elektor International Media website.

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.

DIY Solar-Powered, Gas-Detecting Mobile Robot

German engineer Jens Altenburg’s solar-powered hidden observing vehicle system (SOPHECLES) is an innovative gas-detecting mobile robot. When the Texas Instruments MSP430-based mobile robot detects noxious gas, it transmits a notification alert to a PC, Altenburg explains in his article, “SOPHOCLES: A Solar-Powered MSP430 Robot.”  The MCU controls an on-board CMOS camera and can wirelessly transmit images to the “Robot Control Center” user interface.

Take a look at the complete SOPHOCLES design. The CMOS camera is located on top of the robot. Radio modem is hidden behind the camera so only the antenna is visible. A flexible cable connects the camera with the MSP430 microcontroller.

Altenburg writes:

The MSP430 microcontroller controls SOPHOCLES. Why did I need an MSP430? There are lots of other micros, some of which have more power than the MSP430, but the word “power” shows you the right way. SOPHOCLES is the first robot (with the exception of space robots like Sojourner and Lunakhod) that I know of that’s powered by a single lithium battery and a solar cell for long missions.

The SOPHOCLES includes a transceiver, sensors, power supply, motor
drivers, and an MSP430. Some block functions (i.e., the motor driver or radio modems) are represented by software modules.

How is this possible? The magic mantra is, “Save power, save power, save power.” In this case, the most important feature of the MSP430 is its low power consumption. It needs less than 1 mA in Operating mode and even less in Sleep mode because the main function of the robot is sleeping (my main function, too). From time to time the robot wakes up, checks the sensor, takes pictures of its surroundings, and then falls back to sleep. Nice job, not only for robots, I think.

The power for the active time comes from the solar cell. High-efficiency cells provide electric energy for a minimum of approximately two minutes of active time per hour. Good lighting conditions (e.g., direct sunlight or a light beam from a lamp) activate the robot permanently. The robot needs only about 25 mA for actions such as driving its wheel, communicating via radio, or takes pictures with its built in camera. Isn’t that impossible? No! …

The robot has two power sources. One source is a 3-V lithium battery with a 600-mAh capacity. The battery supplies the CPU in Sleep mode, during which all other loads are turned off. The other source of power comes from a solar cell. The solar cell charges a special 2.2-F capacitor. A step-up converter changes the unregulated input voltage into 5-V main power. The LTC3401 changes the voltage with an efficiency of about 96% …

Because of the changing light conditions, a step-up voltage converter is needed for generating stabilized VCC voltage. The LTC3401 is a high-efficiency converter that starts up from an input voltage as low as 1 V.

If the input voltage increases to about 3.5 V (at the capacitor), the robot will wake up, changing into Standby mode. Now the robot can work.

The approximate lifetime with a full-charged capacitor depends on its tasks. With maximum activity, the charging is used after one or two minutes and then the robot goes into Sleep mode. Under poor conditions (e.g., low light for a long time), the robot has an Emergency mode, during which the robot charges the capacitor from its lithium cell. Therefore, the robot has a chance to leave the bad area or contact the PC…

The control software runs on a normal PC, and all you need is a small radio box to get the signals from the robot.

The Robot Control Center serves as an interface to control the robot. Its main feature is to display the transmitted pictures and measurement values of the sensors.

Various buttons and throttles give you full control of the robot when power is available or sunlight hits the solar cells. In addition, it’s easy to make short slide shows from the pictures captured by the robot. Each session can be saved on a disk and played in the Robot Control Center…

The entire article appears in Circuit Cellar 147 2002. Type “solarrobot”  to access the password-protected article.