circuit cellar 2009-06

91
COMMUNICATIONS Virtual Keyboard Communication Made Simple Understanding High-Speed Signal Transmission Anisotropic Magnetoresistance Explained A New Approach to Embedded Programming Autonomous Vehicle Design CIRCUIT CELLAR www.circuitcellar.com THE MAGAZINE FOR COMPUTER APPLICATIONS $5.95 U.S. ($6.95 Canada) #227 June 2009 Solar Data Logger Project (Part 2) p. 22 • Build an SSI Controller p. 30

Upload: cornelia-baccela

Post on 26-Dec-2014

508 views

Category:

Documents


7 download

TRANSCRIPT

Page 1: Circuit Cellar 2009-06

COMMUNICATIONSVirtual Keyboard Communication Made Simple

Understanding High-Speed Signal Transmission

Anisotropic Magnetoresistance Explained

A New Approach to Embedded Programming

Autonomous Vehicle Design

CIRCUIT CELLAR

ww

w.circuitcellar.com T H E M A G A Z I N E F O R C O M P U T E R A P P L I C AT I O N S

$5.95 U.S. ($6.95 Canada)

#227 June 2009

Solar Data Logger Project (Part 2) p. 22 • Build an SSI Controller p. 30

Cover - 227.qxp 5/8/2009 10:41 AM Page 1

Page 2: Circuit Cellar 2009-06

C2.qxp 1/29/2009 10:42 AM Page 1

Page 3: Circuit Cellar 2009-06

1.qxp 4/3/2009 10:20 AM Page 1

Page 4: Circuit Cellar 2009-06

3x faster

and backward

compatible with TS-72xx

TS-7200 shown with optional A/D converter,Compact Flash and RS-485

Embedded Single Board Computers

Most products stocked and available

for next day shippingEngineers on Tech Support

Design your solution with one of our engineers (480) 837-5200

Custom configurations and designs w/

excellent pricing and turn-around time

Over 20 years in business

Never discontinued a product

Low Price, Low Power, High Reliability

using Linux development tools

options include:onboard temperature sensor, A/D Converter 8 channel 12 bit, Extended Temperature,

Battery Backed Real Time Clock, USB Flash, USB WiFi

8 boards, over

2000 configurations

2 USB ports

10/100 Ethernet - up to 2

DIO lines - up to 55

Fanless, no heat sink

Flash - up to 128MB onboard

SDRAM - up to 128MB

Linux, Real Time extension, Debian

COM ports- up to 10

200 MHz ARM9Power as low as 1/4 Watt

Open Source Vision

Programmable FPGAs

High-End Performance

with Embedded Ruggedness

128MB DDR RAM

Gigabit ethernet

2 host USB 2.0 480 Mbps

12K LUT programmable FPGA

512MB high-speed

(17MB/sec) onboard Flash

Sleep mode uses 200 microamps

2 SD sockets

Linux 2.6 and Debian by default

10 serial ports

qty 100229$Unbrickable

design

5 ADC (10-bit) 2 SATA ports

110 GPIO

Boots Linux in < 2 seconds

Internal PCI Bus, PC/104 connectorshown w/ optional SD Cards

TS-7800

500 MHz ARM9

Low power - 4W@5V

qty 1269$

qty 10099$

qty 1129$

as low as

SD card

option

VGA video

LCD ready

72.qxp 8/11/2008 2:02 PM Page 1

Page 5: Circuit Cellar 2009-06

SystemsTechnologic

Visit our TS-7800 powered website at

We use our stuff.

www.embeddedARM.com

TS-ADC16

ADC, DAC and Digital I/O

Up to 100Ksps (10us)

Prog. pacing clock

1KB ADC RAM-FIFO

TS-RELAY8

see our website for more boards and option details

Featured Products and PC/104 Peripherals

qty 1169$

16 16-bit ADCs

4 ADC voltage ranges

qty 189$

TS-TPC-7390

64MB SDRAM (128MB opt)

Dedicated framebuffer- 8MB RAM

800x480 customizable video core

Programmable FPGA- 5K LUT

512MB Flash w/ Debian Linux

Runs Eclipse IDE out-of-the-box

Boots Linux 2.6 in about 1 second

Unbrickable, boots from SD or NAND

Runs X Windows GUI applications

7” Color TFT-LCD Touch-Screen

Mountable aluminum frame

Low Power, Industrial Quality Design

Eight Software Controlled Relays

see our website for x86 SBCs, peripherals and option details

4 inputs, 1 output

4 16 bit counters

4 12-bit DACs

Externally triggered

Up to 277 VAC @ 5A

Up to 30 VDC@ 5A

8 SPDT relays

40mA draw per coil

I/O jumpers

Software controlled

qty 1449$

Audio codec with speaker

200MHz ARM9 Touch Panel Computer

73.qxp 8/11/2008 2:12 PM Page 1

Page 6: Circuit Cellar 2009-06

FOUNDER/EDITORIAL DIRECTORSteve Ciarcia

MANAGING EDITORC. J. Abate

WEST COAST EDITORTom Cantrell

CONTRIBUTING EDITORSJeff Bachiochi Ingo Cyliax Robert LacosteGeorge MartinEd Nisley

NEW PRODUCTS EDITORJohn Gorsky

PROJECT EDITORSGary BodleyKen Davidson David Tweed

ADVERTISING860.875.2199 • Fax: 860.871.0411 • www.circuitcellar.com/advertise

PUBLISHERSean Donnelly Direct: 860.872.3064, Cell: 860.930.4326, E-mail: [email protected]

ADVERTISING REPRESENTATIVEShannon BarracloughDirect: 860.872.3064, E-mail: [email protected]

ADVERTISING COORDINATORValerie LusterE-mail: [email protected]

CONTACTSSUBSCRIPTIONS

Information: www.circuitcellar.com/subscribe, E-mail: [email protected]: 800.269.6301, www.circuitcellar.com/subscribe, Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650Address Changes/Problems: E-mail: [email protected]

GENERAL INFORMATION860.875.2199, Fax: 860.871.0411, E-mail: [email protected] Office: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] Products: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected]

AUTHORIZED REPRINTS INFORMATION860.875.2199, E-mail: [email protected]

AUTHORSAuthors’ e-mail addresses (when available) are included at the end of each article.

CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) is published monthly by Circuit CellarIncorporated, 4 Park Street, Vernon, CT 06066. Periodical rates paid at Vernon, CT and additional offices. One-year (12 issues)subscription rate USA and possessions $23.95, Canada/Mexico $34.95, all other countries $49.95.Two-year (24 issues) sub-scription rate USA and possessions $43.95, Canada/Mexico $59.95, all other countries $85. All subscription orders payable inU.S. funds only via Visa, MasterCard, international postal money order, or check drawn on U.S. bank. Direct subscription ordersand subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 or call800.269.6301.

Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650.

Circuit Cellar® makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for theconsequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of read-er-assembled projects, Circuit Cellar® disclaims any responsibility for the safe and proper function of reader-assembled projects based upon orfrom plans, descriptions, or information published by Circuit Cellar®.

The information provided by Circuit Cellar® is for educational purposes. Circuit Cellar® makes no claims or warrants that readers have a right tobuild things based upon these ideas under patent or other relevant intellectual property law in their jurisdiction, or that readers have a right toconstruct or operate any of the devices described herein under the relevant patent or other intellectual property law of the reader’s jurisdiction.The reader assumes any risk of infringement liability for constructing or operating such devices.

Entire contents copyright © 2009 by Circuit Cellar, Incorporated. All rights reserved. Circuit Cellar is a registered trademark of Circuit Cellar, Inc.Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.

CHIEF FINANCIAL OFFICERJeannette Ciarcia

MEDIA CONSULTANTDan Rodrigues

CUSTOMER SERVICEDebbie Lavoie

CONTROLLERJeff Yanco

ART DIRECTORKC Prescott

GRAPHIC DESIGNERSGrace Chen

Carey Penney

STAFF ENGINEER John Gorsky

Cover photography by Chris Rakoczy—Rakoczy Photographywww.rakoczyphoto.com

PRINTED IN THE UNITED STATES

I’ve said here before that we think of each project described inthese pages as a key contribution to 21st-century technologicaldevelopment. Each design is the result of thousands of previousprojects, and in turn each will surely lead to exciting newadvances in the embedded design industry and beyond.

This month, some of the projects we present represent excitingnew contributions to some of the most important scientific topicsof our time. From Cambridge to Silicon Valley to Tokyo, engineersand scientists are devoting their work lives to the important top-ics presented in this issue: virtual reality designs, autonomousvehicle construction, wireless navigation, precision sensor tech-nologies, high-speed signal transmission, solar power acquisition,and more. Our authors are truly forward-thinking designers!

In “Keystroke Communication,” Naweed Paya and VenkatGanesh describe how they designed a customizable virtual key-board around a microcontroller and some affordable parts (p. 14).This flat keyboard design is the size of a piece of standard paper,which makes it perfect for use on virtually any flat surface.

Starting on page 22, Ed Nisley presents the second part of his“Solar Data Logger” series. With a redesigned layout, better powersupplies, and a superior inductor, Ed’s data logger project is backon track. Here he presents the new circuitry and covers the topicsof inductor core saturation, solar panel output, and more.

Do you need an SSI controller to retrieve sensor readings?Before you shell out a lot of money to buy one, try your hand atRobert Bowen’s project on page 30. Now you can build your ownSSI readout display for position sensors.

On page 42, a team of engineers from Camosun Collegedescribes an autonomous vehicle design. They cover every aspectof the project, from the embedded system to motor control andsensor technology. This project can serve as a prototype for futuremilitary, industrial, or healthcare autonomous applications.

Data transmission speed is an important topic to everyone fromengineers working on industrial applications to editors trying tomove megabytes of photos to coworkers. Speed is king. In “High-Speed Signal Transmission,” Robert Lacoste covers signal trans-mission theory (p. 52). He introduces the important topic of trans-mission on low-bandwidth cables, and in doing so, he covers thetopics of preemphasis and equalization.

GPS technology isn’t always a good fit for an embedded appli-cation that requires navigation capabilities. Check out JeffBachiochi’s article “Location Notification” for a description of anaccessible alternative to GPS technology (p. 60). He introduces thetopic of magnetoresistance and explains how to use an anisotropicmagnetoresistance (AMR) sensor in a design.

Having trouble with the software side of an embedded designproject? Tom Cantrell presents a new chip and a web-based tech-nique for software development (p. 68). It’s an alternative approachto embedded programming that’s sure to make your future designendeavors a lot easier.

Forward-Thinking Designers

[email protected]

4 CIRCUIT CELLAR® • www.circuitcellar.com

June

200

9 –

Issue

227

TASKMANAGER CIRCUIT CELLAR®

THE MAGAZINE FOR COMPUTER APPLICATIONS

task_masthead_227.qxp 5/12/2009 8:49 AM Page 4

Page 7: Circuit Cellar 2009-06

What’s the difference?

<< Order your FREE catalog today at www.Jameco.com/Price

•Over 100,000 skus

•99% of catalog products

are in stock right now

•Low price guarantee

Electronic components work no matter what price you pay. Jameco carries everything youexpect at prices below what others charge. But the price savings don’t stop there. Jamecooffers additional savings with its array of house brand and factory-overrun products.

The Jameco difference begins with the industry’s highest quality catalog and is backed by the industry’s longest warranty plus much more.

Price!

1-800-831-4242

21.qxp 3/4/2009 9:28 AM Page 1

Page 8: Circuit Cellar 2009-06

6 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

INSIDE ISSUE

TASK MANAGER 4Forward-Thinking Designers

C. J. Abate

NEW PRODUCT NEWS 8edited by John Gorsky

CROSSWORD 78

INDEX OF ADVERTISERS 79July Preview

PRIORITY INTERRUPT 80Lawns and Ponds

Steve Ciarcia

22 INTELLIGENT ENERGY SOLUTIONSABOVE THE GROUND PLANESolar Data Logger (Part 2)Data PointsEd Nisely

52 THE DARKER SIDEHigh-Speed Signal TransmissionFrom Eye Diagrams to Preemphasis and EqualizationRobert Lacoste

60 FROM THE BENCHLocation NotificationA Look at Anisotropic MagnetoresistanceSensorsJeff Bachiochi

68 SILICON UPDATEEasy (E)mbedAn Alternative Approach to Embedded ProgrammingTom Cantrell

22714 Keystroke Communication

Design a Customizable Virtual KeyboardNaweed Paya & Venkat Ganesh

30 SSI Controller for Linear-Position SensorsRobert Bowen

42 Autonomous Vehicle DesignEmbedded Systems, Sensor Technology, and Motor ControlChris Britney, Paul Green, Andy Heath, Stephen Lau, and Kylee Lathrop

June 2009 • Communications

p. 14 VirtualKeyboard Design

p. 30 SSI Controller

p. 22 Data Logging

TOC_227.qxp 5/11/2009 8:45 AM Page 6

Page 9: Circuit Cellar 2009-06

© 2008 Atmel Corporation. All rights reserved. Atmel®, logo and Everywhere You Are® are registered trademarks of Atmel Corporation or its subsidiaries.Other terms and product names may be trademarks of others.

Everywhere You Are®

Performance and power consumption have always been key elements in the development of AVR® microcontrollers. Today’s

increasing use of battery and signal line powered applications makes power consumption criteria more important than ever.

To meet the tough requirements of modern microcontrollers, Atmel® has combined more than ten years of low power research and

development into picoPower technology.

picoPower enables tinyAVR®, megaAVR® and XMEGA™ microcontrollers to achieve the industry’s lowest power consumption. Why be satisfied with

microamps when you can have nanoamps? With Atmel MCUs today’s embedded designers get systems using a mere 650 nA running a real-time

clock (RTC) and only 100 nA in sleep mode. Combined with several other innovative techniques, picoPower microcontrollers help you reduce your

applications power consumption without compromising system performance!

Visit our website to learn how picoPower can help you hammer down the power consumption of your next designs. PLUS, get a chance to apply

for a free AVR design kit!

Hammer Down Your Power Consumption with picoPower™!

http://www.atmel.com/picopower/

THE Performance Choice of Lowest-Power Microcontrollers

picoPower 2008ad indd 1 8/8/2008 8:35:17 AM

/11/

Page 10: Circuit Cellar 2009-06

8 CIRCUIT CELLAR® • www.circuitcellar.com

NEW PRODUCT NEWS

June

2009 –

Issue

227

Edited by John Gorsky

INDUSTRIAL USB-TO-RS-232/422/485 ADAPTERThe USB-FLEXCOM4 offers users the choice of four field-selectable RS-232, RS-

422, or RS-485 protocols per port. This serial module was designed for use in sys-tems where there are never enough serial ports to communicate with legacydevices as well as applications where old-school serial protocolsare still the right choice for the design of new systems.

The USB-FLEXCOM4 conforms to the USB/104 form factorfor flexible mounting either in PC/104 or USB/104 stacks.The device is available either packaged in a small, rugged,industrial enclosure, or as an OEM board (no enclosure). It isfully compatible with both USB 1.1 and USB 2.0 ports. Hot-plug functionality allows for quick connect/disconnect when-ever you need additional I/O on your USB port.

The USB-FLEXCOM4 is supported for use in most operatingsystems and includes a free Linux (including Mac OS X) andWindows 2000/XP/2003-compatible software package. Thispackage contains sample programs and source code in VisualBasic, Delphi, and Visual C++ for Windows. Also incorporated isa graphical set-up program in Windows. Third-party supportincludes a Windows standard DLL interface usable from themost popular application programs, and includes example Lab-VIEW VIs. Embedded OS support includes Windows XPe.

The USB-FLEXCOM4 costs $254.

ACCES I/O Products, Inc.www.accesio.com

npn227.qxp 5/8/2009 8:10 AM Page 8

Page 11: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 9

June

2009 –

Issue

227

S

LOW-PROFILE PCB CONNECTOR The POWERMOD PSX product line is a low-profile fami-

ly of connectors which is 30% smaller than comparableproducts. The family of connectors is perfect for whenboard space is at a premium and overall mating heightsmust be minimized. The connectors are ideal for powerconnections to embedded AC/DC power supplies or forboard-to-board connections in servers, storage enclo-sures and communications equipment. Target marketsinclude telecommunications, datacom/network back-bone, and data storage.

The streamlined design of the POWERMOD PSXoffers excellent performance with power contactsrated to 60 A and signal contacts rated to 1 A (rat-ings per UL1977). The series is available in eitherpower and signal versions or power-only to providepower distribution and control in a single connectorbody. The combined power and signal connectorsoffer 80 signal contacts, in addition to either two orfour power contacts. The power-only connectors areavailable in two-, four-, six-, and eight-contact con-figurations. Both versions offer male connectors invertical and right-angle configurations and a verticalfemale configuration to deliver support for coplanar,backplane, or mezzanine connections.

Pricing is dependent upon configuration, so please contact the manufacturer or a distributor for pricing.

Anderson Power Productswww.andersonpower.com

NPN

npn227.qxp 5/8/2009 8:10 AM Page 9

Page 12: Circuit Cellar 2009-06

10 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

NPN

USB RS-232 ADAPTER The SeaLINK+232-DB9 serial

adapter is a single-port USB-to-RS-232 serial adapter incorporating aruggedized, overmolded enclosure.This enclosure improves reliabilityand durability in industrial andmobile applications, such as GPSnavigation systems, bar codereaders, signature input devices,serial printers, scales, and similarapplications.

The serial port appears as astandard COM port to the hostcomputer to enable easy set-upand provide compatibility withlegacy software. TheSeaLINK+232-DB9 features pro-grammable baud rate and data formats with 128-bytetransmit and 384-byte receive buffers. The USB serial adapter is compatible with allstandard PC baud rates and supports high-speed communication to 921.6 kbps.The adapter is powered by the USB port. Status LEDs molded into the enclosureindicate serial data activity and connection to the host.

All the company’s USB serial adapters ship with the SeaCOM suite of Windowsdrivers and diagnostic utilities. Also included is WinSSD, a full-featured applicationproviding powerful testing and diagnostic capabilities. Use WinSSD for Bit Error RateTesting (BERT), throughput monitoring, loopback tests, and transmitting test pat-tern messages.

Standard operating temperature range for the adapters is 0° to 70°C, andextended operation (–40° to 85°C) is available. The attached 44″ cable is fullyshielded to protect the adapter from RF and EMI interference, which are commonin mobile and industrial environments. The SeaLINK+232-DB9 serial adapter isavailable immediately. It costs $79 (Item# 2105R).

Sealevel Systems, Inc.www.sealevel.com

ANTI-VANDAL SWITCHThe PV8 is a newly available anti-vandal switch. This switch features a metal body

and actuator with a 25-mm diameter panel cutout. Multiple functions are availablewith the PV8 and it is available with or without illumination. The illuminated optionincludes the choice of a dot or a ring lens style. The switch is sealed to IP65 stan-dards.

The switch offers an electrical life of 50,000 cycles minimum and a mechanicallife of 1,000,000 cycles minimum. It is available in 1P2T, 2P2T, momentary, andilluminated configurations. The PV8 offers a contact rating of 2 A at 48 VDC and acontact resistance of 50 MΩ (initial max) at 1 A, 12 VDC with an insulation resist-ance of 1,000 MΩ (min. at 500 VDC). Dielectricstrength is rated at 2,000 VAC for 1 min.

Markets for the PV8 Series anti-vandalswitch include elevators, public ticket dis-pensers, and security panels, among oth-ers. Pricing starts as low as $12 in volumequantities.

E-Switch, Inc.www.e-switch.com

npn227.qxp 5/8/2009 8:10 AM Page 10

Page 13: Circuit Cellar 2009-06

HIGH-POWER DC OUTPUT SSRSThe new D1D and D2D series of FET output DC solid-state relays—

formerly rated up to 40 A at 100 VDC and 12 A at 200 VDC—nowincludes new models rated at 60, 80, and 100 A at 100 VDC, as wellas 40 A at 200 VDC. The new models—offered in the industry-stan-dard “hockey puck” SSR package—add to the present offering,which includes the D06 rated to 100 A at 60 VDC, the D2D andD4D series rated to 12 A, and D5D models rated to 10 A at 200,400 and 500 VDC, respectively.

The new D1D relays feature a low on-state resistance FET out-put capable of carrying 60, 80, or 100 A when the SSR is mount-ed on an appropriately rated heat sink. Likewise, the new D2D40features a similar FET design rated to 40 A with appropriate heatsink. Control for these DC output SSRs is by a transformer isolat-ed 3- to 32-VDC logic-compatible input providing 2,500-VACinput to output isolation. The outputs arediode-protected and specifiedto operate up to 1 kHz. DCoutput SSRs are ideal forheating and lighting control,as well as motor control incommercial, industrial, med-ical, aerospace, rail, and auto-motive applications.

Pricing is available uponrequest. Please contact themanufacturer directly.

Crydom, Inc.www.crydom.com

VCO OPERATES AT 1,560 MHZThe model ZRO1560A1LF is a new RoHS-compliant

voltage-controlled oscillator (VCO) for use in the L-band. The ZRO1560A1LF operates at 1560 MHz with atuning voltage range of 0 to 5 VDC. This VCO featuresa typical phase noise of –121 dBc/Hz at 10 kHz offsetand a typical tuning sensitivity of 0.7 MHz/V.

The VCO is designed to deliver a typical output powerof 0 dBm at 5-VDC supply while drawing 18 mA (typi-cal) over the temperature range of –40° to 85ºC. ThisVCO features typical second-harmonic suppression of–30 dBc and comes in an industry-standard MINI-16package measuring 0.5″ × 0.5″ × 0.22″. It is availablein tape and reel packaging for production requirements.The ZRO1560A1LF is also ideal for automated surface-mount assembly and reflow.

ZRO1560A1LF is well-suited for fixed wireless and testand measurement applications that require superior sec-ond-harmonic suppression and ultra low phase noiseperformance.

The VCO is priced at$29.95 with a five-pieceminimum.

Z-Communications, Inc.www.zcomm.com

www.circuitcellar.com • CIRCUIT CELLAR® 11

June

2009 –

Issue

227

NPN

npn227.qxp 5/8/2009 8:10 AM Page 11

Page 14: Circuit Cellar 2009-06

12 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

NPN

TOWER LIGHTSEZ-LIGHT TL50 tower lights

are exceptional for highly visibleoperator guidance and indica-tion of equipment status. Dis-playing up to five colors in onetower and allowing multiple col-ors to be lit simultaneously,these preassembled and pre-configured multi-segment indi-cators replace conventionalstack lights, which often requiretime-consuming assembly andcomplex wiring. In addition,models featuring audible alertwith adjustable intensity areavailable for applications requir-ing sound indication.

The tower lights require lessthan 2 W of power, compared to15 W for competitive units,making them an energy-efficientsolution. Their aesthetic shape,along with a water- and oil-tightindustrial housing, makes it

possible to mount directly tomachines, while standoff pipe andadapters are available for elevatedmounting. Green, yellow, red, blue,or white LED colors are offered tomeet a variety of application needs.

The lights shed debris and mois-ture with an aesthetic design andfeature a prewired 2 m attachedcable or Euro-style quick-discon-nect, depending on model. Theyoffer bimodal NPN or PNP operationdepending on hookup and are com-patible with PLC or other logic-levelcontrol outputs. The TL50 deliversIP65 protection rating for general-purpose models and an IP50 ratingfor audible models.

Pricing is dependent upon config-uration.

Banner Engineering Corp.www.bannerengineering.com

npn227.qxp 5/8/2009 8:11 AM Page 12

Page 15: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 13

June

2009 –

Issue

227

USB MULTI-FUNCTION RELAY, ADC, & OPTO-IN MODULEThe model JSB-380 is a USB 2.0 controlled multi-function module with four

relays, four ADC channels, and four digital optoisolated inputs. Each ADC channelcan measure –5 to 5 V with an optional 12- or 16-bit resolution and single-endedor differential inputs. There is also a user-controlled PGA in 1, 2, 4, 8 steps. Theoptoisolated inputs can support two ranges of inputs, one trip is at 3.3 V with a 15-Vrange, and the other is 10 V with a 30-V range. Relays are SPST 15 A 240 VAC.Screw-type terminal blocks are on the module to provide a quick and easy connec-tor to all the IO. This small form factor module replaces internal PC-based plug-incards or up to three USB modules for use in various test, control, monitor, andmeasurement applications.

The USB module programming interface is easy to use from Visual Basic, VisualC#, and Visual C++ via a standard windows DLL and a managed class library withsample source included. Any programming language that supports calls to a Win-

dows’s DLL can alsobe used to controlthe JSB380 module.Each module has aunique serial numberstring which allowsmultiple USB devicesto be controlled bythe host USB con-troller as individualdevices.

Single unit pricestarts at $160 for the12-bit version and$190 for the 16-bitversion.

J-Works, Inc.www.j-works.com

LABVIEW DRIVERS FOR CHEETAH ADAPTER & BEAGLEANALYZER

LabVIEW drivers for the Cheetah SPI host adapter, the Beagle I2C/SPI protocolanalyzer, and the Beagle USB 12 protocol analyzer are now available. These newdrivers are available as free downloads on the Total Phase web site.

The new LabVIEW drivers add another dimension to the versatile functionality ofthese tools. The Cheetah SPI host adapter currently features gap-less SPI commu-nication at speeds of up to 40-plus-MHz. The Beagle I2C/SPI protocol analyzer pro-vides a high-performance bus-monitoring solution in a small, portable package thatcan display and filter I2C, SPI, and MDIO protocols in real time. Similarly, the BeagleUSB 12 protocol analyzer can non-intrusively capture, display, and filter full- andlow-speed USB traffic inreal time.

The Cheetah SPIhost adapter costs$350, the BeagleI2C/SPI protocol analyz-er is $300, and theBeagle USB 12 proto-col analyzer is $400.

Total Phase, Inc.www.totalphase.com

NPN

npn227.qxp 5/8/2009 8:11 AM Page 13

Page 16: Circuit Cellar 2009-06

14 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

You can build a customizable virtual keyboard around a microcontrollerand some additional affordable parts. This flat keyboard design is thesize of a piece of standard paper, which makes it perfect for use at adesk or on an airplane tray table.

Keystroke Communication

I

FEA

TURE

ARTICLEby Naweed Paya & Venkat Ganesh

usually like to travel without any carry-on luggage, especially on long international flights. But on a

flight from Chicago to Frankfurt last winter, it seemedlike a good idea to bring my laptop along. I imagined I’dfinally be able to finish my overdue research report dur-ing all that free time onboard. Unfortunately, I realizedall too soon that the tray table was undoubtedly toosmall for the job. There just wasn’t enough space to keepmy 14″ laptop LCD positioned at the right angle and stilltype properly without contorting my fingers in awkwardpositions. And even after I somewhat managed that, Iwas still worried my eight-year-old neighbor would spillthe flimsy glass of soda all over my keyboard.

I first got the idea for a virtual keyboard while thinking

about how to address the dire needs of a modern high-tech traveler. The idea was simple. Imagine if the screenin the front of your plane seat was essentially a PC withsome basic software and the tray table had a keyboardprinted on it that couldn’t get ruined by spilled liquidlike soda. A solution as simple as that would certainlyimprove the in-flight experience of every passenger,right?

Luckily, I had a chance to implement part of this ideawith my partner Venkat Ganesh at Cornell University.After learning the basic functionality of an AtmelATmega32 microcontroller and working through somehands-on lab sessions, Venkat and I designed a customiz-able virtual keyboard in about five weeks.

We replaced a physical keypad with a customizablekeyboard printed on a standard letter-size surface. “Key-strokes” on this printed surface are read and translatedinto real input (see Photo 1). We can place the virtualkeyboard on flat surfaces such as desktops, airplane traytables, and countertops. In theory, it can be interfacedwith any computing device that requires text entry. Thiseliminates the need to carry around cumbersome elec-tronic devices. Lamination protects the paper and pre-vents any mechanical damage in harsh environments. Inaddition, we can reconfigure the device’s buttons on thefly to create a new keyboard layout using a GUI we builtin Java. We can then transfer the data to the device via aPC’s serial port.

FOUR-PART DESIGNThe virtual keyboard has four main components: a laser,

a camera, a microcontroller, and a keyboard printout. Photo 1—This is the finished project. You can use it on a flat surfacesuch as a desktop or tray table on a plane.

Design a Customizable Virtual Keyboard

2906015_Paya.qxp 5/8/2009 9:14 AM Page 14

Page 17: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 15

June

2009 –

Issue

227

The conventional, off-the-shelf red laser has aline-generating diffractive optical elementattached to it. This assembly generates an invisi-ble plane of red light hovering a few millimetersabove the typing surface. When a finger passes throughthis plane, it shines bright red in that region (see Photo 2).

The CMOS camera continuously captures images of theregion where the printed keyboard is supposed to be placed,and it transmits the data to an ATmega32 microcontroller.The microcontroller then checks these images for red colordata that is above a preset threshold and satisfies other key-press detection criteria. The threshold concept works inthis case because the laser shining on a typical human fin-ger generates saturating values of red color data, which iseasily distinguishable from its surroundings.

The keyboard is simply a standard letter-size sheetwith a custom keyboard layout printed on it. We used aPC’s serial port and a GUI we developed in Java to pro-gram the printed keyboard layout into the device. ThisGUI gives us a blank grid of buttons. We can assign anybutton to any letter or number we want.

MICROCONTROLLER & LASERWe started by soldering the ATmega32 microcontroller

and corresponding parts onto a prototype board designed

by Professor Bruce Land (see Figure 1). The boardincludes a power supply, 16-MHz crystal clock, RS-232interface for serial communication, and various bypasscapacitors. In addition, a six-pin header allows flashmemory programming from an STK500 Developmentboard.

Our original plan was to use an invisible infrared laserto detect button presses using the CMOS camera, butafter initial experimentation we quickly realized thatuser safety would be a major issue. A user would neverknow if he was staring directly at the laser, so therewould be no way to prevent eye damage. We also realizedthat the OmniVision OV6630 CMOS camera was not tooeffective at detecting infrared light. So, we settled on aClass II 635-nm red laser instead.

Our laser module came with a built-in driver, so wedidn’t have to worry about biasing the laser properly tomake it operational. All we had to do was connect thelaser to a 3-V power source, which we obtained by con-necting a 3-V voltage regulator to the 9-VDC power sup-ply. The laser module also came with a line-generating

Photo 2—A finger shines bright red when passing throughthe invisible plane of red light hovering a few millimetersabove the typing surface. This plane of light is generated bya 635-nm red laser module with a line-generating diffractiveoptical element attached to it.

Figure 1—Cornell University professor Bruce Land supplied us with this schematic of the ATmega32 prototype board.

2906015_Paya.qxp 5/8/2009 9:14 AM Page 15

Page 18: Circuit Cellar 2009-06

diffractive optical element (DOE)attached to it. However, we didn’tknow the fan angle for this DOE, sowe had to experiment with variousdistances in order to obtain a linelength of at least 10.5″, which wasrequired to cover the entire width ofour printed keypad. The fan anglewas eventually calculated to be 44degrees; therefore, we had to place

the laser at a distance of approxi-mately 13″ to obtain good results(see Figure 2).

CAMERA & CASINGWe used a C3038 1/4″ color sensor

module with digital output, whichuses an OmniVision TechnologiesOV6630 CMOS image sensor. Wechose this camera module for itsaffordability and its ability to outputimage data in progressive scan mode.Progressive scanning was an impor-tant consideration for us because thecomputational power available on a16-MHz ATmega32 microcontrollersimply is not enough to processentire frames at once at reasonablespeeds. Nonetheless, it was certainlypossible to process images line byline. After rigorous testing and a lotof research, we discovered thatinstead of using the entire RGB out-put from the camera, we could workwith only the red channel data andstill be able to identify keystrokesrather accurately. Hence, we con-nected the 8-bit red channel outputfrom the camera (UV[7:0]) toPORTA[7:0] on the ATmega32 (seePhoto 3 and Figure 3).

The hardware assembly for ourdevice—which was made out of acombination of scrap wood and card-board—holds the camera at a fixedposition such that it looks over theappropriate region of the printed key-board (see Figure 4). In addition, italso holds the laser module at a fixedposition such that the plane of redlight completely covers the areaabove the printed keyboard. We per-manently attached a piece of blackposter board to the assembly andmounted four photo-corners on it(see Photo 2). This ensures that newcustom-printed keyboards can be read-ily swapped in and out of the devicewhile maintaining proper distances.

SOFTWARE & I2C COMMUNICATIONBased on prior experience and our

interests, we first split the softwarecomponent of this project into fivemain tasks: implementing the I2Cprotocol to communicate with thecamera; reading image data from thecamera to obtain at least six frames

16 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

Figure 2—Using the geometry shown for laser line generation, we calculatedour laser module’s fan angle to be 44 degrees. Thus, to cover the entirewidth of our keyboard, we had to place the laser approximately 13” away.

Fan angle LLine module

D

2906015_Paya.qxp 5/8/2009 9:14 AM Page 16

Page 19: Circuit Cellar 2009-06

per second; processing theimages to obtain the coordi-nates of a pressed key; convert-ing the pressed key into a scancode, which is then transmit-ted to the PC using the PS/2protocol; and sending serialdata from a PC running ourJava application to update thearray of scan codes in themicrocontroller.

The camera is essentially thedevice’s backbone, so a big partof our challenge was to imple-ment the I2C communicationprotocol to properly read andwrite to the camera. The pro-tocol was not easy to workwith, and there were about 92registers we could use tochange camera settings. Atfirst, we considered using theTwo-Wire Interface (TWI) pro-tocol provided by CodeVisionto communicate with the cam-era, but we were unable to doso. Consequently, we modifiedand used a version developedpreviously by our classmateRuibing Wang.

According to the specifications,two wires in an I2C bus—serial data(SDA) and serial clock (SCL)—carryinformation between the devicesconnected to the bus. Each device isrecognized by a unique address andcan operate as either a transmitter orreceiver, depending on its function.In addition to transmitters andreceivers, devices can be consideredas masters or slaves when performingdata transfers. A master is the devicethat initiates a data transfer on thebus and generates the clock signalsto permit that transfer. At that time,any device addressed is considered aslave.

For our purposes, the microcon-troller provides the clock signal to thecamera. Its frequency is given by thefollowing formula found in theATmega32 manual:

TWBR is the TWI bit rate register.TWPS represents the prescalar bits inthe TWI status register. We decided

SCL Frequency = CPU Clock frequency + 2 TWBR 4TWPS16 ( ) ×

www.circuitcellar.com • CIRCUIT CELLAR® 17

June

2009 –

Issue

227

the fastest solution would beto satisfy the minimum fre-quency requirement, whichwas to set the bit rate registeron the ATmega32 (TWBR) to0x72 and the TWI status regis-ter (TWSR) to 0x00. The restof the code followed the stan-dard I2C protocol originallydefined by Philips. After a bitof trial and error, we learnedthat the camera registers couldbe written in a three-stepprocess: write a start bit, fol-lowed by a target registeraddress, and then the targetdata. There was no need toread from the camera registersexcept in the initial testingphase when we had to makesure the protocol was workingproperly.

MAIN OPERATIONAt first, we initialized PORTA

on the ATmega32 to receiveimage data from the camera andPORTC to communicate with

Photo 3—A C3038 image sensor module is mounted on acustom PCB and connected to the prototype board contain-ing an ATmega32 microcontroller. The camera is mountedat an angle of approximately 52 degrees from the horizontalso it can view the entire printed keyboard area.

HMISerialI/O

IndustrialComputing

DigitalI/O

DistributedI/O

• Digital & Analog I/O• Connection via Ethernet, USB,

RS-485, or RS-232• Daisy Chain Expansion • Field Removable Terminal Blocks• Compact, Rugged Form Factor • DIN Rail or Table Mount Design• Robust Development and

Confi guration Tools

We Listen. Think. And Create.

F CUSOn Success

2906015_Paya.qxp 5/8/2009 9:14 AM Page 17

Page 20: Circuit Cellar 2009-06

18 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

the arrival of new frame data. Subse-quently, we also have to wait for a sin-gle pulse on the HREF signal to go by.Pulses on HREF indicate the arrival ofeach new line of valid data in a givenframe and the first row of data hap-pens to be invalid. At this point, wecan begin capturing 176 pixels of datafrom each of the 144 vertical lines inthe incoming image.

In this mode of operation, the UVline receives blue (B) and red (R) data.However, as we already mentioned,we discovered that we could workwith only red data without sacrificingtoo much accuracy. Therefore, westored only an array of 88 pixel val-ues per line instead of the total 176values by capturing the data on theUV line every two clock cycles. Inaddition, we tried to further stream-line the image-processing work bytrying to take advantage of the factthat the camera outputs informationabout the same set of pixels for con-secutive rows. Our idea for optimiza-tion in this case was to completelydrop data for the even rows, but wesoon realized this was not going tosave us anything. All our processingcould be done anyway in the timeinterval between the end of one rowof data and the beginning of the sub-sequent row.

After each vertical line of valid data,HREF stays negative for about 0.8 msand the camera data becomes invalid.This gives us ample time to process oneline worth of data. The first step indata processing entails looping througheach of the 88 captured pixel values tocheck for values higher than the red

the PS/2 transmission and tries toprocess the next captured frame if thetransmitting queue is empty. If thequeue is not empty, it is updated withthe most recent key press detectedand the PS/2 transmission is allowedto continue.

IMAGE PROCESSINGThe getRedIndex function in our

code captures rows of data from thecamera and processes them one at atime. Before capturing meaningfulimage data, however, we first have towait until a negative edge is seen onthe VSYNC signal, which indicates

the camera over the I2C interface.The data rate was set to 19,200 bpsto allow for sufficiently fast yet reli-able serial communication. We thenran a calibration function thatchecked the keyboard area to deter-mine a distinguishable value for redcolor threshold. This sort of calibra-tion was important in this casebecause different ambient lightingconditions could have affected thedevice’s operation, as we discoveredafter some initial testing.

We then called an init_cam func-tion, which performed a soft reset onthe camera before writing the requiredsettings to appropriate camera regis-ters. These registers changed theimage frame size to 176 × 144 (theminimum resolution required to viewthe entire keyboard area in sufficientdetail), turned on auto white balance,set the frame rate to 6 fps, and set theoutput format to 16 bits in the Y/UVmode. In this mode, the camera out-puts images in the standard Bayercolor format, which gives green colordata on the 8-bit Y line (Y = G G G G)and blue and red color data on the 8-bit UV line (UV = B R B R). The codethen enters an infinite loop, whichcontinuously checks for the status of

Figure 4—This is a diagram of the hardware casing. It was fabricated out of scrap wood andcardboard to minimize cost and save time.

Camera

Designated area for custom printed keyboard

Laser module

Figure 3—Here is the circuitry for the customizable virtual keyboard project. To prevent clutter,we didn’t include the complete details of the ATmega32 connections in this schematic.

2906015_Paya.qxp 5/8/2009 9:14 AM Page 18

Page 21: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 19

June

2009 –

Issue

227

color threshold set during calibra-tion. For every pixel that meets thisthreshold, the code then checks tosee if that particular pixel is part of acontiguous set of red pixels, whichwould indicate a key press. The term“contiguous” in this case impliestwo or more pixels not more thantwo pixels apart. If such a pixel set isfound, its coordinates are thenmapped to a corresponding key bybinary searching through a rectangu-lar array of (x,y) coordinate values.These coordinate points that mapphysical keyboard space to cameraimage coordinates were manuallycalibrated in the beginning using athin wooden dowel.

Eventually, if the scan code isfound to be valid, the key isdebounced by checking for six con-secutive image frames. These givethe same result for that particularkey press and the corresponding keyis then added to the transmissionqueue of keys to send to the PC. Thenumber of consecutive image framesto use in debouncing the key wasarbitrarily set to four during the ini-tial testing phase, but it had to beincreased to six later on to reduceerror. Although a number higherthan six should theoreticallyimprove accuracy even further, wealso have to keep the device’s opera-tional speed in mind.

KEYBOARD OUTPUT (PS/2)The PS/2 keyboard interface typi-

cally uses a bidirectional synchro-nous serial protocol, but we used asimpler approach because we did notneed the computer (host) to commu-nicate with the microcontroller(device). Therefore, for our purposes,the device always generates theclock signal and all the data is subse-quently transmitted one byte at atime. Each byte is sent in a frameconsisting of 11 bits, in the followingorder: 1 start bit, which is always 0;8 data bits, least significant bit first;1 parity bit; and 1 stop bit, which isalways 1.

The parity bit is used for error-detection purposes. It is set to 1 ifthere is an even number of ones inthe data bits and set to 0 if there is

an odd number of ones. Inthis way, the number ofones in the data bits plusthe parity bit always addup to an odd number (oddparity).

The remaining PS/2 codewas structured using twotimer compare interrupts,where Timer1 compare Awas used to start transmis-sions of each data byte andTimer1 compare B was

Photo 4—This is the Java GUI to create custom keyboard lay-outs on the fly. You can run this applet on any PC and thentransfer the data to the microcontroller via a COM port.

2906015_Paya.qxp 5/8/2009 9:14 AM Page 19

Page 22: Circuit Cellar 2009-06

20 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

used to reset the waiting. The proto-col allows a range of frequencies (10to 16.7 kHz) that a computer wouldunderstand. We used a clock time of250 and wait time of 700. Based on the16-MHz microcontroller clock, thesenumbers translate to approximately16 and 44 µs, respectively. When theTimer1 compare A interrupt is fired,it transmits the bits in the ordermentioned above when the clock isset to high. Otherwise, the clockstate is updated. The rest of the codesimply maintains a queue whichholds the elements to transmit ascharacters. The queue also has“queueGet” and “queuePut” methodsthat update two pointers in the queuebased on the number of existing ele-ments and free spaces remaining.

PROGRAM THE EEPROMOne of the virtual keyboard’s

advantages is that it’s customizable,which essentially means that keyassignments can be changed on thefly. This feature can be quite usefulconsidering that an entire QWERTYkeyboard is not always necessary forall applications. For instance, a childmight want to use the device as asimple gamepad, whereas a heavy-duty machine operator might want tohave an entirely different set of keys.To accommodate both scenarios, weimagined the easiest approach wouldbe to store the array of scan codescorresponding to each key in themicrocontroller’s EEPROM and turnon the RS-232 receive interrupt.Since the EEPROM is rewritablethrough a RS-232 port, unlike the

microcontroller’s on-board flashmemory, this enables us to instantlyrewrite the scan codes based on theuser’s needs. And to make the entireprocess of assigning new keys evenmore user-friendly, we wrote a sim-ple java applet which the user canrun on any PC, enter scan codes ofthe keys they desire, and transmitthe entire layout to the microcon-troller through a standard COM porton the PC (see Photo 4).

TESTINGAs a result of the limited viewing

angle of the camera and positioningof the laser, we had to design andcalibrate with various keypad lay-outs to make sure we could detectall of the buttons with reasonableaccuracy. After extensive experimen-tation with various colors, we set-tled on a black background and blueletters for the printed keyboard.Because our device doesn’t use itsown light source, proper contrastwas extremely important to distin-guish the typing finger from the sur-rounding areas in various lightingconditions.

Figure 5 is our final design for thegeneric keypad and the testingresults (percentage accuracy) for thislayout. For the testing, we tried 100keystrokes per key and set theacceptance threshold at 70% for sideareas and 80% for the central area(see Figure 5). This means that if wecan recognize a certain key accurate-ly at least 70 or 80 times, respective-ly, out of the 100 times that it’spressed, that key passes the test.

Figure 5—These are the testing results for keystroke detection accuracy. Note the differencein accuracy in the central region versus the peripheral region.

7878 81 81 84 85 87 86 82 80 75

77 79 81 85 84 85 84 80 81 76

73 77 80 84 84 86 81 81 78 75

84 83 82 85 84 84

Side areaCentral areaSide area

Standards improve quality and enable

designers to share components across

different projects.Today, ARM®

Cortex™-M profile processors, combined

with the Cortex Microcontroller

Software Interface Standard (CMSIS) and

optimized middleware from the

industry’s largest ecosystem, are setting

the hardware and software standards for

microcontrollers.

These standards enable leading vendors

such as Luminary Micro, NXP, and

STMicroelectronics to supply advanced

microcontrollers, while maximizing code

reuse across multiple platforms.

StandardsMakeSense

“The strengths of ARM processor-basedNXP microcontrollers are fundamentallychanging digital products by combiningease-of-use with high connectivity and low

power consumption.”

Geoff LeesVice President and General Manager,Microcontroller Product Line

Cortex-M3MicrocontrollersMake Sense

For more information visit

www.onARM.com

TheArchitecture for the

DigitalWorld®

©ARM Ltd.AD158 | 01.09

2906015_Paya.qxp 5/8/2009 9:14 AM Page 20

Page 23: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 21

June

2009 –

Issue

227

Naweed Paya ([email protected]) isdouble-majoring in Electrical & Comput-er Engineering and Biological Engineer-ing at Cornell University. He is passion-ate about embedded design and plansto combine his knowledge of physiologyand digital design to develop human-implantable systems for biomedicaldiagnostics and treatment.

Venkat Ganesh ([email protected]) isdouble-majoring in Electrical & Comput-er Engineering and Computer Science atCornell University. As a programmer, hisinterest is in the development of effi-cient software for microcontroller-basedapplications. Venkat enjoys playing soc-cer and solving Sudoku puzzles in hisfree time.

ROJECT FILESTo download the code and additional files, go to ftp://ftp.circuitcellar.com/pub/Circuit_Cellar/2009/227.

ESOURCESA. Chapweske, “The PS/2 Mouse/Keyboard Protocol,” 2003, www.computer-engineering.org/ps2protocol/.

Cornell University, “RS232 Serial Communications with AVR Microcontrollers,” Electrical Engineering 476, 2004, http://instruct1.cit.cornell.edu/courses/ee476/Serialcom/.

C. Tomasi, A. Rafii, and I. Torunoglu, “Full-Size Projection Keyboard forHandheld Devices,” Communications of the ACM, Vol. 46, No. 7, 2003.

OURCESADP3300ART-32 Voltage regulator Analog Devices, Inc. | www.analog.com

ATmega32 MicrocontrollerAtmel Corp. | www.atmel.com

C3038 Camera module Electronics123.com, Inc. | www.electronics123.com

OV6630 CMOS Digital cameraOmniVision Technologies | www.ovt.com

P

R

S

Although an accuracy of 70% to 80%might sound unreasonably low for akeyboard, we also had to finish theentire project within five weeks.Thus, we could not afford to spend alot of time perfecting the device’soperation.

RESULTSThis project was a great learning

experience. We successfully built aproof-of-concept device in less thanfive weeks on a $75 budget. The key-board works as we predicted, but typ-ing speed is only about 60 charactersper minute due to the ATmega32microcontroller’s limited processingcapabilities.

Looking ahead, we are thinkingabout increasing the theoretical max-imum typing speed. To do so, wemight use another microcontroller inparallel, or maybe even an externalFPGA to perform extra image pro-cessing. In addition, we mightinclude multiple-key detection,sound effects for keystrokes, and adynamic calibration algorithm thatcan be used to orient the custom-printed keyboard in any direction.This sort of functionality wouldrequire performing 2-D image trans-forms on the fly, which is not feasi-ble with the current microcontroller.Last but not least, we might try toupgrade our current keystroke detec-tion algorithm to improve typingaccuracy. I

2906015_Paya.qxp 5/8/2009 9:14 AM Page 21

Page 24: Circuit Cellar 2009-06

IEIE22 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

path. Notice that the rear edge of the board has a widersolid-copper area, with the top and bottom planes stitchedtogether, connecting the panel input ground terminal in J1with the low side of the sense resistors and Q2. That’s atidier replacement for the heavy wire I soldered across the

planes on the previous layout.An Arduino Diecimila micro-

controller board plugs into thetwo rows of pin headers near thecenter of the board. In a moreformal and permanent arrange-ment, mounting screws andstandoffs would join the boardsat the two holes in diagonal cor-ners of the Diecimila board.

The schematic in Figure 1shows the key circuit changes. Iadded separate power-supply regu-lators for the digital and analogcircuits, with provision to powerthe Diecimila board from thesame wall wart. The ground con-nection between the two boardsnow uses only two adjacent pinsin the power header, isolating theanalog reference ground pin, andpreventing any digital currents

Solar Data Logger (Part 2)

INTELLIGENT ENERGY SOLUTIONS

ABOVE THE GROUND PLANE

by Ed Nisley

With a redesigned layout,better power supplies, anda superior inductor, Ed’ssolar data logger project isback on track. Here hepresents the new circuitryand covers the topics ofinductor core saturation,

PWM filtering (and ripple), and solar paneloutput.

O ne of software development’s key maxims tells you to “build one to throw away,” meaning that

your first attempt provides an opportunity to figure outwhat you really wanted to do and how to make it work.Hardware designers have long known the wisdom of bread-boarding a new circuit; indeed,that term dates back to radiosbuilt on actual bread-kneadingboards.

In my April 2009 column, Iexplored some problems arisingfrom poor layout and an ill-cho-sen inductor (Circuit Cellar 225).This time, I can discuss the solu-tions and show some actualobservations.

This one works!

NEW CIRCUIT & NEW LAYOUTThe new board layout in Photo 1

separates the panel current-sinkand voltage booster circuitry fromeverything else. Although theground plane is common to theentire top and bottom surfaces, thepanel’s relatively high currentsfollow the lowest-impedance

Data Points

Photo 1—The expanded board layout and larger inductor core elimi-nated the previous problems. The Arduino Diecimila microcontrollerattaches below the board on the two rows of pin headers and derivesits power from the wall wart jack on the lower left.

2906004_nisley.qxp 5/7/2009 1:17 PM Page 22

Page 25: Circuit Cellar 2009-06

IEIE www.circuitcellar.com • CIRCUIT CELLAR®

23

June

2009 –

Issue

227

from crossing the analog terrain.The moral of this story is that you cannot neglect analog

design constraints when you’re building a “simple” boardattached to a microcontroller. The usual digital rules canget you in trouble, even if the schematic looks like itshould work.

PWM ANALOG RIPPLEThe Diecimila board uses the Atmel ATmega168’s

hardware PWM modules to produce analog outputvoltages. Of course, your board must apply a filter tothe digital PWM signal that extracts its DC value. Ielected to use a simple RC filter specifically to showthe problems that can crop up from that choice.

PWM outputs, at least of the sort produced by theDiecimila firmware, consist of a fixed-frequency rec-tangular pulse train with a duty cycle proportional tothe desired analog value. The signal’s fundamentalfrequency component is thus the PWM frequency,with additional components mostly at odd multiplesof the fundamental. Surprisingly, the default Diecimilafirmware configuration sets a very low 500-Hz PWMfrequency.

The PWM outputs have an 8-bit resolution over a 5-V

range, so 1 LSB = 19 mV or –48 dB. Ideally, you want toreduce the fundamental frequency component in the outputto less than 1 LSB, so you need a PWM filter with at least48 dB of attenuation at 500 Hz.

Figure 1—The new circuit includes a better inductor, separate power supplies, and protection for the fragile MAX4372 input circuitry. The improved board layout shown in Photo 1eliminated the previous instabilities and had a straightforward bring-up process. The components have been renumbered from the schematic in the April 2009 column.

Figure 2—No matter what the firmware may call for, the actual current depends on the solarpanel’s illumination. Winter sunlight through two panes of glass tops out at 70 mA (Trace 1),with the voltage (Trace 2, measured at C5) dropping from 4 V.

2906004_nisley.qxp 5/7/2009 1:17 PM Page 23

Page 26: Circuit Cellar 2009-06

IEIE24 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

which requires a filter corner frequency of 125 Hz. I paired3.3-kΩ resistors with 1-µF capacitors for a time constant ofabout 3 ms, a settling time under 10 ms, and a corner fre-quency of 50 Hz.

The oscilloscope screenshot in Figure 2 shows that both thecurrent and voltage traces consist of two parallel lines. It turnsout that both are the result of a 32-kHz sine wave modulatingthe DC output.

Each current step in the upper trace represents 10 mA. Thefull-scale response is 500 mA, so 1 LSB = 2 mA and each step is5 LSB. The 32-kHz modulation is roughly the same magnitudeas one step, about –34 dB, so it seems the actual RC filterresponse isn’t nearly as good as you’d expect from the equations.

Does that come as any surprise?As nearly as I can tell from a quick measurement, the equiv-

alent series resistance of those 1-µF capacitors at 32 kHz ishigh enough to invalidate the simple ideal-capacitor modelassumed by all the usual equations.

The moral of this story is that you must choose the PWMfrequency based on your project’s requirements, make sureyour project can tolerate the effects of a given PWM fre-quency, and perhaps spend more on a better ripple filter. In

A single-pole RC filter, the simplest and cheapest filteravailable, rolls off at 6 dB per octave (20 dB per decade)above the corner frequency at:

In order to be down 48 dB at 500 Hz, the corner frequencymust be eight octaves lower, at:

Combining those two equations tells you that you need ratherhigh-valued resistors and capacitors.

Worse, an RC filter’s response to a step input is an exponen-tial, so you must wait about three RC time constants to getwithin –48 dB of the final value. That works out to 250 ms fora 1.95-Hz corner frequency, a rather leisurely pace that maycome as a surprise.

Increasing the PWM frequency therefore pays off in bothsmaller components and faster response. I twiddled theATmega168 hardware configuration bits to select a 32-kHzPWM frequency, a factor of 64 higher than the standard set-up,

f0

5002

5002568 = = = 1.95 Hz

f0

12

12

= RC

=

Listing 1—This snippet of firmware steps the current sink load, measures the resulting values, stores them in arrays, and prints a single line to the serial output for use byan external logging program. The arrays simplify finding the maximum power point for the illumination on the panel, but obviously aren’t needed for this simple application.

for (LoadIndex = 0; LoadIndex < LOAD_STEP_COUNT; ++LoadIndex) {

PrintCSV(LoadIndex,','); // array index

LoadCurrent_Set[LoadIndex] = LoadIndex * LOAD_STEP_I; // Figure load current

analogWrite(PIN_LOAD_I,PWM_SCALE_I(LoadCurrent_Set[LoadIndex])); // Set output load currentdelay(15); // wait of settlingPrintCSV(LoadCurrent_Set[LoadIndex],',');

LoadVoltage[LoadIndex] = AI_SCALE_V(analogRead(PIN_LOAD_V)); // Read load voltagePrintCSV(LoadVoltage[LoadIndex],',');

LoadCurrent_Measured[LoadIndex] = AI_SCALE_I(analogRead(PIN_LOAD_FB_I)); // Read load currentPrintCSV(LoadCurrent_Measured[LoadIndex],',');

PanelVoltage[LoadIndex] = AI_SCALE_V(analogRead(PIN_PANEL_V)); // Read panel voltagePrintCSV(PanelVoltage[LoadIndex],',');

PanelCurrent[LoadIndex] = AI_SCALE_I(analogRead(PIN_PANEL_I)); // Read panel currentPrintCSV(PanelCurrent[LoadIndex],',');

PanelPower[LoadIndex] = (unsigned long int)PanelVoltage[LoadIndex] * (unsigned long int)PanelCurrent[LoadIndex] / 1000UL;

PrintCSV(PanelPower[LoadIndex],',');

BoardTemperature[LoadIndex] = AI_SCALE_T(analogRead(PIN_BOARD_T)); // Read board temperaturePrintCSV(BoardTemperature[LoadIndex],',');

PanelTemperature[LoadIndex] = AI_SCALE_T(analogRead(PIN_PANEL_T)); // Read panel temperaturePrintCSV(PanelTemperature[LoadIndex],' ');

Serial.println();

ToggleLED(PIN_STATUS);

}

analogWrite(PIN_LOAD_I,0); // Turn off load

2906004_nisley.qxp 5/7/2009 1:17 PM Page 24

Page 27: Circuit Cellar 2009-06

25.qxp 4/27/2009 8:36 PM Page 1

Page 28: Circuit Cellar 2009-06

IEIE26 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

any case, you must measure the results, verify themagainst the original equations, and perhaps adjust your sim-ulations to match reality.

In this application, however, it’s close enough to getsome useful information from the panel.

CURRENT SINKHOLEFigure 2 shows that the current sink is now stable, a

pleasant change from the previous results. Notice thatIC6C closes its negative feedback path through Q1 andIC6B, which means there’s enough delay to impose a fairlylow bandwidth on the whole circuit. C10 is thus far largerthan the usual tens-of-picofarads that will generally stabi-lize even the most recalcitrant circuit.

Trimpot R33 adjusts the gain of IC6B so that 1 V fromthe Diecimila’s (filtered!) PWM11 output produces 100 mAof current in Q1. The firmware can then read the actualoutput current through analog input AIN3. That circuitryresides in the upper-left corner of the board in Photo 1,benefiting from the lack of high-current return pathsaround its components.

The setup is simple: measure the voltages at Q1’s emitterand the output of IC6B, then tweak R33 for a voltage gain ofexactly 20. Because the sense resistors generate 0.5 V per amp,the overall gain is 10 V/A or, more conveniently, 1 V/100 mA.I wrote a short program that generates a repetitive currentramp from 0 through 300 mA, triggered the oscilloscope onone of the LEDs, and tweaked the pot.

LOAD TESTINGWith the current sink circuitry up and running, it’s a simple

matter of software to measure the panel’s characteristics, muchas I did by hand in my February column. Listing 1 shows thecore part of that routine: step the current sink load by 10 mA,measure all the analog inputs, dump the data to the microcon-troller’s serial output, and repeat for the next step. The Diec-imila includes a serial-to-USB converter that’s essentially

transparent to the software on both ends of the connection.I used minicom to capture the stream of data to a text file

and a variety of GNU/Linux command-line filters to extractthe relevant sections for the graphs.

Figure 3 shows the result of one such test, which closelyresembles the manual results you saw earlier. Under earlyFebruary sunlight, the large panel produces its maximumpower at about 110 mA and just over 5 V.

The saturation voltage of Q1, a Darlington power transis-tor, plus the voltage drops across two pairs of current senseresistors, limits the low-end voltage to about 1 V even undermaximum load. As you can see from Figure 3, however, thatend of the performance curve lies far from the panel’s maxi-mum power point (MPP). You obviously need a different cir-cuit configuration to characterize very low-voltage panels.

An automated system can take repeated measurements,presumably without getting bored, and Figure 4 shows aseries of MPP measurements recorded later that afternoon.Another chunk of firmware locates the MPP of each loadtest and prints a line with those values.

The abrupt drop after 15 measurements (about 15 min-utes) occurred as the sun moved behind a bare tree. Eventhough the diffuse shadows were barely visible, the poweravailable from the panel dropped dramatically.

Figure 5 presents the MPP values in a different way: eachpoint shows the current-voltage combination that producedthe maximum power for that load test. The horizontal stripesshow the varying voltages at each 10-mA current step.

The current measurements in Figure 5 come from theMAX4372 and appear to be about 10% lower than thenominal value set at the current sink. An additional bit ofsoftware, which I’ll leave as an exercise, can compare thepanel current values with the current sink values and cre-ate a look-up table or calibration equation for later use.

That difference brings us to the last section of the cir-cuitry: the DC-to-DC converter.

INDUCTOR CORE CONCERNSExtracting the maximum power from a solar panel requires

a load that can operate at exactly that power level: it cannotdraw more power than the available sunlight provides. Ofcourse, it may use less, but a typical solar photovoltaic

Figure 4—The panel’s maximum power output varies dramatically due to clouds, treeshadows, and angle of incidence. Each data point represents slightly more than oneminute of elapsed time.

Figure 3—Full winter sun on the panel produces 550 mW at a panel temperature of 12°C.

2906004_nisley.qxp 5/7/2009 1:17 PM Page 26

Page 29: Circuit Cellar 2009-06

IEIE www.circuitcellar.com • CIRCUIT CELLAR®

27

June

2009 –

Issue

227

installation doesn’t havemuch spare power.

I think most solarpower panels charge bat-teries, which generallyrequire either a constantvoltage or a constantcurrent during much oftheir charging profile.For example, NiMHcells require a constant-current charge at a vary-ing voltage and lead-acid(and, oddly enough,lithium) batteriesrequire a current-limitedconstant-voltage charger.

As you can tell fromFigure 5, the current and voltage available at the MPP vary dra-matically, even without those pesky tree shadows, and prob-ably won’t match up with the battery’s requirements over mostof its charging profile. The solution is an intermediate stagebetween panel and charger that extracts the maximum powerfrom the panel and presents either a constant voltage or aconstant current to the charger. The simplest case provides aconstant output voltage, so that’s what I used in this circuit.

The circuitry in the lower-left quadrant of Figure 1implements a simple boost-mode DC-to-DC converter. I

picked a very largeinductor to make theswitching frequency lowenough to show what’sgoing on. A real applica-tion would use a com-mercial IC that switchesat a much higher fre-quency with a muchsmaller inductor. Therereally isn’t much needto build discrete-partDC-to-DC convertersany longer, other thanfor pedagogic purposes.

The converter storesenergy from the panel ininductor L1, then dis-

charges that energy into storage capacitor C5, with Schottkydiode D2 preventing reverse current into the panel. The outputvoltage on the capacitor will be higher than the input voltagefrom the panel, with the load current proportionally lower.

Because the panel’s power output drops dramaticallyon either side of its maximum power point, the inductormust conduct an average DC current equal to the panel’sMPP current. Its core must have the desired inductance even atthat DC bias, which is what killed my previous circuitdesign: the inductor had high inductance, but the core

Figure 5—These points show the maximum power point for each sample in Figure 4. I have notcorrected the panel current values for the gain error described in the text.

2.6 KERNEL

System on Module

The SoM-9307 uses the same small SODIMM form-factor utilized by other EMACSoM modules, and is the ideal processor engine for your next design. All of theARM9 processor core is included on this tiny board including: TouchscreenInterface, Flash, Memory, Serial Ports, Ethernet, I2S Audio Interface, PWMs,Timer/Counters, A/D, Digital I/O lines, and more. Like other modules in EMAC'sSoM product line, the SoM-9307 is designed to plug into a custom or off-the-shelfCarrier board containing all the connectors and any additional I/O componentsthat may be required. The SoM approach provides the flexibility of a fullycustomized product at a greatly reduced cost. Single unit pricing starts at $150.

EQUIPMENT MONITOR AND CONTROL

OVER

YEARS OF

SINGLE BOARD

SOLUTIONS

24

Since 1985

Phone: ( 618) 529-4525 Fax: (618) 457-0110 Web: www.emacinc.com� �

http://www.emacinc.com/som/som9307.htm

Internet Appliance Engine

SoM-9307�

EP9307 ARM9 200Mhz CPU

3 Serial Ports & 2 SPIs

Up to 40 Digital GPIOs

10/100 BaseT Fast Ethernet

& WinCE 6.0

s

Small, 144 pin SODIMM form factor (2.66 x 2.38”)

3 USB 2.0 Host Ports

I2S Audio Interface

SD/MMC Flash Card Interface

Up to 64 MB Flash & 128 MB RAM

Graphic LCD Interface with 2D Acceleration

Linux with Eclipse IDE

8 12-Bit A/Ds & 4 16-Bit Timer/Counters

2906004_nisley.qxp 5/7/2009 1:17 PM Page 27

Page 30: Circuit Cellar 2009-06

IEIE28 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

material couldn’t support the DC current.The two scope shots in Figure 6 show the BH curves for

the two inductors. I measured these using the same circuitas for the much larger transformer described in my Febru-ary 2008 column (“Transformers,” Circuit Cellar 211), butwith a dozen turns of fine magnet wire as the secondarywinding. Even without exact calibration, the general shapeof the BH curves shows you what’s happening.

The x-axis is proportional to H, the magnetizing forceapplied to the core, which is proportional to the current inthe primary winding. The y-axis is proportional to B, the coreflux density, which is proportional to the integral of the sec-ondary voltage. The slope of the BH curve at any point isdirectly proportional to the inductance at the applied H.

The original inductor was a common-mode line filterchoke, normally operated with balanced and opposing cur-rents in its two windings. As a result, its core need notsupport a DC flux and, as shown in Figure 6a, it most cer-tainly doesn’t. Near the origin, the BH curveis nearly vertical, which means it has a veryhigh inductance. For any nonzero H (and,thus, any non-canceling winding current), thecore saturates with the slope of the BH curvebecoming nearly horizontal.

I harvested the inductor shown in Photo 1from a scrapped switching power supply. Asyou can see by comparing it with the photo ofthe inductor in my April column, its core ismuch larger. While that does not guarantee tol-erance of higher core flux density, it’s a goodsign.

The lower scope shot in Figure 6 shows itsmore normal BH curve. The inductance is rela-tively low, but the core doesn’t saturate abruptly.

The area inside an inductor’s BH curve isproportional to its core power loss, so thelarger core has a much higher loss. When youdesign a switching converter, particularly fora solar power project, reducing its core lossmust be on your to-do checklist. Fortunately,

I can leave that as an exercise for the interested reader!Figure 7 shows the inductor in action, switching between

100 mA and 200 mA limits; I used a bench power supply andan 8-Ω resistor to simulate a solar panel. The top trace is pro-portional to the inductor current, as measured by the MAX4372high-side current amp, at 1 V = 100 mA. The lower trace isthe base drive signal for Q2, the converter’s current switch.

The current in this inductor now varies almost linearlywhile charging and discharging. The slopes also show goodagreement with the applied inductor voltages, according tothe familiar equation:

BOOSTER SETTINGSAfter the firmware determines the MPP, it sets the PWM9

and PWM10 outputs to bracket the MPP current by about

v = L didt

Figure 7—The inductor current now behaves as expected due entirely to the larger core. The slower tran-sitions allow the MAX4372T output to accurately represent the inductor current.

Figure 6a—The B-H curve for the common-mode choke inductor I used in the earlier circuit shows a very high inductance and saturates at a low DC current. b—The inductor inthis circuit has a lower inductance, but doesn’t saturate at a few hundred milliamps of DC current.

a) b)

2906004_nisley.qxp 5/7/2009 1:17 PM Page 28

Page 31: Circuit Cellar 2009-06

IEIE www.circuitcellar.com • CIRCUIT CELLAR®

29

June

2009 –

Issue

227

±10%. When the current exceeds the high limit, Q2turns off and the current begins dropping. When the cur-rent falls below the low limit, Q2 turns on and the cur-rent begins increasing. That cycle repeats until thefirmware runs another load test and determines the newcurrent setpoints.

The cross-connections between IC5A and IC5B form aset-reset flip-flop driving Q2 through two paralleledgates. The flip-flop remembers the transistor drive statebetween comparator transitions. You’ll see the need forthis as you probe the circuit: the comparators changestate only briefly as the current goes beyond the set-points, while the transistor must remain active or inac-tive until the current hits the other limit.

For the current limits shown in Figure 7, the boosterruns at 18 kHz, which drives my golden-eared daughterout of my basement laboratory; it’s completely inaudibleto me. A much lower inductance, with a much higherdi/dt, will run at a much higher frequency, but will alsorequire much faster comparators and higher transistordrive. Remember, however, that the inductor core mustsupport the flux required to drive the panel at its MPP:tiny surface-mount inductors probably won’t suffice foran 80-W panel!

In addition to setting the inductor current limits, thefirmware also sets the load current to match the poweravailable from the panel. The boosted voltage on C5 canbe any value you like, as long as it’s higher than thepanel voltage and less than 20 V (which is limited hereby the Diecimila’s 5-V analog inputs through the inputscaling resistors). I set it to three times the panel voltageat the MPP or 15 V, whichever is less.

Then, knowing the desired output voltage and theavailable power, the firmware simply sets the load cur-rent in Q1 to their ratio. For example, with 540 mWavailable at a MPP of 5.4 V and 100 mA, the booster’soutput voltage will be 15 V and the load current will be:

I implemented a very simple voltage-regulation algo-rithm, if you can glorify it with that name, whichadjusts the load current once each second to maintainthe output voltage as the solar input changes. After aminute of that the firmware performs another load test,recalculates the MPP, and picks the best load current forthe new conditions.

Obviously, you can be far more clever, but ... that’sanother exercise!

INPUT PROTECTIONI used a MAX4372 to measure the panel current for

the boost converter because it has a 28-V common-moderating for the current-sense resistor, even with a logic-level power supply. After two of the chips mysteriouslydied on my bench, I sat down with the datasheet to findout why.

36 mA = mW V

54015

SOURCESGnuplot Plotting utilityGnuplot | www.gnuplot.info

LTspice IV Design simulatorLinear Technology Corp. | www.linear.com/designtools/software/ltspice.jsp

Arduino Diecimila MicrocontrollerSparkFun Electronics | www.sparkfun.com/commerce/product_info.php?products_id=666

Ed Nisley is an EE and author in Poughkeepsie, NY. Contacthim at [email protected] with “Circuit Cellar” in the subject toavoid spam filters.

PROJECT FILESTo download the additional files, go to ftp://ftp.circuitcellar.com/pub/Circuit_Cellar/2009/227.

RESOURCESArduino project, http://arduino.cc/.

BH Curve information, E. Nisley, “Transformers,” CircuitCellar 211, 2008.

It turns out that the absolute maximum differential-mode voltage across the sense resistor must not exceed amere 300 mV, most likely because that will turn on theinternal ESD protection diodes and burn out the part.My solar panels can supply only a few hundred milliamps,which the sense resistor converts into half that numberof millivolts and that seemed safe enough.

Perhaps you’ll recall that I mentioned a “real” designmust prevent the booster transistor Q2 from remainingon and driving the inductor core into saturation. Ibelieve that’s exactly what killed those two MAX4372s:after L1 saturates, the panel voltage divides between itsinternal resistance and the sense resistor, with Q2’s satura-tion voltage accounting for only a few hundred millivolts.

Worse, I initially drove the circuit from a bench powersupply through an 8-Ω resistor to simulate a solar panelin the darkness of my basement lab. Even though I hadthe supply current limit set to 300 mA, I think brieftransients killed the MAX4372s before the limiterkicked in.

R36, R37, and D5 now hard-limit the voltage present-ed to the MAX4372 sense inputs and have successfullyprotected the chip from the rigors of my test setup. Welive and learn.

CONTACT RELEASEI don’t have room to describe the process of extracting

and formatting the relevant parts of the firmware’s out-put to make the graphs, but the GNU/Linux commandline will be your friend. Judicious application of grep,cut, sort, and sed to the log files will move you a longway toward the goal of valid input for gnuplot. I

2906004_nisley.qxp 5/7/2009 1:17 PM Page 29

Page 32: Circuit Cellar 2009-06

30 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

For many applications, retrieving sensor readings requires an SSI controller.But it can be expensive. Robert presents an affordable solution forbuilding your own SSI readout display for position sensors.

SSI Controller for Linear-Position Sensors

I

FEA

TURE

ARTICLEby Robert Bowen

like to develop innovative solutions for design problemsrather than rely exclusively on expensive commer-

cial products. For instance, I recently spent a weekendconstructing a synchronous serial interface (SSI) readoutdisplay for position sensors (see Photo 1). In this article,I’ll describe how I built the handy controller, whichincludes an LCD that enables stand-alone operation.

SENSOR EVALUATIONI am a firm believer in the following idea: If it is already

invented, use it. I’m not a “roll-your-own” kind of engi-neer. If my application requires an RTOS or kernel, I willuse a commercial product. If my controller requires an

OK

Art

embedded PC or SBC, I will shop around for one thatmeets my application’s requirements. In my field, timeto market is the key to success.

Recently, I was asked to evaluate a new linear positionsensor, which is used for measuring displacement andvelocity. Think of it as a high-precision electronic ruler.Linear position sensors—which you’ll find in linearmotor applications, CNC/PLC machines, servo-hydraulicclosed-loop systems, and packaging machines—come indifferent flavors. Two popular but different technologiesinclude magnetostrictive and glass scale encoders.

The MTS Systems Temposonics III R-Series linear posi-tion sensor in Photo 2 uses magnetostrictive technology.

Photo 1a—The SSI controller supports both PC and Stand-Alone mode. In the latter, the sensor readings are displayed on the LCD screen. InPC Mode, the sensor data counts are sent to the PC’s RS-232 serial port. b—An NXP P89C668 microcontroller sits at the heart of the design.

a) b)

2906016_Bowen.qxp 5/7/2009 1:15 PM Page 30

Page 33: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 31

June

2009 –

Issue

227

These transducers convert the energy from a magneticfield into mechanical energy. This is accomplished bythe interaction of two magnetic fields. One field is pro-duced by a magnet thatmoves along the outside ofthe sensor’s waveguide. Theother field comes from a cur-rent pulse applied to thewaveguide or tube. The inter-action of the two magneticfields produces a strain pulse.The magnet’s position is cal-culated by measuring theelapsed time between theapplication of the interroga-tion pulse and the arrival ofthe resulting strain pulse.

Unlike the Temposonicssensor, glass scale encodersemploy an optical glass and aphotoelectronic reading head.The optical glass consists of aseries of evenly distributedchrome lines. The readinghead uses a photodetector tosense the chrome line pat-terns on the glass scale. Asthe reading head slides acrossthe glass scale, it produces anelectronic signal or pulse. Forexample, a 20-µm precisionglass scale has 1,270 accuratelyplaced chrome lines per inch.As the reading head is movedacross the glass scale, the pho-toelectronic reading headdetects each chrome line.When the reading head travels1″, it produces a count of1,270.

Common among thesedevices is the SSI, which is a

widely used serial interface between anabsolute position sensor and a con-troller. An SSI uses a clock pulse trainfrom a controller to initiate a readingfrom the sensor. Position data is contin-ually updated by the sensor and madeavailable to the controller. Figure 1illustrates the basic requirements froman SSI controller (often referred to asdigital readout display).

SSI OUTPUTI was a little puzzled when my new

linear position sensor arrived without anSSI controller. Instead I received a list ofavailable readout displays. I didn’t need

anything elaborate, but I had a few requirements. The SSIcontroller had to be small and durable. I planned to usethe device in the field, and it had to be able to withstand

Photo 2—Unlike other sensors, the Temposonics III R-series linear position sensor canbe reprogrammed in the field. Programmable options include: changing the sensor’sresolution, output data format and the type of communication interface, synchronousor asynchronous.

Figure 1—An SSI controller must comply with the timing diagram illustrated in the datasheet (MTSSystems, www.mtssensors.com/fileadmin/media/pdfs/RSeriesSSI.pdf). It is responsible for supply-ing the 24 VDC to the sensor and must provide either an asynchronous or synchronous clock tothe sensor. The Temposonics sensor requires a minimum dwell time of 25 µs between consecutivereadings.

Data (+)

Data (−)

Data (+)

MSB LSB

Clock (+)

Clock (+)

Clock (−)

+24 VCC

Ground

2 V91 Ω 100 Ω

100 Ω91 ΩLED

6N137Optocoupler

Data (+)

MSB LSB

Clock (+)

Clock (+) Clock pulse train

Clock interval25-µs Minimum

Sequential measurements of SSI timing

Clock pulse train

SSI Timing diagram

SSI Interface - sensor SSI Interface - controller

75147Output stage

2906016_Bowen.qxp 5/7/2009 1:15 PM Page 31

Page 34: Circuit Cellar 2009-06

32 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

the punishment of being shipped from customer to cus-tomer. Additionally, I wanted the controller to be able tooperate independently, as well as with a PC for dataacquisition requirements.

One of my options was an Advanced Micro ControlsNEXUS SSI controller (see Photo 3). This compact con-troller included support for linear, rotary, and laser posi-tion sensors. Each unit came standard with a four-chan-nel SSI data interface and provided options for Control-Net, DeviceNet, Ethernet IP, and Modbus TCP/IP. Unfor-tunately, it lacked a display. This meant I would need a PCto operate the device. Additionally, my position sensor

had a standard 15-pin D-SUB connector.I would’ve had to modify either theNEXUS controller or the sensor beforeconnecting. Lastly, the NEXUS camewith a price tag of $2,095, which wasmuch too expensive for my application.

As I later discovered, most manufac-turers offered third-party sources forpurchasing an SSI controller for theirsensors. That meant I would purchase asensor from Company A and then pur-chase the SSI controller from CompanyB. So, if I have a problem with the sen-sor, I would have to work with two dif-ferent companies. That wasn’t the path Iwanted to journey down for a low-budg-

et application. I decided it was time to “roll-my-own” SSIcontroller.

Figure 2—This is an SSI controller’s basic configuration. All that is required are a cleanand stable power source and a microcontroller for retrieving the data from the positionsensor. Common among SSI sensors is the RS-422 interface, which provides the clockand data bus interface.

RS-232P89C668

Microcontroller

UARTRS-422

+/- Data

+/- Clock

+5 VDC

+24 VDC

+24 VDC

LCDI2C

DC/DC

SSI Linear position sensor

Photo 3—The Nexus SSI Inter-faceController supports up tofour SSI devices and hasoptions for ControlNet,DeviceNet, Ethernet IP, andModbus TCP/IP. Unfortunately, itlacks an LCD. This SSI controllerrequires a PC to view readingsfrom the position sensor.

2906016_Bowen.qxp 5/7/2009 1:15 PM Page 32

Page 35: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 33

June

2009 –

Issue

227

converter, power supply, cables, andsoftware. After running the installa-tion CD, I connected the Temposon-ics and launched the MTS R-SeriesSSI Utility application. The softwareestablished a connection with thesensor and then displayed its set-tings in a user-friendly format. Atthat point, I could choose to changeany of the available parameters.After clicking the Apply Changescommand button, the new parame-ters were written to the sensor’s on-board processor.

CONTROLLER HARDWAREThe SSI controller’s configuration

is depicted in Figure 2. The con-troller must provide the 24 VDC andsystem clock to the SSI sensor. AnRS-422 dual-differential line driverand receiver would satisfy the ±Dataline interface requirements from thesensor.

My first prototype used a 24 VDCat 500 mA wall transformer for thepower source. The 24 VDC wouldsatisfy the power requirements for

After a weekend of soldering andcoding, I designed and built my SSIinterface controller for less than$100. The controller includes anLCD screen that enables the unit tooperate in Stand-Alone mode. It alsoincludes an RS-232 interface forsending the sensor readings to a PCfor data acquisition.

For testing, I purchased a Tem-posonics III R-Series linear positionsensor. It has an SSI, a resolution of0.001 mm, and stroke ranges from 50to 10,060 mm. Because it is field-pro-grammable, I can configure the sen-sor’s SSI parameters. I can set thedata length (24 or 25 bit), set thedata format (binary or grayscale), setthe resolution range (from 0.001 to0.005 mm), select either synchro-nous or asynchronous measurement,and select either speed or positionmeasurement.

I also purchased the field-program-ming kit, which enabled me to recon-figure the sensor’s parameters andthoroughly test the digital readoutdisplay. The kit came with a serial

Listing 1—The firmware simply bit-bangsthe Temposonics to acquire the 25-bitdata count. After each high-to-low transi-tion, data is retrieved from the sensor.The BCD_32() processes the readingsand then they are sent to the LCD and tothe RS-232 serial port.

;******************************; READ_TEMPOSONICS():; This routine communicates ; directly with the Temposonics III,; provides the required clock; pulses and reads the 25-bit; binary count result.; The 25-bit binary result is ; stored in (MSB)R4,R5,R6, ; R7(LSB) which is passed to ; the BCD_32() function.;******************************

READ_TEMPOSONICS:SETB SSI_CLK1 ; CLK HIGH

FOR 25uS DWELL TIMEMOV R1,#250NOPNOPDJNZ R1,$CLR SSI_CLK1 ; CLK LOW

MOV ANSWER,#0MOV A,#0CLR CMOV R1,#1 ; 1ST READING

MSB OF TEMPO. RDNG.

MSB: SETB SSI_CLK1CLR SSI_CLK1MOV C,SSI_DATA1 RLC ADJNZ R1,MSB MOV ANSWER,A ; SAVE RDNG

IN ANSWER.

MOV R1,#8 ; READ NEXT 8BITS OF TEMPO. RDNG.

HBYTE:SETB SSI_CLK1CLR SSI_CLK1MOV C,SSI_DATA1 RLC ADJNZ R1,HBYTE MOV ANSWER+1,A ; SAVE

RDNG IN ANSWER+1.

MOV R1,#8 ; READ NEXT 8 BITS OF TEMPO. RDNG.

MBYTE:SETB SSI_CLK1CLR SSI_CLK1MOV C,SSI_DATA1 RLC ADJNZ R1,MBYTEMOV ANSWER+2,A ; SAVE

RDNG IN ANSWER+2.MOV R1,#8 ; READ LAST 8

BITS OF TEMPO. RDNG.

LBYTE:SETB SSI_CLK1CLR SSI_CLK1MOV C,SSI_DATA1 RLC ADJNZ R1,LBYTEMOV ANSWER+3,A ; SAVE

RDNG IN ANSWER+3.;SETB SSI_CLK1;RET

2906016_Bowen.qxp 5/7/2009 1:15 PM Page 33

Page 36: Circuit Cellar 2009-06

34 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

Figure 3—To make a trulycompatible SSI controller,you can add a few jumpersand extra connectors. Thefirmware can be written todetect which sensor isconnected. I included botha nine- and 15-pin DSUBto the SSI controller.

Linear IC Technology

Introductory Circuit Analysis

Op-Amp Design Techniques

ELECTRONICCOMMUNICATIONS

MATHEMATICSIN ELECTRONICS

To update your professor account or to find

out more about our college program, visit

www.circuitcellar.com/products/collegeprogram/

PROFESSORSThe Circuit Cellar college programputs quality engineering informationin the hands of your students everymonth. Sign up now to getCircuit Cellar distributed to yourclass this semester.

2906016_Bowen.qxp 5/7/2009 1:16 PM Page 34

Page 37: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 35

June

2009 –

Issue

227

the Temposonics sensor.The Linear TechnologyLT1107-5 DC/DC con-verter would be used to pro-duce 5-VDC at 300 mA.This would have beensuitable power for themicrocontroller, LCD,and the on-board controllogic. However, I discov-ered that most linearposition sensors requiredat least 5 VDC at 350mA. This would require aslight change to thepower supply circuit.

I replaced the LT1107-5with a TDK-Lambda CC6-2405SF-E DC/DC convert-er, which boasts a 5 VDCat 1.2 A output. It has acompact footprint andsupports both SMT andthrough-hole versions.This made laying out thePCB easy, and it eliminat-ed the extra passive com-ponents.

An NXP P89C668microcontroller is theheart of the SSI controller(see Figure 3). A variantof the 8051 microcon-troller family, it comespacked with a lot of good-ies, including on-boardflash memory and an I²Chardware interface. Inaddition, it supports in-circuit serial program-ming (ISP), which is auseful feature for fieldupdates and firmwaredevelopment. Rememberthe old days when youhad to remove the 8751and erase it under ultravi-olet light for 20 minutes?Firmware developmenttook forever. Today,thanks to flash memoryand ISP technology, youcan be more productive.

I wanted the digital read-out display controller tooperate in both Stand-Aloneand PC modes. In the for-mer, you could connect the

Listing 2—The LCD is connected to the microcontroller through an I²C hardware interface.

;******************************************************************;; LCD_DISPLAY_INCH() - Writes "Inch" on Row 2 Column 3;;******************************************************************LCD_DISPLAY_INCHES:

MOV S1CON,#040H ;Enable I2C - no acknowledgements will be generatedSETB S1CON.5 ;STA = 1JB S1CON.3,$ ;Wait for interruptSETB S1CON.5 ;STA = 1 MOV S1DAT,#254 ;cmd to LCDJB S1CON.3,$ ;Wait for interrupt;MOV S1CON,#040H ;Enable I2C - no acknowledgements will be generatedSETB S1CON.5 ;STA = 1JB S1CON.3,$ ;Wait for interruptSETB S1CON.5 ;STA = 1 MOV S1DAT,#71 ;cmd number to LCDJB S1CON.3,$ ;Wait for interrupt;MOV S1CON,#040H ;Enable I2C - no acknowledgements will be generatedSETB S1CON.5 ;STA = 1JB S1CON.3,$ ;Wait for interruptSETB S1CON.5 ;STA = 1 MOV S1DAT,#3 ;COLUMN = 3JB S1CON.3,$ ;Wait for interrupt;MOV S1CON,#040H ;enable I2C - no acknowledgements will be generatedSETB S1CON.5 ;STA = 1JB S1CON.3,$ ;WAIT FOR INTERRUPTSETB S1CON.5 ;STA = 1 MOV S1DAT,#2 ;ROW = 2JB S1CON.3,$ ;WAIT FOR INTERRUPT;MOV S1CON,#040H ;Enable I2C - no acknowledgements will be generatedSETB S1CON.5 ;STA = 1JB S1CON.3,$ ;WAIT FOR INTERRUPTSETB S1CON.5 ;STA = 1 MOV S1DAT,#049H ;Letter "I"JB S1CON.3,$ ;WAIT FOR INTERRUPT;MOV S1CON,#040H ;Enable I2C - no acknowledgements will be generatedSETB S1CON.5 ;STA = 1JB S1CON.3,$ ;WAIT FOR INTERRUPTSETB S1CON.5 ;STA = 1 MOV S1DAT,#06EH ;Letter "n"JB S1CON.3,$ ;WAIT FOR INTERRUPT;MOV S1CON,#040H ;Enable I2C - no acknowledgements will be generatedSETB S1CON.5 ;STA = 1JB S1CON.3,$ ;WAIT FOR INTERRUPTSETB S1CON.5 ;STA = 1 MOV S1DAT,#063H ;Letter "c"JB S1CON.3,$ ;WAIT FOR INTERRUPT;MOV S1CON,#040H ;Enable I2C - no acknowledgements will be generatedSETB S1CON.5 ;STA = 1JB S1CON.3,$ ;WAIT FOR INTERRUPTSETB S1CON.5 ;STA = 1 MOV S1DAT,#068H ;Letter "h"JB S1CON.3,$ ;WAIT FOR INTERRUPTRET

2906016_Bowen.qxp 5/7/2009 1:16 PM Page 35

Page 38: Circuit Cellar 2009-06

36 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

linear sensor and view the output dis-placement readings directly on theLCD screen. The PC could be option-al and you could use it for data acqui-sition or converting the sensor data tovelocity readings.

Although I hate to admit it, I spentmore time searching for the perfectLCD than it took to develop thefirmware. This was a low-budget proj-ect, so I had to consider cost, displaysize, power requirements, contrast,and, lastly, the type of interface. Afterseveral hours of navigating the Inter-net, I ended up at Matrix Orbital’swebsite, where I found the LCD0821display, which had all the rightingredients for my application. Thistightly packed LCD had a small foot-print measuring 58 mm × 37 mm ×25 mm (see Photo 4). It had a back-light display that could be controlledvia software. It required only 5 VDCat 30 mA, and provided both an I²Cand RS-232 communication inter-face. All of this for less than $40!

FIRMWAREThe P89C668 microcontroller is

responsible for communicating withthe SSI linear-position sensor. It pro-vides the necessary clock pulses andreads the 25-bit binary data code.The binary output code is a datacount value representing the sensor’sposition or displacement. The posi-tion sensor is programmed to pro-duce a count, which represents theamount of travel. For example, theTemposonics has a resolution of0.005 mm. This equates to 5,080counts per inch. To calculate a dis-placement measurement from thedevice, you would take the binarycount value/5,080:

The firmware is written in assem-bly language, and I used the Keil IDEMicroVision compiler. If assemblylanguage is not your preferred pro-gramming language, the Keil IDEsupports C language. For simple proj-ects that require only a few pages of

Temposonics resolution =

= 200 counts/mm

200 25.4

10 005.

× == 5,050 counts/inch

Listing 3—The firmware is responsible for responding to the I²C status codes. The statuscode must be used to vector to an interrupt service routine (ISR).

;*****************************************************************; Received I2C ISR;; Interrupt Service Routine(s) for all I²C Interrupt conditions. ;;*****************************************************************I2C_ISR:;START CONDITION TRANSMITTED. STATUS CODE 08H

MOV R7,S1STACJNE R7,#08H,STATUS_CODE_10HCLR S1CON.5 ;STA = 0CLR AMOV A,#050H ;LCD ADDRESSANL A,#0FEHMOV S1DAT,ACLR S1CON.3 ;SI =0RETI

STATUS_CODE_10H:;REPEATED START CONDITION TRANSMITTED;CJNE R7,#010H,STATUS_CODE_18HCLR S1CON.5 ;STA = 0CLR AMOV A,#050H ;LCD ADDRESSANL A,#0FEHMOV S1DAT,A ;SEND DEVICE ADDRESS AND START SIGNAL RETI

STATUS_CODE_18H:;SLAVE ADDRESS + WRITE TRANSMITTED - ACK RECEIVED;CJNE R7,#018H ,STATUS_CODE_20HCLR S1CON.5 ;STA = 0CLR S1CON.3 ;SI = 0RETI

STATUS_CODE_20H:;SLAVE ADDRESS + WRITE TRANSMITTED - NO ACK RECEIVED;CJNE R7,#020H,STATUS_CODE_28HCLR S1CON.5 ;STA = 0CLR S1CON.3 ;SI = 0RETI

STATUS_CODE_28H:;DATA BYTE TRANSMITTED - ACK RECEIVED;CJNE R7,#028H,STATUS_CODE_30HSETB S1CON.4 ;STO = 1CLR S1CON.3 ;SI = 0RETI

STATUS_CODE_30H:;DATA BYTE TRANSMITTED - NOT ACK RECEIVED;CJNE R7,#030H,STATUS_CODE_38HSETB S1CON.4 ;STO = 1CLR S1CON.3 ;SI = 0

RETI

STATUS_CODE_38H:;ARBITRATION LOST OR DATA BYTES;CLR S1CON.3 ;SI = 0RETI

2906016_Bowen.qxp 5/7/2009 1:16 PM Page 36

Page 39: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 37

June

2009 –

Issue

227

code, I prefer using assembly. Let’s examine the sourcecode in Listing 1.

The timing diagram illustrates that data is shifted outwhen the sensor receives a clock pulse from the con-troller. Data is valid on each high-to-low clock transition.To acquire the 25-bit data count from the sensor, the con-troller must provide 25 clock cycles. For asynchronous com-munication, bit-banging is a viable option. It is importantto consult the sensor’s datasheet. Some position sensorssupport only synchronous communication. Thus, tryingto communicate with it in the wrong mode could resultin data loss.

As you can see in the source code, I created four loopsfor acquiring the 25-bit result. The first loop is a singleclock to acquire the first MSB. The next three loops eachconsist of eight high-to-low clock transitions. The 25-bitresult is stored in the following format: MSB – bit 25;HBYTE – bit 24-17; MBYTE – bit 16-8; and LBYTE – bit7-0.

The firmware contains two binary coded decimal func-tions, BCD_24() and BCD_32(). These functions areused to convert a 24-bit binary and 32-bit binary num-bers to BCD format. Once converted, the result is sentto serial port.

For the LCD, a little more work has to be performedwith the BCD result. Displaying a count value on theLCD screen would not be very useful to the user. To pro-vide a meaningful output, the BCD value is converted toengineering units—inches, in this case. To accomplishthis, the firmware utilizes a few integer math routinesto complete the conversion:

This result represents the sensor’s absolute position andis ready to be sent to the LCD.

In previous projects, I implemented the I²C protocol infirmware. This time, I decided to take advantage of theI²C hardware interface on the P89C668 microcontrollerto communicate with the LCD. Before examining thispart of the source code, I will briefly review the high-lights of the I²C protocol as it pertains to the P89C668

Engineering units (inches) = BCD Value5 080,

microcontroller.The I²C (Inter-IC Bus) interface uses two wires (SDA

and SCL) to transfer data between devices connected tothe bus. The P89C668 uses four special function regis-ters: S1CON (control register), S1STA (status register),S1DAT (data register), and S1ADDR (slave address regis-ter). The CPU can operate in either Master or Slavemode. In this case, the CPU is configured to be the mas-ter. The master device generates all of the serial clockpulses and the START and STOP conditions. To senddata to a slave device (the LCD screen in this case), themaster first transmits a byte containing the slave’saddress and the data direction bit. After each byte istransmitted, an acknowledgement bit is received whilethe START and STOP conditions are output to indicatethe end of the serial transfer.

Listing 2 illustrates how to write the word “Inch” onthe second row of the LCD screen. Table 1 displays theMaster Transmitter response table. After a byte has beensent to the slave, an interrupt is generated and it is up tothe application to respond accordingly to the responsecodes. Listing 3 illustrates how to implement this in thesource code.

DIGITAL READOUT APP It’s convenient to have the linear-position sensor dis-

play its readings on the LCD screen. Data collection ormanipulating the sensor readings to displayvelocity/speed is work best left to the PC. The digitalreadout display controller automatically sends the sen-sors data count to the serial port.

All that is left to do is develop an application to listenon the computer’s serial port and present the data to theuser. There are several tools available for developing auser interface application. For data acquisition applica-tions, I prefer using either National Instruments’s Lab-VIEW or Microsoft’s Visual Basic. LabVIEW has trulyrevolutionized the ease of developing test and measure-ment applications. The LabVIEW IDE comes with asuite of tools that enables you to create a professionallook and feel. Creating real-time chart recorders and dis-playing panel meters for instrumentation readouts arestandard tools included within the LabVIEW environment.

To complete the SSI controller, I created a simple GUIin Visual Basic (see Photo 5). The application enablesyou to select the type of readout, either actual encodercounts or engineering units. In the Counts/Inch section,you can enter the linear-position sensor’s resolution.

Table 1—The I²C interface is interrupt-driven. The application isresponsible for responding to the I²C status codes. Creating a look-up table in the firmware allows the microcontroller to be responsivewhen activity is detected on the I²C bus.

Status code Status of I2C bus

08H A start condition has been transmitted.

10H A repeated START condition has been transmitted.

18H SLA+W has been transmitted. ACK has been received.

20H SLA+W has been transmitted. NOT ACK has been received.

28H Data byte in S1DAT has been transmitted. ACK has been received.

30H Data byte in S1DAT has been transmitted. NOT ACK has been received.

38H Arbitration lost in SLA+R/-W or data bytes.

Photo 4—The LCD0821has a 2 × 8 linealphanumeric liquidcrystal display. It sup-ports both RS-232 andan I2C communicationinterface.

2906016_Bowen.qxp 5/7/2009 1:16 PM Page 37

Page 40: Circuit Cellar 2009-06

38 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

Robert Bowen ([email protected]) holds an Associate’s degree in electronic technolo-gy and electronic engineering and has worked for AT&T Consumer Products designing testequipment. Currently, Robert works as a senior field service engineer for MTS SystemsCorp., where he designs automated calibration equipment and develops testing methods forcustomers involved in the material and simulation testing fields. In his spare time, he enjoysamateur radio (call sign N0PAU), and he recently started playing the guitar with his 8-year-oldson, Elijah, and his 11-year-old daughter, Madison.

ROJECT FILESTo download the code, go to ftp://ftp.circuitcellar.com/pub/Circuit_Cellar/2008/227.

ESOURCESMatrix Orbital, “LCD0821 Technical Manual,” Rev. 2.0, www.matrixorbital.ca/manuals/LCDVFD_series/LCD0821/LCD0821_rev_20.pdf.

MTS Systems Corp. (Sensors Division), “Magnetostriction: Principle,Technology, and How It Works,” www.mtssensors.com/technology/how-magnetostriction-works/index.html.

OURCESMicroVision CompilerKeil | www.keil.com

LT1107-5 DC/DC ConverterLinear Technology | www.linear.com

LCD0821 LCD Matrix Orbital | www.matrixorbital.com

Temposonics III R-Series linear position sensorMTS Systems Temposonics | www.mtssensors.com

P89C668 MicrocontrollerNXP | www.nxp.com

CC6-2405SF-E DC/DC converterTDK-Lambda Americas, Inc. | www.us.tdk-lambda.com

P

R

S

The application uses this value tocalculate the displacement readingsproperly from the sensor. Finally,the Device section provides a con-venient way to support multiplesensors. This is useful if each sen-sor’s output is scaled differently.The application will know how tohandle the data accordingly.

Communicating with the positionsensor begins when power is applied tothe SSI controller. The sensor’s read-ings, in engineering units, are auto-matically sent to the LCD, while thesensor’s data count value is simulta-neously sent to the RS-232 serialport. If a PC is connected, you maychoose to view either the data countor the sensor’s absolute position.

A LOW-COST SOLUTIONIn this article, I presented a low-

cost solution for building an SSI read-out display for position sensors.There are many different sensingtechnologies. Each has its advan-tages. Typically, the environment andresolution required for an applicationwill dictate the correct choice.Selecting the proper sensor for yourapplication is only half the battle.Retrieving the sensors readingsrequires an SSI controller. Whilethere are several manufacturers thatprovide commercial products, theyare often expensive and require modi-fications for connecting the sensor tothe SSI controller. Additionally, Ifound that most commercial SSI con-trollers provide either a stand-alone

or PC solution. My design accommodatesboth options for a fraction of the cost.

I chose the RS-232 interface for thisdesign for the reasons of cost and con-venience. But it would be easy toimplement the design to supporteither USB or an Ethernet interface.Actually, I’ve been considering imple-menting a wireless solution. Today,

wireless modules are relatively inex-pensive, and many wireless technolo-gy companies have made incorporat-ing this equipment painless. Whenyou start your next project thatrequires an SSI sensor, remember toconsider the following requirements:power consumption, data speedoptions, and the connection type.

If you’re like me, you tend to lookfor off-the-shelf solutions for yourprojects. However, there are timeswhen your budget will dictate howyou tackle a specific task. And, yes,sometimes this means reinventing thewheel. If it can be built for less and itprovides a smoother ride, then itmakes sense. I

Photo 5—The SSI controller is responsible forcommunicating with the sensor. All data issent to the RS-232 port. Creating a GUI appli-cation is effortless. The GUI simply listens onthe serial port and can manipulate the dataand present it to you in engineering units.

2906016_Bowen.qxp 5/7/2009 1:16 PM Page 38

Page 41: Circuit Cellar 2009-06

Wi-Fi and Ethernet Versions

42.qxp 12/27/2008 11:55 AM Page 1

Page 42: Circuit Cellar 2009-06

41.qxp 1/7/2009 3:07 PM Page 1

Page 43: Circuit Cellar 2009-06

63.qxp 1/7/2009 3:20 PM Page 1

Page 44: Circuit Cellar 2009-06

42 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

Autonomous vehicles and mobile applications are becoming increasinglyincorporated in the military, industrial, and healthcare industries. Thisautonomous vehicle design implements the full potential of embedded,sensor, and modular electronic technologies.

Autonomous Vehicle Design

A

FEA

TURE

ARTICLEby Chris Britney, Paul Green, Andy Heath, Stephen Lau, & Kylee Lathrop

utonomous vehicles are sprouting up everywhere, from military bases (e.g., unmanned surveil-

lance systems) to luxury car dealerships (e.g., self-parkingcars) to home appliance stores (e.g., robotic vacuums).With such designs in mind—and inspired by the DARPAGrand Challenge, where autonomous cars race a long-dis-tance course through the desert—our design team atCamosun College created an autonomous vehicle calledthe Interurbanator (see Photo 1).

The recent development of satellite navigation andvideo imaging enables the development of inexpensiveautonomous vehicles. We didn’t have the budget toimplement LIDAR or gas-powered technologies, so weused a small hobby vehicle as our chassis, whichincludes two small 12-VDC motors and hollow plasticwheels. We used mostly off-the-shelf and recycled com-ponents for this do-it-yourself, modular-style project.

In this article, we will explain how we built ourautonomous vehicle system, which features a modularLinux “brain” that runs a custom C++ program, a differ-ential GPS and algorithm, a custom serial protocolbetween microcontrollers, low-level sensors, and a web-cam laser rangefinder. We used Open Source ComputerVision (OpenCV) for the image-processing aspect of thisapplication.

SYSTEM OVERVIEWThe vehicle uses many different sensors to reach its

destination (see Figure 1). At the center of everything is

the CPU, which is a Pentium 4 computer running aLinux operating system. This gives us the ability totime slice and run multiple processes at the same time.The vehicle can approach its destination by avoiding allthe objects in its way. When an object is detected andavoided, the system reroutes itself to the target.

We implemented infrared (IR) range sensors, an ultra-sonic sensor, and webcam laser rangefinding to detectobstacles. From the CPU’s perspective, each group ofsensors has different priorities. The IR range sensorsdetect surfaces using analog voltage to represent rangeto a surface. The IR sensors detect only objects 30 cmaway. If something is that close to the vehicle, actionneeds to happen immediately.

The webcam laser rangefinding system is designed foravoiding objects. Although it is accurate up to 6 m, it ismounted to the front of the vehicle and can’t see what’sbehind it. The ultrasonic sensor is mounted to a steppermotor so it can rotate 360° to sense objects in all direc-tions.

The vehicle’s drive train consists of two 12-VDCmotors driven by a pulse-width-modulated (PWM) sig-nal. The wheel RPMs are then picked up by two infraredsensors in the motor gear boxes. From this we canchoose multiple speeds and keep track of how far thevehicle has traveled. A Firgelli Technologies linear actu-ator enables steering control. This is a simple and easyreplacement for a steering wheel. A digital compass pro-vides steering feedback.

Embedded Systems, Sensor Technology, and Motor Control

2906014_Lathrop.qxp 5/11/2009 1:18 PM Page 42

Page 45: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 43

June

2009 –

Issue

227

We used microcontrollers for low-level sensordata acquisition. This includes IR sensors, steppermotor control, ultrasonic sensors, digital compass,steering control, and driver motor control. EachMCU collects and controls each device at all times.The computer gives a command or requests datastored in the MCU. We designed a serial protocolfor this communication to work. This protocolenables each thread in the brain to access eachdevice without interfering with any other device.Figure 1 is a block diagram of the system.

CENTRAL PROCESSINGRunning a Linux operating system enables us to

run multiple processes at one time. We use individ-ual threads to divide up the brain’s tasks. Threadsare used for computing calculations, obstacleavoidance, and navigation. All autonomous vehi-cles require some form of obstacle avoidance andnavigation control. We use a Linux kernel runninga C++ program to control the autonomous vehicle.To simplify code management, we produced aseries of files. Each file contains the relevant codeand variables required to control and read informa-tion from a particular system. By using multiplethreads, we allow the different parts to run andleave timesharing for the computer.

Each thread communicates with the othersthrough a series of global structures. Primaryavoidance is left to the webcam laser rangefinder.IR sensors manage secondary avoidance. The ultra-sonic rangefinder isn’t particularly accurate; there-fore, it is only used as a secondary system to thewebcam laser rangefinder. Nevertheless, its versa-tility is useful. Mounted on a stepper motor, it cansee 360° around the vehicle.

SERIAL PROTOCOLFigure 2a is the general communication format. Fig-

ure 2b is a special packet for IR/sonar data. FF isthe header used for the easy identification of pack-ets. Length H is one of two bytes given for thelength of the packet. Length L is the second of twolength bytes. TYPE is for device identification, sothe brain can tell different devices apart. DATAcontains information such as the sensor number,angle, and distance. CHKSUM is the checksum forerror checking. Figure 2c is a motor control packet.Note that FF, Length H, Length L, TYPE, and CHK-SUM are the same as they are for the IR/sonar datapacket. Speed sets the speed of the motors. Direc-tion sets the motors’ direction (forward or back).Brake sets the motors to brake.

The vehicle has numerous integrated subsystems. Toenable communication, we needed a standard method ofpassing data and commands between devices.To handlethis task, we used a serial connection and a custom pro-tocol. Early on, we decided a master/slave relationship

would work best and that the brain would be the masterand each of the subsystems would be designed as slaves.

To pass data or a command between the brain and oneof the microcontrollers, the brain initiates communica-tion. The microcontroller then replies with either the

Photo 1a—Take a look at the Interurbanator in action. Here it’s traversingfairly rugged terrain. b—IR range sensors enable the vehicle to avoidobstacles like people (seen here) and stationary objects. c—The designfeatures two 12-VDC motors and a simple chassis. Everything fits nicelyinside.

a)

b)

c)

2906014_Lathrop.qxp 5/7/2009 1:26 PM Page 43

Page 46: Circuit Cellar 2009-06

The type identifies the device thatthe brain is communicating with,which is important because somemicrocontrollers have more thanone device connected to it. Eachdevice is set to receive only the cor-rect type or data. Data is the infor-mation passed to and from thedevice. Distance (to an object) andmotor speed are examples of data.The checksum is added to the endfor the microcontroller. The braineasily identifies bad data, whichthen results in an ACK or NACK.

Most of our devices had a serialconnection to the motherboard fordesign flexibility. This gives us theability to remove and troubleshoot a

44 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

required data or an acknowledgecommand (ACK) to confirm recep-tion. If the command is not receivedcorrectly, a non-acknowledge(NACK) is returned to the master.An ACK/NACK allows for a simplemethod of passing a yes/no messageto indicate if data is understood.The protocol helps eliminate errorsand, at a minimum, recognize erro-neous data.

The basic protocol is shown in Fig-ure 2a. The important parts commonto each subsystem protocol areLENGTH, TYPE, DATA, andCHECKSUM. The length is commu-nicated so that the receiving deviceknows how much data is being sent.

broken board without having tocompromise the entire system,which worked out well for a proto-type design. The protocol is alsomodular enough for each device tobe on one serial bus. The TYPE fieldin the protocol enables each deviceto determine if a packet is destinedfor it.

In summary, the master (brain)initializes all communication. Theslave device (microcontroller) thenresponds with an appropriate reply.When bad data is received, the slaveresponds with a NAK. Depending onthe system, bad data is eitherrequested again or simply ignored.Most of our systems (e.g., IR) do not

Figure 1—Each module is connected to the CPU by either a USB or a serial connection running one of the protocols in Figure 2a. As youcan see, the various threads are a part of the CPU system and communicate as the master in a master-slave relationship with eachmodule.

Sonar

Steering actuator

Driver chips x 2

Wheel encoder x 2

From device

To device

Sonar thread

Compass thread

IR thread

Compass

IR sensor x 8

IR code &

compass code microcontroller

Steering codemicrocontroller

Sonar steppermotor

CPU

Sonar/sonarmotor code

microcontroller

Steering thread GPS thread

Mapping

Webcam

GPS 2

GPS 1

RPM thread

Motor control threadMotor control

microcontroller

IR avoidancethread

Webcamavoidance

thread

Sonar avoidancethread

Webcam signal-processing

thread

Navigationthread

2906014_Lathrop.qxp 5/7/2009 1:26 PM Page 44

Page 47: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 45

June

2009 –

Issue

227

control board for adding cur-rent-sensing and fault detectionusing the VNH2SP30’s addi-tional outputs (see Figure 4).We took advantage of themicrocontroller’s on-boardPWM module to providesmooth speed control for thedrive wheels. Our custom serialprotocol controls motor speed,direction, and braking com-mands. A two-bit parallel inter-face controlled directly to themotherboard provides the steer-ing input control. For feedbackfor the drive wheels, we drilleda small hole through the firstset of reduction gears in the

motor housing. We use an integratedIR photosensor and matching light-emitting diode to achieve a reliablepulse count for wheel rotation. Thelinear actuator’s built-in poten-tiometer provides an analog refer-ence voltage that’s interpreted bythe microcontroller’s on-board A/Dmodule.

INFRARED SYSTEMThe infrared system includes eight

fully integrated H-bridge motor driv-er. The voltage and current require-ments of the power wheels’ stockmotor, and that of the linear actua-tor, were well within the capabili-ties of the driver chip. This is anideal motor controller for smallmobile robotics applications. It has alow on-state resistance that enablesit to run reliably without any addi-tional heat sinking.

We made provisions on the motor

retransmit in the event of bad databecause that data would no longer bevalid in avoiding obstacles. There areslight amendments to the general pro-tocol for each device (see Figure 2band Figure 2c).

MODULE DESIGNWe took a modular approach to the

hardware design process. We felt itwas important to develop each sys-tem as a single entity. This enabledus to concentrate on eachsubsystem until it wasfully realized. A MicrochipTechnology PIC18F4620 8-bit microcontroller is oursubsystem’s processor (seeFigure 3).

All of the vehicle’s sys-tems are assembled oncustom PCBs that we cre-ated in-house with state-of-the-art milling equip-ment. Each board receivesa 12-V supply from thevehicle’s deep-cycle bat-tery. Regulators aremounted to each board togive the necessary voltagerequirements to each sub-system.

MOTOR CONTROL SYSTEMThe motor control sys-

tem, for both steering andthe drive wheels, compris-es a PIC18F4620 MCUthat controls an STMicro-electronics VNH2SP30

Figure 2a— This is the general protocol design with length and checksum. Type identifies the subsys-tem that the data is being communicated with. Data size varies with the system in question and thechecksum provides a means of error checking. b—The Infrared/Compass/Ultrasonic Communicationprotocol layout. This shows the specific data for these subsystems. c—The Motor Con-trol Communication protocol layout. This shows the specific data for these subsystems.

FFLengthH

LengthL Type Data CHKSUM

FFLengthH

LengthL Type

DistanceH

DistanceL CHKSUM

Sensor# Angle

FFLengthH

LengthL Type Speed Direction Brake CHKSUM

Figure 3—This board connects to the motor controller board. It receives a serial package from the CPU"Brain" and produces a PWM output with a PIC for controlling each motor individually. It includes feedbackand support hardware for the rotary wheel encoders.

a)

b)

c)

2906014_Lathrop.qxp 5/7/2009 1:26 PM Page 45

Page 48: Circuit Cellar 2009-06

process. The output was only 0 to3.2 V, so the 100-mV of noise causedlarge amounts of error, particularly

46 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

Sharp GP2Y0A21YK sensors con-trolled by a PIC18F4620 microcon-troller (see Figure 5). These sensorsproduce a 0- to 3.2-V ana-log output, which is thenrun through thePIC18F4620’s 10-bit ADCmodule. Six of our sen-sors are mounted verti-cally and slightly angleddown for object detection(four in the front and twoin the back). The othertwo are mounted hori-zontally to detect signifi-cant drops in the terrain.

The two horizontal sen-sors are far enough awayfrom the vehicle that ifsomething lies ahead(e.g., a cliff) the vehiclehas time to stop. Becausethe webcam laserrangefinder cannot dealwith drops in terrain, theIR system must work per-fectly to avoid a drop.The vertically mountedsensors on the left andright are used to detectobjects on the left andright (e.g., walls). Figure 6shows how the IR sensors

are mounted.These sensors proved to be suscep-

tible to noise during the testing

Figure 5—This board has a PIC that collects data from the compass and IR sensors. It then packages thedata into the serial protocol shown in Figure 2 and forwards it to the CPU “brain” when requested.

Figure 4—The motordriver board includesthe H-bridge with built-incurrent protection. Thisboard receives a signalfrom the motor daughterboard and can also becontrolled directly fromPorts 5, 6, 7 for testingpurposes.

2906014_Lathrop.qxp 5/7/2009 1:26 PM Page 46

Page 49: Circuit Cellar 2009-06

PIC18F4620 outputs one of twostates for each sensor to show eithersomething is there or nothing isthere.

During the final steps of testing,we tied the IR MCU to the motordriver MCU to increase our stoppingtime. This enables the vehicle to stop

www.circuitcellar.com • CIRCUIT CELLAR® 47

June

2009 –

Issue

227

at longer ranges where 100 mVequated to a difference of 10 cm. Inaddition to the noise, these sensorsalso faced interference from eachother, as well as from ambient light.To deal with these situations, weintegrated hysteresis and a look-uptable into the infrared thread. The

Figure 6—This is themounting configurationof the IR sensors. Thedots are downward sen-sors for “Cliff” detection.

= Horizontal sensors

Figure 7—This board has a PIC that queries the ultrasonic sensor via I2C and controls the step-per motor through an H-bridge chip. It sends data to the CPU “brain” via the serial protocolshown in Figure 2 upon request.

2906014_Lathrop.qxp 5/7/2009 1:26 PM Page 47

Page 50: Circuit Cellar 2009-06

48 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

without having to command throughthe brain, which takes much longer. Thesystem’s reaction time is extremely fast.The IR-avoidance thread deals with thedata in a simple way. For instance, if thebrain sees something on any of the hori-zontal sensors, the vehicle stops imme-diately, turns its wheels left, backs up 1m, and the reassesses its environmentusing other sensors. The short programuses simple algorithms.

ULTRASONIC RANGEFINDERFor object detection, we imple-

mented a Devantech SRF08 ultra-sonic rangefinder in conjunctionwith a stepper motor (see Figure 7).Both the motor and sensor are inter-faced via a PIC18F4620 microcon-troller. Having the motor and rangingcontrol on the same PIC enabled usto easily synchronize the turning ofthe motor with the rangefinder’s tim-ing constraints. The SRF08 featuresan on-board EEPROM for easy inter-facing. Data reading and commandissuing to the rangefinder is achievedby reading from and writing to theI2C bus. Commands from the CPUenable the motor to change the scandirection to provide object detectionwhen it’s traveling backwards, aswell as forwards. The main SRF08-related limitation in this applicationis its inherent 55° span of detection.

The module is mounted to a mastextending from the top of the vehicle.A stepper motor housed in the lowerportion of the vehicle rotates it. Thesystem enables us to take distancemeasurements at precise angles,

which generates a thorough renderingof the environment. A custom serialprotocol relays the distance andangle information to the CPU. AnL293D quadruple half H-bridge driv-er controls the stepper motor withinput from the microcontroller. Arotary encoder mounted to the step-per motor’s armature provides posi-tion feedback.

When the vehicle moves forward,the sensor scans forward in only 7.5°increments of the stepper motor.This data is communicated to thebrain’s ultrasonic-avoidance thread.The thread divides the data into sec-tions as shown in Figure 8.

WEBCAM IMAGINGWe first ordered the ultrasonic sen-

sor thinking it would work well. Butwhile performing the actual testing,we realized that we needed a moreaccurate method of object detection.Fortunately, some ’Net searching ledus to Todd Danko’s excellent tutorialon webcam laser rangefinding, “Web-cam Based DIY Laser Rangefinder”(Drexel University, 2004). This tech-nique turned out to be a great optionbecause it was easy and affordable.The first few webcam tests did notgo well. Some of the webcam’s docu-mentation was lacking, so it washard to find and manipulate the filesto make the images work properly.We ended up using a PhilipsSPCNC900 webcam after reviewingdocumentation. With the Philips driverinterface, we could fully control thebrightness and resolution throughOpenCV, which is a library of program-ming functions aimed at real-timecomputer vision. There is not much

Figure 8—Sections 0, 1, and 2 are used forforward object avoidance. Section 3 is usedfor backwards object avoidance. The brainhandles the avoidance routine similarly tothe IR avoidance algorithm.

Front

0

3

2 1

Back

Figure 9—The laser webcam rangefinder canuse trigonometry to calculate a distance toan object.

Webcam

Laser

Object

h

D

θ

2906014_Lathrop.qxp 5/7/2009 1:26 PM Page 48

Page 51: Circuit Cellar 2009-06

www.mouser.com

The Newest Wireless Solutions

Over A Million Products Online

ZigBee®

RFID

Bluetooth™

GPS

WLAN

Cellular

ISM

Experience Mouser’s time-to-market advantage with no minimums and same-day shipping of the newest products from more than 390 leading suppliers.

(800) 346-6873

The Newest Products For Your Newest Designs

The ONLY New Catalog Every 90 Days

RF Front End Range Extender: CC2591www.mouser.com/TICC2591/

New Products from:

CYRF7936 CyFi™ Transceiverwww.mouser.com/cypresscyfi/

MRF24J40MA Radio-Frequency Transceiver Modulewww.mouser.com/MRF24J40MA/

MC13224V ZigBee™ Platform-in-Packagewww.mouser.com/freescale_mc13224v/

Mouser_CircuitCellar_6-1.indd 1 4/17/09 4:20:54 PM

49.qxp 4/27/2009 10:26 PM Page 1

Page 52: Circuit Cellar 2009-06

50 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

up-to-date documentation on the ’Netfor OpenCV, so it was time-consumingto figure out some of the functions.The functions did, however, prove tobe useful and easy to use. They were abig help in getting our webcam laserrangefinder up and running. Using theOpenCV libraries enabled us to imple-ment such image processing asCanny edge detection. Canny pro-duced impressive results. It essential-ly output a black background withwhite lines at the edges of objects inthe image. It would have been an

excellent addition to our project ifwe’d had more time to implement it.

The webcam’s main purpose is tofunction as a laser rangefinder. Anarray of three lasers is mounted parallelto the camera. It is important thatthese lasers don’t move and remainperfectly parallel to the camera. If theydon’t, the image processing won’t workas it should. The distance of the threepoints is calculated based on the num-ber of pixels below center, along withsome simple trigonometry. Each lasershould be tested individually to ensure

accuracy within the program. Thebasic theory is depicted in Figure 9.The distance is:

D is the distance to the target. h isalways constant, because we alwayshave the lasers mounted at the sameheight below the camera. We now findtheta using:

pfc is the number of pixels from thecenter of the focal plane. rpc is the radi-ans per pixel pitch. ro is the radian off-set, which compensates for alignmenterrors. ro and rpc are always constant.This needs to be done and set in code.With these constants, we wrote thecode to calculate pfc from the imagebecause it changes in each condition.This is done by counting the number ofpixels from the center of the image toget the maximum column and row forthe brightest point of the picture,which should be the lasers. We canthen easily calculate the distance.

Our program finds the brightest pixelin three sections because there arethree lasers. The sections can be madeby scanning only the bottom half of theimage and making three vertical sec-tions. Each laser will be in its own sec-tion, and this will make the code lessprone to error. When the brightest pointis found, the program will compare thatposition in the 2-D image to the expect-ed pixel position based on calculationsof where the laser should be. If they areequal, then we use the data. If they arenot equal, we discard it. Why do we dothis? If there is a brighter object thanthe laser, or if the laser point is lost, wedon’t get faulty data. By using OpenCVand our own auto-brightness algorithms,we can under-expose images to make iteasier to detect the lasers we are trans-mitting (see Photo 2a and Photo 2b).

We found this system to beextremely accurate. For objects at 0.5to 3.5 m, the error is always less than0.5%. The algorithm for object avoid-ance using the webcam laserrangefinder is performed using thedata from the three sections. The dis-tance returned is then divided intoone of three states: close, midrange,

= pfc rpc + ro×( )

D = htan

Photo 2a—This is the original laser image taken by the webcam. b—White lines indicatewhere the brightest points in each section are located.

a) b)

2906014_Lathrop.qxp 5/11/2009 1:24 PM Page 50

Page 53: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 51

June

2009 –

Issue

227

Chris Britney ([email protected]) is acomputer engineering technologist work-ing toward a degree in computer engi-neering. His interests include program-ming, robotics and microcontrollers.

Paul Green ([email protected])graduated from Camosun College’s elec-tronics engineering technology program.He is currently completing his electricalengineering degree at the University ofVictoria. His interests include powersystems and renewable energy.

ROJECT FILESFor additional schematics and to download code and a project video, go toftp://ftp.circuitcellar.com/pub/Circuit_Cellar/2009/227.

ESOURCEST. Danko, “Webcam Based DIY Laser Rangefinder,” Drexel University,Philadelphia, PA, 2004, www.pages.drexel.edu/~twd25/webcam_laser_ranger.html.

Devantech Ltd (Robot Electronics), “SRF08 Ultrasonic Range Finder (Techni-cal Specification),” 2008, www.robot-electronics.co.uk/htm/srf08tech.shtml.

A. Geiger, “Using Philips Webcam Features with OpenCV and PWC,” 2007,www.rainsoft.de/projects/pwc.html.

Microchip Technology, Inc., “PIC18F2525/2620/4525/4620 Data Sheet:28/40/44-Pin Enhanced Flash Microcontrollers with 10-Bit A/D andnanoWatt Technology,” 2008.

OpenCV Basic Structures and Operations Reference, www710.univ-lyon1.fr/~bouakaz/OpenCV-0.9.5/docs/ref/OpenCVRef_BasicFuncs.htm#decl_cvSumhttp.

Open Source Computer Vision Library, 2008, http://sourceforge.net/projects/opencvlibrary/.

OURCESLinear actuatorFirgelli Technologies, Inc. | www.firgelli.com

PIC18F4620 MicrocontrollerMicrochip Technology, Inc. | www.microchip.com

SRF08 Ultrasonic rangefinderDevantech Ltd (Robot Electronics) | www.robot-electronics.co.uk

SPCNC900 WebcamPhilips | www.webcam.philips.com

GP2Y0A21YK SensorSharp Electronics Corp. | www.sharpusa.com

VNH2SP30 H-Bridge motor driverSTMicroelectronics | www.st.com

P

R

S

Andy Heath ([email protected]) is a computer engineering technologistwhose interests include embedded systems, robotics and programming. Hecurrently resides in Nanaimo, BC.

Stephen Lau ([email protected]) earned a computer engineering technologydiploma from Camosun College. He is continuing his education at the Univer-sity of Victoria, where he looks forward to researching new electronic androbotic technologies.

Kylee Lothrop ([email protected]) graduated from the electronics engi-neering technology program at Camosun College. She is currently workingtoward a degree in electrical engineering at the University of Victoria. Kylee isinterested in green energy as well as embedded and control systems.

and far. Again, this simplifies theobject-avoidance algorithm.

TESTING & RECOMMENDATIONSThe modular hardware design of

each subsystem, as well as the modu-larity of the brain’s threads, we easilymodified the code and hardware foron-the-spot testing. This is excellentfor testing individual systems whenothers may not be working.

Budgetary and time limitations pre-vented us from fixing a few problems.When we tested the laser system outsideon a bright day, it did not work verywell. We can deal with this situation byusing the ultrasonic rangefinder andinfrared for object avoidance. This iswhy we have back-up systems. A solu-tion to this problem would be a betterlaser. We used 5-mW laser modules,which were about $20 each. It is impor-tant to get a laser module because itcomes with casing and prealigned lenses,but it is more costly than laser diodes. Alaser at a higher power such as 80 mWwould better suit outdoor conditions.

When the vehicle is near metalobjects, the digital compass may returnincorrect and possibly harmful data. Ifwe know ahead of time that there willbe an excess of metal in the area, we cancalibrate the compass to the specificenvironment.

FUTURE APPSThis project may seem like a cool toy,

but when you investigate the system’scapabilities, it is easy to imagine manynew applications for this technology.Our system’s modularity and affordabili-ty make it a potential development toolfor future applications in the defense,industrial, and healthcare industries. I

2906014_Lathrop.qxp 5/7/2009 1:26 PM Page 51

Page 54: Circuit Cellar 2009-06

52 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

When it comes to high-speed signal transmission, there’s more than meetsthe eye. Robert simplifies the topic in this thorough explanation of signaltransmission theory. He describes transmission techniques on low-bandwidthcables, and covers the important subjects of preemphasis, equalization, andinter-symbol interference.

High-Speed Signal TransmissionFrom Eye Diagrams to Preemphasis and Equalization

W

by Robert Lacoste

elcome back to The Darker Side. You are used to connecting your

RJ-45 plugs to the nearest router and assumingthey will work without any problems—andthey usually do. You understand that wirelessnetworks like Wi-Fi can be a little trickier, yeteven reputed electrical engineers think thatwired communications are, well, just wires.But have you ever thought twice about theblack magic that actually enables you to send

THE DARKER SIDE

Figure 1—Inter-symbol interference appears due to the transmittingcable’s relatively long RC time constant. The line voltage is perturbedseveral bits later than the original bit. This spreading makes receptionfar more difficult.

Low-passfiltering channel

Bit N − 1 Bit N Bit N + 1 Bit N + 2 Bit N + 3 Bit N + 4

Inter-symbol interference (ISI)

and receive 100 Mbps, 1 Gbps, or even 10 Gbpson these small twisted-copper pairs? Similarly,do you know how to use a low-cost FR4 PCBand connectors costing less than $1 to buildyour PC motherboard with its 2.525-Gbps PCIExpress 2.0 busses?

This month I will present basic techniquesfor high-speed signal transmission on low-band-width cables. I will cover concepts ranging fromeye diagrams to preemphasis and equalization.You may find this information useful for yournext high-speed design.

HIGH-SPEED ISSUESSuppose you are tasked to design a transmit-

ter and a receiver to send a binary datastreamthrough a roll of twisted-pair wire. As an engi-neer, you want to ensure your design will work,so you first measure the wire’s actual transmis-sion channel. A simple technique involvesinjecting a sine signal with a sweeping genera-tor at one end of the cable and then connectinga receiver, oscilloscope, or power meter at theother end. Since you take care of impedance

2906005-lacoste - ver2 - use.qxp 5/7/2009 1:28 PM Page 52

Page 55: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 53

June

2009 –

Issue

227

matching, you can easily measure thecable’s 3-dB cutoff frequency, which isthe frequency at which the receivedsignal decreases to 50% of its originalpower. Imagine that you are luckyenough to find a 100-MHz cutoff fre-quency, which is already good for astandard copper pair.

You want to transmit binary sig-nals and not just pure sines, so youneed to transmit frequencies signifi-cantly higher than the bit rate.Namely, you must cope with a cou-ple of harmonics, in order to havewell-shaped bits, meaning more orless rectangular waveforms. So, youmust use a bit rate reasonably lowerthan 100 MHz—10 times lower than thecutoff frequency, giving 100 MHz/10 =10 Mbps, may be a reasonable guess.Therefore, you will go back to themarketing department and announcethat the system will be 10 Mbps.You know what will happen next,right? The reply will be somethinglike: “Are you joking? We need 1Gbps.” And then your life becomesfar more difficult as a result of anunpleasant phenomenon: inter-sym-bol interference (ISI).

Figure 1 shows where ISI comesfrom. Basically, a cable used closer orhigher to its cutoff frequency behaveslike a highly damping RC network.The rising and falling edges of anytransmitted bit are reshaped withexponentially decaying slopes, with atime constant that could be signifi-cantly longer than the bit duration.That’s a problem. But the most criticalconsequence is that the received volt-age for a given transmitted bit will notonly depend on this specific bit, butdepend also on the previously trans-mitted bits. This will inevitably gener-ate erroneous bits on the output

because a binary receiver is basicallynothing more than a comparator to agiven threshold. For example, if you

send alternating zeros and ones, theoutput signal could be distorted butwill still cross the comparator

Figure 2—The test setup for an eye-diagram display requires only a pseudorandom generator and an oscilloscope. The required trick is to trigger the scope with a referenceclock, either from the transmitter or a clean clock regenerated locally.

Clock

Output

C

R

Pseudorandom

binary generator

Figure 3—These are actual signal waveforms corresponding to the eye diagram when the line’s RC constant isincreased step by step. The ISI percentage is the ratio, on the center horizontal line, between the width of the tran-sition region (where plenty of lines are superposed) and the bit period. It ranges from zero at the top to 100% atthe bottom.

Null

RC Timeconstant

Time domain oscillogram Eye diagram

Small

Medium

Large

Very large

Null

Inter-symbolinterference

Null

Low

Large

Too large

2906005-lacoste - ver2 - use.qxp 5/7/2009 1:28 PM Page 53

Page 56: Circuit Cellar 2009-06

54 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

threshold each time and give a solid transmission. Howev-er, if you send a long string of ones, the data line voltagewill reach its maximum even if the RC time constant islong. Then, if you send only one zero followed by new setof ones, the line voltage will decrease little, but not enoughto be identified as a zero by the receiver. This “history”phenomenon is the basic form of ISI, and it could actuallymake error-free reception nearly impossible.

DO YOU SEE THIS EYE?The inter-symbol issue is not new. It was a problem asso-

ciated with telegraphic lines right from the start. Telecomworkers needed a way to visualize and evaluate a signal’s

ISI level, so they invented the eye dia-gram. This powerful, intuitive methodneeds just two pieces of equipment. First,a pseudorandom binary sequence genera-tor must be connected to the transmitter’sinput to ensure all possible ISI scenariosare sent through the channel. Such apseudorandom generator is available aspart of many telecom test sets, but youcan also build one with a shift register anda couple of XOR gates. If you search theInternet for “Linear Feedback Shift Regis-ter” (or “LFSR”), you’ll find plenty ofschematics. You also need a simple single-channel oscilloscope. It must have anexternal trigger input, and its bandwidth

must be significantly higher than the signal’s bit rate. You shouldn’t think that “high-speed techniques” are

only for multi-Gbps systems that will inevitably require afancy high-end digitizing scope. It could be the case ifyou’re working on Gigabit Ethernet or PCI express, but“high speed” can simply mean your required bit rate ishigher than what your wire could support (as in my exam-ple). So, these techniques are also valuable with medium-rate transmissions (e.g., a few megabits per second), at leastif you have to use a long or poor transmission line.

The eye diagram test setup requires you to connect thescope input to the signal to be measured and to trigger itwith the original clock (see Figure 2). If you can’t—for

Figure 4—The correction of the channel transfer function can be done either on the transmitter side (preem-phasis), on the receiver side (equalization), or on both.

00001011110001101110

00011011100001101110

Emphasis

0001101110

Equalization

0001101110

Figure 5—This a Scilab simulation of pre-emphasis. The blue curves are the transmitted waveforms. The dark curves are the received waveforms. The left column is without pre-emphasis, respectively with a single bit (a) or a sequence of ones (c). It is clearly visible on the right side (b and d). The preemphasis enables the drastic reduction of the ISI.

Single pulse, no emphasis1.0

0.9

0.8

0.7

0.6

0.5

0.4

0.3

0.2

0.1

0.00 50 100 150 200 250

Single pulse, de-emphasized1.0

0.9

0.8

0.7

0.6

0.5

0.4

0.3

0.2

0.1

0.00 50 100 150 200 250

Single pulse, no emphasis1.0

0.9

0.8

0.7

0.6

0.5

0.4

0.3

0.2

0.1

0.00 50 100 150 200 250

Single pulse, de-emphasized1.0

0.9

0.8

0.7

0.6

0.5

0.4

0.3

0.2

0.1

0.00 50 100 150 200 250

a) b)

c) d)

2906005-lacoste - ver2 - use.qxp 5/7/2009 1:28 PM Page 54

Page 57: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 55

June

2009 –

Issue

227

example, if both ends of the cablearen’t in the same room—you canregenerate the clock locally througha phase-locked loop (PLL). The oscil-loscope’s horizontal time setting isset to twice the bit duration, and thetrigger delay is adjusted to have asingle bit centered on the display.What would you see on the oscillo-scope’s display? Basically a superpo-sition of bit transition waveforms,which will include every possible bitsequence thanks to the pseudrandomgenerator.

I used my Lecroy Waverunner 6050oscilloscope. It was driven by thepseudorandom generator section of anold Schlumberger 7703B 2-Mbps bit-error tester through a simpleadjustable RC filter. The results areshown in Figure 3. If the RC time con-stant is low—meaning that the trans-mission channel is good in compari-son to the bit rate—then the shape ofthe data signal is rectangular and theeye diagram shows only a simpleimage made with the superposition ofthe four possible bit transitions in the

Figure 6—This simulation shows the impressive effect of preemphasis at least with a transmission channel modeled as a RC network. Left is without emphasis, right is with it.The eye diagram looks better, doesn’t it? However, keep in mind that a real-world situation could be a little more complex than this simulation.

pseudorandom stream (0 to 1, 1 to 0, 0to 0, 1 to 1). What happens if you sendthis signal to a comparator-basedreceiver? Ideally, the threshold will becentered vertically and you will get anideal bit stream as an output, withoutany time jitter. The ISI is 0%.

As long as the RC time constantstays low in comparison to the bitperiod, the image looks the same.The center hole in the eye diagram,the center of the “eye,” is said to befully open, which means that bitrecovery by the receiver will be easy.However, if you increase the RCconstant, the eye diagram starts tobe more complex (the third case inFigure 3). The raising and fallingfronts are so damped that the signalcan’t reach their steady level beforethe arrival of the next bit, whichmeans that there will be some ISI.The ISI percentage can be evaluatedas the ratio, on the horizontal line,between the width of the transitionregion (where plenty of lines aresuperposed) and the bit period. It isthere around 5%. The more the RC

time constant is increased, the moreshut the eye. The fourth test case, acomparator, even with a perfectlycentered threshold, shows a veryhigh level of time jitter on its out-put, meaning a higher risk of biterror. There is around 50% ISI.

At a given point the eye is fullyshut, which means that a compara-tor-based detector will no longer beable to reliably detect if the bit is azero or a one. The transmission nolonger works, ISI is 100%, and theeye is fully shut.

The eye diagram enables you toquickly evaluate the ISI level and thelink’s reliability. Using the eye dia-gram, I can also give you more datathan just the ISI level. For example,the channel noise margin is simplyproportional to the eye’s height. Theallowed level of timing errors,including clock jitters, is proportion-al to the eye’s width.

PREEMPHASISAssume that you are in a bad situa-

tion: the eye diagram is fully closed

Input signal, time domain plot

Received signal (not emphasized), time domain plot

Received signal (not emphasized), eye diagram

Emphasized signal, time domain plot

Received signal (emphasized), time domain plot

Received signal (emphasized), eye diagram

2906005-lacoste - ver2 - use.qxp 5/7/2009 1:28 PM Page 55

Page 58: Circuit Cellar 2009-06

56 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

when you have a mandatory wire andbit rate. How can you still build areliable transmission system withoutcompromising the requirements?Think twice. You are in troublebecause the channel (your wire) has alow-pass-shaped transfer functionwith too low of a cut-off frequency.The answer seems obvious. You needto amplify the high frequencies inorder to get back to an overall flatfrequency response end to end.

As you can see in Figure 4, youhave two main options. You canamplify the high frequencies on thetransmitter side with a techniquecalled “preemphasis,” oryou can do it at thereceiver side with a tech-nique called “equaliza-tion.” Many systems useboth techniques togetherfor optimum results.

Let’s focus first on theTX side with preempha-sis. The ISI comes fromthe shape of the pulses,which are too slow torise or fall. It meansthere isn’t enough high-frequency energy duringthe bit transitions. Themost usual and clever

sent after a one, the firstwill be a strong zero (e.g.,0 V) and the next bits willbe weak zeros (approxi-mately 1 V). This way alittle more energy is givenduring each transitionthanks to the strong bits.As a consequence, the ris-ing is quicker and thelong-term damping isreduced, and it can benearly zeroed with a properemphasis ratio. Figure 5shows you a simulation ofemphasis done with theScilab simulator. (Thesource code for all thesimulations is posted onthe Circuit Cellar FTPsite.) If you look at thefrequency domain, yousee that such a preempha-sis scheme increases thesignal’s high-frequency

components—exactly what you arelooking for.

Just to be exhaustive, note thattwo variants of preemphasis canexist. In the first, the voltages of thestrong bits are actually increased incomparison to the standard logicvoltages. This has an importantdrawback because you will needhigher-than-normal and negativevoltages on your transmitter. Themost usual way is to use standardlogic voltages for the strong bits andreduced voltage swing for the weakones, with a fixed and preset ratiothat’s optimized depending on the

transmission line andbit rate (e.g., by look-ing at an eye diagram).

If you read my Octo-ber 2007 column, “NoFear with FIR” (CircuitCellar 207), you under-stand that such a pre-emphaser is actuallyequivalent to a two-tapFIR filter. More evolvedemphasizing tech-niques are possiblewith more evolved FIRfilters. The idea is infact to add to the wave-form to be transmitted

trick for signal emphasis uses only alimited amount of electronics.Whenever there is a bit transition(i.e., whenever a transmitted bit isdifferent from the previous one), youcan simply boost its voltage. Thisworks by using not just two but fourvoltage levels: strong high, stronglow, weak high, and weak low. Forexample, if the line is zero and youhave to transmit a couple of ones,your circuit first sends a strong onefor the first bit (e.g., 5 V) and then alower voltage for the next ones(weak one, 4 V or so). Similarly,when a couple of zeros have to be

Figure 7—This is a discrete preemphasis circuit. The top section is a simple 16-step pseudorandom sequence generator made withfour D latches and an XOR gate. The bottom portion uses one more D gate and an XOR gate to compare the current bit to the pre-vious one. A weak signal is generated through R3 if it is the same. The XOR gate enables a strong signal if not. Both outputs aresent to a virtual scope for simulation (directly and through an RC network).

Photo 1—This is the result of Proteux VSM simulation of the schematic provided in Figure 7. Ihave not built the circuit, but I am pretty sure the actual measurements would be close.

2906005-lacoste - ver2 - use.qxp 5/7/2009 1:28 PM Page 56

Page 59: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 57

June

2009 –

Issue

227

case, if you know the problem, you can fix it. This caneven be done if the channel’s behavior changes over time,as is the case on a wireless link. This technique, adaptiveequalization, is used in many modern wireless systems.

Without using a complex adaptive filter, how can youbuild an equalization filter for my example RC simula-tion? As you can see in Figure 8, you need to calculateor measure the channel’s frequency response (includingpreemphasis, if any). It’s then easy to deduce the ampli-fication factor over frequency required for a flatresponse. A simple Fourier transform then gives you thecoefficients required to implement the corresponding FIRfilter. (Once again, please refer to my column on FIR filtersto refresh your memory.) I did it in Scilab (see Figure 9).

a delayed and reversed copyof the erroneous channelresponse. But I won’t coverthat in this column.

Can a simple preemphasissolve the problem in my RCfilter example? Yes. Refer tothe Scilab simulation in Figure6. When using a preemphasistransmitter, the received sig-nal level is obviously lower,because we are reducing thelevel of the weak bits, but ithas a far lower ISI, whichmeans a far better bit errorrate.

You may wonder how toactually build a preemphasiscircuit. I will describe exist-ing dedicated chips. But youcan do it yourself too, atleast if the signal speedstays reasonable. Figure 7shows a possible solutionthat uses old 74xx serieschips. As I drew the firstversion of this schematicwith the Proteus CAD suite(a Circuit Cellar staff editorredrew it for this article), Iclicked the Simulate iconand got what you see inPhoto 1. Nice, isn’t it?

EQUALIZATIONEqualization is an option

that involves building somekind of selective high-fre-quency booster on thereceiver side. Equalization isusually less of a magicalsolution than pre-emphasis,because a high-pass filter hasthe disadvantage of amplify-ing any high-frequency noise on the line. This is whyequalization is usually used as a complement to preem-phasis. Preemphasis does 80% of the job, then equaliza-tion finishes it. On the hardware side, an equalizer isoften simply a digital FIR filter and called a feed-forwardequalizer (FFA). More complex nonlinear algorithms existlike the distributed feedback equalizer (DFE), but a FIR isusually enough.

Equalization provides a great bonus: a receiver actuallysees the degraded received signal, which a transmittercan’t, at least without a dedicated feedback informationchannel. It is then theoretically possible for the receiver toadjust the equalization filter to compensate for the chan-nel’s behavior and implement a “perfect” channel. In that

Impulse response of the channel filter

1.00.90.80.70.60.50.40.30.20.10.0

0 50 100 150 200 250 300

Corresponding frequency response

50454035302520151050

0 200 400 600 1000 14001200800 1600

Frequency response for the equalization filter

50454035302520151050

0 200 400 600 1000 14001200800 1600

Corresponding FIR Filter coefficients

0.30

0.25

0.20

0.15

0.10

0.05

0.00

-0.0510 20 30 40 50 60

a)

b)

c)

d)

Figure 8—This Scilab simulation shows how an equalization filter could be generated. The top plot is the time domain impulseresponse of our reference RC channel. Take its FFT and you get the second plot. The horizontal axis is the frequency. This is thetransfer function of the transmission channel. Negate it in order to get an ideal compensation network (third plot). You can thentake its inverse FFT to get the required impulse response of the equalization filter, which is nothing less than the coefficients ofthe equalizing FIR filter.

2906005-lacoste - ver2 - use.qxp 5/7/2009 1:28 PM Page 57

Page 60: Circuit Cellar 2009-06

58 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

high-speed equalizer chips, but theyare scarce. Examples are NationalSemiconductor’s EQ50F100n andDS64EV100. The latter is an equal-ization filter that improves datalinks up to 10 Gbps on cables or on astandard FR4 PCB through a choiceof eight preset filter settings. ANational DS40MB200 is a dual 4-Gbps buffer with both programmablepreemphasis and a fixed equalizationfilter, which is available from Digi-Key if you want to play with it.

However, the majority of preem-phasis/equalizer applications aredone with FPGAs and not dedicatedchips. This makes sense becausethese techniques are mainly usefulfor high-speed systems, and FPGAsare the de facto choices for suchprojects. You will find preemphasingand equalizing blocks (or IP) frommost FPGA vendors. A good example isAltera’s Stratix II GX family of FPGAs.These monsters integrate no less than20 high-speed (up to 6.375 Gbps) ports

The eye diagram is not perfect becauseof the filters, but at least the signal isimproved.

SOME SILICONOf course, silicon suppliers have

ready-made chips for implementingpreemphasis or equalization. Fewsolutions exist for relatively low-speed data links, but notable excep-tions are Maxim Integrated Prod-ucts’s MAX3291 and MAX3292.These chips look like classic RS-485/422 transceivers, except theyinclude preemphasis circuitry toallow higher bit rates on long cables.The MAX3291 is programmable forpreset data rates of 5 and 10 Mbps,while the MAX3292 is configurableup to 10 Mbps through an externalresistor. The corresponding Maximapplication note (AN643) states thatthese chips enable you to double thebit rate in comparison to standardRS-485 drivers.

Conversely, you’ll also find dedicated

and a built-in adaptive equalizerblock called the adaptive dispersioncompensation engine (ADCE), whichuses an impressive mixed-signalapproach. In a nutshell, a capacitor-based booster amplifies bit transi-tions on each input, with a boostingeffect controlled by a low-speedDAC. Your application can thentune the DAC for a minimal biterror rate.

A last word: Equalization can beanalog too. Nothing prevents youfrom designing an analog high-passfilter that could more or less exactlycompensate the frequency behaviorof a given cable. It can be difficult todo, but it is possible. For example,Tyco Electronics Corp. proposed aline of high-speed interconnectcables with a built-in equalizationPCB through its high-speed serialdata connector (HSSDC) family.These cables are specified for no lessthan a 2-Gbps transmission up to 30 maway on a copper cable. Try to do

FIgure 9—An example of the application of the equalization filter calculatedin Figure 8 to a random non-preemphasized signal. The eye diagram withthe equalization is not perfect (bottom), but the ISI level is far reduced ascompared to a non-equalized one (middle).

2906005-lacoste - ver2 - use.qxp 5/7/2009 1:28 PM Page 58

Page 61: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 59

June

2009 –

Issue

227

ROJECT FILESTo download code, go to ftp://ftp.circuitcellar.com/pub/Circuit_Cellar/2009/227.

ESOURCESAgilent Technologies, Inc., “Understanding the Effects of Limited Band-width Channels on Digital Data Signals,” Agilent Measurement Journal,Issue 5, May 2008, www.agilent.com/go/journal.

Lattice Semiconductor Corp., “Transmission of Emerging Serial StandardsOver Cable,” 2005, www.latticesemi.com/lit/docs/ generalinfo/Transmission_whitepaper.pdf.

Maxim Integrated Products, Inc., “Pre-Emphasis Improves RS-485 Commu-nications,” AN643, 2001, www.maxim-ic.com/appnotes.cfm/ an_pk/643.

National Semiconductor Corp., “Setting Pre-Emphasis Level for DS40MB200Dual 4Gb/s Mux/Buffer,” AN-1389, 2005, www.national.com/an/AN/AN-1389.pdf.

R. Stephens, “Answering Next-Gen Serial Challenges,” Tektronix KnowledgeSeries, Parts 1–3, Tektronics, Inc., www.tek.com/Measurement/programs/americas/serialdata_webinar/.

W. Wong et al, “Digitally Assisted Adaptive Equalizer in 90 nm with WideRange Support from 2.5 Gbps to 6.5 Gbps,” Altera Corp., 2007, www.altera.com/literature/cp/cp-01026.pdf.

J. Zhang and Z. Wong, “White Paper on Transmit Pre-Emphasis and ReceiveEqualization,” Mindspeed Technologies/Conexant, 2002, www.analogzone.com/io_shoot_mindspeed.pdf.

OURCESStratix II GX FPGA Altera Corp. | www.altera.com

ScilabINRIA | www.scilab.org

Proteus VSM mixed-signal simulator Labcenter Electronics | www.labcenter-electronics.com (North Americandistributor: www.r4systems.com)

Waverunner 6050 digital oscilloscope Lecroy Corp. | www.lecroy.com

RS-485/RS-422 Transceivers with preemphasisMaxim Integrated Products, Inc. | www.maxim-ic.com

EQ50F100n Equalizer, DS64EV100 Equalizer, and DS40MB200 mux/bufferNational Semiconductor Corp. | www.national.com

HSSDC Cable assembliesTyco Electronics | www.tycoelectronics.com

P

S

R

Robert Lacoste lives near Paris,France. He has 18 years of experi-ence working on embedded systems,analog designs, and wireless telecom-munications. He has won prizes inmore than 15 international designcontests. In 2003, Robert started aconsulting company, ALCIOM, toshare his passion for innovativemixed-signal designs. You can reachhim at [email protected]. Don’tforget to write “Darker Side” in thesubject line to bypass his spam filters.

that without equalization.

HIGH-SPEED COMMUNICATIONThe techniques I covered in this

article are used in high-speed commu-nication systems. Roughly speaking, asimple “strong/weak bit” preemphasistechnique can boost the high frequen-cies. It could be a good fit for the lesscomplex situations you encounter.Equalization, and adaptive equaliza-tion in particular, enables you to fine-tune a channel for optimal perform-ance. It’s a must whenever a givenchannel must be used at its best. Thismeans quite often nowadays.

You won’t need these techniquesfor every design. If you need them toimplement standard high-speedtransmission protocols (e.g., GigabitEthernet or PCI-Express), you’llprobably get them as part of achipset, so it should be more or lesstransparent for you. But if you needto work on an exotic data transmis-sion project and can’t achieve morethan 70% of the target’s perform-ance, knowing the basics of preem-phasis and equalization may enableyou to come up with the missing30%. Don’t forget that “high speed”just means quicker than the maxi-mum the transmission channel cannatively accept, which may be quiteslow. And don’t forget the marvelouseye-diagram investigation method.

I hope you found this review ofhigh-speed transmission techniquesinteresting and useful. Be sure tokeep one eye in the time domain andthe other in the frequency domain. Ifyou do, preemphasis and equaliza-tion shouldn’t be on the darker sideanymore. I

2906005-lacoste - ver2 - use.qxp 5/7/2009 1:28 PM Page 59

Page 62: Circuit Cellar 2009-06

60 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

Electronic compasses are an affordable alternative to GPS technology forsome embedded designs. After introducing the topic of magnetoresistance,Jeff describes how he used an anisotropic magnetoresistance (AMR) sensorto add navigation capabilities to a recent design.

Location NotificationA Look at Anisotropic Magnetoresistance Sensors

I

by Jeff Bachiochi

’d looked at Honeywell products in the past. But to be honest, I’d kept away from

them because they were costly and hard tofind. More recently, however, many of the dis-tributors I use have been carrying them withmore favorable pricing structures.

Last fall, for instance, while reading a newsrelease about a Honeywell three-axis magne-toresistance sensor, I was interested enough todownload the datasheet and take a closer lookat the part. I remember getting excited as Iread through the specs until I came to thepackaging reference: a 4-mm-square leadlesschip carrier (LCC). Whoa, leadless! I didn’tlike the sound of that. I can deal with tinyleadless contacts that extend partially up thesidewalls of a chip. But this leadless packagehad no side contacts (only on its bottom sur-face, like a BGA). For those of you steady-handed hand solderers, you know this is usu-ally a dead end.

There has been a lot of serious experimenta-tion with using the typical kitchen toasteroven to solder SMT PCBs. I’ve always wantedto give this a try, and now I had a reason.Although I haven’t gone through the steps ofcreating a microcontrolled oven (if you think

FROM THE BENCH

this is worthy of a column, or if you haveinput, let me know), I graphed my oven’s tem-perature profile to see if it fit within reason-able parameters. After comparing what I saw, Ifelt there was a good chance for success.

My first prototype PCB has a single SMT—aHoneywell HMC5843—right in the center. Iwon’t go into the process here other than tosay I first pinpointed the solder paste meltingpoint on a blank PCB so I knew what to lookfor when the HMC5843 was placed on thePCB. I left the heat applied for another 30 safter reaching that point and then let it coolcompletely before moving the PCB. It wasimpossible to see what had actually happenedto all the solder joints under the chip, so Ineeded a good deal of faith.

THE SENSORThe HMC5843 incorporates three anisotrop-

ic magnetoresistance (AMR) sensors, each ofwhich is aligned to an axis (x, y, or z).Anisotropic, or directional dependence,describes the sensor’s response to the Earth’smagnetic lines of force. A magnetoresistancesensor is made from nickel-iron (Permalloy),which is deposited as a thin film on a silicon

2906002-bachiochi.qxp 5/7/2009 1:29 PM Page 60

Page 63: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 61

June

2009 –

Issue

227

wafer in a bridge configuration. Eachsensor outputs a voltage—correspon-ding to the strength of the field itmeasures—and is oriented to a differ-ent axis. Thus, each measures a per-centage of the field depending on itsorientation to the field. The bridgeoutput is positive when the magneticfield runs with the direction of sensi-tivity. It is negative when the field isreversed.

You, of course, can measure afield’s strength with a single sensor,but it must be aligned with the field.With a three-axis sensor, you canmeasure the field without alignmentby mathematically adding each sen-sor’s outputs. To prevent the sensorsfrom accumulating any biasing mag-netic properties, the sensors have amechanism to condition the magnet-ic domains. This is done by sendingand reversing a current through aninternal strap on each sensor, therebydegaussing the sensor.

ASICIn addition to its three magnetore-

sistance sensors, the HMC5843 alsohas an array of circuit elements thatapplies signal conditioning to the

and a 12-bit ADC (A/D, providing adigital representation of the threemeasured field strengths). A logicblock controls the system timing, I2Cinterface, deguassing function, andsensor bias.

sensors and provides a user-friendlyinterface to the measurement resultsand property configuration (see Figure 1).Each sensor’s differential outputs aremultiplexed into an instrumentationamplifier (IA, providing gain control)

Figure 2—AMR sensors mounted at right angles will output magnetic measurements in a sine-cosine relationship with each other, as they arerotated 360° through the Earth’s magnetic field.

Figure 1—The HMC5843 is a multi-chip module containing a HMC1043 AMR sensor and ASICsupport circuitry. It measures a mere 4-mm square.

HMC5843

ASIC

Test

CLK I2C

ADC

H-Bridge

SETC

TP0TP1

DRDYSDASCL

SDAPSCLPVREN

AVDD

AGND

DGND

DVDD

C1C14.7 µF

Amp

AMR

AMR

AMR

Offset BP

BN

Set/Reset

HMC1043

SCDD

AGND

Biascurrent

Voltageregulator

Currentlimit

Controllogic, and

POR

SETP SETNC2

0.22 µF

MU

X

N E S W N

400

300

200

100

0

–100

–200

–300

–400

0 45 90 135

180

225

270

315

360

X (forward)

Y (left)

Heading (degrees)

Mag

neto

met

er o

utpu

t (co

unts

)

Y

X

2906002-bachiochi.qxp 5/7/2009 1:29 PM Page 61

Page 64: Circuit Cellar 2009-06

62 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

The HMC5843’s operating voltage is 2.4 to 3.3 V. Inter-nally, it requires 1.8 V (for the digital section). This volt-age can be self-generated via an internal regulator, or itcan be supplied externally as a second supply voltage.

The IA, referenced to AVDD/2, amplifies the AMRbridge’s differential output. The Earth’s magnetic fieldstrength is approximately 0.6 G (the AMR bridge). TheHMC5843’s seven possible gain settings cover a range of0.7 to 6.5 G. The ADC converts full-scale outputs to±2,047 counts. If you have the gain too high and theADC’s input level is exceeded, the conversion value isforced to 0xF000. Note that external ferrous metals (iron)can distort the Earth’s magnetic field by providing aneasier path than through the air. This draws the fieldtoward itself. And magnetized materials can influencethe Earth’s magnetic field by adding a “fake” source.This not only pushes the Earth’s field, but it can alsooverpower the sensors.

ARCTANTwo of AMRs are parallel to the PCB’S surface. If you

rotate the PCB so the x-sensor’s positively sensitive axisaligns toward the north magnetic pole, the x-sensor canmeasure a maximum amount of the Earth’s magneticfield. The y-sensor is perpendicular to the field so itmeasures a minimum amount of the Earth’s magneticfield. As the chip is rotated clockwise from 0 to 360°, thex and y measurements have a sine-cosine relationship(see Figure 2). The angle or heading can be calculatedusing the arctangent of the y-sensor measurement divid-ed by the x-sensor’s measurement.

When the x-sensor’s measurement equals zero, youhave a divide-by-zero error. A check for x = 0 can have

two possible headings: one at 90°, if y is greater thanzero, and one at 270°, if y is less than zero.

Arctan transforms measurements into a heading of0–90° four times in one 360° rotation. The polarity of thex and y values indicates the quadrant of a circle to whichthe measurement refers. You must add (or subtract) thearctan heading from a quadrant offset to get the actualheading. After you have a heading value of 0 to 359°, youknow the direction to the magnetic north pole. The top

Photo 1—This circuit will turn on the most northern LED (or LEDpair) to give you a general northern direction. When used as aperipheral, this circuit provides the actual heading via a serial port.

Figure 3—This map shows the declination error between the (true) north pole and the Earth’s magnetic north pole. The dark line (0°) is aplace where the magnetic and true north poles are aligned (the magnetic pole being presently approximately 800 km south of true northpole along this line).

22ºE

20ºE

18ºE

16ºE

14ºE

12ºE

10ºE

8ºE

6ºE4ºE 2ºE

2ºW

4ºW

6ºW

8ºW

10ºW

12ºW

14ºW

16ºW

18ºW

20ºW

22ºW

N

2906002-bachiochi.qxp 5/7/2009 1:29 PM Page 62

Page 65: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 63

June

2009 –

Issue

227

of most maps is oriented toward truenorth. Aligning the north/south lon-gitudinal lines to magnetic northcan throw off the map from +20° to–20°, depending on your location(see Figure 3). Most maps indicatethis difference between magneticand true north as a declination con-stant (in the map’s key). Correctmap orientation is achieved usingthe declination constant.

If you want your compass to pointto true north instead of magneticnorth, you need to add the declina-tion constant for your area to themagnetic heading. For example, I livein Connecticut, which has a declina-tion constant of approximately –15°.This means magnetic north is –15°(CCW) from true north. So, I mustadd 15° to my magnetic heading toget a true north heading.

IRON ERRORSI covered how the environment can

distort the Earth’s magnetic lines offorce. Measuring a distorted fieldwill not provide accurate resultsunless you can know how the field is

Figure 4—While Photo 1 showsa through-hole prototype, thiscircuit was redesigned to sup-port SMT parts. This circuit nowoperates on 3.3 V. R1 is analternate to R11 when using aserial vs. USB connection.

2906002-bachiochi.qxp 5/7/2009 1:29 PM Page 63

Page 66: Circuit Cellar 2009-06

64 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

up or down about the x-axis, whilethe pitch would be the nose (tail) upor down about the y-axis. Either ofthese movements will produce anamount of tilt from level. Level isconsidered the plane that is perpendi-cular to a vector directly toward thecenter of the Earth (Earth’s gravityvector).

Using the z-axis’s relationship tothe compass’s x-axis and y-axis, youcan calculate the Earth’s magneticvector—that is, the direction of theEarth’s magnetic field. I previouslymentioned that the Earth’s magneticfield is aligned toward thenorth/south magnetic poles. But ifyou look more closely, you willnotice that while the field is relative-ly perpendicular to gravity at theequator, as you move closer to a pole,

the field eventually becomes parallel to the gravity vec-tor (as it enters the Earth directly into the pole). For therelationship of the x-axis to y-axis (or heading calcula-tion to be accurate), they must remain as level as possi-ble. A tilt may change this relationship. If it does, it will

distorted. If the compass is mountedin something like a car or robot, fer-rous materials will introduce distor-tion that you can easily remove witha calibration routine. All of this dis-tortion-altering content rotates alongwith the compass while the Earth’smagnetic field remains constant, soyou can take calibration measure-ments by rotating this in a circle. Dis-tortion causes the measurements tostray from ideal conditions, but youcan create adjustments based on whatyou see.

Under perfect conditions, each axishas the same range—that is, the x-sen-sor’s maximum count should equalthe y-sensor’s maximum count. A dif-ference in range can be adjusted byapplying a gain adjustment to eachaxis. The axis with the largest range(positive count + absolute value of negative count) isgiven a gain equal to one. The other axis is given a gainof whatever is necessary to make its range the same asthe first: gain = x. In this case, x is the largestrange/smallest range (i.e., 2,000/1,800 = 1.11). A sensor’sgain adjustment must be applied to each ofthe sensor’s measurement values.

In addition to the range adjustment,each sensor’s maximum positive countshould be equal to its maximum negativecount. If a distortion is pulling the meas-ured values one way or the other, the max-ima won’t be the same. If the x-sensor’spositive maximum is, say, 100 countsmore than the x-sensor’s negative maxi-mum, you must add an adjustment of –50counts to each measurement taken by thex-sensor. The y-sensor measurementsmust be treated the same way. Calibrationis necessary whenever the environmentchanges. The calculated gain and offsetadjustments can be stored and used eachtime a sensor measurement is made.These are compensated measurements:

x-sensor value = (x-sensor gain × x-sensormeasurement value) + x-sensor offset

y-sensor value = (y-sensor gain × y-sensormeasurement value) + y-sensor offset

TILTTilt is a measurement of pitch and roll

about an axis. (Here I reference the com-pass’s x-axis.) If you imagine the x-axis asthe nose and tail, and the y-axis like thewings of a plane, roll is the wingtip swing

Figure 5—The flow chart on the left shows a simple main loop. The HMC5843 routinein the center illustrates how the data is converted. One of the conversions is chartedon the right. It uses integer math and a table lookup to determine heading from theindividual sensor measurements.

Initialization

X = 0?

Y > 0?

Degrees = 90

Degrees = 270

Y * 1000/X

N

N

NY

Y

Y

Y

Call

Read X/Y/Z

Data ready?

Read X/Y/Z

HMC5843

Call

I2C

Call

Convert to absolute

Use X and Ypolarity to define

quadrant andapply the

Arc Tan result

Call

Arc Tan lookup

Convert todegrees

Call

Read X/Y/Z

Call

Convert todegrees

Update

LEDs

Call

Adddeclination

Call

Convert degrees toLED

Return

Return

Table 1—These 13 registers are availablevia an I2C interface between the HMC5843and the PIC microcontroller. The result of ameasurement (±2047) is stored in registerpairs for each axis.

Register address Name Access0 Configuration A R/W

1 Configuration B R/W

2 Mode R/W

3 X-axis MSB R

4 X-axis LSB R

5 Y-axis MSB R

6 Y-axis LSB R

7 Z-axis MSB R

8 Z-axis LSB R

9 Status R

0A Identification A R

0B Identification B R

0C Identification C R

2906002-bachiochi.qxp 5/7/2009 1:29 PM Page 64

Page 67: Circuit Cellar 2009-06

This year we’ve decided to combine our annual Circuit Cellar reader survey with a special sample pool evaluation program. This gives readers the chance to provide Circuit Cellar with vital feedback while also registering for sample product consideration.

In addition to survey participants having the chance to win Circuit Cellar CD archives and subscrip-tions, a larger group of qualify-ing survey participants will also be able to receive a wide variety of product samples from our sponsors.

See page 73 of this issue for a few of the participating sample pool sponsors. (Additional sponsors may be added after this issue prints.)

The world of publishing has changed dramatically within the last 1-2 years. Now more than ever it’s crucial that Circuit Cellar has your input so that we can maintain a course that’s most beneficial to our core readership.

Please take a moment to complete this reader survey today!To participate, visit www.circuitcellar.com/RS

65.qxp 5/12/2009 12:25 PM Page 73

Page 68: Circuit Cellar 2009-06

66 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

introduce an error. A particular tilt will cause an increas-ing error as the compass moves further north or southfrom the equator, so keeping a compass level is moreimportant to those of us living in New England.

I’ve used Analog Devices iMEMS accelerometers inpast projects to reference the direction of Earth’s gravity(“What’s the Slope?: Use an Accelerometer to MeasureSlope,” Circuit Cellar 202, 2007). In this project, theaccelerometer’s z-axis measures maximum Gs (1), whilethe compass (PCB) is level. The accelerometer’s x-, y-,and z-axes are aligned with the AMR’s. Therefore, as theaccelerometer’s z-axis begins to register a tilt, the z-axisand y-axis can be used to determine the direction of thetilt, and one of the four inside LEDs will indicate whichdirection in which you need to tilt (actually, anti-tilt) thePCB.

PROTOTYPEMy first prototype was through-hole, except for the

HMC5843 (see Photo 1). The original idea was to use thecompass’s z-axis as a leveling indicator. Unlike the docu-mented declination constant, the downward componentto the Earth’s magnetic field is not well documented.Because the magnetic pole and true north are not thesame, I couldn’t just use the latitude to calculate the z-axis component. So, I redesigned the circuit to include athree-axis accelerometer to better determine tilt. Idesigned with SMT parts and was able to reduce the PCBto 2” square (see Figure 4). At that point, it made senseto reduce the working voltage to 3.3 V. It also reducedthe complexity by eliminating some level translationcomponents.

The HMC5843 uses an I2C interface while theaccelerometer has analog outputs. To interface withexternal circuitry, the PCB can be set up to use a serialUART or USB interface. In this column, I’m focusing onthe AMR and how its measurements relate to magnetic(or true) north. Using the I2C interface, you can access 13registers within the device (see Table 1). These registerscan be divided into three groups. The first group (regis-ters 00–02) has read/write access and can configure howthe chip operates. The second group (registers 03–08)holds the measurements taken from each of the threeaxes. Each register pair holds signed values from 0 to2047. The last group (registers 09–0C) contains statusand identification information.

The device has four operating modes: Sleep, Idle, SingleMeasurement, and Continuous Measurement modes. Thelowest current consumptions (a few microamps) comefrom Sleep mode (supplying dual voltages, no internalregulator). Normal operations (using the internal regula-tor for 1.8 V) consume approximately 1 mA. The moderegister determines operational modes. After a singleconversion, the device returns to Sleep mode. The config-uration registers set up sensor gain, conversion delay, andcontinuous conversion rate. By reading the status regis-ter, you can determine when the compass is done updat-ing the axis measurement registers. In addition, after you

begin reading them, the compass will hold off updatingany of these six registers until you’ve finished reading allof them. The Identification registers have fixed valuesthat relate to the device itself. In this case, the registershold the ASC values H34.

COMPUTATIONSMath is always a concern when you’re writing code.

Independent of the language you’re using, you can expectthat math support may often require more code space thanthe rest of the application. Floating-point routines requirethe most space. Integer math requires considerably lessspace but may not be able to provide adequate accuracy.Tables also can be used to reduce the need for floating-point support, although they can be potentially large.

In this application, I used function arctan = y/x to con-vert from axis measurements to degrees. I used a tableholding precomputed values for degrees versus the arctanequivalent. You can find tables for arctan values in manyreference books. This is a list of degrees with its equiva-lent arctan value: 0° (an arctan = 0) through 90° (an arc-tan = infinity). The values in my reference table are list-ed with a resolution of thousandths. Noticing that 89°(the largest value) = 57.290, I can multiply all values by1,000 and keep them within a 16-bit word table entrywithout decimal headaches. Thus, when I divide y by xto get an arctan value, this result needs to be 1,000×larger to relate to the table. So, my math routine mustuse the form arctan = Y × 1,000/x. Two integer mathroutines will satisfy my needs: a 16-bit × 16-bit multiplyand a 32-bit × 16-bit divide.

As you can see in Figure 5, the main loop consists ofthree routines: read the HMC5843, read the AXL330,and the update of the LEDs. The read HMC5843 routinehas four routines to read and convert the data: I2C rou-tines are used to retrieve axis measurements for thedevice; each measurement is converted into an absolutevalue along with a sign polarity notation; the measure-ments are converted to a degree equivalent, and a pre-stored declination constant modifies the heading; andthe heading in degrees is used to determine which LEDsshould be on to indicate true north. The declinationconstant adjustment can be skipped if you want to pointto magnetic north.

Let’s look closer at the Convert to Degree routine. Acheck for divide by zero (X = 0) is made to prevent a com-putational error. Depending on y’s polarity, when X = 0,degrees will equal 90 to 270. Otherwise, you want toconvert the x-axis and y-axis measurements into an arctanvalue that can be used for table look-up. The table consistsof arctan values for degrees 1 to 89. Beginning with thefirst table value (for 1°), compare the table’s value with thecomputed value. If the computed value is bigger, incrementthe degree counter and continuing checking the next tableentry. The degree counter is the converted equivalent.However, this is a measurement of position within onequadrant (0–90°) of a circle (360°). Using the polarity flagsfor the x-axis and y-axis measurements, you can determine

2906002-bachiochi.qxp 5/7/2009 1:29 PM Page 66

Page 69: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 67

June

2009 –

Issue

227

Author’s note: Thanks to Mark Amundson at Honeywell Aerospace and Robert Cook atProComp Associates for their assistance.

Jeff Bachiochi (pronounced BAH-key-AH-key) has been writing for Circuit Cellar since1988. His background includes product design and manufacturing. You can reach himat [email protected] or at www.imaginethatnow.com.

RESOURCEHoneywell International, Inc., “Compass Heading Using Magnetometers,”AN-203, www.honeywell.com/sites/portal?smap=aerospace&page=Literature&theme=T5.

OURCESADXL330 AccelerometerAnalog Devices | www.analog.com

HMC5843 Compass ICHoneywell | www.honeywell.com/magneticsensors

PIC18F2450 Microcontroller Microchip Technologies, Inc. | www.microchip.com

S

which quadrant the conversionreflects and make an adjustment rel-ative to 0 or 180° by adding or sub-tracting the conversion from 0 or180°.

While the microcontroller holdsthe actual heading in degrees and canbe read through a serial or USB con-nection, eight LEDs on the PCB areused to indicate the heading to truenorth. Note that 360° divided byeight LEDs equals 45° for each LED.To improve the resolution, multipleLEDs can be used to imply a headingbetween the two, giving a resolutionof 22.5°. The LEDs are meant toshow you a general direction.

Holding the compass level isimportant to accurate measure-ments. Four additional LEDs are ref-erenced to the x- and y-axes. TheADXL330 accelerometer measuresthe gravity vector. If the accelerome-ter measurements determine a non-level situation in either the x-axis orthe y-axis, LEDs illuminate to showhow to correct the tilt.

PAYING FOR MOREAs designers, we must constantly

review the buy-versus-build choice.GPS can give you heading informa-tion, but this is based on movement.

It must use multiple positions todetermine direction of travel. Elec-tronic compasses will cost far lessthan including a GPS in your designjust for heading information. At theopposite end of the cost spectrum areindividual magnetic sensors that youcan combine with your own ampli-fiers, multiplexers, ADCs, andmicrocontrollers to create what theHMC5843 offers. However, $20seems like a pretty good bargain forall of that. Don’t want to deal withcomputations? You can buy a two-axis version (HMC6352) that inter-nally converts the heading for youfor $30. But you still must makesure the device is level! To step upto a device that contains a three-axisAMR, a three-axis accelerometer,and internal algorithm computa-tions, you can use the HMC6343 ata mere $175.

I’ve yet to receive the second(SMT) prototype, but I want to addroutines like calibration. I think thiscircuit is flexible enough to be usefulin future projects. However, the mostfulfilling aspect of this project wasovercoming my fear of staying awayfrom those SMT parts that can’t behand-soldered. I might need to goshopping for a toaster oven. I

2906002-bachiochi.qxp 5/7/2009 1:29 PM Page 67

Page 70: Circuit Cellar 2009-06

68 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

A fter all these years in the chip biz, one trend is clear to me. Ironically, it’s the “hardware” that’s gotten “easy,”

while writing “software” is “harder” than ever.Actually, the irony goes deeper than that. After all, at a certain

level—namely, chip design using Verilog or VHDL—creating hard-ware is little different from creating software. As I’ve said before,if you see an engineer scratching their head staring at a screen, theonly way to tell whether they’re designing software or hardware isto check and see if they’re wearing shoes.

It’s the users of the chips (i.e., the board- and box-levelhardware designers) that have it easy. Thanks toMoore’s Law, hardware design for the vast majority ofembedded designs involves little more than dropping afew do-it-all chips onto a PCB. I was reminded of the factwhen I recently fired up my first computer, a circa-1970sIMSAI. (Refer to my October 2008 article, “The Way WeWere,” which appeared in Circuit Cellar News Notes,Vol. 4.) With hundreds of chips and thousands of connec-tions, that was “hardware” the hard (and expensive) way.These days, doing a similar hardware design would involvelittle more than choosing which 50-cent MCU to use.

Meanwhile, software stays hard. Yes, the tools get incre-mentally better and reuse is an easy way out. But the prob-lem is that the aforementioned growth in hardware capabilityhas simply fueled demand for more software features. You’veheard the old saying that software, like a gas, expands to fill allavailable space. That old-timey, 8-bit micro chewing through a1,000-line program has evolved into a fancy 32-bit MCU thathungers for a million lines of code. Feed me!

It’s no surprise that in this month’s column you’ll see theusual miracle-working MCU. But this time, the story is alsoabout the software tools as much as the silicon. Is it time for achange we can believe in?

MACRO MICROThe LPC236x lineup is just one horse in NXP Semiconductors’s

stable of ARM-based flash memory MCUs (see Figure 1). Keep my

Thanks to the march of silicon designing hardware these days is assimple as choosing which of the latest and greatest wunderchips to use.Ah, but software, well, that’s another story. There’s no Moore’s Law forsoftware and it isn’t getting any easier. Maybe it’s time for a change.

Easy (E)mbedAn Alternative Approach to Embedded Programming

by Tom Cantrell

SILICON UPDATE

Photo 1—The LPC263x-based mbedmodule uses a DIP form factor, agreat option for easy prototyping.Note the “transformerless” Ethernetconnection on the right side.

2906003-cantrell.qxp 5/7/2009 1:30 PM Page 68

Page 71: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 69

June

2009 –

Issue

227

Different members of the LPC236xlineup offer a mix of high-end I/O capa-bilities including 10/100 Ethernet MACand a full-speed (12 Mbps) USB devicecontroller. These bring their own RAMto the party (16 KB for Ethernet and 8 KBfor USB), which is also available for gen-eral-purpose use by the CPU. There’s afancy DMA controller and dedicatedbussing to keep the data flowing fastwith minimal overhead. Other notableI/O options in the lineup include a CANcontroller and multimedia card interface.

Along with the big-ticket peripherals,the LPC236x crams in virtually everyflavor of serial I/O (UART, I2C, SPI, I2S,

“hardware is easy, software is hard”premise in mind as you contemplatethe long list of features packed ontothis 100-pin hotrod.

Under the hood, we find a venerableARM7 core—not the newest micro onthe block, but nevertheless running at upto 72 MHz, which is more than adequatefor blue-collar embedded apps. Differentmodels come with 128, 256, or a whop-ping 512 KB of flash memory, which ismore than enough to keep the program-mers busy. The smaller versions (i.e.,with 128-KB flash memory) come with8 KB of general-purpose RAM, whilethe larger ones boost that to 32 KB.

and more), nearly a dozen timersincluding high-resolution (32-bit),PWM, a watchdog, and an RTC (whichadds another 2 KB of battery-backableRAM into the memory mix). The analogbases are covered with a fast (2.4-µs) six-channel, 10-bit ADC and a 10-bit DAC.

Going beyond the major bullets in thedatasheet, I’m impressed with NXP’sattention to embedded details. For exam-ple, the memory interface features asophisticated 128-bit prefetch mecha-nism to reduce the inevitable flash bot-tleneck. Bit-twiddling operations werenever ARM7’s forte, so NXP includesdedicated bit set and reset registers for

I/O ports. The clock gener-ation and power distribu-tion scheme is fully inte-grated so you can tweak allthe dials to minimizepower. For example, clock-ing can be driven on-chip(built-in RC oscillator) andoff-chip (main and RTCoscillators), and eachperipheral’s clock can beindividually controlled (i.e.,disabled or divided).

CHIPS & DIPAlthough the LPC263x is

impressive, the chip itselfisn’t really the focus of thismonth’s column. The factis, it isn’t even the newestarrow in NXP’s quiver, andit’s no secret all the majorMCU suppliers offer partswith similar capabilities.The most amazing thingabout the LPC263x is thatit really isn’t all that amaz-ing in this day and age.Referring back to my open-ing premise, rather thanthe chip itself, I’d like tofocus on a unique approachto software developmentthat that comes with it.

The “mbed” moduleshown in Photo 1 highlightshow hardware has become“easyware.” Just plop downthe MCU and a few LEDs,and voila, instant EV board.Actually, there are a coupleof extra housekeeping chips

Figure 1—In the old days, the hardware design for a 32-bit micro with almost half a meg of memory,Ethernet, USB, and a bunch of I/O was “hard.” Now, thanks to flash MCUs like the NXP LPC263x, it’s easy.Software? That’s another story.

LPC2364/65/66/67/68

High-speedGPI/O70 Pins

totalVectoredinterruptcontroller

USB with4-KB RAMand DMA[2]

Internalcontrollers

Test/debuginterface

Em

ulat

ion

trac

e m

odul

e

128/256/512-KB Flash

memoriesP0, P1, P2,

P3, P48/32-KBSRAM

Systemclock

Internal RCoscillator

Systemfunctions

AHB2

External interrupts

I2S Interface

AHB1

SPI, SSP0 Interface

SSPI Interface

UART0, UART2, UART3

UART1

CAN1, CAN22

I2C0, I2C1, I2C2

PWM1

A/D Converter

D/A Converter

2-KB Battery RAM

Watchdog timer

System control

RMI(8)

*EINT3 to *EINT0

P0, P22 × CAP0/CAP1/

CAP2/CAP3 4 × MAT2,

2 × MAT0/MAT1/MAT3

6 × PWM1

2 × PCAP1

P0, P1

6 × AD0

AOUT

VBAT

Power domain 2

RTCX1RTCX2

I2SRX_CLKI2STX_CLKI2SRX_WS I2STX_WS

VBUS

USB_D+, USB_D−USB_CONNECT USB_UP_LED

I2SRX_SDA I2STX_SDA

MISO, MISO0SSEL, SSEL0

SCK, SCK0MOSI, MOSI0

MISO1SSEL1

TXD0, TXD2, TXD3RXD0, RXD2, RXD3

MCICLK, MCIPWRMCICMD,MCIDAT(3:0)

SCK1MOSI1

EthernetMAC With

DMA

Capture/comparetimer0/timer1/timer2/timer3

16-KBSRAM

AHBBridge

AHB-to-APBBridge

AHBBridge

8-KBSRAM

GP DMAController

Master AHB-to-SlavePort AHB Bridge port

SD/MMC Cardinterface1[1]

Legacy GPI/052 pins total

RTCOscillator

Real-timeclock

DTR1, RTS1DSR1, CTS1, DCD1, RI1

TXD1RXD1

RD1, RD2TD1, TD2

SCL0, SCL1, SCL2SDA0, SDA1, SDA2

[1] LPC2367/68 only. [2] LPC2364/66/68 only.

TMS TDI

TCK

PLL

SRAM Flash

*TRST *RESET

ARM7TDMI-S

XTAL2XTAL1

VDDA

VDD(3V3)

VREFVSSA, VSSVDD(DCDC)(3V3)

TDOEXTIN0

Trace signals

2906003-cantrell.qxp 5/7/2009 1:30 PM Page 69

Page 72: Circuit Cellar 2009-06

70 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

my PC. And it’s here where mbed thinksoutside the box, literally. To make along story short, there’s zero software toinstall because the tools are web-based.

Here’s how it works. All you do isconnect the mbed module to a USB portand it is recognized by your PC as ageneric mass-storage device just like atypical thumbdrive. Open the mbed

on the underside of the board startingwith a separate LPC MCU devoted tohandling the USB interface with thehost PC. The extra MCU frees up themain LPC USB interface for your appli-cation and minimizes the intrusivenessof host PC communication. There’s alsoan Ethernet transceiver (aka “PHY’)from National Semiconductor(DP83848). Getting on the ’Net canbe as easy as adding an RJ-45 con-nector, especially since the Nationalpart has a “transformerless” optionthat uses capacitors, instead of atransformer, for coupling.[1]

Over the years, I’ve seen a lot of“evaluation boards,” usually one oftwo varieties, the first being theolder-school larger boards and morerecently all manner of cute USBgadgets. To my mind, the mbedmodule, with its DIP plug-inapproach, is a smart way to go (seeFigure 2). Although small and inex-pensive like other USB plug-ins, it isbreadboard-friendly for prototypingand experimentation, and it couldeven make sense for low volumeproduction.

Usually, it’s about now that I’mtaking a coffee break while gigs ofthe typical “C” IDE get installed on

“drive” and look in the directory tofind the “mbed.html” file. Double-click it and it will open with yourbrowser just like any other webpage. Voila, you’re on the air andready to start programming withnary a byte of software installed onyour PC.

Invoking the “Compiler” linktakes you to a web page that actsas an extremely simplified GUI. Iguess you could call it a “WUI”(i.e., “Web-based User Interface”)that pretty much boils down tobasic file operations (create, open,save) and a button that says “Com-pile.” Click that and a momentlater a link appears that allows youto download the compiled code toyour mbed “drive.” Then push theReset button on the mbed moduleand the LPC263x flashes itselfwith the new code and you’re offto the races.

Needless to say, this is a differ-ent way of doing things that has

rather profound implications worthy offurther contemplation. But for now, let’shold those thoughts while we take acloser look at a web-based vision of whatmight be called “Embedded Program-ming 2.0.”

IT’S ALL “C” TO MENow that you’ve compiled and

downloaded your code, it’s time toget up to speed with the debugger.That doesn’t take long becausethere isn’t one. Time to resurrectthe old ways and use PRINTF fordebugging. To that end, the mbedlibrary includes a feature thatroutes serial traffic across the USBconnection to a terminal emulatorrunning on your PC (see Photo 2).

Other handy built-in routinesare shown in Table 1. For example,AnalogOut allows you to set thelevel on the LPC263x DAC outputpin (see Photo 3). For convenience,two versions of the AnalogOutfunction are provided. The one usedhere expresses the rail-to-rail outputas a fraction between 0 and 1, whileanother version uses unsigned 16-bitintegers between 0x0000h and0xFFFFh.

The LocalFileSystem function

Figure 2—The mbed module DIP form factor makes hardware experimenting and prototyping, well, easy.

GND

20

19

18

17

16

15

14

13

12

11

10

9

8

7

6

5

nR

VB

VIN

0 V

4.5 V – 14.0 V In

mosi

miso SPI

sck

mosi

miso SPI

sck

tx Serialrx

tx Serialrx

sda Serialscl

AnalogOutAnalogln

VOUT

21

22

23

24

25

26

27

28

29

30

D+

D−

TD+

TD−

RD+

RD−

IF+

IF−

VU

3.3-V Regulated Out

5.0-V USB Out

Ethernet

USB

rdCan td

txSerial

rx

sdaI2C scl

PwmOut

Photo 2—Absent a debugger, you’ll need to fall backon PRINTF to test your program. Fortunately, thereare built-in functions that implement a virtual serialport via USB so you can use a terminal emulator onthe PC to see what’s going on.

2906003-cantrell.qxp 5/7/2009 1:30 PM Page 70

Page 73: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 71

June

2009 –

Issue

227

enables you use standard “C” file operations (fopen,fprintf, fclose, etc.) on the mbed flash drive. This isnoteworthy because it allows straightforward interchangeof data between your program and a PC via the FAT filesystem (see Photo 4). For instance, it would be easy to usean mbed module as a data logger, creating a log file on itsown flash memory that could subsequently be openedwith a PC application (e.g., word processor, spreadsheet,etc.). Similarly, a PC could be used to “configure” anmbed module by writing a data file to the flash drivewhich the mbed application could query after being dis-connected from the PC.

Going beyond the built-in functions, the mbed webpagehas a “Cookbook” link that takes you to a bunch of add-on projects and examples. Many of these show how toconnect the mbed module to popular I/O devices (e.g.,LCDs, sensors, motors, etc.) and there are some handyutilities (e.g., a routine to set the real-time clock).

I found some interesting dishes in the “Cookbook,”starting with a simple web server that exercises the mbedEthernet interface (see Photo 5). Taking advantage of theNational transceiver’s “transformerless” feature mentionedearlier, I was able to jack-in simply by cutting one end offan Ethernet cable and connecting the transmit and receivewires directly to the mbed module.

Another demo takes advantage of the mbed “Remote Proce-dure Call” (RPC) capability. In essence, RPC is a mechanismthat provides hooks to the functions shown in Table 1. Theexample in Photo 6 shows how to assign a service name (“pot”)to an mbed function (AnalogIn). Once the logical connectionis established, the mbed functions are exposed to the outsideworld and you can use the terminal to interact with them.

NEW IDEANow that you’ve got a glimpse under the hood, let’s con-

template the big picture and examine the various factors

comprising the altogether unique mbed experience. “Keepit simple” is advice that’s clearly taken as gospel by thembed folks. I must say I found it refreshing that I didn’thave to deal with the clutter and complexity of the usualbig-ticket IDE. There’s no doubt it lacks the features andoptions that a professional programmer is used to. But onthe other hand, the mbed approach makes things easy foranyone who just wants to get a simple app working with-out a lot of fuss and bother. Recalling my opening “hard-ware easy, software hard” premise, it seems to me that astraightforward solution to the “software crisis” is simplertools that enable more folks to write their own code.

Simplicity is nice, but it isn’t really what makes mbedstand out from the crowd. Rather, it’s the fact theentire experience is web-based that is totallyunique and would seem to have rather significantimplications.

For instance, the fact the GUI is a web-browserfeels quite liberating. Notably, it sweeps away allreligious issues related to your platform of choice.PC, Mac, Linux—have it your way. Heck, I supposeyou could figure out a way to program mbed withyour iPhone or any other web-capable gadget.

Another thing that felt very liberating was beingtotally relieved of “IT” responsibilities. Keeping upwith revising, upgrading, and migrating (e.g., XP toVista) a pro toolchain can be a chore, one I’m gladto let the mbed folks take care of. It’s all the moreliberating, for your wallet, to realize you’re gettingaccess to some pretty fancy software (ARM’s ownRealview compiler) for free.

On the other hand, I found my browser (Explorer)had some trouble with GUI basics. Keyboard andscreen updates are a bit sluggish and the interfacecan be quirky or lacking compared to a real editor

Table 1—The mbed library includes built-in functions that make program-ming easier. The more software someone else writes, the less you have to.

Routines UsesPwmOut Set a PWM output period, frequency, duty cycle

SPI SPI master configuration (frequency, format) and data transfer

AnalogOut Set analog output voltage level

Wait Wait specified number of milliseconds/microseconds

Timer General-purpose timer (seconds/milliseconds/microseconds)

DigitalIn Read the state of an input pin

LocalFileSystem Use C file functions to access mbed disk drive

Debug Output error message to PC and debug LEDs

Ticker Call a function at a recurring interval

DigitalOut Set the state of an output pin

BusOut Set the state of a collection of output pins

AnalogIn Read analog input voltage level

Serial UART configuration (bitrate, format) and data transfer

RTC Set and read the real-time clock

Timeout Call a function at a future time

BusIn Read the state of a collection of input pins

SPI3 3-wire SPI master configuration (frequency, format) and data transfer

Stackheap Functions return code, data, stack and heap addresses

I2C I2C master configuration (frequency) and data transfer

Photo 3—Another built-in function, AnalogOut, makes it easy to drive theMCU’s on-chip DAC.

2906003-cantrell.qxp 5/7/2009 1:30 PM Page 71

Page 74: Circuit Cellar 2009-06

72 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

when it comes to things likecut and paste, find andreplace, etc. And thoughintuitive, having to clickthrough Windows hoops(e.g., “Replace existingfile?”) every time you com-pile gets old really fast.

The web angle puts aninteresting spin on issueslike community, collabora-tion, commerce, reuse, andsupport. In principle, a web-based solution like mbedcould evolve to become acomprehensive programming“portal.”

Of course, there are issueslike security and intellectualproperty that can’t be over-looked. It’s easy to forgeteverything you’re doing isgetting sent across the Inter-net. In fact, as best as I cantell, the programs you enterand save aren’t even storedon your own PC. If BigBrother is watching me hackaway, so be it. Maybe he’lleven help me get my pro-gram working.

FORWARD TO THE PAST?It’s kind of ironic how simi-

lar mbed’s “leave the drivingto us” web-based approach isto the way things workedback in the days of mainframe

computers, albeit now on a muchgrander I-Way scale. After the main-frames came the “Personal Computer,”which itself felt liberating, at least at thetime. But when it comes to wrestlingwith complicated toolchains and ITchores, I’m not sure today’s PC experi-ence feels that liberating anymore.

Of course, the issue of web-hostedsoftware goes beyond the niche ofembedded programming to encompassall types of applications. Indeed, whenyou consider the likes of Google oriTunes, it’s apparent a transition to web-based functionality is already underway.

Keep in mind I’ve been working witha beta pre-release version of the mbedhardware and software. Things maychange by the time you read this, socheck the NXP web site (see the Sourcesbelow) for the latest information. Surethere are lots of questions and no doubtsome bumps in the road ahead. But mygut feeling is that the mbed folks areonto something here. The web-basedapproach won’t totally replace the oldway of doing old things (i.e., the tradi-tional toolchain running on the PC),but it doesn’t need to. Instead, consid-er the mbed solution an alternativeapproach to embedded programmingthat may not be industrial strength,but is easy and accessible for all. I

Photo 4—From the PC’s perspective, the mbedmodule appears as a typical USB thumbdrive.The LocalFileSystem function takes advantage ofthat by making it easy for an application program toexchange file data with the PC.

Photo 5—One of the projects in the mbed “Cookbook”is a mini-web server that made it easy to check out the“transformerless” Ethernet feature.

Photo 6—Remote Procedure Call (RPC) is an interest-ing feature that provides hooks to access the mbedbuilt-in functions. This example shows the AnalogInfunction being invoked via the console.

Tom Cantrell has been working on chip,board, and systems design and marketingfor several years. You may reach him bye-mail at [email protected].

EFERENCE[1] D. Miller, D. Seely, and T. Ngo, “DP83848 PHYTER Trans-formerless Ethernet Operation,” Application Note 1519, 2006,www.national.com/an/AN/AN-1519.pdf.

ESOURCET. Cantrell, “The Way We Were,” Circuit Cellar News Notes, Vol. 4,2008, www.circuitcellar.com/newsletter/1008.html#1.

OURCEDP83848 TransceiverNational Semiconductor Corp. | www.national.com

NXP LPC263x “mbed” module and web-based C IDE NXP Semiconductors | www.nxp.com/microcontrollers

S

R

R

2906003-cantrell.qxp 5/7/2009 1:30 PM Page 72

Page 75: Circuit Cellar 2009-06

WWW.CIRCUITCELLAR.COM/RS

USB Bus Analyzers

1-888-7SAELIG

[email protected]

www.saelig.com

Packet-Master™ - best value inUSB1.1/2.0 USB analyzers andgenerators. Identify USB problemsfast, f ine-tune performance, easi lyv iew Host Commands, emulatehost/device sequences, etc.

USB12 (USB1.1) $699

USB480+ (USB1.1/2.0) $1199

USB500AG (USB1.1/2.0/Gen) $1399

CUSTOMIZE YOUR MCU!

CAPFPGAARM

StandardProduct

www.atmel.com/products/AT91CAP

2009 CIRCUIT CELLAR READER SURVEY & SAMPLE POOL SPONSORS

73.qxp 5/11/2009 4:26 PM Page 73

Page 76: Circuit Cellar 2009-06

74 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

THE DIRECTORY OFPRODUCTS AND SERVICES

AD FORMAT: Advertisers must furnish digital submission sheet and digital files that meet the specifications on the digital submission sheet. ALL TEXT AND OTHERELEMENTS MUST FIT WITHIN A 2" x 3" FORMAT. Call for current rate and deadline information. E-mail [email protected] with your file and digital submissionor send it to IDEA BOX, Circuit Cellar, 4 Park Street, Vernon, CT 06066. For more information call Shannon Barraclough at (860) 875-2199.

The Vendor Directory at www.circuitcellar.com/vendor/ is your guide to a variety of engineering products and services.

IDEABOX

UUSSBBAdd USB to your next

project—it’s easier than youmight think!

USB-FIFO up to 8 mbps

USB-UART up to 3 mbps

USB/Microcontroller boards

pre-programmed with firmware

2.4GHz ZigBee™ & 802.15.4RFID Reader/Writer

Absolutely NO driver software

development required!

www.dlpdesign.com

���

�������������

��������������

���� ������� � ��� ����������� ������������������

������������� ��� ���� ����

����� ��������

www.copelandcommunications.com

Low Cost 56K V.92 MNP4 Modems, Dialup Device Servers, Ethernet and WiFi—all in one form factor!

��300 – 56K baud V.92 ��V.42 - V.42bis - MNP4 ��Global Compliance—

5KV ��FCC, CE and TBR21 approvals��AT command set��SocketModem™ compatible ��Low Power—35mA ��Small Footprint

1.045” x 2.54”

��Wireless Modules—902-928MHz - 33Kb

��Auto Error Detection& Flow Control

��Modules are H/W & S/Wcompatible

��Custom antennas ��USB 2.0 Modules—Adapt

legacy RS-232 DB9 to USB ��WiFi, Ethernet available soon!

Low Cost Embedded OEMModems & Device Servers

ib-227.qxp 5/8/2009 8:23 AM Page 74

Page 77: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 75

June

2009 –

Issue

227

Starting at $125!

Program inAssembler, BASIC, C, and Forth

www.TechnologicalArts.com

Adapt9S12XDP512Modular Prototyping System

* Robotics and Mechatronics * Electronic Fuel Injection* Freescale 9S12XDP512

* RTOS-capable

Evaluate * Educate * Embed

ib-227.qxp 5/11/2009 4:13 PM Page 75

Page 79: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 77

June

2009 –

Issue

227

7 in 1 Scope !

1-888-7SAELIG

[email protected]

www.saelig.com

CircuitGear CGR-101™ is a unique new, low-cost

PC-based instrument which provides the features of

seven devices in one USB-powered compact box:

2-ch 10-bit 20MSa/sec 2MHz oscilloscope, 2-ch

spectrum-analyzer, 3MHz 8-bit arbitrary-waveform/

standard-function generator with 8 digital I/O lines.

It also functions as a Network Analyzer, a Noise

Generator and a PWM Output source. What’s

more – its open-source software runs with

Windows, Linux and Mac OS’s! Only $180

ib-227.qxp 5/8/2009 8:23 AM Page 77

Page 80: Circuit Cellar 2009-06

78 CIRCUIT CELLAR® • www.circuitcellar.com

June

200

9 –

Issue

227

1 2

3

4

5

6

7

8

9

10 11

12 13

14

15

16

17

18

CROSSWORD

The answers are available atwww.circuitcellar.com/crossword.

Across1. xfr4. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …5. No change in polarity9. Damaging or problematic programs like viruses or spyware11. Example: “mcu_fanatic2009”13. Carbon copy15. “P” in P2P16. A test to determine if current is moving17. Signal strength reduction18. Circuit Cellar News Notes is an electronic what?

Down1. 1012 flops2. Character series3. A board with sockets for other boards6. An autoresponder7. statC8. Electronic mag9. Data about data10. The second square number12. Software not released14. Convert analog to digital

crossword2.qxp 5/8/2009 8:14 AM Page 78

Page 81: Circuit Cellar 2009-06

75 AAG Electronica, LLC

11 AP Circuits

20 ARM

75 All Electronics Corp.

77 Apex Embedded Systems

7, 73 Atmel

33, 73 CWAV

16 CadSoft Computer, Inc.

11, 73 Calao Systems

63 Comfile Technology, Inc.

74 Copeland Communications

76 Custom Computer Services, Inc.

74 DLP Design

10 DesignNotes

27 EMAC, Inc.

77 Earth Computer Technologies

The Index of Advertisers with links to their web sites is

located at www.circuitcellar.com under the current issue.

Page

19 ExpressPCB

8 ezPCB

76 FlexiPanel Ltd.

50 General Circuits

32 Grid Connect, Inc.

25 HI-TECH Software, LLC

10 HobbyLab, LLC

74 I2CChip

40, 41 ICbank Inc.

1 Imagineering, Inc.

75 Ironwood Electronics

32, 34 JKmicrosystems, Inc.

74 JKmicrosystems, Inc.

5, 76 Jameco

67 Jeffrey Kerr, LLC

48 Keil Software

67, 73 Lakeview Research

77 Lawicel AB

9, 77 Lemos International Co. Inc.

27 Linx Technologies

77 MCC (Micro Computer Control)

75 microEngineering Labs, Inc.

49 Mouser Electronics

76 NKC Electronics

C2 NetBurner

67 Nurve Networks LLC

21 PCB-Pool

C4 Parallax, Inc.

77 Phytec America LLC

47, 73 Pololu Corp.

75 Pulsar, Inc.

12 R4

Page Page Page

9, 39 Rabbit, A Digi International Brand

76 Rabbit, A Digi International Brand

76 Reach Technology, Inc.

73, 77 Saelig Co.

17 Sealevel Systems

13 SEGGER Microcontroller Systems LLC

C3 Tech Tools

73, 75 Technical Solutions, Inc.

2, 3 Technologic Systems

75 Technological Arts

77 Tern, Inc.

73 Total Phase, Inc.

76 Trace Systems, Inc.

74 Triangle Research Int’l, Inc.

Internet Weather Display

Master Control: Implement an I2C Master Bus Controller in a FPGA

Web Camera

iMash: Build an Ethernet-Controlled HERMS

LESSONS FROM THE TRENCHES C Start-Up: Get a C Program Up and Running

FROM THE BENCH Embedded Speak: A Text Library for Allophone Translations

SILICON UPDATE LiOn King: A Look at “Battery-in-a-Chip” Technology

www.circuitcellar.com • CIRCUIT CELLAR®

INDEX OFADVERTISERS

PREVIEWof July Issue 228

Theme: Internet & ConnectivityAugust Issue 229

DeadlinesSpace Close: June 11

Material Close: June 19

ThemeEmbedded Development

Bonus DistributionHot Chips; Flash Memory Summit

ATTENTION ADVERTISERS

Call Shannon Barraclough now to reserve your space!

860.875.2199e-mail: [email protected]

79

June

2009 –

Issue

227

79-advertiser's index.qxp 5/12/2009 10:53 AM Page 79

Page 82: Circuit Cellar 2009-06

80 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

PRIORITY

During college I stayed with out-of-state relatives. One of my jobs in “being part of the family” was that I got to mow thelawn every week during the summer. This wasn’t just any lawn, mind you. It was a bloody golf course! No, seriously, it wasabout an acre of rocks, outcroppings, tree stumps, and hills. OK, I didn’t have to cut it with a manual push mower, but 5 hoursbehind a non-self-propelled gas mower wasn’t much better. Their attitude was that all that sweat-equity would “build charac-ter,” and the hotter and more humid the weather, the better the experience. My perception was that I was “cheap labor.”

I never wanted to deal with this short green stuff ever again, and as absurd as it sounds, I’ve been true to this directive forthe last 30-plus years of home ownership. If you look back at the photos in my solar system article series, you’ll see that I don’thave a lawn. My house is completely surrounded by hemlock mulch (spreading 60 yards of mulch may seem equally absurd tosome people). ;-)

A couple years ago, we bought a “cottage” for vacation getaways. It’s in a very nice “gated community,” where part of theownership understanding is that people are to maintain their property to specific “community standards” (kinda like a condoagreement). The major concession for me was that these standards dictated that I keep a well-manicured lawn instead of a brownblighted-looking quarter-acre mulch smudge among the rows of green encircled houses. At least that’s how the community’s“little old lady patrol” would have viewed my territorial preferences.

Of course, I completely miss the rationale where people try to grow lawns where none should normally exist—like deserts,swamps, and arid areas. At the cottage, I have a service that cuts the grass weekly, but unless I pour a thousand gallons of wateron this lawn two or three times a week, it will be like the Mohave desert. As you might have guessed, along with all my neigh-bors, the cottage needs an automatic lawn irrigation system.

For those of you readers living in temperate climates, let me just say that a lawn irrigation system is simply a bunch of buriedpipes separated into various areas called zones. Each zone is connected to the water supply through a solenoid “zone” valve.The irrigation controller is typically nothing more than an electromechanical timer that turns on a water pump and sequencesthrough the zones on a preset schedule.

Since I’m basically an absentee owner, I have to trust that things still function properly when I’m not there. Certainly I canalways count on a call from the management if the lawn starts looking like a dried up oasis or a small pond, but emergencyrepairs from a distance are both aggravating and expensive. The preventive course was to add supervisory monitoring andremote activated controls like I have in the Connecticut house. When I am at the cottage, I can check oil tank levels, room tem-peratures, web cams, and more in Connecticut. It made perfect sense to install a similar system in the cottage.

The irrigation controller, albeit electromechanical, seemed straightforward. I monitor the control lines that tell me the poweris on, the rain sensor is on or off, and that the zone valves are on or not. Since I know which days it is supposed to run, I canlook at the monitoring log and see that all the irrigation control outputs trip in the right sequence. Or, if I really need moreassurance, I can turn on a web cam and see the sprayers running in real time (at 5 AM) and that the lawn is still green. The irri-gation system and my electronic oversight has worked fine for 2 years.

I always start the system before packing up to check that all the spray heads are clear. Then I put it back on automatic. Thistime was no different. As expected, the controller turned the water pump on, sequenced through the four zones, and shut off.But wait, the pump and zone 4 were still on. My voltage sensors said the controller and zone valves were powered off, but thewater was still pouring out. “Help!” I thought. The irrigation company was there in less than a half hour. By then I had pulledthe breaker on the water pump, but I couldn’t help but wonder about the consequences of this happening a couple days laterwhen I was back in Connecticut.

Well, welcome to the world of plumbing control versus electronic control. You’d think that the irrigation controller wouldactually control the water pump. Closed loop control? Yeah, right. Guess again. Apparently, the water pump is only controlledby a pressure switch. When the irrigation controller turns on a solenoid valve, the pressure switch turns the pump on to main-tain pressure in that zone. Turn the valve off and the pressure goes up to where the pump shuts off again. So, what happenswhen a little tree root grows into the underground zone valve that causes it to stick open? How about Niagara Falls! Who theheck designed this thing?

Cleaning the area around all the zone valves restored some confidence, but I know I have to close the control loop. I have tokeep the present electromechanical controller because workmen access the system in my absence, but I can’t deal with such “openloop” uncertainties. You can bet your life that very soon the water pump will have an HCS-controlled power relay that coordinatesthe zone actuation and pump runtime. Lawns are bad enough. I don’t need a pond to go with it.

Lawns and Ponds

[email protected]

by Steve Ciarcia, Founder and Editorial Director

INTERRUPT

steve_edit_227.qxp 5/7/2009 12:32 PM Page 96

Page 83: Circuit Cellar 2009-06

C3.qxp 3/30/2007 1:38 PM Page 1

Page 84: Circuit Cellar 2009-06

June09_CC-News.indd 1 4/20/09 11:55 AM

C4.qxp 4/27/2009 9:30 PM Page 1

Page 85: Circuit Cellar 2009-06

22 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

CIR

CU

ITC

ELLA

R D

IGIT

AL

PLU

S B

ON

US

In their last article, Mike and Lizie described how to add a GUI to a co-operative scheduler and then obtain detailed timing information whiledeveloping a multitask audio project. Now they present a revised Thereminsystem design. They also describe how make a co-operative schedulerrecover from various data acquisition issues.

Time-Triggered Systems (Part 3)

A

BO

NU

S

ARTICLEby Mike Smith & Lizie Dunling-Smith

fter seeing the initial design for our modernized Theremin musical instrument in the second part

of this article series, a member of my fourth-year capstonedesign team at the University of Calgary said, “Dr. Smith,you have no soul.” The comment was unexpected becauseI have always seen myself as a warm and considerate pro-fessor (in a highly demanding sort of way). However, thestudent explained that he meant the music generated bythe proposed Theremin instrument had no background“beat,” so the music had no rhythm.

“Rather than adjusting the Theremin’s volume by calcu-lating how much light falls on a light sensor, why don’t webuild a beat stick for you?” another team member asked. Theidea for a beat stick was apparently the generic (home-built)

FFiigguurree 11——The revised plans are to give “a soul” to the Theremin. An accelerometer adds beats to the Theremin’s musical output.DSP algorithms manipulate the tempo of an input audio stream to provide a “beat” background music accompaniment.

equivalent of a Wii stick using an accelerometer to sense themovement of the Theremin-ist’s hands. By waving the stickaround, you can add a beat (a sudden volume change) to themusic.

Currently, a pulse-width modulated (PWM) signal streamfrom a TAOS light sensor is used to control the volume. Itwould be figuratively “5 minutes work” to replace this PWMstream with one from an Analog Devices ADXL213accelerometer. Recalibrate the volume scaling factors calculat-ed in the code, and the Theremin-ist will be up and playingagain!

However, the second aspect of the team’s idea was a littlemore complicated. First, they would write a DSP program todetermine the basic beat from the generated Theremin

music. Then a second output audio stream wouldbe generated by changing the frequency of thebeats in some music having a good basic beat to bethe same as that of the Theremin music. A teammember’s parting comment was: “So theTheremin-ist will get automatic accompanimentto the music—all done in real time, of course.”

Figure 1 shows their new proposed design. Thehardware was not a problem. A Blackfin BF533 eval-uation board (used for teaching at the University ofCalgary) is easily capable of handling multipleaudio inputs and outputs. The BF533 has consider-able DSP capability. The software needed to sup-port the new student project would be, in principle,easy to modify from the original Theremin code(covered in our past articles) already running using

THE MAGAZINE FOR COMPUTER APPLICATIONS

Tackle Data Acquisition

DSPAlgorithms

Othertasks

Co-operativescheduler

RevisedTheremin system

Possiblefuture extensions

Videomanipulationin time with

sounds

Sensor calibration through

pushbuttons

“Music with a beat”

audio stream

TAOS TSL230RLight sensor

andADI ADXL213accelerometer

to controlTheremin audio

frequencyand volume

Thereminaudio channel

Beat outputaudio channel

Blackfin evaluation board ADSP-BF533

Jeff
Text Box
Circuit Cellar, the Magazine for Computer Applications. Reprinted by permission. For subscription information, call (860) 875-2199, or visit www.circuitcellar.com. Entire contents copyright ©2009 Circuit Cellar Inc. All rights reserved.
Page 86: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 33

June

2009 –

Issue

227

CIR

CU

ITC

ELLA

R D

IGIT

AL

PLU

S B

ON

US

an operating system based around a co-operative scheduler(see Listing 1).

Switching from controlling the volume of theTheremin using a PWM pulse stream from a light sensorLightSensorVolume() to a PWM pulse stream from anaccelerometer AccelerometerSensorVolume() (Line 11)is essentially a recalibration issue. The old audio taskOutputAudio() requires minor modification (Line 7) tohandle two output channels rather than one. A secondaudio task InputAudioBeat() (Line 8) picks up thenew input audio stream.

Developing the DSP algorithm DSPTasks() (Line 14)to determine the “beats” present in the two audiostreams would be a challenge for a fourth-year univer-sity design team. However, given sufficient time, theteam could make the system work even with theadditional complication of having to smoothly inte-grate the two audio streams together. However, as thesystem state history snapshot shown in Photo 1 indi-cates, there is a serious data acquisition problem tobe overcome. The moment DSPTasks() cuts in (topline), the processor becomes fully occupied with thistask. No other task can now be executed in the co-operative scheduler, so every other task blocks(shown as orange) and the system dies. How do youfit a long DSP task into the operation of a co-opera-tive scheduler that is running many sampling tasksthat need to be serviced at regular 20-µs intervals?

LENGTHY HARDWARE TASKSWe could easily switch back to a preemptive scheduler

to provide a solution. In that case, we’d place the DSP

tasks as part of the loop in main() and let all the audioand measuring tasks performed by the light sensor andaccelerometer be fired off in the background as part of anumber of interrupt service routines, or ISRs (see Listing 2).

However, Lizie and I didn’t think constructing thisproject was about making the “eerie Theremin music”that was so attractive to the fourth-year project team. Forus, it had more to do with rediscovering the advantagesof designing embedded systems with “highly predictable

PPhhoottoo 11——The moment that the DSPTasks() task starts to execute, all theother tasks start to block (shown in orange). When the DSPTask() com-pletes execution, all the blocked tasks start to “play catch-up” and executewith every scheduler tick rather than at their proper times. This would firstblock and then distort the audio signal.

LLiissttiinngg 11——The scheduler code for the revised Theremin musical instrument requires that two existing tasks will need minor modification(ModifiedOutputAudio() and AccelerometerSensorVolume()), and two new tasks need to be added (InputAudioBeat() andDSPTasks()).

1 #include "./Theremin.h"23 int main(void) {4 TTCOS_Init(TICK_TIME_IS_10us);5 InitHardware( );67 TTCOS_AddTask(ModifiedOutputAudio, NO_DELAY, EVERY_2_TICKS); /**** MODIFIED ****/8 TTCOS_AddTask(InputAudioBeat, NO_DELAY, EVERY_2_TICKS); /**** NEW TASK ****/910 TTCOS_AddTask(LightSensorFrequency, ONE_TICK_DELAY, EVERY_10_TICKS); 11 TTCOS_AddTask(AccelerometerSensorVolume, THREE_TICK_DELAY, EVERY_10_TICKS); /**** MODIFIED ****/1213 TTCOS_AddTask(AdjustParameters, FIVE_TICK_DELAY, EVERY_MS); 14 TTCOS_AddTask(DSPTasks, 10, 2 * EVERY_MS); /**** NEW TASK ****/15 TTCOS_AddTask(AdjustLightSensitivity, SEVEN_TICK_DELAY, EVERY_TENTH_SECOND);1617 TTCOS_Start(); 1819 while (1) { // Wait, in low power mode, for an interrupt20 TTCOS_GoToSleep( ); // The interrupt service routine calls TTCOS_Update( )2122 // Run all the tasks in the system according23 TTCOS_DispatchTasks( ); // to whether their delays have expired24 }2526 return 0; // Make compiler happy27 }

Page 87: Circuit Cellar 2009-06

44 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

CIR

CU

ITC

ELLA

R D

IGIT

AL

PLU

S B

ON

US

performance” present when using a co-operative scheduler. In the second article in this series, we described how a

similar problem arose when there were a number ofscheduler tasks being used to determine the frequency ofthe output signals from a light sensor. While the proces-sor was waiting for the changes in the sensor signals,these support hardware tasks prevented the time-criticalaudio output tasks from running. The solution was tobreak the long running task into a large number of short-er tasks that interacted in a co-operative fashion withother tasks.

LENGTHY SOFTWARE TASKSThe original Theremin code design had tasks “wait-

ing” for an external hardware signal to change its state.This required tasks with durations between 10 µs to 30 msdepending on the signal’s frequency. Such a hardware-ori-ented task can be easily broken up into a series of “tiny”tasks (300 ns in duration and a period of 10 µs) that“poll,” rather than “wait” for, the external signalchanges.

Imagine trying the same approach with a lengthy soft-ware-oriented task. For the code in Listing 1 to actuallywork, the capstone project team would have had to writeDSPTasks() as a series of code overlays that wereswapped in and out of memory between the 10-µs timerinterrupts. That sounds like a really practical, time-effi-cient solution!

If this rediscovery of using co-operative schedulers inembedded systems is not to die a sudden death, a numberof things need to be tackled to make the revised Theremindesign work. What code development process will make itpossible to simultaneously service a number of highlytime-critical “fast” data acquisition tasks without thesetasks being blocked by an equally important (but long-run-ning) DSPTasks() routine?

There are now multiple tasks that interact with eachother. How do you modify the operation of a co-operativescheduler to ensure that you can recover from one of thetasks failing? Sure, the Theremin does not need to meetsafety-critical requirements, but we would like to be able

to continue in a default mode if a cable is temporarilydisconnected.

FIND TIME FOR DSPExecuting a “long DSP task” using a co-operative sched-

uler is obviously a pretty standard thing to do. Rather thanreinvent the wheel, we went back to Michael Pont’s Pat-terns for Time-Triggered Systems (2001) to see what he sug-gests to handle these issues. (The book is available for freeat www.tte-systems.com/books.) He recommends twoapproaches. The first is to avoid frequent software polling.The second is to allow the scheduler to execute a single“preemptive task.”

Consider hardware polling. Currently, the LightSen-sorFrequency() task examines (polls) the input light sen-sor signal by monitoring a general-purpose I/O (GPIO) pin.Each signal transition causes the task either to movebetween one of four states (HIGH1, LOW1, HIGH2, or

LLiissttiinngg 33——Code that “waits” for a hardware event to occur willblock other tasks in a co-operative scheduler. The blocking disap-pears if the code “polls” the hardware to see if an event hasoccurred, but absolute accuracy is lost.

enum {HIGH1, LOW1, HIGH2, LOW2};void LightSensorTask( ) {// Set system state the first time this task runs

static int currentState = HIGH1; int newState = currentState;

// Determine level of sensor input// either HIGH or LOW

int pinState = GPIOPin( );

switch (currentState){ // SOFTWARE poll// Find leading edge of the pulse

case HIGH1: // Test for sensor going lowif (pinState == LOW) newState = LOW1;

break;

case LOW1: // Test for sensor going highif (pinState == HIGH) {

newState = HIGH2;time1 = CurrentTime( );

}break;

// Find leading edge of the next pulsecase HIGH2: // Test for sensor going lowif (pinState == LOW)

newState = LOW2; break;

case LOW2: // Test for sensor going highif (pinState == HIGH) {

newState = HIGH1;sensorPeriod = CurrentTime() – time1;

}break;

}

// Update the task statecurrentState = newState;

}

LLiissttiinngg 22——The code for a pre-emptive scheduler involves a low-priority task running within a while() loop in main() with high-er priority tasks running as part of the interrupt service routine.

int main(void) {SetupInterrupts( );ActivateInterrupts( );while (1) {DSPTask( );

}}

EX_INTERRUPT_HANDLER(EverythingISR) {AcknowledgeInterrupt( );AudioInput( );AudioOutput( );etc.

}

Page 88: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 55

June

2009 –

Issue

227

CIR

CU

ITC

ELLA

R D

IGIT

AL

PLU

S B

ON

US

one for monitoring the light sensor signal (frequency con-trol), and an extra one for a future feature. However,switching from software polling to hardware polling doesnot really solve anything. There are still the frequent (10 µs)tasks needed to handle the audio input and output sam-ples, and these will still be prevented from running byDSPTasks(). To solve this problem, Pont suggests makinga minor modification to the co-operative scheduler’s ISR toallow two types of scheduler tasks.

Standard co-operative tasks (Listing 5, Lines 24 to 29) arerun by TTCOS_DispatchTasks(), which is part of theTheremin’s main loop (Line 37). These “standard tasks”can be interrupted by a single “preemptive task” (Line 22)that is set up to run as part of the co-operative scheduler’sISR (Listing 6, Lines 60 to 68).

The audio manipulation tasks involve moving one ortwo words to and from the Blackfin’s audio CODECs, sothey take very few processor cycles. Thus, moving all thesetasks into a single preemptive task should have negligibleimpact on the overall performance of the system.

Thus, the short PreEmptiveTask() will meet therestrictions on the preemptive task used in a co-operativescheduler—restrictions that are stronger than those placedon the tasks (threads) present in a pre-emptive scheduler.There must be only one preemptive task in order to main-tain the predictability of the co-operative scheduler. It isnot necessary that the preemptive task be executed everytime the timer interrupt occurs. However, it must be guar-anteed that the preemptive task will complete in a shortertimer than that of the scheduler’s timer interrupt.

The Theremin preemptive audio manipulation task willprobably meet these requirements without any re-coding.However, given the expected small size of these tasks(Listing 5, Lines 1 to 14), attempts to inline this task tofurther improve system performance is unlikely to causeany significant code bloat that would over tax the embed-ded system’s memory.

Permitting this single preemptive task has given back tothe co-operative scheduler much of the flexibility present inhandling tasks with a preemptive scheduler. However, thetotal predictability of the co-operative scheduler is retained.

RECOVERY FROM SOFT ERRORS In a typical embedded project, minor data acquisition

errors could be easily introduced by a sensor signal disap-pearing as a cable is temporarily unplugged. In this situa-tion, we want to make a soft recovery. For example, if thevolume sensor has been temporarily removed, then wewant to set the system to a safe volume. When the signalreappears, the system should automatically resume normaloperation. This situation can be handled by introducingsoftware watchdog code that permits a soft system recov-ery. This is illustrated in Listing 7, where the LightSen-sorFrequency() task code has been modified to preventthe system from having conniptions. This means the codewill not produce unbearable high-pitched sounds if thelight sensor becomes unplugged.

The SOFTWATCHDOG_SETUP macro (Line 84) establishes a

LOW2) or to return from the task and free up the processorfor other tasks to run.

The software polling task needs to be executed at 100-µsintervals to ensure that the frequency is determined with ahigh enough accuracy to ensure that the Theremin doesnot produce sour notes (see Listing 3). As an alternative toperforming frequent software polling, we could set up theprocessor for hardware polling. This approach requirespolling the done flag of a general-purpose timer set to mon-itor the PWM stream via a pulse-width count and capturemode. In this mode, the timer automatically watches forthe beginning and end of the light sensor pulse and recordsthe elapsed time in its PERIOD register (see Listing 4).

Switching from software polling to hardware pollingusing the general-purpose timer offers a number of advan-tages. First, we have switched from a frequent time-criticaltask to an infrequent non-time-critical task. The time con-straint on the duration of DSPTasks() has shifted fromhundreds of microseconds to tens or hundreds of millisec-onds. That’s a load of cycles on the DSP-capable Blackfinprocessor.

The second advantage is that we are getting much higherprecision time measurements of the sensor signals, eventhough we are performing less frequent time-measuring tasks.In this Theremin application, poor timing accuracy is bestavoided as it translates into terrible tonal quality of the music!

PERMIT A PREEMPTIVE TASKA Blackfin ADSP-BF533 processor has three general-pur-

pose timers that can be used in the Theremin project: onefor monitoring the accelerometer signal (volume control),

LLiissttiinngg 44——Off-loading the measurement of a signal to a timer in“captured pulse period mode” both increases timing accuracy andreducse overall processor load.

enum {CAPTURE_NOT_COMPLETE, PERIOD_CAPTURED}

void LightSensorFrequency( ) {

static int currentState = CAPTURE_NOT_COMPLETE;int newState = currentState;

// Check if timer has captured pulse periodint timerState = TimerCountDone( );switch (currentState) { // HARDWARE poll

case CAPTURE_NOT_COMPLETE: // Measuring completed?

if (timerState == DONE)newState = PERIOD_CAPTURED;

break;

case PERIOD_CAPTURED: // Read Timer period register

sensorPeriod =*pPERIOD;ResetTimer( );newState = CAPTURE_NOT_COMPLETE;

break;}

// Update the task statecurrentState = newState;

}

Page 89: Circuit Cellar 2009-06

66 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

CIR

CU

ITC

ELLA

R D

IGIT

AL

PLU

S B

ON

US

for adding a software watchdog timerto any data acquisition task in thesystem.

RECOVERY FROM HARD ERRORSA major error might occur if one co-

operative scheduler is being driven asa slave by an interrupt signal from asecond processor (shared clock sched-uling). Suppose the master processorsuffers a hard error so that the sharedinterrupt signals stop arriving. Theslave co-operative scheduler will com-plete its current task and then “hang.”In this situation, we must be able toactivate a “back-up” interrupt thatwould allow the slave co-operativescheduler to run tasks and put the sys-tem into a safe or shutdown mode.

number of static variables. In thisexample, the software watchdog time-out condition is set to be a QUAR-TER_SECOND, and the watchdog isdirected to record LIGHTSENSOR_ERRtype errors. Finally, the system isinstructed to move on to recoverytask state RECOVERY (Line 102,which in this case leaves the noteunchanged) if the software watchdogever times out because the task can’tbe completed.

Upon a watchdog timeout, theerror condition is recorded in theglobal errorRecorder variable, thetask is directed to move to therecoveryState, and the watchdogtimer is reset. See Listing 8 formacro details.

In Line 79, the task’s state variableis initialized so that the first timethe task is run it will immediatelycall the new FEED_SOFTWATCHDOGcase statement (Line 87). There themacro SOFTWATCHDOG_HANDLER (seeListing 8) resets the software watch-dog and causes a move to theNOT_READY state, which was theoriginalFirstTaskState for theLightSensorFrequency task.

The final state in the original task(Line 99) is now directed to callFEED_SOFTWATCHDOG to reset thewatchdog timer each time the taskhas run to completion. This intuitiveapproach of initializing a softwaretimer and adding a newFEED_WATCHDOG case is applicable

LLiissttiinngg 55——Combining a preemptive task (Line 24) with hardware polling (Lines 26 and 27) removes the need for the signal manipulationcode DSPTasks() to meet very strict time constraints.

1 #pragma always_inline2 inline void ModifiedOutputAudio( ) {3 // Unchanged Task Code;4 }56 #pragma always_inline7 inline void InputAudioBeat( ) {8 // Unchanged Task Code;9 }1011 void PreEmptiveTask(void) {12 ModifiedOutputAudio( );13 InputAudioBeat( );14 }1516 int main(void) {17 int maxNumberTasks = 7;1819 TTCOS_Init(TICK_TIME_IS_10us);20 InitHardware( );2122 TTCOS_AddPreEmptiveTask(PreEmptiveTask, NO_DELAY, EVERY_2_TICKS); /**** NEW TASK ****/2324 TTCOS_AddTask(LightSensorFrequency, ONE_TICK_DELAY, EVERY_10_MS); /**** HARDWARE TASK ****/252627 TTCOS_AddTask(AccelerometerSensorVolume, THREE_TICK_DELAY, EVERY_10_MS; /**** HARDWARE TASK ****/28 TTCOS_AddTask(AdjustParameters, FIVE_TICK_DELAY, EVERY_MS); 29 TTCOS_AddTask(DSPTasks, 10, 2 * EVERY_MS);30 TTCOS_AddTask(AdjustLightSensitivity, SEVEN_TICK_DELAY, EVERY_TENTH_SECOND);3132 TTCOS_Start(maxNumberTasks); 33 while (1) // Wait, in low power mode, for an interrupt34 TTCOS_GoToSleep( ); // The interrupt service routine calls TTCOS_Update( )3536 // Run all the tasks in the system according37 TTCOS_DispatchTasks( ); // to whether their delays have expired38 }3940 return 0; // Make compiler happy41 }

Page 90: Circuit Cellar 2009-06

www.circuitcellar.com • CIRCUIT CELLAR® 77

June

2009 –

Issue

227

CIR

CU

ITC

ELLA

R D

IGIT

AL

PLU

S B

ON

US

LLiissttiinngg 66——Many of the issues with using a co-operative scheduler with “long” software tasks vanish if support for a single “short-duration”preemptive task is added to the co-operative scheduler’s interrupt service routine.

43 EX_INTERRUPT_HANDLER(TTCOS_Interrupt) { // Only ISR operative in the co-operative scheduler44 Acknowledge_TTCOSInterrupt( );45 TTCOS_Update( ); // Update the Run-Me-Now variables for each task46 }4748 void TTCOS_Update(void) { // Part of scheduler interrupt service routine49 int taskIndex;5051 for(taskIndex = 0; taskIndex < NUMBERTASKS; taskIndex++) {52 if (Tasks[taskIndex].pointerToTask != DOLIST_ENTRY_EMPTY) { // Is there a valid task in the todoList?5354 if (Tasks[taskIndex].taskDelay != 0) // If taskDelay is non-zero then task is not ready to be run55 Tasks[taskIndex].taskDelay--; // simply decrement the remaining delay time5657 else { // If the task is READY_TO_RUN58 Tasks[taskIndex].RunMeNow++; // then increment the RunMeNow flag5960 // New code to handle a pre-emptive task61 if (Tasks[taskIndex].pre_emptiveTask == true) { // Check to see if pre-emptive task62 (*Tasks[taskIndex].pointerToTask)( ) // If pre-emptive task then run the task63 Tasks[taskIndex].RunMeNow--; // and decrement the RunMeNow flag6465 // Remove 'RUN_ONCE' pre-emptive tasks from todoList66 if (Tasks[taskIndex].taskPeriod == RUN_ONCE)67 TTCOS_DeleteTask(taskIndex);68 }6970 if (Tasks[taskIndex].taskPeriod != RUN_ONCE) // Prepare periodic tasks to run again71 Tasks[taskIndex].taskDelay = Tasks[taskIndex].taskPeriod - 1;72 }73 }74 }75 }

LLiissttiinngg 77——The use of a several global defined macros makes it straightforward to add software watchdog capability to each task.

76 enum {CAPTURE_NOT_COMPLETE, PERIOD_CAPTURED, SOFTWATCHDOG_STATES}; /** CHANGED **/7778 void LightSensorFrequency(void) { 79 static int currentState = FEED_SOFTWATCHDOG; /** CHANGED **/80 int newState = currentState;81 int timerState = TimerCountDone( );8283 // Indicate software watch dog timeout, error code, and recovery state84 SOFTWATCHDOG_SETUP(QUARTER_SECOND, LIGHTSENSOR_ERR, RECOVERY); /*** NEW ***/8586 switch (currentState) {87 case FEED_SOFTWATCHDOG: /**** NEW ***/88 SOFTWATCHDOG_HANDLER(CAPTURE_NOT_COMPLETE); /* Next state used after feeding complete */89 break;9091 case CAPTURE_NOT_COMPLETE: /* Check if hardware counting complete */92 if (timerState == DONE) 93 newState = PERIOD_CAPTURED; 94 break;9596 case PERIOD_CAPTURED: 97 sensorPeriod = ReadTimerCounter( );98 ResetTimer( );99 newState = FEED_SOFTWATCHDOG; /** CHANGED **/100 break;101102 case RECOVERY: /**** NEW ***/103 DoRecovery( );104 newState = CAPTURE_NOT_COMPLETE;105 break;106 }107108 currentState = newState; // Update the task state109 }

Page 91: Circuit Cellar 2009-06

88 CIRCUIT CELLAR® • www.circuitcellar.com

June

2009 –

Issue

227

CIR

CU

ITC

ELLA

R D

IGIT

AL

PLU

S B

ON

US

This is can be handled by activating a hardware watch-dog timer and adding a FeedHardwareWatchTimer() task tothe system’s to-do list. Provided the shared interrupt keepsarriving, the co-operative scheduler would be able to run Feed-HardwareWatchTimer(), which ensures that the watchdogtimer interrupt does not occur. If the external signal stops,then the watchdog timer interrupts start occurring and canbe used to allow the co-operative scheduler to produce a sys-tem-safe condition.

THE NEXT DESIGN PROBLEMIn this article, we have looked at how to allow a co-oper-

ative scheduler to recover from hard and soft data acquisi-tion issues—missing interrupts or external sensor signals.We have also shown that using hardware, rather than soft-ware, polling, combined with a single pre-emptive task,gives the co-operative scheduler a great deal of flexibility.

The capstone design project team has indicated that theyplan to prototype their system by pairing the Theremin musicstream with a recording of a snare drum. The repetitive beat inthe snare drum music should be identifiable by using a corre-lation algorithm. They will then use this beat time, and a

sample of the beat note itself, to establish a new musicstream whose tempo can be manipulated (see Figure 2).

It sounds like they will need to use multiple bufferingtechniques where they gather audio signals into one buffer,process a second, and place the DSP results into a thirdbuffer, while outputting previous calculations from a fourth.That means they will need the Blackfin’s direct memoryaccess (DMA) capability to move the large amount of audiodata stored in the evaluation board’s external memoryinto the core for processing while not disrupting thebasic DSPTasks() operation. How all this is handled with-in a co-operative scheduler environment might be the subjectof a future DSP-related article that the team submits. I

LLiissttiinngg 88——These macros provide the functionality to place a software watch timer inside every task to ensure that the lack of an input signaldoes not cause the system to end up in an unsafe state. The variable errorRecorder uses a bit to signify errors associated with eachindividual task. Errors can be identified and a recovery procedure initiated as part of the preemptive task that is run at every tick of thescheduler.

52 #define SOFTWATCHDOG_STATES FEED_SOFTWATCHDOG = 0x70000000, NO_ERROR5354 #define SOFTWATCHDOG_SETUP(timeOut,taskErrorBit,recoveryState) \55 static unsigned int watchDogReset = timeOut;\56 static unsigned int watchDogTimeOut = 0xFFFFFFFF; /* Avoid immediate time out */\57 \58 if (CurrentTime( ) > watchDogTimeOut) {\59 errorRecorder |= (1 << taskErrorBit);\60 currentState = recoveryState;\61 watchDogTimeOut = CurrentTime( ) + watchDogReset;\62 }6364 #define SOFTWATCHDOG_HANDLER(originalFirstTaskState) \65 currentState = originalFirstTaskState;\66 watchDogTimeOut = CurrentTime( ) + watchDogReset;6768 // Each software watchdog error sets an error bit in the errorRecorder variable69 enum {LIGHTSENSOR_ERR, ACCELEROMETER_ERR /* .etc... */};

Beat period

Beat sample

Beat period

Update

Update

Reload

Beat audio stream

Attack anddecay

information

Count downto output of next beatsample

Correlationalgorithm

Correlationalgorithm

“Music with a beat”

audio stream

Thereminaudio stream

Thereminaudio stream

FFiigguurree 22——This is the proposed “adaptive drum tempo” DSP algorithm.

Mike Smith ([email protected]) has been contributing toCircuit Cellar since the 1980s. He is a professor in computerengineering at the Schulich School of Engineering, University ofCalgary, Canada. Mike’s main interests are developing new bio-medical engineering algorithms and moving them onto multicoreand multiple-processor embedded systems in a systematic andreliable fashion. He recently became a convert to the applicationof Agile Methodologies in the embedded environment. Mention“test-driven development” and his eyes light up. In 2008, Mikehad his Analog Devices University Ambassadorship renewed forthe eighth straight year.

Lizie Dunling-Smith is a fourth-year undergraduate student at theUniversity of Alberta, Canada. She will graduate in 2009 with aB.Sc. in engineering physics, specializing in electrical engineering.

OURCESADSP-BF533 Blackfin processor and ADXL213accelerometerAnalog Devices, Inc. | www.analog.com

TTSL230R SensorsTAOS, Inc. | www.taosinc.com

SS