Circuit Cellar 215 - June 2008

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 100

CIRCUIT CELLAR

High-Current Wiring, Safety, & Fusing p. 30 • Crystal Oscillators Explained p. 70 • New Touch Sensor Gadgetry p. 78
www.circuitcellar.com

THE MAGAZINE FOR COMPUTER A P P L I C AT I O N S


#215 June 2008

COMMUNICATIONS
Build A Call-Monitoring Device
Coding Techniques For An
Interactive System
A Design For Decoding AIS
Transmissions
Simple Human-To-Circuit
Communication
Implement A Ray Tracer
On An FPGA
A Drive System For
Pump Control

0 6>

7 25274 75349 9
$4.95 U.S. ($5.95 Canada)
SERIAL TO ETHERNET SOLUTIONS
Simple Ethernet connectivity
for serial devices
Works out of the box -
no programming is required
Device P/N: SB70-100CR Customize to suit any
Kit P/N: NNDK-SB70-KIT
application with low-cost

$69 SB70 development kit

2-port serial-to-Ethernet server Features:


Qty. 100
with TTL support 10/100 Ethernet
TCP/UDP mode
DHCP/Static IP Support
Data rates up to 921.6kbps
Web-based configuration

Need a custom solution?


NetBurner Serial to Ethernet
Development Kits are available
Device P/N: SB72-EX-100CR to customize any aspect of
Kit P/N: NNDK-SB72EX-KIT operation including web pages,

SB72EX $139
data filtering, or custom network
applications. All kits include
2-port serial-to-Ethernet server platform hardware, ANSI C/C++
Qty. 100 compiler, TCP/IP stack, web server,
with RS-232 & RS-485/422 support
e-mail protocols, RTOS, flash file
system, Eclipse IDE, debugger,
cables and power supply.

Device P/N: PK70EX-232CR


Kit P/N: NNDK-PK70EX232-KIT
Information and Sales | sales@netburner.com
Web | www.netburner.com

$269 PK70EX232 Telephone | 1-800-695-6828

4-port serial-to-Ethernet server


Qty. 100
with RS-232 support
New from Pico Technology
the Market Leader in USB PC oscilloscopes

417
U-VERSION VFD
Drop-in Replacement for LCD Modules
The new family of U-Version modules is compact, low power and lower in cost with a

custom designed chip. This new VFD technology has an 8 and 4 bit parallel interface

and enables the replacement of LCD's with Noritake U-Version VFD modules.

LCD

VFD

UPGRADE Brightest Display


NOW... Widest Viewing Angles
Widest Temperature Range
Fits Right In
No Programming Change
Low Cost

www.noritake-elec.com/53
Noritake Co., Inc. 2635 Clearbrook Dr., Arlington Heights, IL 60005 phone 1-800-779-5846 e-mail electronics@noritake.com
TASK MANAGER
Communications Hub FOUNDER/EDITORIAL DIRECTOR CHIEF FINANCIAL OFFICER

I n its early days, Circuit Cellar was known as the essential monthly print maga-
zine for computer applications. By the late-1990s, it was known as the essential
Steve Ciarcia
MANAGING EDITOR
Jeannette Ciarcia
MEDIA CONSULTANT
C. J. Abate Dan Rodrigues
monthly print magazine that also offered some useful online content. Today, the WEST COAST EDITOR CUSTOMER SERVICE
name “Circuit Cellar” has various meanings to different people. This was clear in Tom Cantrell Debbie Lavoie
April when I spoke with readers, authors, and advertisers at the Embedded CONTRIBUTING EDITORS CONTROLLER
Systems Conference in San Jose, California. Jeff Bachiochi Jeff Yanco
For some, the name simply meant the interesting print magazine started by Ingo Cyliax
Robert Lacoste ART DIRECTOR
Steve Ciarcia in 1988. For others, it meant the easy-to-navigate, downloadable George Martin KC Prescott
Electronic Edition (EE). Other conference-goers regarded Circuit Cellar as the Ed Nisley GRAPHIC DESIGNERS
company that runs design contests and puts new design kits in the hands of eager NEW PRODUCTS EDITOR Grace Chen
John Gorsky Carey Penney
engineers. Others still referred to Circuit Cellar as the name of the website that
publishes viewable articles, projects, code files, and highly trafficked online forum PROJECT EDITORS STAFF ENGINEER
Gary Bodley John Gorsky
discussions.
Ken Davidson
To each his own, but I like to put it this way: Circuit Cellar is the hub of com-
David Tweed
munication for the entire embedded engineering community. Running this hub
ASSOCIATE EDITOR
is a rewarding yet challenging task for our staff. During the last several months, Jesse Smolin
we’ve found ourselves developing new website- and email-based initiatives for
delivering fresh content and useful reminders to our readers on a more fre-
quent basis. Why? Recently, we’ve learned (via surveys, etc.) that our readers
ADVERTISING
860.875.2199 • Fax: 860.871.0411 • www.circuitcellar.com/advertise
require more information—about projects, code, and parts—more regularly
PUBLISHER
than once a month. They also need to be able to easily share this information Sean Donnelly
with their peers and colleagues. Direct: 860.872.3064, Cell: 860.930.4326, E-mail: sean@circuitcellar.com
A decade ago, most engineers would slowly read each issue and then mail off ADVERTISING REPRESENTATIVE
their ideas to authors, staff members, and other designers at a leisurely pace. But Shannon Barraclough
Direct: 860.872.3064, E-mail: shannon@circuitcellar.com
things are much different in today’s need-it-now culture. So, we’ve been success-
fully adapting our various delivery systems for disseminating Circuit Cellar-quality ADVERTISING COORDINATOR
Valerie Luster
content about embedded technologies. We publish in-depth articles via our print E-mail: val.luster@circuitcellar.com
magazine, EE, and website. Our EE and online articles link to code files, manu-
facturer websites, and author websites, as well as to other useful content found
Cover photography by Chris Rakoczy—Rakoczy Photography
at Circuitcellar.com. The forums on our site foster active discussions between www.rakoczyphoto.com
designers from around the world. A new feature on our site is the “SHARE” button, PRINTED IN THE UNITED STATES
which enables readers to share articles (and ideas about them) by linking to con-
CONTACTS
tent-sharing websites, blogs, and more. We will continue developing these prod- SUBSCRIPTIONS
ucts and features because we believe that ease of communication is key to keep- Information: www.circuitcellar.com/subscribe, E-mail: subscribe@circuitcellar.com
Subscribe: 800.269.6301, www.circuitcellar.com/subscribe, Circuit Cellar Subscriptions, P.O. Box 5650,
ing our readers informed and interested in communicating their ideas with others. Hanover, NH 03755-5650
As managing editor, I strongly encourage you to depart from and return to Address Changes/Problems: E-mail: subscribe@circuitcellar.com
GENERAL INFORMATION
Circuit Cellar—the hub of communication for the embedded engineering com- 860.875.2199, Fax: 860.871.0411, E-mail: info@circuitcellar.com
Editorial Office: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: editor@circuitcellar.com
munity—during your future design journeys. The following authors did just that. New Products: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: newproducts@circuitcellar.com
On page 14, Peter Csaszar and Monica Flores describe their PIC18F4520- AUTHORIZED REPRINTS INFORMATION
860.875.2199, E-mail: reprints@circuitcellar.com
based voicemail monitoring system. In “Pump Control,” Richard Wotiz describes AUTHORS
his award-winning spa pump controller system (p. 20). Turn to page 30 for Ed Authors’ e-mail addresses (when available) are included at the end of each article.

Nisley’s description of how to connect circuitry directly to an AC power line. On


CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) is published monthly by Circuit Cellar
page 36, Scott Bingham and Yunfan Donald Zhang describe how they imple- Incorporated, 4 Park Street, Vernon, CT 06066. Periodical rates paid at Vernon, CT and additional offices. One-year (12 issues)
mented a ray tracer on an FPGA.You’ll enjoy Peter Baston’s article if you want to 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 in
build a system for receiving and decoding data transmissions (p. 46). On page 54, U.S. funds only via Visa, MasterCard, international postal money order, or check drawn on U.S. bank. Direct subscription orders
and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 or call
Andrew March describes an MCU-based, dot-matrix game that he programmed 800.269.6301.
in C. Turn to page 62 for Jeff Bachiochi’s article about replacing an old doorbell Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650.

switch with a capacitive touch pad. For information about crystals, turn to page Circuit Cellar® makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for the
consequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of read-
70, where Robert Lacoste explains the difference between “series” and “parallel” er-assembled projects, Circuit Cellar® disclaims any responsibility for the safe and proper function of reader-assembled projects based upon or
from plans, descriptions, or information published by Circuit Cellar®.
crystals, and more. Finally, on page 78, Tom Cantrell introduces new touch sen- The information provided by Circuit Cellar® is for educational purposes. Circuit Cellar® makes no claims or warrants that readers have a right to
build things based upon these ideas under patent or other relevant intellectual property law in their jurisdiction, or that readers have a right to
sors from Cypress Semiconductor and Silicon Laboratories. construct 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 © 2008 by Circuit Cellar, Incorporated. All rights reserved. Circuit Cellar is a registered trademark of Circuit Cellar, Inc.
cj@circuitcellar.com Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.

4 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


June 2008: Communications
FEATURES
14 Message Acquisition 36 Ray Tracing Made Simple
Ring Signal Detection And Interpretation A Ray Tracer Implemented On An FPGA
Peter Csaszar & Monica Flores Scott Bingham & Yunfan Donald Zhang
20 Pump Control 46 AIS Transmission Decoding
Build A Variable-Speed Drive For Motors Peter Baston
Richard Wotiz
54 MCU-Based Game System
First Place Microchip 2007 Design Contest
A Dot-Matrix Game That Targets C Coding Efficiency
Andrew March
Ring Signal Detection System (p. 14)
AIS Decoding & Vessel Tracking (p. 46)

COLUMNS
30 ABOVE THE GROUND PLANE 70 THE DARKER SIDE
Resistance Soldering Let’s Be Crystal Clear
Ed Nisley Robert Lacoste
62 FROM THE BENCH 78 SILICON UPDATE
Self-Destructive Behavior Touch Me
Processor Action Requires Power Supply Removal Tom Cantrell
Jeff Bachiochi
New Touch Sense Technology (p. 78)

The “Magical”World Of Crystal Oscillators (p. 70)

DEPARTMENTS
4 TASK MANAGER 94 INDEX OF ADVERTISERS
Communications Hub July Preview
C. J. Abate
96 PRIORITY INTERRUPT
8 NEW PRODUCT NEWS It’s All In The Whiskers
edited by John Gorsky Steve Ciarcia

93 CROSSWORD

6 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


Edited by John Gorsky
NEW PRODUCT NEWS Visit www.circuitcellar.com/npn
for more New Product News.

LOW-POWER WIRELESS CONNECTIVITY STARTER KIT


The JN5139-EK020 IEEE802.15.4/JenNet Starter Kit allows developers with little or no wireless experience to develop
wireless products. The kit simplifies the evaluation and application development of low-power wireless connectivity prod-
ucts using the robust and reliable JenNet networking stack. The Starter Kit provides the flexibility to develop wireless
capability by using JN5139 microcontrollers and modules as wireless processors or coprocessors.
Each node includes a module, which integrates a JN5139 wireless microcontroller, and an antenna. Operating in the
license-free ISM band at 2.4 GHz, the modules have worldwide RF approval and provide a seamless route from concept-
proving and easy application development using the evaluation kits to prototyping and volume production using either
the ICs or modules.
The JenNet stack provides a powerful higher-layer networking solution based on the IEEE802.15.4 standard. It imple-
ments networks ranging from simple point-to-point
systems to large tree or linear networks of devices.
The Jenie and AT-Jenie programmer interfaces sim-
plify access to the commands for building and run-
ning the network, de-skilling the task of designing
the network, and allows developers to concentrate
on designing their applications.
Developers also have free access to a full and
unlimited SDK, which uses the Code::Blocks IDE
with a GNU-based compiler and linker. This pro-
vides a complete development environment and
eliminates the need to purchase additional develop-
ment tools. The AT-Jenie serial interface and Jenie
C programmer’s API are accessed through the SDK
to simplify the design of the application software.
The JN5139-EK020 IEEE802.15.4/JenNet Starter
Kit costs $219.

Jennic
www.jennic.com

EMBEDDED MODULE BASED ON ATOM PROCESSOR


The Catalyst Module combines the Atom processor Z500 companies or a third party create the carrier card to
series and a US15W system controller hub. accompany the Catalyst Module. A full-function carrier
The Catalyst Module, with a system-level power draw board in a Catalyst Module development system is
below 5 W, brings Intel architecture-compatible capabilities available that manufacturers can use to develop their
to applications for low-power environments, so devices can application early in the process.
be enclosed, without fans or heatsinks, while still supporting The Catalyst Module starts at around $300.
the latest multimedia, positioning, and networking capabili-
ties in portable, battery-operated, handheld devices. Building Eurotech, Inc.
on the Catalyst Module platform, manufacturers can build www.eurotech.com
applications in the entertainment, gaming, defense,
medical, and control industries.
With the Intel Atom processor, device manufac-
turers choose from several operating systems, even
bringing desktop operating systems to handheld
units for mobile workers or end users. Microsoft
Windows applications such as XP, XP Embedded,
Vista, and CE extend the OS options manufacturers
can use for their applications. In addition, Linux is
fully supported. Select real-time OS options can be
supported as required.
The computer-on-module design enables manufac-
turers to get to market quickly by separating the
processor module from the I/O carrier card. Manufac-
turers have the flexibility to have Eurotech member

8 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


NEW PRODUCT NEWS
FULLY PROGRAMMABLE SECURE INTERNET SOLUTION FOR M2M APPLICATIONS
The IIEVB-PIC-2128-110/220 evaluation board brings application from network attacks. The CO2128 supports
together the CO2128 iChip and the PIC24FJ64GA006 LAN, Wi-Fi, and all types of dial-up/wireless modems.
microcontroller for application control and secure, reliable The CO2128 includes a fully secure TCP/IP stack, plus
TCP/IP connectivity to LAN and GPRS networks. The upper-layer protocols such as SMTP, POP3, MIME,
marriage of these two devices offers an attractive option to HTTP, WAP, FTP, and TELNET. It includes an integrated
system architects needing to develop and manage an open web server for easy application management.
and flexible Internet-enabled application. With the CO2128, developers can take advantage of 10
Using the evaluation board, developers can quickly and simultaneous TCP/UDP sockets; two listening sockets;
easily develop an IP-enabled embedded system where the SMTP, MIME, POP3, FTP, Telnet, and HTTP/HTTPs
application resides on the PIC24 MCU and the networking clients; a web server with a web site for the application
and security are provided by the and one for configuring the
CO2128 iChip. Working togeth- iChipSec CO2128; and SerialNet
er, the chips offer a significant mode for serial-to-IP bridging.
value proposition for developers Secure Socket iWi-Fi supports
featuring a secure architecture 64-/128-bit WEP encryption,
where all connectivity features WPA1 and WPA2 Wi-Fi encryp-
are isolated from the application. tion, AES-128/256, SHA-
The flexible MPLAB IDE along 128/192/256, 3DES, the
with Connect One’s black-box SSL3/TLS1 protocol for a
solution, where the application secure client socket session,
requests connectivity and securi- and a secure FTP session.
ty services from the iChip via The IIEVB-PIC-2128-110/220
the AT+i command set, greatly evaluation board costs $149.
reduce design time.
The CO2128 also acts as a Connect One
firewall-in-a-chip, protecting the www.connectone.com

Online Training for Microchip


PIC® Microcontrollers
8 Week Online Course
Learn at your own pace with confidence!

Next Class Starts


June 23!
Uses EasyPIC5 Development Board!
Accepts a wide range of PIC®
processors and is used in follow-on
courses! Great for Development!

We don’t have to brag about our


quality - - - Our former students do!

See Webpage for Course Contents,


Schedule and what former students say!

The Best way to Learn


Interaction with professional
Instructor: Tom Chrane checking
about PIC® Micros!
your Programs & Work!
Engineers, Embedded
Designers, Educators,
Technicians
Avoid lost work days & travel! Applied Micro Training proudly
Course is loaded with Flash Videos incorporates Microchip
that show you how-to for major topics! products in our courses. Visit the
Programming Projects in Assembly Microchip Technology's
Language are used to reinforce all University web site
major topics! 4 Week Grace Period! (www.microchip.com/academic) for
Sample code to get you started! more information.
Lots of Hands-on development with
the EasyPic5 board!

WWW.TOMCHRANE.COM

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 9


NEW PRODUCT NEWS
TOUGH ETHERNET SWITCH
The SEL-2725 is an unmanaged, Ether-
net edge switch and media converter,
with four wired ports and one fiber-optic
port. You can use the SEL-2725 to build
reliable, safe Ethernet networks in elec-
trical substations, generating plants,
industrial plants, and other mission-criti-
cal sites.
Connect the Ethernet ports of up to
four devices in the same cabinet or
panel to an SEL-2725, using Category 5
shielded, twisted-pair (STP) cable. Use
the fiber-optic port with fiber-optic
cable to safely link the SEL-2725 to a
station Ethernet network. It withstands
vibration, electrical surges, electrostatic
discharge, fast transients, and extreme
temperatures. This switch meets or
exceeds IEEE 1613 (Class 2) standards
for communications networking devices
and drops no packets throughout this
rigorous testing.
The SEL-2725 costs $450.

Schweitzer Engineering Laboratories, Inc.


www.selinc.com

SENSOR RESISTS HARSH ENVIRONMENTS TO RELIABLY DETECT OBJECTS


The R-GAGE QT50R is an advanced radar-based sensor for close and long-range presence detection in a broad range
of weather conditions. The QT50R features frequency-modulated technology to accurately monitor or detect objects
while resisting rain, wind, humidity,
and extreme temperatures.
The QT50R uses frequency modu-
lated continuous wave (FMCW) radar
to reliably detect moving or station-
ary cars, trains, trucks, and cargo.
The QT50R detects target objects up
to 15 m away and ignores anything
beyond the setpoint. The IP67-rated
sensor operates at 24 GHz in the
Industrial, Scientific, and Medical
(ISM) telecommunications band, with
no special licensing required.
The QT50R is ideal for outdoor and
challenging environments, making it
well-suited for a wide variety of uses
in locomotive, traffic control, and
many additional applications.
The list price for the QT50R is
$589.

Banner Engineering Corp.


www.bannerengineering.com

10 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


NEW PRODUCT NEWS
ZigBee RADIO MODULE FEATURES CC2430 TRANSCEIVER PLATFORM
The new Matrix module is based on the CC2430 transceiver platform and
joins other Freescale Semiconductor-based modules in providing a fully-integrat-
ed, drop-in ZigBee radio solution.
Designed for low-cost, low-power networks, Matrix modules are ideal for home
and building automation, industrial control, security, and remote sensor applica-
tions. Output power can be configured up to 10 mW, enabling performance to be
optimized for specific applications. Because they’re limited to 10 mW, Matrix
modules are ideal for regions where regulatory agencies limit transmission power.
The module measures just 23 mm × 29 mm, so it requires little real estate. An
integrated antenna helps reduce total system costs, while an integrated ADC
allows direct connection to analog sensors. Modules ship with point-to-point and
point-to-multipoint software, which streamlines development and gets you
quickly to market.
Matrix modules are FCC, IC, and CE certified, eliminating the time-consum-
ing, uncertain, and often costly certification process. Matrix evaluation kits pro-
vide two modules mounted on self-contained interface boards. These boards can
be optionally battery-powered to enable developers to create and test network
connections under real-world environmental conditions. Matrix evaluation soft-
ware is also included in the kits. Its easy-to-use GUI
interface makes it simple to configure the modules’
settings: transmission channel, network ID,
node ID, transmission power, send and receive
packets, and determine packet error rates.
The Matrix module costs $17.95 in 1,000-piece
quantities.

California Eastern Laboratories


www.cel.com

EMBEDDED V2.0 BLUETOOTH SERIAL MODULE


The Parani-ESD1000 is a Class 1-type embedded Bluetooth serial module
designed for embedding Bluetooth connectivity directly onto the circuit boards
of RS-232-based equipment like security systems, POS, industrial machinery,
and medical devices.
It can be connected to the device via a built-in UART interface and communi-
cate with other Bluetooth-enabled devices such as mobile phones, handheld
computers, and laptops.
The Parani-ESD1000 module incorporates a Bluetooth 2.0 protocol stack with
enhanced data rate (EDR) support that offers increased data transfer rates, and
lower power consumption. The ESD1000 now supports data transfer speeds up
to 921.6 kbps. The module supports General access and Serial port profiles. The
dimensions of this module are 1.93″ × 0.9″ × 0.43″.
With no software required, the Parani-ESD1000 is developed for wireless seri-
al communications. Nominal transmit distance is 100 m and can be extended
up to 1 km using the optional patch antenna. The unit can be configured and
controlled by using typical AT comments.
The benefits of integrating Bluetooth wireless capabilities include eliminating
cable installation cost, and reduc-
ing installation and set up, while
adding wireless device monitor-
ing and diagnostics.
The unit with the antenna
option (antenna and cable not
included) costs $45 in 100-piece
quantities.

Lemos International
www.lemosint.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 11


NEW PRODUCT NEWS
ROBUST SMART CARD INTERFACE
The DS8113 is a low-power, low-cost, smart card interface. This device performs level translation between a host
microcontroller and a 5-, 3-, or 1.8-V smart card, while supplying up to 80 mA for smart card operation. The DS8113 fea-
tures the industry’s lowest power stop mode, which allows applications to support smart card communication and draw
only 10 nA while the card is inactive. Addition-
ally, it provides ±8-kV ESD protection, thus pro-
tecting applications from damage during card
insertion and removal. Designed to meet all ISO
7816, EMV(TM), and GSM 11.11 specifications,
this robust smart card interface is ideal for finan-
cial terminals, set-top boxes, and other smart
card reader applications.
The DS8113 is a replacement upgrade for
devices with higher power consumption and no
stop mode, such as the TDA8024 and the
ST8024. This smart card interface allows design-
ers to improve the performance of their applica-
tions with few or no changes to the existing
hardware and relatively minor software modifi-
cations. Available in a lead-free, 28-pin SO pack-
age, the DS8113 operates over the –40° to 85°C
extended temperature range.
Prices start at $0.88 (1,000-up, FOB USA).

Maxim Integrated Products, Inc.


www.maxim-ic.com

NEW TWISTED-PAIR IDC CABLE


These new FFTP and FMTP series of twisted-pair IDC nector on the second end and are RoHS compliant.
cable assemblies provide up to 2.5 times the performance Pricing per pin for a cable assembly (connector plus
of traditional IDC flat cable, but at a lower cost than cable) is $0.20 per contact assembly.
mid-data-rate-flex and high-data-rate coax cables. The dif-
ferentially routed assemblies employ 32-AWG 7/40 Samtec, Inc.
tinned, twisted-pair cable with PVC insulation and the www.samtec.com
high-quality, multi-finger 0.050″ (1.27 mm) pitch Tiger
IDC contact system. This is ideal for high-reliability and
high-mating cycle applications.
The female assembly
(FFTP series) is double-
ended with standard
notch polarization and
mates with standard
0.050″ (1.27 mm)
micro, shrouded, and
ejector headers. The
male assembly (FMTP
series) is available
double-ended or with a
transfer end (socket
has notch polarization)
and mates with stan-
dard 0.050″ (1.27 mm)
low-profile and micro
socket strips.
Both assemblies are
available in a choice of
cable lengths with an
optional reverse con-

12 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


NEW PRODUCT NEWS
LOGIC ANALYZER ADAPTER
The LA-BGA88D-FLASH-PSRAM-01 is a logic analyzer adapter, which allows
high-speed operation, simultaneously enabling memory device analysis used in
PDAs, cell phones, digital cameras, and MP3 players using Tektronix logic ana-
lyzer systems. Features of the adapter include shortest possible trace length for
maximum speed, low inductance, low capacitance, blind and buried via, and
rigid-flex PCB design technology. This adapter is designed to interface with
FBGA packages.
The LA-BGA88D-FLASH-PSRAM-01 adapter consists of two parts. The surface-
mount foot is soldered to the target system board in place of a BGA, 0.8-mm
pitch IC using standard
BGA soldering methods.
The probe board plugs into
the SMT base and employs
a PCB with power planes
to deliver all data, address,
control, and clock signals
to Mictor connectors. The
64-MB flash memory with
a PSRAM chip is surface-
mounted onto the male
BGA adapter, which will
plug into the female BGA
socket soldered to the probe board. A typical IC used with this adapter is the
STMicroelectronics flash memory M36W0R6040T1ZAQF.
The LA-BGA88D-FLASH-PSRAM-01 adapter costs $1,275 in quantities of one
to 10 parts, with a lead time of five days. The component parts are also avail-
able individually.

Ironwood Electronics
www.ironwoodelectronics.com

PINK, PURPLE, AND TURQUOISE LEDs


The new InspirationLEDs—available in pink, purple, and turquoise—add impact,
excitement, and product differentiation to all types of electronics equipment.
Potential applications include home electronics, automotive and appliance dis-
plays, medical equipment, or anywhere soft pastel colors are desired—with the
reliability and low-power consumption of LEDs.
These devices achieve their distinctive colors by starting with state-of-the-art,
high-brightness, InGaN-on-silicon chip technology that provides light output at
470 nm. Then, unique phosphor coatings are applied to shift the color to the
desired pink, purple, or turquoise. The parts have an axial intensity of 2,200 mcd
(typical) at an IF of 20 mA and a
viewing angle of 20°. The angle is
defined by the points where light
output is 50% of the on-axis intensi-
ty.
These LEDs come in a standard
T-5mm package with radial leads
and epoxy lenses. The pink LED is
part number SSL-LX5093PC, the
purple is part number SSL-
LX5093VC, and the turquoise is part
number SSL-LX5093TC.
The devices cost approximately
$0.40 each in quantities of 10,000.

Lumex, Inc.
www.lumex.com
www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 13
FEATURE ARTICLE by Peter Csaszar & Monica Flores

Message Acquisition
Ring Signal Detection And Interpretation
You’ll never miss another voicemail message with Peter and Monica’s voicemail monitoring
system. Their device monitors the signal from an analog phone line, analyzes it, tracks the
number of calls and messages, and displays the number on a VFD.

I n some institutions, the internal


phone exchange system (aka private
only if the service is supported by the
PBX, which was not the case in our
Microchip’s C18 compiler, we devel-
oped the firmware entirely in C lan-
branch exchange, or PBX) offers voice- study. We designed a solution to this guage. In this article, we’ll describe
mail, but it can’t drive the “Message problem for use at Lawrence Technologi- how we built the system.
Waiting” indicator (typically a flashing cal University in Southfield, Michigan.
light). In other institutions, the tele- Our design, code named the Phone VOICEMAIL DETECTION
phones are not equipped with such a fea- Call Monitoring Facility (PCMF), moni- A classic method used by phone
ture. The only indication of unchecked tors the ring signal coming through an exchanges to notify users about new
messages is a distinctive dial tone that analog phone line, analyzes it, and then, messages is a stutter dial tone. For a few
plays when the handset is picked up. In based on the number of rings, tracks the seconds after the phone is picked up, the
such systems, some messages aren’t total number of calls, and calls with the dial tone is interrupted by short pauses.
received on time, which causes a variety possibility of a voicemail message (see Voicemail indicators designed for stutter
of embarrassing situations. The incom- Photo 1). We designed the system dial tone detection poll the line to “lis-
ing call indicator of certain caller ID around a Microchip Technology ten” to the nature of the dial tone.
boxes could serve as a workaround, but PIC18F4520 microcontroller. Using Unless “silent” voicemail is supported

a) b)

Photo 1a—This is the fully assembled circuit board, without the display. b—This is the monitoring system in operation. The end user will interact only with the blue Call Count
Reset button.

14 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


Figure 1—The system’s circuitry is fairly simple. The PIC18F4520 microcontroller requires very few external components.

(where a message can be left by there is a possibility that a message Harvard architecture. In addition, we
means other than calling the recipi- was left. Mathematically speaking, the needed a chip that was widely avail-
ent’s own phone number), it suffices desired ring count is only a necessary able, had enough code space to reason-
to poll the line after the phone rings, condition for the message. Callers ably support firmware development in
or after the subscriber gets off the often let the voicemail kick in, but C language, had plenty of features for
phone. However, phone companies hang up before the outgoing message experimentation, and had a PDIP
don’t like polling because it keeps is over. These false positives are not a packaging that enabled prototyping in
their circuits unnecessarily busy. major problem. A bigger criticism of a solderless breadboard. In terms of
A technology that is gaining more this method is its inherent false nega- the I/O resources, the PIC18F4520 is
popularity is frequency shift keyed tives: messages that are left while the more generous than necessary. But due
(FSK) proactive voicemail notification. phone was off-hook. However, for a to our aforementioned needs, it was
In this approach, the phone exchange user who doesn’t use the phone too our final choice.
sends a burst of data signals, similar to often (and for whom this device is One of our primary design goals was to
signals carrying caller ID information, intended), the odds of this situation keep the entire circuit as simple as pos-
which is recognized by the FSK receiv- remain negligible. sible. Power is supplied from a 9-VDC
er on the subscriber’s side. wall adapter. The 5 V for the PIC18F4520
In addition to these methods, some HARDWARE DESIGN and the display is supplied by a 7805
PBX systems put a high-voltage DC Figure 1 shows the system’s circuitry. regulator. Although the fundamental
signal on the line. This drives a neon The heart and soul of the circuit is U1, task of the firmware is time measure-
bulb that is typically built into the a Microchip Technology PIC18F4520 ment performed on the ring signal,
phone set. microcontroller. We selected the parts the precision of these measurements
Our PBX provided only a stutter dial for this design based on a few techni- is not critical. Therefore, it is possible
tone for message indication. Designing cal and educational considerations. As to run the microcontroller from its
a circuit that reliably detects the stut- part of the computer engineering cur- internal oscillator, which requires no
ter dial tone and picks the right riculum at Lawrence Technological additional hardware components
moments for polling is not an easy University, students gain significant whatsoever.
task. Instead, we chose a more experience with 16-bit Freescale Semi- The microcontroller receives two
straightforward approach: monitoring conductor microcontroller devices, such input signals: the ring pulses from the
ring signals. If the number of rings in a as the 68HCS12 microcontroller. We optocoupler (U2) and the Call Count
given call reaches the ring limit (i.e., used a PIC microcontroller for this proj- Reset button. The output peripheral of
the number after which the call is ect so that we could work with this the PCMF is a dot-matrix vacuum fluo-
automatically forwarded to voicemail), chip family’s significantly different rescent display (VFD1) module, which

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 15


we’ll describe in the next section. The inside the optocoupler is no exception. font magnification, font selection,
firmware also drives an LED, referred to To protect it from the negative half- scrolling, virtual display area, flashing
as Heartbeat, in a flashing pattern. In cycles of the ring signal, D3 is connect- display, and more.
addition to making the device look more ed across to it in the opposite direction. For ease of implementation and
gadgety, the light’s purpose is to aid diag- By making D3 an LED, it can also serve debugging, we decided to communicate
nostics. The same can be said about the as a debugging aid that visually indi- with the display using its 8-bit SPI con-
power LED, the Master Reset button, cates the presence of ring signals in the nected to the PIC18F4520’s on-chip SPI
and the test points. They can be removed circuit. In this arrangement, the two module. Considering that the display
from the production version of the cir- LEDs are “watching each other’s back.” always acts like a slave with certain sig-
cuit, but—as Monica experienced first The values of C1 and R4 are chosen so nal timing requirements, the microcon-
hand—they provide invaluable help dur- ring signals, with extreme amplitude troller’s SPI is configured as a master,
ing prototyping. In the current design, and frequency values, register with the clocked by 1/64 of the 8-MHz CPU fre-
the only non-power test point is the out- microcontroller, but do not damage the quency, and follows the SPI standard
put of the optocoupler. The signal was optocoupler. Trimmer potentiometer R1 Master Mode 11 for data clocking.
helpful during the debugging process, can be used to fine-tune the sensitivity Interfacing this VFD module posed a
because it showed whether the ring sig- of the circuit. (Texas Instruments used couple of challenges, adding tremendous
nal made it through the optocoupler. It to manufacture a chip specifically value to the educational content of this
also offered an easy way to insert the designed for ring detection, the project. (Monica appreciated it a lot, but
logic-level output of a signal generator TCM1520A. However, it’s no longer only in retrospect.) You may easily refer
into the circuit to test the firmware available.) to the first problem as “the mother of all
without the need to make actual phone ironies”: the SPI modules on the micro-
calls. VFD MATTERS controller and the display use opposite
The display is a Noritake GU140X32F- bit orders! Another complication is that,
RING MY BELL 7003, which is a 140 × 32 pixel graphic in certain display commands, the value 0
The detection of phone rings using a VFD module. It is an elegant, pricey can occur as a parameter, which is not a
microcontroller requires both hardware display intended primarily for high-end legitimate character in a C-style zero-ter-
and firmware support. In hardware, the applications such as vending machines, minated string, per definition. These
ring detector circuitry interfaces the ring office appliances, casino equipment, issues are addressed in our firmware by
signal with one of the microcontroller’s and more. If designed for mass-market- the putsVFD function. It is dedicated to
digital input ports. The timing of the sig- ing, a simple appliance such as the sending a string character by character to
nal is then analyzed by the ring inter- PCMF with this kind of display would the VFD using the WriteSPI function
preter portion of the firmware, which only make financial sense in the gold- from Microchip Technology’s MPLAB
can group ring pulses into separate rings plated, diamond-encrusted edition. The C18 compiler library, replacing the API’s
and rings into individual phone calls. standard version would probably generic putsSPI string function.
The ring signal is a pure sinusoidal employ an LCD module with compara- One well-known property of a VFD
AC waveform, with a root mean square ble features. However, due to a gener- is its tendency for the infamous
(RMS) amplitude of 40 to 100 V and a fre- ous donation from Noritake to “burn-in” phenomenon. Because the
quency of 16 to 67 Hz (typically 20 Hz in Lawrence Technological University, a individual display elements gradually
the U.S.).[1] Our ring detector follows couple of these displays were available lose brightness the longer they are
the logic of the widespread ring detec- for faculty and students to use in illuminated, a predominant static pat-
tion circuitry described in detail in design projects, so it became a natural tern can reduce the brightness of its
Julian Macassey’s article “Understand- choice for our project. forming elements (in this case, pixels)
ing Telephones,” which appeared in The VFD module is an intelligent more than that of the surrounding
Ham Radio Magazine in 1985.[2] The peripheral that includes driver electron- ones. Multiple “screen saver” schemes
role of C1 is to cut the DC path of the ics responsible for the low-level opera- have been developed throughout the
ring detector and serve as a series imped- tion of the display panel. Towards a decades to address a similar issue with
ance in addition to R4. Zener diodes host, the module offers both asynchro- cathode ray tube (CRT) displays.
D1 and D2 make the circuit unrespon- nous and synchronous serial interfaces. The PCMF firmware employs two
sive to low-amplitude audio signals and The former is semi-compatible with the strategies. When there are no phone
noise. One half period of the AC ring RS-232 standard (the same signal tim- calls to report, the display is switched to
signal turns on the optocoupler’s LED, ing, but TTL logic levels). The latter is a Power Save mode after 4 s of inactivity.
which with the pull-up resistor R2, pro- particular implementation of the SPI In this mode, the VFD’s filaments are
vides the digital input for the microcon- bus standard. This project uses only the also turned off, which, in addition to
troller. Aside from being a simple and display in Character mode, with its saving the pixels, also spares the fila-
elegant solution, electric isolation of the native size of 20 × 4 characters. The ments from extended use and reduces
optocoupler is required for user safety. interface supports a long list of com- the power consumption of the entire
LEDs are infamous for having a low mands in addition to displaying ASCII device considerably. When phone calls
tolerance for reverse bias. The LED characters, such as cursor positioning, are captured, the display is switched

16 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


exact nature of the ring pulse gaps.
All counters = 0
To provide the most elegant solu-
1
Ring pulse Call count reset tion, we decided to take full advantage
Event = ?
of the PIC18F4520’s interrupt system
Eon
for event handling. The high-priority
EonCount = 0 EonCount++ CallCount = 0
interrupt is associated with the Input
Capture module, signifying the arrival
PulseCount++ EonCount = ? MessageCount = 0
of a ring pulse. The responsibility of
Other
RING_GAP CALL_GAP the interrupt service routine (ISR) is to
1 1
reset Timer1 immediately, so time
N N
PulseCount MIN_PULSE? RingCount MIN_RING? measurements will be precise even for
Y Y short time periods. In this application,
RingCount++ CallCount++ this is not absolutely crucial, but it
may be required in future enhance-
N
PulseCount = 0 RingCount RING_LIMIT? ments. Considering that the VFD mod-
Y ule is a textbook case of a slow periph-
MessageCount++ eral (certain commands, such as scroll-
ing, can take up to 100 ms to execute),
RingCount = 0 clearing the timer in the Main loop
would generally be a bad design. On
1 1 1
the other hand, the response to a
Timer1 overflow has no such particular
Figure 2—This is the ring interpreter algorithm and the role of the Call Count Reset button. In the firmware, this
functionality is implemented by the Main loop. urgency. Therefore, this event is imple-
mented as a “silent interrupt,” where
the interrupt flag is set by the timer
between normal and reverse with the same call. The duration of the rings module, but the invocation of the cor-
exactly 50% duty cycle. When poten- is not measured; however, the compile- responding ISR is not enabled.
tial messages have been detected, the time constant RING_MIN_PULSE is One additional event is the push of the
flashing is done rapidly, so the device used to define the minimum number of Call Count Reset button, which is used
draws immediate attention. pulses an admissible ring must contain. to acknowledge that the reported call
This feature is used to reject fake pulses numbers are understood and can be reset.
FIRMWARE DESIGN if the sensitivity of the ring detector This event could also be handled with a
The most challenging part of the needs to be increased due to an anemic silent interrupt triggered by the micro-
firmware is the interpretation of the ring signal. As a result, the circuit controller’s INT1 input. However, to
received ring signal, which eventually detects the transients caused by the become familiar with the concept of
provides the number of rings in the phone going on- or off-hook (referred as multi-level interrupts and its implemen-
phone calls. Our algorithm is based on “bell tap” in the literature). This may tation in PIC devices, Monica config-
the measurement of time elapsed also be caused by the ticks of pulse ured INT1 as a low-priority interrupt.
between the ring pulses (more precise- dialing from a vintage phone. The operation of the firmware’s pri-
ly, the half periods that turn on the The microcontroller’s Timer1 is mary functionality is shown in Figure 2.
optocoupler’s LED). used in 16-bit mode to measure the The corresponding code is implement-
In the U.S., the ring cadence is time periods between ring pulses; it is ed by the familiar infinite Main loop,
defined as 2 s of ringing, separated by clocked from the internal clock source which serves as the “background
4 s of silence; however, the different through 1:8 prescaling. Because the process” in low-complexity firmware
distinctive ring patterns use periods of accuracy of the measurements is not environments. The device also sup-
silence shorter than 4 s within the highly critical, we used the microcon- ports the setting and nonvolatile stor-
same ring. The documentation of troller’s 8-MHz internal oscillator. This age of the Ring Limit. This mode is
cadence for distinctive rings and rings in brings the clock of Timer1 to 250 kHz. invoked if the Call Count Reset but-
different countries is somewhat sketchy. With an overflow cycle time of 262 ms, ton is pressed during boot-up.
Based on the tidbits of information we this period is referred to as an “eon.”
collected, our firmware assumes that We also employed the microcontroller’s CONSTRUCTION
pulses separated by less than 1.3 s Input Capture 1 module as the Timer1- Due to the large footprint of the dis-
(called Ring Gap Timeout) belong to based “stop watch,” although its read- play module, we could have crammed the
the same ring. If no pulses arrive for ings ended up serving only experimental entire electronics on a PCB of equal size.
more than or equal to 4.5 s (called Call and debugging purposes. For the ring However, we designed our PCB slightly
Gap Timeout), the current call is con- interpreter algorithm, the resolution of larger, so the components that need
sidered over. All other gaps are inter- time intervals measured in eons is access or visibility are not covered by the
preted as silence between rings within sufficient to properly identify the display’s circuit board. The ExpressPCB

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 17


(www.expresspcb.com) board layout file this project, therefore we dropped them
is on the Circuit Cellar FTP site. from the initial specifications. I
The two PCBs are held together by
four #4 screws, utilizing the mounting Peter Csaszar (peterc@ieee.org) is a
holes provided by the VFD module senior firmware engineer at Synap-
(see Photo 1b). The distance between tics in Santa Clara, CA. Previously,
them is defined by the height of the he worked as an assistant professor
phone jacks, the tallest components in the Electrical and Computer Engi-
on the PCMF board. A plastic or metal neering departments at Lawrence
casing can also take advantage of the Technological University in South-
screws. It is recommended that the field, MI. Peter also worked as a sen-
VFD be covered with green translu- ior software engineer at Motorola in
cent acrylic. This improves display Schaumburg, IL. His technical inter-
visibility in ambient light. ests include hardware and software
One interesting challenge was the design for embedded systems.
fact that the geometry of the VFD
module (except the connector’s header Monica Flores (mfloresky@gmail.com)
pins) follows the metric scale (i.e., the earned a degree in Electrical Engi-
different positions are round values of neering at Lawrence Technological
millimeters). Fortunately, the University in Southfield, MI. She is
currently working as an electrical
Hundreds of complete ExpressPCB board design software
engineer at Johnson Controls Hybrid
supports switching between the two
embedded projects. scales and does an impressive job. Battery Group in Milwaukee, WI. She
has worked as a co-op electrical engi-
FUTURE DEVELOPMENTS neer at DTE Energy in Detroit, MI.
Although working on this project Her main areas of interest are elec-
was an excellent learning opportunity, tronics and embedded systems.
the idea itself is not new. Voicemail
indicator devices (albeit less fancy PROJECT FILES
than this one) are available for less To download code and board layout,
than $50. However, due to its relative go to ftp://ftp.circuitcellar.com/pub/
simplicity, this design was a feasible Circuit_Cellar/2008/215.
task for one student to complete while
Start with demonstrating the entire cycle of prod- REFERENCES
www.circuitcellar.com/ uct development: problem identifica- [1] J. Macassey, “Understanding Tele-
tion, idea inception, design specifica- phones,” Ham Radio Magazine, Sep-
microchip2007 tion, research of possible solutions, tember 1985.
research of prior art, electronic and
mechanical design, parts selection, [2] J. Darwood, “Telephone Ring Detec-
parts procurement, firmware develop- tor Circuit,” U.S. Patent 4066848, 1978.
ment, prototyping/testing, debugging,
circuit board design, production, and RESOURCES
final verification. This project proves
Mike Sandman Enterprises, Inc.,
that the devil is indeed in the details,
“Message Waiting Products,”
and that on top of the expected hur-
www.sandman.com/messwait.html.
dles, there are also plenty of unexpect-
ed surprises lurking around (e.g., the Noritake Electronics, www.noritake-elec.
strange behavior of the VFD after a com.
hardware reset).
Our voicemail monitoring system SOURCES
works as expected. It has put an end
C18 Compiler, MPLAB C18 compiler
to missed voicemail messages.
library, and PIC18F4520 microcontroller
If you want to build on this idea, true
Microchip Technology, Inc.
stutter dial tone detection and the imple-
www.microchip.com
mentation of call logging with time
stamps would be two great opportunities GU140X32F-7003 VFD
for improvement. Both of these features Noritake, Inc.
were beyond the intended complexity of www.noritake-elec.com

18 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


Change
the design,
not the deadlines
PSoC flexibility enables changes anytime: at concept, through GET STARTED WITH PSoC NOW.
production, in the field. Specifications change constantly. Yet
Download our “Change Happens” White Paper
pressures to differentiate, minimize costs, and speed time-to-market
and get 50%* off a PSoC development kit:
remain the same. To stay ahead of the curve, you need flexibility, cypress.com/go/changepaper
programmability, and scalability. PSoC’s unique programmable
Download free PSoC Express™ or PSoC Designer™
architecture delivers this and more. Futureproof your design; make embedded software: cypress.com/go/changesoft
PSoC your agent of change.
Request free PSoC device samples:
cypress.com/go/changechip
PSoC delivers:
Free online training:
The configurability of an FPGA, the mixed-signal integration cypress.com/go/changetrain
of an ASIC, and the familiarity of an MCU.
Purchase PSoC development tools:
cypress.com/go/changetools
Reusable IP, compatible device families and variable
resource options so you can optimize design efforts
and accommodate changes.

Two powerful development platforms: PSoC Express™ Software for


code-free visual embedded system design and PSoC Designer™
Software for complete flexibility to write code.

PSoC includes programmable analog and digital blocks, a fast MCU, flash
and SRAM memory, all in a compact package (as small as 3mm x 3mm).

© 2008 Cypress Semiconductor Corporation. All rights reserved. PSoC is a registered trademark, PSoC Express and PSoC Designer are trademarks of Cypress Semiconductor Corporation. All other trademarks are properties of their respective owners.
*50% off applies to the PSoC Development Kit featured on www.cypress.com/go/changepaper.
FEATURE ARTICLE by Richard Wotiz

Pump Control
FIRST PLACE CONTEST WINNER

Build A Variable-Speed Drive For Motors


Richard’s single-phase, variable-speed drive for AC induction motors is an excellent device
for powerful, yet quiet, pump operation. Designed for use with a capacitor-start/capacitor-run
motor, it includes active power factor correction (PFC) and inrush current limiting.

O ver the past few years, I’ve done


various renovations to my house,
anything as large as 2 hp. I didn’t want
to deal with the mechanical complexi-
chose it because I needed certain fea-
tures of its PWM controller that aren’t
including adding a new backyard deck ty of adapting a three-phase motor to present in the motor control family. I
to support a hot tub. Last year, I final- the existing pumps. The only solution used a three-phase Smart Power mod-
ly decided to buy one. I looked for a was to design my own electronic ule, consisting of three IGBT half
self-contained model, and found many speed control to work with the exist- bridges with integrated drivers and
choices with varying numbers of ing motor, and so the Spa Pump Con- fault detection, to drive the motor.
pumps and jets. They all had automat- troller was born (see Photo 1). The PFC section is a boost regulator
ic control systems to keep the water using a MOSFET switch with a
properly heated and filtered. I bought a THE BIG PICTURE Microchip TC4427A driver. Two
six-seat spa with 43 jets and a pair of The Spa Pump Controller is a vari- Microchip MCP6022 dual op-amps
two-speed, 2-hp pumps. able-speed drive for a 2-hp single-phase provide input and output current sens-
I was planning on putting the spa AC induction motor (see Figure 1). It ing. A pair of Microchip MCP9700
outside of my bedroom, so I was con- includes active power factor correc- temperature sensors in the PFC and
cerned about the volume of the tion (PFC), inrush current limiting, motor drive power sections monitor
pumps. I didn’t want to be woken up and has a control port that interfaces the heatsink temperature.
if the heat came on at night. The with a standard spa control system. The drive communicates through an
model I bought was very quiet at low The motor drive hardware is built optoisolated serial port to a separate
speeds while heating. But after I used around a Microchip Technology spa interface unit, which is designed
the spa for a while, I found the pumps dsPIC30F2020 digital signal controller. around a Microchip PIC16F687 micro-
annoyingly loud at high speeds. Also, Although this part is targeted for controller (see Photo 2). It connects
the jets were so powerful that I could switching power supply systems, I between the spa’s control pack and
enjoy them for only a few minutes at
a time. There were various valves to
control the water flow, but that didn’t
help with the noise. At low speeds,
there wasn’t quite enough water pres-
sure to be enjoyable. An intermediate
speed would have been perfect.
None of the spas I found in my
search had a variable-pump speed con-
trol. I started searching for variable-
speed drives, figuring I’d have to retro-
fit something myself. I found endless
choices for three-phase motors. But
Photo 1—This is the drive unit. The dsPIC30F2020 and all of the control circuitry is at the upper right, with all of the
there were few with single-phase out- power components below. The line filter and low-voltage supplies are in a separate box to the left. It’s designed to
puts, and none of them could handle sit vertically with the three large filter capacitors at the bottom, so they stay as cool as possible.

20 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


Most of the output drive circuit-
Temperature
Temperature sensor ry is contained in a Fairchild Semi-
sensor MCP9700
MCP9700 conductor FSBB30CH60 Smart
Current Current
Three-
AUX MAIN Power module (see Figure 3). It
Inrush sense PFC sense
230 EMI
current Boost phase has three 30-A, 600-V IGBT half-
VAC Filter converter IGBT
limiter power bridge outputs along with drivers
module
that don’t require isolation for
5V
Power
Op-amp Driver Op-amp their logic-level inputs. The
15 V MCP6022 TC4427A MCP6022 2-hp
supply
15 V One-phase module has separate negative
induction motor
inputs for each output. I put a
I/O ADC, ADC ADC PWM ADC ADC PWM pair of current-sense resistors
CMP
ICSP dsPIC30F2020 UART Optoisolators (R33 and R34) on two of them so
I can measure the currents for
MCLR I/O
ICSP Serial each of the two windings. A
Connector connector third resistor (R35) measures the
Voltage detector MCP121 total motor current and feeds the
LED
module’s short-circuit detect
input.
ICSP PIC16F687 UART

ADC, POWER FACTOR CORRECTION


ICSP
CMP SPI I/O
Serial The PFC is a standard continu-
Connector connector ous conduction mode (CCM) boost
Digital potentiometer
MCP4011 regulator (see Figure 4). It steps up
Buttons
the line voltage to 400 VDC, while
To spa LCD data To spa enabling the input current to fol-
keypad control pack
Power low the input voltage waveform.
5V This provides a high power fac-
tor, similar to a resistive load,
Figure 1—The system is partitioned into two parts. All of the power circuitry is in the drive unit, which appears in the top which puts less stress on the
half of the diagram. The spa interface unit on the bottom connects the drive unit to the spa’s control system.
power grid. A non-PFC system
would draw most of its input
top-side keypad, so the keys can be used pins also have RC noise filters. I sprin- current at the peaks of the AC wave-
to control the pump speed. It monitors kled several optoisolators throughout form, rather than spread out over the
incoming key presses and sends out its the design to reduce noise coupling entire cycle. Many countries have reg-
own as varying analog levels using a and avoid ground loops. This might ulations that mandate a high power
Microchip MCP4011-103E/SN digital seem excessive, but tracking down factor on products such as this with a
potentiometer. It can also modify the intermittent noise problems could
data sent from the control pack to the have taken a long time!
keypad’s LCD. The system is designed to work
Power for the drive unit is supplied with a capacitor-start/capacitor-run
by a pair of offline switching supply motor. The motor has two windings
modules. They provide 5 V for the approximately 90° apart from each
control section and two isolated 15-V other and could be thought of as a
outputs for the PFC and motor drive two-phase motor. One winding con-
sections. The spa interface unit gets nects directly across the line. A start
its 5-V supply from the spa’s control capacitor provides 90° of phase shift
pack. for the other winding during start up
and a run capacitor takes its place
HARDWARE DETAILS after the motor has come up to speed.
The dsPIC30F2020 has all of the fea- A centrifugal switch controls which
tures I need for this application (see capacitor is connected. This type of
Figure 2). It has just enough ADC motor is more efficient than a capaci-
inputs and I/O pins. There is one spare tor-start or split-phase type, both of
pin, but it is not functional in the cur- which use only one winding while
rent mask revision. The entire system running. I needed to control each
Photo 2—The spa interface unit is wire-wrapped on a
operates in an extremely high-noise winding individually, without using
small protoboard and fits in a plastic box that sits next
environment. All of the pins have the capacitors, because the necessary to the spa control pack. Some of the parts were only
Zener surge suppressors, and the input capacitance varies at different speeds. available as surface-mount, so I had to make do.

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 21


Figure 2—All of the control circuitry is surrounded by surge suppression and noise filtering. The default jumper settings use the same pins for the ICSP and serial ports. I
found that the serial port didn’t interfere with ICD2 operation, but I had to unplug the ICSP cable to use the serial port.

power consumption of 2.5 kW. Refer current when the MOSFET switch is Low-voltage power for the various
to Olin Lathrop’s article titled “Digi- on), which is amplified and sent to an parts of the system comes from a pair
tally Control Power Factor Correc- ADC input. It’s also compared to a fixed of power supply modules. I chose two
tion” for a more in-depth introduction threshold to generate an overcurrent evaluation boards for STMicroelec-
to power factor correction (Circuit fault signal. Refer to the PFC_design.doc tronics’s VIPer12A line of offline
Cellar 174, 2005). file on the Circuit Cellar FTP site for switcher components, mainly due to
The operating theory of a CCM PFC more details about the PFC hardware their availability and wide tempera-
is fairly straightforward. The boost design. ture range of 0° to 80°C. I had to
converter operates with two control modify the modules to adapt them to
loops. A fast inner loop controls the POWER SOURCE work with my design. Refer to the
MOSFET switch duty cycle to main- The Spa Pump Controller connects LVPS_mods.doc file on the Circuit
tain an input current that is propor- to a 230-VAC line, and can accept Cellar FTP site for a complete list of
tional to the instantaneous power line between 200 and 264 V. It draws up to changes.
voltage. This simulates a resistive 12 A RMS at 200 V. I used an EMI fil-
load. A slower outer loop gradually ter with low leakage current to elimi- SPA INTERFACE
adjusts the average input current over nate the possibility of tripping the I wanted to be able to control the
a long period of time (several power spa’s ground fault circuit interrupter. pump speed using the control keypad
line cycles) to maintain the output DC When power is first applied, the DC mounted on top of the spa. It has eight
bus voltage at the proper level, which bus capacitors charge up to the peak membrane push buttons and a four-
is 400 V in my case. line voltage through a pair of surge- digit LCD with several status icons. It
The AC input and bus voltages have withstand resistors. (Refer to R81 and connects to the main spa control unit
101:1 voltage dividers feeding ADC R82 in Figure 5.) Once the bus voltage with an eight-wire cable, which I set
inputs. A sense resistor measures the is high enough, a relay turns on to out to reverse engineer. Pressing a but-
input current (equal to the inductor bypass the resistors. ton connects a particular tap of an

22 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


GIVE YOUR DESIGNS THE GREEN LIGHT
Design flexibility has never been more simple. NKK’s SmartSwitch™
allows you to design what you want, any way you want. Our series
of LCD programmable switches and displays are developed for use
with a wide variety of applications. You’ve got the green light to
explore design freedom.

IS Dev Kit-2

Power your designs with NKK.


Visit us online to:
Get Your FREE • ORDER Dev Kits to drive your creativity
3D CAD Model at:
• DOWNLOAD software to expedite your design process
http://cc.nkksmartswitch.com • PROTOTYPE and test new design ideas cost effectively
Figure 3—All of the power switching is done by SPM1. Note the numerous RC fil-
ters and the four different ground nodes. The logic, inverter control, and power bus
grounds are each connected together by only a single-tie trace. The analog ground
is kept separate.

eight-step voltage divider to a single- ADC, as well as enough pins to 512 bytes of RAM. It uses almost all
output wire. The LCD data is sent accommodate future improvements. of the CPU’s processing capacity
using a three-wire SPI, with a block of An MCP4011-103E/SN digital poten- while running at 20 MIPS.
13 bytes sent every 16.7 ms. The tiometer generates virtual key presses I was careful to avoid any potential-
remaining wires provide 5 V, ground, to send to the spa control. I included a ly hazardous coding practices to
and power for the panel backlight. For 32.768-kHz crystal and a backup bat- reduce the possibility of a crash, con-
more information, refer to the Inter- tery for a real-time clock, another sidering the damage that could result.
face_Schematic.doc file on the Circuit future enhancement. There are no loops anywhere in the
Cellar FTP site. code outside of one main loop. There
I designed the interface as a separate DRIVE UNIT SOFTWARE are no pointer variables (other than
board that sits next to the spa control I wrote the drive unit code in C with function parameters), and I check for a
unit, connecting it and the keypad. It Microchip’s MPLAB 7.5.2 and MPLAB nonzero denominator before all divide
can interpret user key presses and C30 v2.05. I used an ICD2 for initial operations.
modify the data sent to the LCD. It debugging. Later on, I used the electri- Refer to the Flowcharts.doc file on
communicates with up to two drive cally isolated serial port to output the Circuit Cellar FTP site. The main
units over a logic-level serial port to debugging data when operating the sys- loop makes repeated passes through a
control the motor speed. I chose a tem from line power. The code weighs state machine. When the system is
PIC16F687 microcontroller because it in at just over half of the 12 KB of first powered up, the DC bus capaci-
had the requisite SPI, UART, and flash memory, and about 75% of the tors charge up for about 150 ms. Then

24 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


PC Oscilloscopes & Analyzers
DSO Test Instrument Software for BitScope Mixed Signal Oscilloscopes

4 Channel BitScope 2 Channel BitScope Pocket Analyzer

Digital Storage Oscilloscope BitScope DSO Software for Windows and Linux

Up to 4 analog channels using industry standard
probes or POD connected analog inputs. BitScope DSO is fast and intuitive multi-channel test and measurement software for your
PC or notebook. Whether it's a digital scope, spectrum analyzer, mixed signal scope,
Mixed Signal Oscilloscope logic analyzer, waveform generator or data recorder, BitScope DSO supports them all.


Capture and display up to 4 analog and 8 logic Capture deep buffer one-shots or display waveforms live just like an analog scope.
channels with sophisticated cross-triggers. Comprehensive test instrument integration means you can view the same data in
different ways simultaneously at the click of a button.
Spectrum Analyzer DSO may even be used stand-alone to share data with colleagues, students or


Integrated real-time spectrum analyzer for each customers. Waveforms may be exported as portable image files or live captures replayed
analog channel with concurrent waveform display. on other PCs as if a BitScope was locally connected.
BitScope DSO supports all current BitScope models, auto-configures when it connects
Logic Analyzer and can manage multiple BitScopes concurrently. No manual setup is normally required.


8 logic, External Trigger and special purpose Data export is available for use with third party software tools and BitScope's networked
inputs to capture digital signals down to 25nS. data acquisition capabilities are fully supported.

Data Recorder


Record anything DSO can capture. Supports
live data replay and display export.

Networking


Flexible network connectivity supporting
multi-scope operation, remote monitoring and
data acquisition.

www.bitscope.com
Data Export


Export data with DSO using portable CSV files or
use libraries to build custom BitScope solutions.
Figure 4—The PFC converter is the noisiest part of the entire system. I put plenty of filtering around the current sense amplifier (U6) and used a shielded optoisolator to keep
noise from coupling into the control circuitry. I used paired resistors for the voltage sense dividers so a single failure wouldn’t send hundreds of volts into a microcontroller pin.

the inrush control relay is turned on The dead time is a short gap during on the Circuit Cellar FTP site for
to bypass the current-limiting resis- the transitions of complementary more details.
tors and the PFC system is started up. PWM signals where neither output is The two motor windings are physi-
Once the bus voltage reaches its final on. This gives one IGBT switch in the cally spaced 90° apart from each other.
value, the motor drive inverter is three-phase driver module time to To get a 90° phase shift between the
started. The main loop also calls the turn off before the opposite one turns voltages across the two windings, the
serial handler to process any incoming on to avoid a momentary short circuit. individual inverter output voltages
commands and flashes the LED at a I set the dead time to 3 µs. This means need to be driven 180° apart from each
rate proportional to the motor speed. I’m not controlling the output voltage other (see Figure 6). The resulting
In the event of a hardware fault, the for 3 µs twice out of every 56-µs period winding voltages will be 283-V peak,
PFC and inverter are immediately (once per transition). This causes dis- or 200-V RMS. This is 3% below the
shut down. Only a command from the tortion at very high or low duty motor’s 230-V ±10% operating range. I
serial port or a power cycle can restart cycles, where 3 µs is a significant por- felt this wouldn’t be a problem and
them. tion of the on or off time. found that the motor had no trouble
To compensate for this distortion, accommodating such a minor
INVERTER PROCESSING you can take advantage of the induc- brownout condition.
Low-level motor drive processing is tive nature of the motor windings. If The magnetic field inside the motor
done in the PWM interrupt routine at an current is flowing out to the motor, it is actually determined by the winding
18-kHz PWM rate, which is just above will continue to flow even when both currents. You want these currents, not
my hearing threshold and below the switches are off, pulling the output the voltages, to have the proper 90°
power module’s 20-kHz limit. It gener- voltage low to ground. If it’s flowing phase shift and appropriate ampli-
ates the properly phased sinusoidal out- inward, it will pull the voltage up to tudes. The interrupt routine finds the
put signals and captures motor current 400 V during the dead time. I imple- phase difference between the main
samples from the ADC. The waveforms mented an algorithm that shifts the and aux winding current zero crossing
are generated by incrementing a phase PWM duty cycle by 3 µs just before points (see Listing 1). It also computes
accumulator by a fixed amount each the motor current changes direction.[1] the sum of the square of the currents
interrupt and using that value as an It’s more complicated than simply (RMS squared). Once each cycle of the
index into a cosine table. The result is waiting for the zero crossing, but it output waveform, the mainline code
scaled by the desired amplitude and provides a cleaner signal. Refer to looks at these values and adjusts the
adjusted to reduce dead time distortion. Duty_adjust() in the Inverter.c file PWM phase values as needed to maintain

26 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


without any protection, the
bus voltage could exceed
the component ratings.

SERIAL PORT
The drive unit connects
to the spa interface unit
over a serial port running
at 9,600 bps. Both act as
watchdogs for each other.
The drive unit expects to
receive commands at regu-
lar intervals. If not, it
immediately shuts down.
Conversely, the spa inter-
face unit expects to receive
a response to its commands
within 100 ms. If not, it
sends a virtual key press to
the spa control pack to
shut off the pump relay,
removing power from the
drive unit. The commands
are described in the Seri-
al_Commands.doc file on
the Circuit Cellar FTP site.

SPA INTERFACE CODE


The PIC16F687 code was
written in assembly using
Figure 5—Take a look at the input power and inrush control. The power wiring is all 14 AWG to handle the high current. I didn’t MPLAB 7.5.2. It uses only
include input fuses because power comes from the fuse-protected pump output of a spa control pack.
25% of the 2K words of
flash memory, and 46 of
the proper current waveforms. This faster MOSFET and found the faster the 128 bytes of RAM. However, I
dynamic adaptation automatically switching speed improved perform- expect to fill this up in the future
adjusts the waveforms to best suit the ance and system stability. I had with user interface features not
actual motor speed and mechanical already built the inductor for a 20-kHz directly related to controlling the
loading. system, but it worked fine at the high- pump speed. The system runs at the
The inverter state machine periodi- er speed. default speed of 4 MHz.
cally checks to see if the motor speed The ADC is triggered at the center The code continuously monitors the
needs to be changed and adjusts it of the PWM output pulse and captures
accordingly. It also sets the waveform the inductor current, AC input and
amplitude according to the V/F control DC bus voltages, and heatsink temper- 400 V
Aux 200 V
algorithm, where the motor voltage is ature. The code computes the average 0V
180
proportional to its frequency. The code AC input voltage once each cycle. The 400 V
also adjusts the amplitude to compen- values are fed to the PFC algorithm Main 200 V
0V
sate for variations in the DC bus volt- that’s based on Microchip application
400 V
age. Finally, it checks the PWM fault note AN1106.[2] Com 200 V
0V
status and heatsink temperature. I also included some interaction
with the inverter section. If the bus 283 V
Aux - Com 0V
PFC ROUTINES voltage gets too far out of range, a flag -283 V
90
Most of the PFC processing is done causes the inverter to stop changing 283 V
in the ADC interrupt routine at the the motor speed until the bus is back Main - Com 0V
-283 V
50-kHz PFC PWM rate. I originally within the limits. This avoids over-
chose 20 kHz because the design start- load during acceleration, but more
Figure 6—The individual output pin voltages (top wave-
ed out using an IGBT switch that was importantly, it prevents the bus from
forms) are driven 180° apart from each other. This
limited to 20 kHz, but it turned out to overvoltage. An induction motor acts results in the correct 90° phase shift between the two
be unavailable. I ended up using a as a generator while decelerating, and winding voltages (bottom waveforms).

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 27


spa’s keypad for button presses. It Listing 1—This code finds the value of the PWM phase accumulator when the motor current waveform rises
either passes them on to the spa con- through its 75% point. The signal is extremely noisy, especially near the zero crossing. To combat this, there’s
trol pack unchanged or uses them to lots of margin between the rising and falling thresholds, and you average the result over several cycles.
initiate speed control commands to
if (isense > iphase->max) iphase->max = isense; // Find max
the drive unit. It also taps into the if (isense < iphase->min) iphase->min = isense; // and min
LCD datastream to monitor various if (isense > iphase->rising) { // Positive transition
icons that indicate the state of the if (iphase->sign & SIGN_NEG) {
control pack’s relays and can modify if (iphase->rising > iphase->falling + _IPHASE_THRESH) {
// Update running average of relative transition time
the data to display its own messages. stemp = phase_accum - iphase->time.w.hi;
iphase->time.l += (SLONG)stemp << (16L - 4L);
PUTTING IT TOGETHER iphase->flag = 0xFF; // Set data valid flag
I built the drive system on a PCB }
// Set new thresholds to 75% and 50% of waveform span
due to the critical nature of the high- iphase->rising = (iphase->max>>2)*3 + (iphase->min>>2);
power circuitry layout. All of the iphase->falling = (iphase->max>>1) + (iphase->min>>1);
components except for the high-power iphase->min = 32767; // Re-init min and max
semiconductors are on the top side. iphase->max = -32768; // for next cycle
}
Photo 3 shows the bottom side. iphase->sign = SIGN_POS;
Designing the double-sided PCB was }
quite a challenge given the various else if (isense < iphase->falling) // Negative transition
trace widths and spacings I’d need to iphase->sign = SIGN_NEG;
safely handle the high voltages and
currents. I used several ground planes
and lots of space between the low- and Micrometals web site. It enabled me can see some of the construction
high-power sections. Component to enter the PFC design parameters steps in the Inductor_Photos.doc file
selection took me longer than usual and then it listed the various core on the Circuit Cellar FTP site).
because I had to make sure every part and winding options. I picked a pair The two power supply modules and
could handle the full outdoor tempera- of Micrometals E305-8A iron powder the EMI filter fit in a 6″ × 5″ × 4″ metal
ture range, even with California’s E-core halves and a PB305A bobbin. I box, and everything else went into a
mild winters. wound 80 turns of six parallel larger 12″ × 7″ × 4″ box. I used a lot of
I had to make my own PFC induc- strands of 20-AWG heavy-build mag- polyimide tape to insulate the box
tor, because I couldn’t find anything net wire (rather than a single 12 walls from the many nearby live parts.
that was large enough. I used an AWG), insulating each layer with At first, I built up the PCB using dif-
inductor design program from the two wraps of polyimide tape. You ferent bus voltage divider resistors, cur-
rent sense resistors, and PFC power
components that were designed for 10%
of the original voltage and current specs.
(Refer to the parts marked with asterisks
in Figures 3 and 4.) That enabled me to
power the system from a 24-V 1-A trans-
former for debugging and loop stability
measurements without risking any com-
ponent damage. I used two 12-V 6-W car
interior light bulbs in series with each
motor winding as a 24-V test load.
After finalizing the hardware, I tried
out the system with an old 0.25-hp,
split-phase AC motor while supplying
power from a 120-V isolation trans-
former and a Variac. I could hardly
believe it when I saw the motor shaft
starting to turn for the first time!
The spa pump motor has the start
and run capacitors mounted on the
outside of the motor casing. I was
able to remove them and connect to
one of the wires from the run capaci-
Photo 3—The heatsink dominates the back side of the PCB. You can see the smart power module poking out from tor that goes to the auxiliary winding.
underneath. The two black cables run to the temperature sensors located between the heatsink fins on each side. This bypasses the motor’s internal

28 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


start switch, so I didn’t have to do REFERENCES Microchip Technology, Inc., 2003.
any disassembly to get to the connec-
tions I needed. The main winding [1] R. Valentine, Motor Control Elec- Venable Industries, “Venable Techni-
connects directly across the line ter- tronics Handbook, D. Wilson, cal Paper #13: Testing Power Factor
minals, so it was accessible without “Deadtime Distortion Correction,” Correction Circuits For Stability,”
any modifications. McGraw-Hill, New York, NY, 1998. www.venable.biz/tp-13.pdf.

[2] V. Skanda, “AN1106: Power Factor


AHHHHH Correction in Power Conversion
I left room for some advanced fea- SOURCES
Applications Using the dsPIC DSC,”
tures that I’d like to add someday. DS01106A, Microchip Technology, FSBB30CH60 Smart Power module
The spa interface unit has extra 2007. Fairchild Semiconductor Corp.
inputs for pressure sensors, which www.fairchildsemi.com
will control the pump speed based on
pump outlet pressure. This will auto- RESOURCES dsPIC30F2020 DSC, MCP4011-
matically compensate for changes in S. Bowling, “AN984: An Introduction 103E/SN potentiometer, MCP6022 op-
jet settings as individual jets are to AC Induction Motor Control Using amp, MCP9700 temperature sensor,
turned on or off. For now, I’m happy the dsPIC30F MCU,” DS00984A, PIC16F687 microcontroller, and
pushing the up and down buttons Microchip Technology, Inc., 2005. TC4427A MOSFET driver
myself while I enjoy a quiet soak. I Microchip Technology, Inc.
Fairchild Semiconductor Corp., “AN- www.microchip.com
Editor’s note: For more information 9035: Smart Power Module—Motion-
SPM in Mini-DIP User’s Guide,” 2005. E305-8A Inductor core half, PB305A
about the Microchip 16-Bit Embedded
bobbin, and inductor design software
Controller 2007 Design Contest and
O. Lathrop, “Digitally Control Power Micrometals, Inc.
the other winning projects, visit
Factor Correction,” Circuit Cellar 174, www.micrometals.com
www.circuitcellar.com/microchip2007/.
2005.
VIPer12A Offline switcher
Author’s Note: Caution! This project R. Parekh, “AN887: AC Induction STMicroelectronics
uses voltage and power levels that Motor Fundamentals,” DS00887A, www.st.com
could be lethal or cause considerable
damage if not properly respected.
You should have experience working
with high voltages. Take all appropri-
ate safety precautions before
attempting to operate the system
from line power. Make sure there’s
someone else within earshot who
knows how to turn off the power if
something should go wrong. Use an
isolation transformer when connect-
ing the system to non-isolated equip-
ment. Always use a discharge resis-
tor because the bus capacitors will
hold a charge long after power is
removed.

Richard Wotiz earned a B.S.E. in


Electrical Engineering and Computer
Science from Princeton University. He
has run his own hardware consulting
business for the past 17 years, spe-
cializing in consumer products and
children’s toys. You may contact him
at dick601@mystics.org.

PROJECT FILES
To download code and additional files,
go to ftp://ftp.circuitcellar.com/pub/
Circuit_Cellar/2008/215.

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 29


ABOVE THE GROUND PLANE by Ed Nisley

Resistance Soldering
In his last two columns, Ed discussed transformer action and the simulated triac control of an
inductive load. This month, he describes a real-world application: circuitry connected directly
to an AC power line.

H aving investigated transformer


action in my February 2008 column
resistor is “below” the common refer-
ence: positive current into the triac’s
optoisolator and, as a side effect, lights
LED1.
(“Transformers,” Circuit Cellar 211) MT2 produces a negative sense voltage. A separate 5-V wall-wart switching
and simulated triac control of an Remember that you must use an supply provides logic power to the
inductive load in April 2008 column isolation transformer when you con- microcontroller board, so this prototype
(“Triac Behavior,” Circuit Cellar 213), nect line-powered test equipment to has three line cords: logic, drivers, and
now it’s time to put everything togeth- this circuit and that Variac-style trans- the high-current transformer. That was
er and match theory with reality. formers do not provide isolation. easier than trying to combine everything
The circuitry described in this col- The orange rocker switches on the into a single cord and allows independ-
umn connects directly to the AC “front panel” control power to TR1, ent adjustment of the main trans-
power line and, as you can see in the high-current transformer primary, former’s supply voltage through an iso-
Photo 1, the breadboard I built poses a and TR2, the small transformer for the lation transformer. You must plug all
clear and present danger of electrocu- triac driver. Their built-in neon indica- three cords into the same branch cir-
tion. If you’re not familiar with tors show when line voltage is present. cuit to maintain the correct phase rela-
power-line circuitry, this is not the TR2 has unusual output voltages tionships between TR1 and TR2.
place to gain that experience: get that were better-suited to its original IL2 optoisolators have a current
expert help before building anything! microwave-oven application: its 2.6-VAC transfer ratio over 100%, so driving
winding barely suffices for the ±4-VDC them with 15 mA ensures enough out-
POWER CONTROL HARDWARE gate supplies. The 14-VAC winding put current to saturate Q1–Q4. You
The power supply in Figure 1 corre- adequately drives the line-sync can substitute other isolators with
sponds to the SPICE simulation in my
April column. The perfboard with the
two fat caps in the middle of Photo 1
holds most of those components, with
the triac, snubbers, and current sam-
pling resistor mounted on the black
heatsink to its right. I harvested the
power components from a defunct
microwave oven, which led to some
rather ad-hoc mounting solutions.
The coaxial cable connects across
R10, a 100-mΩ sandbox resistor rated
at 5 W, to sample the primary winding
current. The cable shield should con-
nect to the 0-V “common” of the
drive circuitry, not to the power-line
neutral, so that you can plug it direct-
Photo 1—Mounting the components on a plywood base prevents inadvertent short circuits while probing. The Vise-
ly into the oscilloscope. The current Grip clamped on the transformer’s secondary terminals forms a deliberate short that simulates a resistance-solder-
sense will be negative, because the ing joint. Yes, the front of that plywood base is slightly curved: it’s not barrel distortion in the lens.

30 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


lower CTRs if you recalculate the tran- switches on the circuit board simplified zero crossing to the start of the inter-
sistor base and triac gate currents. testing while I was wiring it up. rupt handler code. Whether that mat-
Figure 2 shows the straightforward ters in your application depends on
microcontroller circuitry residing on PHASE TIMING how fussy you are about getting an
the left perfboard in Photo 1. An I filled the 89C2051 with 2 KB of C accurate zero-crossing signal, because
Atmel 89C2051 has 2 KB of code code compiled with SDCC and, after I the delay can produce a noticeable
space, just barely enough for this proj- stomped two nasty picket-fence errors, glitch at the start of the switched
ect, and its outputs drive 20-mA LEDs everything worked fine. The firmware cycle.
directly. is straightforward, but the pulse tim- For example, Photo 2 shows a single
I had intended to provide serial I/O ing deserves a mention because it’s half-cycle with a 25-A peak, similar to
for remote control, but the surplus vital to triac triggering. the simulation in Figure 1 of my April
vacuum-fluorescent display in the The timing reference for each cycle column. The 2-ms triac triggering
lower-left corner lacked the optional starts when optoisolator OK5 in Figure 1 pulse starts 400 µs after the zero-
oscillator that would produce standard triggers an external interrupt as the crossing point with the line voltage at
serial rates. As a result, I used a 12-MHz line voltage rises through 0 V. Saturat- 25 V, showing the effect of a small
microcontroller crystal to get 62.5 kbps ing its output transistor requires about delay.
and the perfboard has an unused serial 500 µA, which corresponds to an LED Just as in the simulation, the volt-
connector and an empty MAX232 current of 2.5 mA at the TIL116’s age on the Gate terminal remains at
socket. nominal 20% CTR. about 1 V after the end of the trigger
Four Hall-effect keyboard switches The TIL116 has a threshold of about pulse, due to the small Gate current
increment and decrement the gate pulse 1.5 V, so it will switch when the volt- from the heavy current between MT2
pattern selection and heating duration. age reaches: and MT1, then drops abruptly when
Unlike ordinary mechanical switches, the triac shuts off as the current hits
1.9 V = 1.5 V + 2.5 mA × 150 Ω [1]
these have absolutely no contact zero.
bounce, but their active pull-up outputs The 14-VAC winding has a peak Unlike the simulation, however,
have very little pull-down current. I amplitude of 19 V, so it hits 1.9 V at: the actual circuit commutes correct-
added 2.2-kΩ pull-down resistors to get ly after the zero point, even though
⎛ 1.9 ⎞
a valid logic-low input level. 5.7° = arcsin ⎜ ⎟ [2] the voltage across the triac changes
⎝ 19 ⎠
The circuit board includes two 3.5-mm abruptly from nearly 0 to –70 V. The
stereo jacks for external switches. A In units of time, that works out to: slight ringing after the transition
“contact” closure indicates that the tip shows the circuit is under-damped,
5.7°
electrode is firmly pressed against the 270 μs = 16.7 ms × [3] but the triac doesn’t retrigger on that
360°
workpiece and a “burn” foot switch edge.
activates the heating pulses. Duplicate I measured 300 µs from the true Because the transformer presents a

Figure 1—This utterly uneconomic triac


drive circuitry provides close control over
the gate current. I harvested the trans-
formers and triac components from a
dead microwave, so your circuitry will
most certainly differ.

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 31


Figure 2—An 8051-style microcontroller monitors the switches
and provides precisely timed pulses to the triac drive circuitry.
The VFL display uses a nonstandard serial data rate requiring
a 12-MHz CPU crystal.

highly inductive load, I planned to use from April. The first trigger pulse Firing half-cycles into a real transformer
maximum-voltage switching at 90° occurs at the voltage peak, with suc- isn’t good practice, because the unipo-
into the cycle. For a bit more flexibili- cessive negative and positive pulses lar current draws DC power from the
ty, I set up Timer0 to generate eight maintaining conduction for another AC line-voltage supply and biases the
interrupts per power-line cycle at each complete cycle. The Gate voltage core magnetization. That bias can
45° point. The nominal time between modulation isn’t as crisp as in the cause large transients as a subsequent
interrupts is therefore: simulation, but the effect is still obvi- current of the other polarity drags the
ous. Again, the actual circuit shuts off core flux across the entire hysteresis
1
2.083 ms = cleanly when the triac current hits loop. Although I programmed several
8 × 60 Hz [4]
zero after the final trigger pulse, even half-cycle patterns to match the simu-
I subtracted 20 µs from that value as the triac’s main-terminal voltage lations, they’re just for comparison
to account for the instructions snaps downward. purposes.
between each IRQ event and The firmware distributes
its ensuing timer reload. A triggering pulses over six con-
410-µs Finagle Constant for secutive power-line cycles to
the first delay put the first provide duty-cycle control in
90° output at 2.083 ms after 17% increments. Each six-
the exact line-voltage zero cycle pattern lasts for 100 ms,
crossing, thus aligning the so the transformer thumps at
remaining seven interrupts at 10, 20, or 30 Hz as the triac
their nominal phase angles. switches on and off. An over-
Each zero-crossing interrupt all “burn timer” controls the
resynchronizes the Timer0 power-on duration in incre-
interrupts to eliminate any ments of 100 ms.
accumulated timing error. It’s Each tap on the foot switch
a simple matter of software! produces a single, well-
defined heating event that can
LOOKING AT CYCLES Photo 2—Zero-cross triggering involves a slight delay while the circuitry turns
range from 100 ms (a single
Photo 3 corresponds to the on and the interrupt-handler firmware gets control. Unlike the simulated circuit, six-cycle pattern) up to 255.9 s
simulation results in Figure 3 the triac turns off cleanly when Trace 2, the main current, reaches zero. (probably a mistake!). The tip

32 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


contact switch must
remain closed; open-
ing it will immediate-
ly cancel the heating
pulses.
The “pattern num-
ber” is an index into
an array of pointers to
lists of patterns: the
half-cycle pulse in
Photo 2 corresponds
to Pattern 1. Patterns
1 through 5 produce
test sequences and
Patterns 11 through Photo 3—Triggering the triac at maximum voltage closely matches the lagging
current waveform found in an inductive circuit.
16 produce 1/6
through 6/6 duty-
cycle controlled heating sequences. a commercial product, but it provides
Each pattern list entry contains a an extremely adaptable testbed for
phase number and the corresponding triac control experimentation. It’s also
triac gate drive transistor bit pattern. a good way to sanity-check your reac-
When the “phase counter” matches tive-load triac switching simulations.
the phase number, the firmware
copies the bits to the output port driv- HIGH-CURRENT RESULTS
ing the optoisolators. A state machine My Sencore PR57 isolation trans-
ensures that can happen only when former has 3-A continuous and 4-A
the foot switch is pressed after the intermittent current ratings. The fact
contact switch has been active; the that the high-current transformer’s
firmware forces the gate clamp tran- primary current was only 7 A RMS
sistors active at all other times to hold with the secondary shorted showed
the triac off. that the PR57 limited the overall cur-
For example, Photo 4 shows Pattern rent and, while the few cycles
14, the 4/6 duty cycle pattern. The required for Photos 2 to 4 didn’t trip
triac is on during four cycles of the the PR57’s breaker, it did complain
six-cycle pattern: two cycles on, one loudly at the abuse.
off, two on, and one off. The Gate The high-current transformer’s five-
drive starts with a high pulse at the turn secondary produces 5 V to drive
maximum voltage point, then alter- 200 A into a 25-mΩ load, roughly a kilo-
nates between low- and high-drive. watt applied to the soldering joint. On
This combination of transistorized the primary side, that would be a
gate drive circuitry and microcon- tractable 8 A, less than a typical hair
troller logic is utterly uneconomic for dryer. The transformer’s 7-A reactive cur-
rent pushes the total
load over 10 A, but
that’s still reasonable.
My parts heap
emitted 45 ft of sur-
prisingly flexible dou-
ble-braid-shielded six-
conductor signal
cable that, with all
the conductors and
shields crimped and
soldered in parallel,
had a resistance of 1
mΩ/foot. I made up a
Photo 4—The six cycles shown here have a 2/3 duty cycle: four on, two off. pair of 7-ft leads by
The second group starts with a distinctly distorted cycle. swaging heavy copper

34 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


cauterize the stump in a small parts, providing enough heat to
matter of seconds. Don’t melt solder in a few seconds while pre-
put rings in your pocket, venting the tip from glowing. The con-
either, unless you want a troller’s ability to set an exact time and
leg brand. duty cycle simplifies the whole
process; it’s much better than I could
ELECTRODES do by hand.
Soldering a joint requires
connecting the transformer CONTACT RELEASE
secondary to the work- The duty-cycle pattern table occu-
piece through electrodes pies 10% of the 89C2051’s 2 KB of
Photo 5—Reworked copper crimp connectors adapt the high-current that must carry high cur- memory, but organizing the informa-
cable lugs to the circular electrodes. The graphite block provides a low- rent without joining them- tion that way simplified the inevitable
resistance return path through the brass support plate: those plastic
clamps never get warm.
selves to the surface. Pro- tweakage. A trivial state machine
duction-line resistance sol- tracks the various push buttons and
ring lugs on each end, then flowing dering can benefit from custom-made switches, so the code is fairly straight-
solder into the joint to fill the air gaps electrodes, but I build one-off projects forward. The entire C program, com-
and add mechanical stability. Solder’s that require more adaptability and less ments, blanks, and all, occupies only
conductivity is so poor in comparison fixed expense. 740 lines. How tough can it be?
to copper that a good crimped joint is Photo 5 shows some simple elec- I must now stuff all that hardware
mandatory. trodes made from available materials. into a box to eliminate the electrocu-
Bolting the leads to the trans- The small electrode in the front is a tion hazard, although mounting a sin-
former’s secondary terminals, then bolt- copper-plated steel welding rod, the gle-chip microcontroller alongside a
ing the free ends together produced a middle one is a 4-mm copper-plated 15-lb power transformer poses some
tidy 14-mΩ load. I measured 280 A carbon gouging rod, and the hulking interesting packaging challenges.
with 4.1 V at the secondary terminals, rear electrode came from a military- As I learned many years ago, Finagle
for a total power of about 1,150 W, surplus electric-arc antiaircraft spot- Constants adjust offsets, Fudge Factors
with the high-current transformer light. All three connect to the cable adjust first-order terms, and Diddle
plugged directly into the wall outlet. with a 10-32 machine screw. Coefficients tweak second-order
On the primary side, the trans- The gouging rod produces the best terms. Use them wisely. I
former drew 12.8 A. The Kill-a-Watt results for small-to-medium parts. I
meter reported 1,470 VA and 1,435 W, forged a heavy copper crimp connector Ed Nisley is an EE and author in Pough-
with a power factor of 0.94. into a ferrule and added steel-wire keepsie, NY. Contact him at ed.nisley@
The secondary winding and connect- clamping springs to ensure good con- ieee.org with “Circuit Cellar” in the
ing lugs have about 4 mΩ of resistance tact along the rod. The rod’s tip can be subject to avoid spam filters.
at 280 A, higher than I expected, mak- filed into an appropriate shape to fit
ing the loaded output voltage some- the workpiece.
PROJECT FILES
what lower than predicted. The other “electrode” is a small slab
The accuracy and repeatability of all of machinable graphite clamped to a To download code, go to ftp://ftp.circuit
those measurements is debatable, brass base plate. The graphite is soft cellar.com/pub/Circuit_Cellar/2008/215.
because dumping a kilowatt into 14 ft enough and conductive enough to
of cable raises its temperature enough avoid burning the bottom of the work- RESOURCES
to change the conductivity from shot piece, while eliminating the need to
Transformer design using SI units:
to shot. The numbers fall in the right manipulate two electrodes. The 4-mm
Homo Ludens Homepage, “Transform-
ballpark, though, with transformer carbon electrode conducts about 150 A
ers and coils,” www.ludens.cl/Electron/
losses under 100 W and the high directly to the graphite block; the rod’s
Magnet.html.
power factor reflecting the in-phase tip glows white-hot.
primary current. Although the transformer can deliv- Wikipedia, “Fudge factor,” http://en.
CAUTION! A few hundred amps er a kilowatt, the actual power wikipedia.org/wiki/Fudge_factor.
makes the cables twitch in their own depends on the joint resistance. While
magnetic field and creates an unusual that resistance should be higher than SOURCES
safety issue. If you normally wear a the rest of the secondary circuit, it
PR57 Isolation transformer
finger ring, bracelet, necklace, or must also be low enough to create
Sencore, Inc.
body jewelry, remove it. A metallic enough heat. The 5-V secondary will
www.sencore.com
ring in an alternating magnetic field create only 25 W in a 1-Ω joint and
looks exactly like a single-turn trans- 250 W in a 100-mΩ joint, so pay atten- SDCC Compiler
former secondary winding: a wedding tion to cleanliness. Source Forge
band can burn your finger off and A 50% duty cycle works well for http://sdcc.sourceforge.net

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 35


FEATURE ARTICLE by Scott Bingham & Yunfan Donald Zhang

Ray Tracing Made Simple


A Ray Tracer Implemented On An FPGA
Scott and Yunfan implemented a ray tracer on an FPGA.The ray tracer can draw spheres and
planes with reflections, shadows, Lambertian lighting, patterns on planes, and antialiasing.

W hile working on Master’s degrees


at Cornell University, we took a
to render more complicated objects
with sufficient bounding. We used an
+z

course called Advanced Microcon- Altera NIOS II processor to update the +x


troller Design (ECE 576). Throughout sphere table in the hardware. This
the course, we implemented various enabled us to rotate spheres about any +y

FPGA designs on an Altera DE2 board, axis and have them move without
which contains a Cyclone II FPGA adding significant complexity to the
and an array of peripherals, such as hardware. Switches and push buttons
Ethernet, RS-232, and a VGA port. In were used to allow motion of the
this article, we will describe a ray light source, motion of the origin,
tracer implemented on an FPGA that’s rotation of the scene, selection of the
capable of rendering, rotating, and resolution, the level of reflections,
moving spheres and depicting planes. the level of antialiasing, reset, the
Figure 1—This is a 3-D view of the coordinate system
Our initial goal was to realistically option to render planes, and finally that was used in the ray tracer design. x and y form
render and shade spheres with reflec- the telescoping and widening of the planes that are parallel to the screen, while z repre-
tions while navigating through the camera. sents the depth of an object.
scene and enabling the spheres to
bounce and roll around. Once we RAY TRACING where many calculations can occur
achieved this goal, we added antialias- Ray tracing can be implemented in in parallel. The basic idea is to trace
ing and the ability to render planes as software without much difficulty; the path of a photon, through a
well. Planes can be used as polygons however, it is more suited to FPGAs scene, to the eye. Because we are
concerned only with the photons
that hit the eye, we simulate rays
Reset coming out of the eye, through the
Reset
Initialize ray tracer
Send done screen, and into the scene and see
Sphere list signal to
Reflection ray
what objects they hit. The ray picks
Initial ray loaded CPU
Yes
Yes (Hit a sphere?)
End of frame
(Hit a sphere?) up color based on the reflectivity as
Apply No Load spheres from CPU
Launch
No Apply it collides with objects in the scene.
Lambertian reflection Lambertian
lighting New ray Send done
ray lighting Eventually, the ray is stopped
signal to
Initial ray CPU Reflection ray because it misses objects in the
(Hit a plane?) (Hit a plane?) scene or picks up negligible color in
Yes No Set up next ray No Yes
subsequent reflections. Shadows are
Launch Launch (Ray intersection?) Launch Launch
Determine Determine
shadow shadow
color of (More reflections?) color of
shadow shadow determined by shooting rays from
ray ray ray ray
pixel and if pixel and if
pixel done
(Antialiasing?)
pixel done intersection points back toward the
Shadow ray (End of line?) Reflection shadow ray
(Hit sphere before light?) (End of frame?) (Hit sphere before light?) light source or sources in the scene
and seeing if there is an object in the
Figure 2—This is a high-level state machine diagram for the FPGA ray tracer. It shows the decisions the ray tracer way to block the light. Shading is
goes through after reset to display one frame on the screen. also performed by weighting light

36 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


ow ray is needed. If the ray does not hit
t a sphere, the planes in the scene are
Definition of Ray tHC checked for the closest intersection.
tCA
Origin = R 0 = [x 0 y0 z0 ] RO RD
Direction = R D = [x D yD zD ] oc SR
D SPHERE BACKGROUND MATH
LOC
R (t) = R 0 + R D • t SC Figure 3 gives us the implicit equa-
tion for a sphere. We can test points in
Definition of Sphere our ray to see if they lie on the
Center = SC = [x C yC zC ] sphere’s surface. The algebraic solu-
Radius = s R tion follows. By combining the para-
Surface = SS = [ x S yS z S ] metric expression for the ray with the
implicit equation, we get:
(xS − x C ) ( yS − y C ) + ( zS − z C )
2 2 2
Equation: s R 2 = +
• •
Calculation of Intersection •
t I = intersection distance
t CA = OC • R D •

d OC2 = OC2
The general form of a quadratic equa-
d 2 = d OC2 − t CA2 tion is:
t HC2 = s R 2 − d 2 = s R 2 − d OC2 + t CA2
a • t2 + b • t + c = 0
( )
t I = t CA − sqrt t HC2
In this case:
Intersection = R I = [x I yI zI ] = [x 0 + x D • t I y0 + yD • t I z 0 + z D • t I ]
⎡( x − x C ) ( x I − x C ) ( x I − x C )⎤
Normal = R N = [x N yN zN ] = ⎢ I
sR sR sR
⎥ • • •
⎣ ⎦
• • •

Figure 3—These are essential equations to solve in order to determine whether a ray intersects with a sphere.
All vectors in our calculations are normalized. Values are represented in 24-bit fixed points with 12 integer and
12 decimal bits. You can then solve the quadratic
equation for t and find the closet
intersection point, if any. This is
that hits a surface perpendicularly for the closest intersection, if any, exactly what we do. However, we use
greater than light that merely glances with the spheres in the scene. If it our knowledge of the geometry of the
off. The coordinate system we used hits one, Lambertian lighting is situation to come up with a sequence
is shown in Figure 1. Depth is in the applied to give it a color based on the of steps that delays the square root of
z direction. amount of shadow. If the intersection the quadratic equation and offers
Each ray that intersects with an is completely in a shadow, no shad- checks to bail out of the calculations
object shoots a shadow sooner if an intersection
ray and possibly a reflec- is impossible.
tion ray depending on First, we check if the
the switches and weight Definition of Ray ray originates inside the
given to the reflection Origin = R 0 = [ x 0 y 0 z 0 ] sphere by calculating a
ray to be launched. If Direction = R D = [ x D y D z D ] vector from the ray origin
less than 1% of the light R (t ) = R 0 + R D • t to the center of the
will be reflected, a sphere and the square of
reflection ray won’t be Definition of Plane its magnitude:
launched. We also Normal = P N = [a b c] , where a 2 + b 2 + c 2 = 1 OC = SC − R 0
impose the restriction of d is distance from origin [0 0 0] to plane
d OC2 = OC2
a maximum of three Equation: a • x + b • y + c • z + d = 0
reflection rays to limit If dOC2 is less than SR2,
the time spent per pixel. Calculation of Intersection then we know the ray
A high-level state dia-
tI =
(PN • R 0 + d ) originated inside the
gram for the ray tracer is PN • R D sphere. If the ray origi-
shown in Figure 2. At Intersection = R I = [ x I y I z I ] = [ x 0 + x D • t I y 0 + y D • t I z 0 + z D • t I ] nates inside any sphere,
reset, the tracer is ini- we color the pixel black
tialized and the sphere and move on because no
Figure 4—Fewer equations are needed to determine plane intersections. The intersection
list is loaded from the point is used to determine what color to apply when a pattern (e.g., checkerboard) is light penetrates our
CPU. A ray then checks applied to the plane. spheres. Note that this is

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 37


point and the normal:

Shadow vector reuses RI = R0 + RD • tI


Normalize Initial Calculate new direction vector, next
hardware/states of normal
R I − SC
direction direction pixel or antialias ray, combine
ray sphere checking RN =
vector vector color & write to SRAM if pixel done
SR
No, Miss
We check all of the spheres in the
No, Miss sphere list to find the closest intersec-
More More planes
spheres to
No, Hit No
to check?
tion if there is more than one.
check? Doing reflections? Yes, Yes Calculate No, Hit
Yes All direction vectors are normalized
Weight/reflections reflection
Yes
within bound? vector Calculate vd
in our calculations to reduce the num-
Calculate
ber of calculations required. This also
ray from Check if ray helps prevent overflowing when we
ray origin to Yes parallel to
center of plane and No
determine the magnitude of vectors by
Check if in Calculate
sphere and normal limiting the size of the result. The
shadow of shadow
magnitude pointing
own sphere vector
towards ray inverse radius and radius squared are
Yes precomputed and stored in the sphere
Check if ray
Apply Normalize list to save calculation time at the
No originates
from outside Lambertian shadow Calculate vo expense of memory/register usage.
lighting vector
sphere
Yes Calculate
No Yes
t = vo/vd PLANE BACKGROUND MATH
No Check if ray
Normalize
More
hits sphere
Planes, in comparison, require fewer
Calculate spheres to
closest normal check?
Check if
No calculations to determine if there is a
intersection
approach
Yes Calculate in front of ray intersection (see Figure 4). We start
along ray to half courd ray origin
sphere distance with the implicit equation for a plane.
center Check if
squared
Calculate No sphere Yes Given point P = [x y z], then:
normal closer than
Yes Calculate
Check light source
intersection PN • P + d = 0
sphere is in Check
No point
front of ray Yes sphere is in
origin No front of ray By combining the parametric expres-
Calculate origin
Yes
intersection Checker sion for the ray with the implicit
Calculate point Calculate Calculate
board equation for the plane, we get:
half chord ray from pattern/
closest
PN • ( R 0 + R D • t I ) + d = 0
distance ray origin to plane
approach bounds
squared center of along ray to
sphere and sphere
magnitude center Key: We can solve this for tI, the intersec-
Calculate
No Check if ray Yes intersection Common Shadows tion distance, and get:
hits sphere distance
Planes Spheres

tI =
(PN • R 0 + d)
PN • R D
We calculate the denominator first.
Figure 5—This is a detailed version of the ray tracer state machine. The states are grouped by color based on their
If PN · RD equals zero, the ray is paral-
functions. There are states that perform functions that are shared by all states and states dedicated to drawing
shadows, planes, and spheres. lel to the plane and we can disregard
it. Likewise, if PN · RD is positive, the
plane’s normal is pointing away from
not true of shadow rays because they Following that comparison, we cal- the origin and we disregard it in our
may originate (RI) under the surface culate the half-chord distance
because of the limited precision of squared, where the half-chord dis-
our calculations. We ignore the result tance is the distance from the point
of this comparison for shadow rays. found by tCA and the surface of the
1/16 1/8 1/16 1/8 1/8
Next, we calculate the distance sphere:
from the origin to the point along the d 2 = d OC2 − t CA2 1/8 1/4 1/8 1/2
ray that is closest to the sphere’s
t HC2 = s R 2 − d 2 = s R 2 − d OC2 + t CA2
center: 1/16 1/8 1/16 1/8 1/8

t CA = OC • R D If t2HC is negative, the ray misses the


8× 4×
sphere. We then calculate the intersec-
If tCA is negative, then the sphere is not tion distance:
in front of the ray origin (as defined by t I = t CA − sqrt t HC2 ( ) Figure 6—These are the weights that were used in the
4× and 8× antialiasing functions. Antialiasing takes a
the ray direction), so we know the ray
weighted average of a pixel and the eight pixels (or four
does not intersect this sphere and can Once we have the intersection distance, pixels in the case of 4× antialiasing) immediately sur-
move on to the next one. we can calculate the intersection rounding it and uses that as the new value for the pixel.

38 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


rendering. This is done so planes can-
not block spheres. If we move the ori- a) b)
gin behind a plane, it is not drawn.
This gives the effect of it being a one-
way mirror. When behind it, it
c) d)
appears not to be there. But when in
front, it acts as a normal surface (mir-
rored if the reflection is not zero).
Next, we calculate the numerator
PN · R0 + d and then t. If t is negative, e) f)
the intersection is behind the origin
and therefore not a hit. Again, the
intersection point is calculated:
RI = R0 + RD • tI g) h)

We do not have to calculate the


normal with planes because we
already have it in the plane table in Photo 1—This is an identical scene drawn with various
PN = [a b c], which was used in the levels of antialiasing and reflection.
previous calculations. Also, the nor-
mal is the same for any point on the most of the math using hardware
plane (opposite sign on the other modules. The software, on the other
side), which is not true of spheres.
This also makes planes much quicker
to render than spheres.

REFLECTIONS
Physics tells us that the following
two statements are true:
θI = θR
VR = θ • VI + θ • VN

The angle of incidence equals the


angle of reflection and the reflection
vector is a linear combination of the Photo 2—This is a zoomed-out view of a scene with 13
incident and normal vectors. This can spheres and one light source (white sphere). The frame is
drawn with all of the features except planes turned on.
be transformed into a useable equa-
tion by the following:
cos (θ I ) = cos (θ R )
hand, can compute more complex cal-
culations that are not crucial to ray
− VI • VN = VN • VR
tracing itself. Calculations such as
− VI • VN = α ( VN • VI ) + β
If we set α= 1 , then β = –2 · (VN · VI).
Substituting into our physical law, we
get:

VR = VI − 2 • ( VN • VI ) • VN
The resulting reflection vector VR is
also normalized when the incident
vector VI and the normal vector VN are
also normalized.

SOFTWARE/HARDWARE TRADE-OFF
Many of the functions in the ray trac-
er can be performed by either the hard- Photo 3—Six small spheres are embedded on a larger
green sphere, with two more equally sized purple
ware or the software. We tried to take
spheres farther in the background. The light source is at
advantage of the hardware parallelism the lower-right corner. One purple sphere is experiencing
as much as possible by calculating an eclipse due to the green sphere and is barely visible.

40 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


Look at the Peripherals
You Can Map to I/O Pins
The Microchip name and logo, the Microchip logo and MPLAB are registered trademarks of Microchip Technology Incorporated in the USA and in other countries. All other trademarks mentioned herein are property of their respective
companies. ©2007, Microchip Technology Inc. All rights reserved.

Now you have the flexibility to customize your microcontroller with


Microchip’s Peripheral Pin Select feature.
Get up to 64 KB of Flash and 8 KB of RAM
in as few as 28 pins with a peripheral set
Purchase and program your microchip
16-bit PIC24 devices and
that can be dynamically customized for your related development tools at... DIRECT
www.microchipdirect.com
application with Microchip’s 16-bit PIC24
RAM Flash
microcontrollers! Device Pins (KB) (KB) Features include up to:
PIC24FJ16GA002 28 4 16 5x 16-bit Timers
GET STARTED IN 3 EASY STEPS
at www.microchip.com/PPS PIC24FJ16GA004 44 4 16 5x Output Compare/PWM
1. FREE 16-bit web seminars PIC24FJ32GA002 28 8 32 5x Input Capture

2. FREE product samples PIC24FJ32GA004 44 8 32 Real Time Clock Calendar


PIC24FJ48GA002 28 8 48 2x UART
3. Exclusive development tool discounts
PIC24FJ48GA004 44 8 48 2x SPI
Check out our web PIC24FJ64GA002 28 8 64 2x I²C™
site for special pricing
on the 16-bit 28-pin PIC24FJ64GA004 44 8 64 Parallel Master Port
Development Kit and
MPLAB® ICD 2 PIC24HJ12GP201 18 1 12 2x Analog Comparators
In-Circuit Debugger! PIC24HJ12GP202 28 1 12 10/12-bit ADC

Registration is now open!

www.microchip.com/MASTERs www.microchip.com/PPS

Microcontrollers • Digital Signal Controllers • Analog • Serial EEPROMs


SDRAM

NIOS II

8 16 24 24 24 12 12 24 12
sphere color x1 y1 z1 reflect radius r2 R_inv valid rotz done

Switch Address Writeback VGA


18 18
Ray tracer buffer blank Control To monitor
16 Data
4 Key

SRAM

Figure 7—This is a hardware-software interface. The ray tracer communicates with the embedded NIOS II processor with an array of parallel I/O lines. The software runs on
the NIOS II processor and uses SDRAM for its instruction and data cache. The ray tracer communicates with the VGA control via a writeback buffer and SRAM.

sphere movement and rotation are point unit, the software also has the which coordinates with the VGA con-
performed by the software while the advantage of having a higher precision troller to access the SRAM. The VGA
hardware draws the frames. This than the hardware, which uses a fixed controller reads the screen values
maximizes the efficiencies of both point. from SRAM and sends them to the
parts so the hardware state machine The ray tracing hardware consists of VGA DAC along with the necessary
can run as fast as possible while the a large state machine responsible for clock and synch signals. The ray tracing
software does not sit idle waiting for calculating the color of all the pixels. hardware interfaces with the NIOS II
the hardware. By using a real floating- Pixel data is written to a write buffer, CPU through the sphere table and one
state in the state machine where it
reads values from the CPU.
The detailed state machine is
shown in Figure 5. The initial ray is
normalized over several cycles, which
requires a magnitude calculation, a
square root, and a division. Then for
each sphere, we check whether the ray
origin is inside a sphere. If a ray origin
is inside a sphere, the ray is not drawn
because it would be impossible to see
it. If it is, the pixel is drawn black and
we can move on to the next one. Oth-
erwise, we check to see if a sphere is
in front of the ray and whether or not
it intersects.
If an initial ray does not intersect
with a sphere, it would then be
checked with the plane list. The same
is true for a reflection ray. Also, if a
shadow ray intersects with any sphere
closer than the light source, a shad-
ow is cast on the origin of the shad-
ow ray. Because we are concerned
with the closest intersection, we
must check every sphere after an
intersection is detected, so the clos-
est distance and its intersection
point are stored until all spheres
have been checked. Shadow rays can

42 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


stop once a single intersection has intersected with thus far is multiplied rays are shot per pixel and the result-
been found, so they typically take less together so less light reaches the eye ing color from each is summed using
time. Also, we impose the limitation from further intersections. If there is a the weights in Figure 6. The weight
that the light source itself does not reflection vector, the color produced for 4× antialiasing is also shown in the
cast shadows. Although the light from the previous ray is stored and a figure. The effects of antialiasing are
source is a single point in space, we reflection color is added on top of that clear in Photo 1. Photo 1a has no
draw it as a small “pure” white sphere when the reflection ray completes. We antialiasing or reflections. Photo 1b
to make it more convincing. check for saturation on any given has 4× antialiasing, followed by 8×
To create a reflection vector, we color, so adding more of the color to antialiasing (Photo 1c), followed by
must know that the normal to the the pixel does not help. This gives the one (Photo 1d), two (Photo 1e), and
intersection point on the sphere’s sur- realistic effect that you see reflections three (Photo 1f) levels of reflections
face is used to calculate the angle of better on dark, shiny objects. Antialias without antialiasing, followed by
incidence and reflection. For planes, sub-pixel rays are stored in a special three levels of reflections and 8×
this is trivial because it is already buffer until all of the rays for that antialiasing (Photo 1g), and finally
stored in the plane table. The direc- pixel have been calculated and then three levels of reflections, 8×
tion of the sphere’s normal is easy to they are combined. antialiasing, and planes being ren-
get; however, it takes many cycles to Planes are checked in a similar way dered (Photo 1h).
normalize it. Once we have the nor- to spheres, but with more restrictions,
mal and the direction of a shadow vec- such as xyz bounding and rendering WRITE BUFFER & SQUARE ROOT
tor, we take the dot product and scale plane faces that are on the correct side To decouple the execution of the ray
the color of the intersection accord- of the scene (i.e., you can see through tracer from writing to the VGA mem-
ingly. This creates realistic shadows the “back” side of the plane). This is ory, we implemented a 64-entry circu-
that are brighter when the light vector for performance reasons and the fact lar FIFO buffer to store information to
coincides with the normal. We store that we will use only planes as bound- be written to the SRAM. The buffer
the inverse of the radius in the sphere ing mirrored surfaces in our scenes. stored both the 18-bit SRAM address
table to make normalization slightly and the 16-bit data to be written. This
faster by doing a multiply instead of a ANTIALIASING enabled us to calculate pixels at full
divide. Once we have the normal, we Jaggies appear in images rendered on speed without having to wait on the
have part of the reflection vector cal- a computer screen due to the finite VGA reading of SRAM to store data
culations done. pixelation/quantization used. The and move to the next pixel.
At this point, we need to check solution is to super-sample the image We implemented our own square-
whether or not we want to launch a and average the color among adjacent root function by porting a C code
reflection based on the number of rays. Our antialiasing implementation square-root function that we found
reflections so far and the weight of the has the option to do either 8× or 4× online into Verilog and modularized it
reflection. The weight of each object antialiasing. For 8× antialiasing, nine to do multiple iterations per cycle.[1]
The square-root module used an edge-
Rays per Cycles Rays/sec Frames/ triggered start signal to begin calcula-
frame (25 MHz)/frame second tions. When the correct number of
Image 1 Simple 277,814 12,662,119 548,514 1.974 iterations for the number of submod-
Eight spheres Full reflection 310,175 14,003,794 553,734 1.785 ules was complete, the result was
No plane Full antialiasing 2,500,295 113,981,083 548,401 0.219 placed on the outputs and a done sig-
Full antialiasing + reflection 2,792,565 126,094,828 553,664 0.198 nal was raised.
Image 1 Simple 490,699 22,300,008 550,111 1.121
Eight spheres Full reflection 1,802,813 78,305,473 575,571 0.319 VGA/SRAM
Four planes Full antialiasing 4,413,303 200,596,329 550,023 0.125 The VGA controller was responsible
Full antialiasing + reflection 16,213,574 704,338,405 575,489 0.035 for fetching pixels to draw on the
Image 2 Simple 353,528 22,544,244 392,038 1.109 screen from the SRAM, producing
Eight spheres Full reflection 547,627 33,850,568 404,444 0.739 synchronization signals, and creating
No planes Full antialiasing 3,182,440 203,017,700 391,892 0.123 the front and back porches required
Full antialiasing + reflection 4,929,447 304,791,218 404,330 0.082 for VGA displays. We implemented
Image 2 Simple 492,358 28,868,738 426,376 0.866 both 320 × 240 and 512 × 480 (really
Eight spheres Full reflection 1,804,498 102,301,169 440,977 0.244 640 × 480 with part of the screen
Four planes Full antialiasing 4,428,189 259,797,987 426,118 0.096 black) resolutions. The VGA con-
Full antialiasing + reflection 16,225,005 920,108,168 440,845 0.027 troller has two counters, one for hori-
Best case 108,422 4,678,168 579,404 5.344 zontal pixels and one for vertical lines.
Table 1—A total of 17 scenes were drawn to show the speed of the ray tracers in terms of rays per second and
First, a synch signal (active low) is
frames per second. They include four configurations for four different scenes, which all have a resolution of 512 × 480 produced. After the counter reaches a
and a best-case performance (a low-resolution scene of 320 × 240 with no features turned on). certain value, the synch returns high

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 43


700,000 2.500
600,000

Rays per second


2.000

Frames per second


500,000
400,000 1.500
300,000
1.000
200,000
100,000 0.500
0
0.000
Simple Full Full Full AA+ Simple Full Full Full AA+
reflection antialiasing reflection reflection antialiasing reflection

Image 1 no plane Image 1 with planes


Image 2 no plane Image 2 with planes

Figure 8—These charts show the performance of the ray tracer for two images with different complexities and at various antialiasing and reflection settings. The performance of
the ray tracer in terms of frames per second decreased greatly when additional features, such as reflection and antialiasing, were turned on.

and the back porch begins. Once the gradient). data on the buses is valid to read. Rotz
back porch is completed, the VGA [7:0] (input) sets the different modes
controller uses the horizontal and ver- NIOS II & FPGA COMMUNICATION for rotating all of the spheres around
tical counters to produce coordinates Several buses are used to interface the x, y, and z axes. Done (input)
for the current pixel being drawn. between the C code running on the means that only when done is high
Once the visible resolution is complet- NIOS II processor and the hardware in will the software send out the sphere
ed, the front porch begins. Following the FPGA. Sphere [7:0] (output) con- information one by one.
the front porch, the process repeats trols the total number of spheres As soon as the hardware gets all of
with a synch signal. Similar actions drawn and the number of spheres that the updated sphere information, it
are taken by the vertical line counter, are currently being drawn. Color [15:0] will draw the frame. In the meantime,
except the clock is the end of a line (output) specifies the color of a sphere. the software will call motion and rota-
rather than a pixel. While the VGA X1 [23:0] (output) is the x location of tion functions to calculate the new
controller was synching, the write the current sphere. All locations are locations of the spheres.
buffer was free to write to SRAM at represented in fixed-point format,
one pixel per cycle. with 12 bits each for integer and deci- SOFTWARE
The coordinates produced by the mal portions. On the software side, The hardware-software interface for
VGA controller were used to access the location needs to be multiplied by the ray tracer is shown in Figure 7.
memory at the word level. We used 4,096 (i.e., 212) so the hardware will The software running on the NIOS II
the lower 9 bits from each of the x get the correct value. Y1 [23:0] (out- has three main functions. It stores the
and y coordinates to index SRAM. put) is the y location of the current list of spheres to be drawn on the
This limited our resolution to 512 sphere. Z1 [23:0] (output) is the z loca- screen, performs motion calculations
pixels wide, but it made indexing tion of the current sphere. Reflect on the spheres, and rotates the camera
easy. Because SRAM can hold 16-bit [11:0] (output) is reflectivity of a angle to enable you to “look around”
words, we used 1 bit to indicate that sphere in a 12-bit integer. Radius the environment. Each data entry for a
a pixel was the light source and 5 to [11:0] (output) is the radius of a sphere sphere contains information such as
represent the red, blue, and green in a 12-bit integer. R2 [23:0] (output) is its location, color, velocity, radius,
content of a pixel. When read back the radius squared of a sphere in a 24-bit and reflectivity. The NIOS II processor
from SRAM, the RGB values were integer. R_inv [11:0] (output) is the was designed as a DRAM controller,
used as the upper 5 bits of the 10-bit inverse of the radius of a sphere in a enabling us to store a large number of
RGB lines going to the DAC. If the 12-bit decimal point. The valid signal spheres and polygons on the DRAM
pixel being drawn was part of the (output) tells the hardware that the without writing a separate memory
light source, the lower bits were set controller. Putting the scene object
high to enable us to produce “pure” Family Cyclone II list on the DRAM frees up the SRAM
white. Otherwise, they were left as 0. Device EP2C35F672C6 for the VGA memory.
Representing each color in 5 bits, Total logic elements 32529/33216 (98%) The motion function software
however, lead to some quantization Total registers 6,348 updates the current location for each
of color. This is most clearly visible Total memory bits 94,688 (20%) sphere by its current velocity. It also
in the Lambertian shading where Total PLL 2/4 (50%) performs boundary and collision
there are small concentric rings of a detection with other spheres. A 2-D
Table 2—These are the FPGA usage statistics from the
shade of the sphere color before sphere-collision algorithm is expanded
compilation report of the final design. In the end, our
jumping to the next slightly different design was limited by the number of logic elements to work in 3-D.
shade (rather than being a smooth available on the FPGA. The rotation function rotates all of

44 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


the spheres in the list about the x, y, all have a resolution of 512 × 480 and objects, there are no visible artifacts
or z axis by a fixed radian every frame. a best-case performance (a low-resolu- on the screen.
The rotation is always revolving tion scene of 320 × 240 with no fea- In the future, we plan to add trian-
around the center (0, 0, 0) in space. tures turned on). gular polygon detection to the plane
The direction of rotation is controlled Figure 8 shows our ray tracer’s per- hardware. We also intend to use mul-
by user input switches. formance statistics. The number of tiple FPGAs to increase the frame rate
All of the location calculations in rays per second varied between and we will reuse multiply hardware
software are done in floating point. 440,000 and 540,000, depending on across multiple stages. Finally, we
Whenever the data is ready to be sent the specific scene. As expected, the plan to pipeline the design on a larger
to the hardware, the result is convert- number of spheres and planes both FPGA to increase the frame rate. I
ed to integers by multiplying the cor- have a big impact on the performance
rect two’s power. of the ray tracer. Certain relationships Scott Bingham received B.S. and
can be observed from those graphs. M.E. degrees in Electrical and Com-
SOPC BUILDER SPECS The number of rays per second is puter Engineering from Cornell Uni-
We used the highest level NIOS II/f more affected by the number of versity. He currently works as a com-
CPU available so we could send the spheres and planes and less by what puter engineer for Advanced Micro
sphere list as fast as possible. The features are turned on. On the other Devices in Sunnyvale, CA. You may
CPU runs at 50 MHz. It has a 1-KB hand, frames per second is mostly contact him at stb25@cornell.edu.
instruction cache, an 8-KB data affected by which features are turned
cache, and a line size of 16 bytes. on. For the same scene, when both Yunfan Donald Zhang was born in
The data cache is big enough to hold eight times antialiasing and three lev- Beijing, China, in 1984. He received his
all of our sphere data without evic- els of reflection are turned on, the B.S. and M.E. degrees both in Electrical
tions that would force costly DRAM frame rate can have up to a 30 times and Computer Engineering from Cornell
accesses. decrease from the standard case. University. He is currently working at
The CPU also has a floating-point In the end, we had to limit our Raytheon in Marlborough, MA. His
unit for the floating-point calculations design because of a limited number of interests include digital hardware design
in the software. Logic elements were logic elements available to us on the and FPGA design. You may contact
used for hardware multiply. The per- FPGA. The NIOS II CPU uses about him at yunfan_d_zhang@raytheon.com.
formance of this processor is up to 51 1,400 to 1,800 LEs, which leaves us
DMIPS. with 33,216 LEs for the ray tracer
hardware. We had to shrink the num-
PROJECT FILES
DESIGN DIFFICULTIES ber of spheres that can be drawn so To download code and additional files, go
Our biggest design challenge was our design could fit on the FPGA. to ftp://ftp.circuitcellar.com/pub/Circuit
signed arithmetic. We had to explicitly Table 2 shows the statistics from the _Cellar/2008/215.
manage the signs of operands in multi- compilation report of our final design.
plications by making both operands
REFERENCE
positive, multiplying, and then fixing THINKING AHEAD
the result’s sign, if necessary. Meeting Overall, our ray tracer performed [1] K. Turkowski, “Fixed Point Square
the clock-cycle timing requirements much better than expected. The Root: Technical Report No. 96,”
while trying to pack as many calcula- graphics look quite impressive on Apple Computer, 1994, www.world
tions as possible into a given state was some of the pictures with full server.com/turk/computergraphics/
also tricky at times. antialiasing and three times reflec- FixedSqrt.pdf.
Debugging on a per-pixel basis was tions (see Photos 2 and 3). Because we
also impossible once a large number of used almost every logic element on RESOURCES
spheres, shadows, and reflections were the FPGA, we were unable to instanti-
added. We mostly had to rely on the ate multiple tracers or pipeline our A. Glassner, An Introduction to Ray
VGA output to see if our changes were giant state machine. This limited our Tracing, Morgan Kaufmann, San Fran-
correct. frame rate; however, drawing a few cisco, CA, 1989.
bouncing spheres on the 320 × 240 B. Land, “Ball Bouncing Physics,”
STATISTICAL ANALYSIS resolution with 4× anti-aliasing and ECE476 Lab 4, Cornell University,
Now we will describe some of the full reflections still ran at a reasonable http://instruct1.cit.cornell.edu/courses
performance statistics of our ray trac- rate. Adding antialiasing, reflections, /ee476/.
er. A total of 17 scenes were drawn to and planes was a better use of the
show the speed of the ray tracers in hardware resources than pipelining
terms of rays per second and frames our design. The realistic renderings SOURCE
per second. The 17 scenes are listed in we were able to produce support this. DE2 Board and NIOS II processor
Table 1, which include four configura- While the tracer draws slowly on the Altera Corp.
tions for four different scenes, which complicated scenes with many www.altera.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 45


FEATURE ARTICLE by Peter Baston

AIS Transmission Decoding


Peter created a system that receives and decodes data transmissions from ships and
other vessels via the Universal Automatic Identification System. Built around a Luminary
Micro LM3S811 evaluation board, the decoder displays a “virtual” radar screen, showing
the position of vessels in the area.

A s a ham radio and embedded hard-


ware/software engineer, I have long
Test point

RX DATA
been interested in decoding off-air data Audio from
CMX589A GMSK
RX CLK
LM3S811
U0Tx
To host
RX S/N FT2232C USB
receiver USB
transmissions. From an early interest discriminator
Modem PLLAcq Microcontroller
U0Rx Device controller computer
RXDCAcq
in radio teletype (RTTY) transmis- RXHOLDn
sions, I moved on to DOS programs to
LM3S811 Evaluation board
decode the data from trunked radio
systems and paging systems. When I
Figure 1—This system features a GMSK modem interfaced to an LM3S811 evaluation board.
heard about a new marine data system
carrying ships’ positions, I just had to
have a go at decoding the data! Gaussian minimum shift-keying 161.975 and 162.025 MHz. To receive
The Universal Automatic Identifica- (GMSK) transmissions used by the AIS. the transmissions, a narrow-band FM
tion System (AIS) is a data system that I used a CML Microcircuits CMX589A (NBFM) receiver that is capable of cover-
operates on two frequencies in the modem for this purpose (see Figure 2). ing the VHF marine band is required. I
marine VHF FM band. Ships, and other My complete system, including the used an Icom IC-R7000 communications
fixed installations, make frequent modem and the LM3S811 module, is receiver. This is a fairly old, but very
broadcast transmissions that may be shown in Photo 1. able, communications receiver that
received by other vessels in range. The covers the 25-MHz to 2-GHz frequency
transmissions carry both “dynamic” HARDWARE range. My receiver was modified to
information (i.e., position and speed) AIS transmissions can be heard on two bring the discriminator output out to
and “static” information (i.e., name, frequencies in the marine VHF band, an RCA jack in the rear. This provides
call sign, and more). A decoder receiv-
ing the transmissions can display a
“virtual” radar screen showing the
position of other vessels in the area.
The Luminary Micro LM3S811 eval-
uation board seemed like the ideal
platform for developing an AIS
decoder (see Figure 1). The Stellaris
microcontroller has a low-interrupt
latency, and it is ideal for decoding a
serial stream in software. Also, a USB
COM port is connected to one of the
microcontroller’s UARTs. This is per-
fect for transferring data back to a PC
program with serial data.
In addition to the microcontroller, I
needed a modem to demodulate the Figure 2—This is the CMX589A GMSK modem section.

46 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


output is demodulated by the
CMX589A, which outputs clock and
data signals at a rate of 9,600 bps. The
signals are interfaced to I/O pins on
the LM3S811 microcontroller. Other
I/O pins enable you to monitor a
received signal/noise ratio and control
the modem’s acquisition sequence.
UART 0 on the LM3S811 is connected
to a Future Technology Devices Interna-
tional FT2232C USB device controller
on the evaluation board. This appears as
a COM port on the PC, enabling com-
munication with the UART via a stan-
dard communications program.

GMSK DEMODULATOR
Figure 2 shows the GMSK modem
section, which I constructed on strip-
board. I followed the recommendations
Photo 1—This is my AIS decoder board connected to the Icom IC-R7000 communications receiver. given in the CMX589A datasheet.
Note that the CMX589A is a full
the linearity and DC coupling required a busy shipping area in northwest modem, enabling both transmitting
by the GMSK modulation scheme. England. and receiving of GMSK signals, but
Of course, the receiver also requires a only the reception section is used in
suitable antenna to be within receiving DECODER BOARD this application.
range of shipping traffic! Luckily, I live Figure 1 shows the entire system. The discriminator audio is DC-cou-
within 10 miles of the River Mersey, Audio from my receiver’s discriminator pled into the modem with a gain and a

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 47


Exclusively at Jameco…
The Lowest Prices…
Guaranteed!
Save 3% to 5% Save 15%-25% Save 30% or more!
Looking to save on thousands of Save more when a specific Looking for killer deals? Jameco
Name Brand components? Jameco manufacturer is not required. Major buyers often find Factory Overruns
offers their popular products for 3% Brand semi’s are sourced from 5-6 from some of the industry’s biggest
to 5% below market price, and we major manufacturers, plus we offer names. That means savings of 30%
and more to you!
guarantee it! Jameco brand and generic passives
for even greater savings.

3 Levels of Choice
3 Levels of Savings

Other Jameco Advantages:


 We offer over 300 Major Manufacturers
 99% of catalog products ship the same day.
 Lowest prices guaranteed, or we pay 10%.

Order 24 hours a day, 7 days a week


www.Jameco.com
Or call800-831-4242 anytime
SEMICONDUCTORS • PASSIVES • INTERCONNECTS • ELECTROMECHANICAL • POWER
pin to the microcontroller, but it is board. This makes it easy to move the
not currently used by the software. evaluation board onto other projects, if
The CMX589A requires a single required, or to operate it on its own.
supply rail between 3 and 5.5 V. I pow- Figure 3 shows how I interfaced my
ered the circuit from the 3.3-V rail on GMSK modem to the evaluation
the LM3S811 evaluation board, which board. As you can see, I used only a
is regulated down from the 5-V supply few GPIO pins. I chose them to avoid
from the USB port. pins already used by peripherals on the
evaluation board.
INTERFACE TO THE LM3S811 I defined GPIO pin PD0 as a test
I fitted two strips of 0.1″ sockets to point, which was used to connect an
my LM3S811 evaluation board, enabling oscilloscope during debugging. This
it to plug into headers on my decoder allowed me to check that my interrupt

Figure 3—These are the connections to the LM3S811


evaluation board.

DC-level adjusting circuit. This is


designed to give a roughly 1-VPP signal
on the RX FB pin, centered on VBIAS.
Because the discriminator output of my
receiver has a DC offset of around 4 V, I
had to add the DC balance circuit com-
prising RV1 and R5 to achieve the
VBIAS level.
In addition to the 9,600 bps and
clock outputs, the modem has an RX
SN output, giving an indication of the
received signal/noise ratio. This is a
useful test point for monitoring with
an oscilloscope during debugging.
The PLLAcq and RxDCAcq pins
control the start-up and acquisition
sequence of the CMX589A. The pins
are connected to the microcontroller’s
I/O pins and controlled by software.
At initial power-up, both of the pins
need to be low and stay in that state
for at least 1,024 bit times to initialize
the device. Both pins are then taken
high, while no data is received, put-
ting the device into the “acquire”
state with wide PLL bandwidth. As
soon as a packet preamble is detected
and data is received, the PLLAcq pin is
taken low, narrowing the PLL band-
width. When packet reception is com-
plete, the pin is taken high again.
In addition, the RXHOLDN pin
enables the correction of the clock fre-
quency and the DC level to be stopped
during a signal fade. I interfaced the

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 49


service routine was running and to
measure the amount of time spent in Training sequence
Start
Data FCS
End
Buffering
flag flag
the routine.

SOFTWARE Figure 4—The AIS packet structure is based on HDLC.


Before writing any code, I had to
understand the low-level coding and My program does not use an RTOS. It format and send it out serially.
packet structure used by the AIS data. relies on simple round-robin processing.
The information is freely available in At power-up, the start-up code is INTERRUPT HANDLER
public domain documents. executed. It is contained in the mod- The heart of the decoder is the
AIS data is low-level coded using ule Startup.s on the Circuit Cellar interrupt handler IntGPIOE() in the
non-return-to-zero-insertion (NRZI) FTP site. This is standard assembler module rxint.c, which is posted on the
coding. This gives a change in level startup code that is modified to add Circuit Cellar FTP site. The handler is
when a zero is encountered in the data the IntGPIOE handler to the vector responsible for receiving AIS packets
to be transmitted. To decode the table for GPIO port E interrupts. one bit at a time. It is executed on
NRZI, I need to compare each received The start-up code passes control to each rising edge of the clock coming
bit with the previous bit. If the level the main() function (in the module from the CMX589A modem.
has changed, the decoded data is a main.c on the Circuit Cellar FTP site). The first job of the interrupt handler
zero; otherwise, it is a one. The function first initializes the is to decode the NRZI data by compar-
Figure 4 shows the AIS packet struc- processor and peripherals before enter- ing each received bit with the last bit.
ture, which is based on the high-level ing the main program loop. As part of The resulting data is then shifted into a
data link control (HDLC) protocol. It the processor initialization, the PLL 16-bit register. The remainder of the
is a bit-oriented protocol, which needs has to be set up, setting the instruc- handler is implemented as a state
to be processed one bit at a time in tion clock rate used by the processor. machine, with five states corresponding
software. Although the LM3S811 will operate at to the progress with receiving a packet.
The message starts with a training up to 50 MHz, I decided to clock my The current state is held in the rxstate
sequence consisting of either 24 or 32 bits project at 20 MHz. I suspected that I variable.
of alternating ones and zeros did not need the full 50-MHz rate. The initial state is RX_INIT, which
(1010101….). This sequence is modi- Running at 20 MHz will enable me to is entered at start-up. After 1,024 bit
fied by NRZI coding to 001100110011. move to a low-end Stellaris device in times, this state raises the RxDCacq
The start of the message is identi- the future. and PLLacq control lines going to the
fied by a start flag (Hex 7E), which is The main loop is an infinite loop CMX589A and changes the state to
followed by the message data. To pre- that continuously checks if a packet RX_PREAMBLE.
vent the false detection of flag charac- has been received by the interrupt han- The RX_PREAMBLE state waits for
ters, the data is subject to bit stuffing. dler and stored in a FIFO buffer. If so, 16 bits of valid training sequence to be
This means that an extra zero is the packet is extracted from the FIFO. received. It then drops PLLacq, clears
inserted after a string of five ones in Next, the function NMEA_Send() is the bit count, and changes the state to
the data. called to convert the packet to NMEA RX_START.
A 2-byte frame check The RX_START state waits
sequence follows the data. for a start flag (0x7E) to be
This is a 16-bit CRC con- received. When found, the bit
forming to the HDLC stan- count is cleared and the state
dard. The standard CCITT is changed to RX_PRELOAD. If
polynomial is used (X16 + a start flag is not found
X12 + X5 + 1). within 24 bits, then the
The end of the message is PLLacq is raised again and
identified by the end flag the state is changed back to
(Hex 7E). After the end flag, RX_PREAMBLE.
buffering time is allowed. The RX_PRELOAD state
This is to allow for bit stuff- waits for 8 bits to be
ing and various radio trans- received and preloaded into
mission delays. the shift register. This
means that when the end
PROGRAM STRUCTURE flag is found, you will have
My code was written just passed the last bit of the
entirely in C. I used the Figure 5—The top trace shows the clock from the CMX589A. The bottom trace
FCS through the CRC calcu-
Keil RealView MDK for shows the execution of the receive interrupt handler, which takes about 5 µs on lation. After 8 bits, the state
compilation and debugging. each clock rising edge. is changed to RX_DATA.

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 51


This structure enables up to multiple messages (0 to 9). c is the
eight packets of variable lengths AIS channel number (1 or 2). s..s is
to be stored, up to a total size of the AIS packet, encoded using a 6-bit
1,024 bytes. These sizes are fairly field type. f is the number of “fill
arbitrary and are easily config- bits” added to complete the last 6-bit
urable by means of #defines at the character. hh is a two-character hex
In_index start of the module. The fifo.c checksum, computed by XORing all of
Pkt_index Buffer
(eight (1,024 bytes) module on the Circuit Cellar the characters between the ! and the
index
values) FTP site contains the functions *. Depending on the packet length,
Out_index necessary to initialize the FIFO one to nine VDM sentences may be
structure, write packets into the required to transmit it.
FIFO, and check for and recover The packet data uses an encoding
packets from the FIFO. scheme that splits the binary packet into
6-bit fields. Each field is then assigned to
NMEA OUTPUT a unique, printable ASCII character.
The International Electrotech- My code to encode and transmit
Figure 6—The receive FIFO uses indirect pointers and stores nical Commission’s IEC Stan- NMEA VDM sentences is contained
up to eight packets of variable lengths. dard 61162-1 specifies a serial in the nmea.c module on the Circuit
interface between pieces of Cellar FTP site. When the main loop
The RX_DATA state receives data and marine electronic equipment. It is has a packet to send, it calls the func-
waits for an end flag to be detected. While closely related to the National Marine tion NMEA_Send(), which encodes the
data is received, stuffing bits are removed Electronics Association’s NMEA 0183 packet according to the 6-bit encoding
and each bit is passed through the CRC specification. scheme. It then calculates how many
calculation. Every 8 bits, a new byte is A VDM “VHF Data-Link” sentence VDM sentences are required to send
loaded into the receive FIFO. When an has been defined, allowing the entire the packet. The VDM_Send() function
end flag is found, the CRC is checked. If contents of a received AIS packet to be is then called to build and transmit
it is good, the new packet is released into transmitted. I used this format for the each required VDM sentence.
the FIFO for processing by the main loop. output from the decoder, enabling it to
To measure the amount of time spent link to standard PC plotting software. OPERATION
in the interrupt handler, my code sets The VDM sentence is normally I used the Tera Term communications
the test point pin high at the start of the transmitted at the NMEA high speed program to verify the correct output of
routine and low at the end. By observing of 38,400 bps. Its format is: NMEA sentences, although any PC-
this pin on an oscilloscope, it is possible based serial terminal program could
to measure the width of the pulse, !AIVDM,n,m,i,c,s..s,f*hh<CR><LF> have been used. Tera Term was set up to
which equates to the time spent in the connect to COM4, the port used by the
routine. With the processor running at n is the number of sentences needed USB serial port on the LM3S811 evalua-
20 MHz, I found that the interrupt han- to transfer the message (1 to 9). m is tion board. Photo 2 shows a typical out-
dler took about 5 µs to execute every the message sequence number (1 to 9). put of AIVDM sentences in Tera Term.
100 µs, only 5% of the available pro- i is a sequential identifier used to link After checking that the NMEA output
cessing time (see Figure 5).

PACKET FIFO
To enable the interrupt routine to
continue receiving while the main pro-
gram is processing, I decided that a
FIFO structure was required to store
received packets. Because the packets
are of a variable length, I chose the
structure shown in Figure 6, which
uses indirect addressing.
The two index values—In_index and
Out_index—point to a table of eight
packet index values, which in turn
point into a 1,024-byte circular buffer.
The two values are used as indirect
pointers to the locations where the
next packet in may be written and the
next packet out read. Photo 2—This is a Tera Term screen showing typical AIVDM sentences output by my decoder.

52 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


PROJECT FILES
To download code, go to ftp://ftp.circuit
cellar.com/pub/Circuit_Cellar/2008/215.

RESOURCES
CML Microcircuits, “CMX589A
GMSK Modem datasheet,” D/589A/4,
2002, www.cmlmicro.com/products/
datasheets/Docs/cmx589ad.pdf.

International Electrotechnical Com-


mission, “IEC Standard 61162-1: Mar-
itime Navigation and Radiocommuni-
cation Equipment and Systems—Digi-
tal interfaces—Part 1: Single talker
and multiple listeners,” 2007,
www.iec.ch.

International Maritime Organization,


www.imo.org.

National Marine Electronics Associa-


Photo 3—This is the ShipPlotter screen showing shipping positions around the River Mersey in northwest England.
tion, “NMEA 0183 Standard,” 2002,
www.nmea.org/pub/0183/.
from the decoder looked correct, I was this project has used only a small part
“ShipPlotter chart generator,”
ready to display some real ships’ posi- of the I/O and memory on this part.
http://emit.demon.co.uk/map2.php.
tions. There are a number of pieces of The decoder software could form the
software available that enable NMEA heart of a complete display system, Universal Automatic Identification
data to be plotted on a PC. I chose a built around the LM3S811, and drive a System, www.uais.org.
package called ShipPlotter by COAA. graphical LCD directly.
ShipPlotter requires a chart for the area Adding Ethernet to the decoder
of interest, as well as calibration data, board could produce a dedicated AIS SOURCES
enabling positions on the chart to be server, making position information CMX589A GMSK Modem
located by latitude and longitude. I available via the Internet. CML Microcircuits, Inc.
found a handy chart generator on the Those are just a couple of ideas. I www.cmlmicro.com
Internet that uses NASA satellite hope this project will inspire you to
ShipPlotter
imagery and created a chart for the come up with more! I
COAA
River Mersey area (see Photo 3).
www.coaa.co.uk/shipplotter.htm
As soon as ShipPlotter was configured Editor’s note: This project received
to use the correct COM port, small ship Honorable Mention in the Luminary FT2232C USB Device controller
icons started to appear on the chart. Micro Designstellaris2006 Contest Future Technology Devices Interna-
This was confirmation that my project (www.circuitcellar.com/designstellaris tional
was correctly decoding the data and 2006/winners/1740.html). www.ftdichip.com
formatting the NMEA sentences.
IC-R7000 Communications receiver
Peter Baston (pete@petebaston.co.uk)
Icom, Inc.
AREAS FOR IMPROVEMENT is an electronic design engineer with
www.icomamerica.com
The goal of this project was to show more than 25 years of experience
how off-air AIS transmissions can be developing hardware and software for RealView MDK
decoded with the aid of a Stellaris micro- embedded systems. He graduated Keil
controller. This has been achieved, and I from the University College of North www.keil.com
have learned a lot about AIS and the Stel- Wales, Bangor, with a degree in Elec-
LM3S811 Microcontroller
laris range in the process. tronic Engineering in 1979. Peter is
Luminary Micro, Inc.
There are a number of areas for currently employed as a senior design
www.luminarymicro.com
improvement. Measurement of the engineer with Tyco Electronics. When
interrupt processing time has shown he is not tinkering with embedded Tera Term terminal program
that the LM3S811 still has plenty of systems, he likes hill walking and Tera Term
processor cycles available, in addition enjoying folk music. Peter holds the http://hp.vector.co.jp/authors/VA0024
to decoding the data. Also note that ham radio call sign GW0PJA. 16/teraterm.html

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 53


FEATURE ARTICLE by Andrew March

MCU-Based Game System


A Dot-Matrix Game That Targets C Coding Efficiency
Andrew built a hand-held, dot-matrix video game that features scrolling scores and sound
effects. You can implement an Atmel AT90S2313 and the C programming language to build
a similar system. This project proves that you can use a modern CPU architecture and an
efficient compiler to produce compact code without having to resort to assembly language to
achieve your desired functionality.

S ome problems in life are easy to


solve. Others, when you first encounter
scrolls bidirectionally across both
sides of the display as a snappy song
sides of the display while more music
plays (“Toreador”). Another game can
them, seem truly intractable. For (“Can-Can”) plays. The normal play- begin straight away.
instance, I recently had to figure out ing screen then appears. It shows two Game play is highly interactive
what to get my 12-year-old god-daughter three-dot paddles at the ends of the because two people are holding the
Chelsea for her birthday. Solutions display and a single-dot ball. Each unit at the same time. A physical tus-
often emerge when you reframe your player has three buttons: Move Paddle sle often develops as players jostle
problem. So, being an engineer, I Left, Serve (the center red button), and each other when they stab down on
decided that this should be an engi- Move Paddle Right. Either player can their paddle buttons, frantically trying
neering problem. I call the result start the game by pressing a paddle to outfox their competitor with a
“Chelsea’s Challenge.” The design is button to take the ball. Pressing the tricky return angle.
a hand-held LED dot-matrix Pong-like middle button serves the ball.
game—complete with scrolling scores Once the ball is moving, the idea is CIRCUIT DESCRIPTION
and sound effects—that’s built around to move the paddles left and right to Figure 1 shows the system’s key
an Atmel AT90S2313 microcontroller intercept the ball and send it back to hardware elements. The microcon-
(see Photo 1).[1] the other player. The ball bounces off troller at U1 is a 20-pin AT90S2313
Despite the fact that the microcon- the paddles at different angles depend- clocked at 8 MHz (see Figure 2). Four
troller has 2 KB of program memory, I ing on whether it hits the paddle on standard 5 × 7 dot-matrix LED modules
coded the software entirely in C the left, center, or right side. A short are wired together to create a 10 × 14
using the WinAVR toolset. This proj- beep sounds every time the ball display. To save AT90S2313 pins, the
ect demonstrates how effectively bounces off a paddle. If a player misses display is multiplexed and each row is
modern CPU architectures and effi- the ball, the paddles flash and a modu- turned on individually in a scanning
cient compilers can work together to lated tone is sounded. A random cheer sequence. To select one of the 14 rows,
produce compact code without resort- message (e.g., TOP SHOT, EXCEL- the AT90S2313 presents a 4-bit “row-
ing to assembly language to achieve LENT, AWESOME) is then unidirec- select” code to the four- to 16-line
the desired functionality. tionally scrolled across the display on decoder at U2 and U3. This causes the
the side of the player who won the selected decoder output to go low,
PLAYING THE GAME point. The score (e.g., 6–4) then scrolls turning on one of the PNP high-side
The game is held in portrait orienta- bidirectionally across the display for driver transistors at Q1 to Q14, which
tion between the two players. The both players. connects an entire row of LED anodes
playing screen is a 10 × 14 LED matrix, The winner is the first player to to VCC.
which is treated as separate 10 × 7 halves reach nine points. After the final score At the same time, the AT90S2313
when scrolling text. At power-up, a title is displayed, the words GAME OVER presents a 10-bit-wide “column-
message (CHELSEA’S CHALLENGE) are scrolled bidirectionally across both select” pattern directly to the LED

54 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


a) b)

Photo 1a—This is the assembled PCB. Player 1 has yellow paddle buttons on the right side of this photo. Player 2 has green paddle buttons. The speaker is on the solder side. b—This is
the boxed game. The enclosure lid has been replaced with a sheet of red perspex. The circuit board’s height was chosen so the switches protrude only slightly above the surface.

cathodes. A low in the bit pattern that cyclically calls the main game The background loop is interrupted
grounds the cathode it is connected to, routine and updates the display. Dis- every 10 ms by the AT90S2313
causing the LED in the selected row to play updating is done either in Message Timer0, which serves as the system’s
light up. Directly driving the LED mode by the routine show_msg(), “tick timer.” The tick timer governs
cathodes takes full advantage of the which refreshes all 14 rows, or in Pong the execution rate of the music player
20-mA current-sink capability of the mode by the routine show_pong(), and message scrolling routines, which
AT90S2313’s port pins. Cycling which refreshes only the three rows must be called at regular intervals to
through the rows is repeated rapidly so containing the two bats and the ball. ensure a constant music tempo and
the eye, due to persistence of vision,
perceives the entire display to be oper-
ating at once. Display multiplexing
10 x 14 LED M a t r ix
uses 14 of the 16 decoder outputs. The ma d e fr o m fo u r 5 x 7 dis p la y s
Four- to 16-lin e
fifteenth output turns off the display (LED1–L ED4)
de c o d e r (U 2,U3)
when changing the “column-select”
patterns. This avoids ghosting artifacts
caused by the slow turn-off times of
14
the high-side driver transistors.
Because there are so few pins on the
H ig h -sid e
AT90S2313, six of the 10 “column- dr iv e r s
(Q 1– Q 14)
select” port pins are periodically repro-
grammed as inputs to read the states of
the push button switches that share Swit c h
en a b l e
the port pins. To prevent the switches
from interfering with the display, they
are diode isolated and enabled by
selecting the sixteenth decoder output,
P u s h bu t t o n s
which guarantees that all display rows (S1–S6)
are disabled when switches are active.
The AT90S2313 port pin (PB3) drives 10 C o lu m n 4 Row
se le c t se le c t
the piezoelectric speaker directly. The
signal waveform is automatically gen-
erated by the AT90S2313’s Timer1, as I A T90S23 13
will describe in the next section. For (U 1)

portability, four AAA batteries power P ie z o


sp e a k e r
the game by dropping diode D7. 8.00 0-MHz
Cr y s t a l

SOFTWARE
At the highest level, the software is Figure 1—The design features a few key hardware elements: the microcontroller, the display, the row decoder/driv-
structured as an endless while loop er, and the push buttons.

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 55


Figure 2—Note how the rows of the display are controlled by
high-side driver transistors, which must supply current for up
to 10 LEDs at a time.

56 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


Products
NEW Technologies
Suppliers

The Newest
Products and
Technologies Are
At mouser.com

The ONLY New Catalog Every 90 Days

Experience Mouser’s time-to-market


advantage with no minimums and same-day
shipping of the newest products from more
than 335 leading suppliers.

2,128 Pages

The Newest Products


For Your Newest Designs

www.mouser.com (800) 346-6873


Over 965,000 Products Online
fluid text scrolling. The tick timer START_UP (show title message and that can be read from both sides. My
interrupt service routine also updates play opening tune), NEW_GAME solution divided the display into
scheduling timers for less time-criti- (display bats and ball, reset score), halves (see Figure 4). The first player
cal routines that run in the back- SERVE_BALL (wait for serve, allow sees his own message scroll from left
ground. serve selection), PLAY_BALL (update to right in the lower half of the dis-
The main game routine play_pong() moving bat and ball positions, check play, while an apparently upside-down
is coded as a state machine using a for missed ball, and display cheer message scrolls from right to left in
switch statement (see Figure 3). message if point won), and the upper half. The second message is
This approach involves partitioning CHECK_GAME (check for end of the right way up for the other player.
the game logic into separate phases game or give new serve to player Normally, the same message is
or states and deciding on the rules who won the point). scrolled across both halves. However,
for transitioning from one state to Two players hold the game, so the cheer messages scroll only on the side
another. The chosen states were messages must be displayed in a way of the player who won the point. The
bitmap for the text message is gener-
ated by the scroll_msg() routine,
which is called at the regular tick
timer rate to ensure smooth motion.
A drawback associated with the mes-
sage-scrolling feature is the amount of
memory needed to store character
fonts. Because each 5 × 7 character
requires 5 bytes, the full alphabet plus
digits consumes 180 bytes. To claw
back a few bytes, a modified ASCII
sequence was used to avoid storing
font codes for unused characters. (The
font for “W” is placed where the
unused “B” font would have gone.
“X” is in place of “J,” and “Y” is
issued instead of “Q”).
Music and sound effects (the ball hit
and miss tones) are generated by the
play_tune() routine, which reads
musical “scores” encoded as a table of
note frequency and duration pairs.
The note frequency value, which rep-
resents the half-period duration of the
audio tone, is written to the
ProtoMat® S-Series AT90S2313’s Timer1 output compare
PCB Milling Machines register. Timer1 is configured to con-
Electrical engineers agree: with a Protomat S-Series tinuously count up to this value, then
prototyping machine at your side, you’ll arrive at the auto-clear to zero, and repeat. Every
best solutions, fast. These highly accurate benchtop time the counter reaches the output
PCB milling machines eliminate bread-boarding and compare register value, it toggles the
allow you to create real, repeatable test circuits— state of the AT90S2313’s port pin PB3.
including plated vias—in minutes, not days. The resulting square wave generated
on this pin drives the speaker directly.
• Declare your independence from board houses
The note duration value read from the
• Affordable, entry-level price tag note table initializes a note timer vari-
able that is decremented at the system
• The best milling speed, resolution, and accuracy tick rate every 10 ms. Once the note
in the industry
timer reaches zero, Timer1 Toggle
• Single-sided, double-sided, and multilayered mode is disabled for a brief period of
machining without hazardous chemicals For complete details visit:
silence before another note frequency
www.lpkfusa.com
• Optional vacuum table and autosearch camera or call:
and duration pair are read from the
for layer alignment 1-800-345-LPKF note table. This cycle repeats until a
note frequency of 255, denoting the
end of the tune, is read from the table.

58 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


Although Timer1 is a 16-bit timer, to
conserve memory, only the high byte
for the output compare register is Start * S croll title text
stored in the note table. The lower up * In itiate “Can-Can” tune

byte is always written as zero, which


has a small impact on pitch accuracy.

DEVELOPMENT ENVIRONMENT
Code for this project was developed New * Reset scores
game
with the WinAVR suite of open-source * Serve defaults to Player 1

development tools for AVR microcon- Either score == 9


trollers. WinAVR includes an AVR Game over

version of the GNU C compiler (avr-


gcc), a C library package (avr-libc), and
a device programmer utility (avrdude). * Give next serve to * If score = 0–0,
point winner Check Serve
let players decide
It comes with a Windows-based text * If game over, initiate game ball
who serves first
“Toreador” tune Neither score = = 9
editor called Programmer’s Notepad, Point winner serves again
which also serves as a basic IDE.
Once WinAVR is installed, you need Player with ball
presses their
to edit the makefile that is called by Point won Serve button
Programmer’s Notepad to launch the
Play
compiler and device programmer in ball
order to customize the compiler and
device programmer options to suit * Update bat and ball positions
your target microcontroller. Atmel’s * If point won, scroll cheer message

AVR Studio 4 IDE was used for debug-


ging and code inspection instead of Figure 3—To make the game implementation easier to manage, the control logic was coded as a state machine
the debugger (gdb) supplied with with a C switch statement.
WinAVR. This is possible because of
the avr-gcc linker’s ability to generate
object files in ELF format, which are the software description, getting all of used to promote C coding efficiency
compatible with AVR Studio 4. the code to fit in the 2 KB of flash and minimize code size.
memory on the AT90S2313 may seem As a starting point, take the time
C CODING EFFICIENCY doubtful at first. But with care, a sur- to get acquainted with the tools you
A goal from the outset of this proj- prising amount of functionality can be are using. Most compilers support
ect was to write the software entirely crammed into a small microcon- various options for code optimiza-
in C without resorting to assembler. troller. In this section, I will describe tion. Generally, these options are
Given the list of features outlined in some of the tricks and techniques aimed at a smaller code size or faster
execution speed. An improvement in
one direction will generally force a
trade-off in the other. For example,
T e x t s c r o l lin g d ir e c t io n f o r Pl a y e r 2 an optimization technique called
loop unrolling improves speed by
converting loops into repeated blocks
of code. This avoids the overhead of
maintaining a loop variable and hav-
ing to execute a branch instruction
at each iteration. Clearly, this kind
of compiler behavior is undesirable if
you want to minimize code size.
Because the AT90S2313 executes
nearly 1 million instructions per 1 MHz
of clocking frequency, foregoing
speed in return for a smaller code
T e x t s c r o l lin g d ir e c t io n f o r Pl a y e r 1
size won’t be a problem in most
applications. In a gcc compiler, opti-
Figure 4—The text is displayed simultaneously in two orientations because players face each other from opposite mization options are set by command-
sides of the game. line switches. By default, optimizations

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 59


are off. To force the compiler to mini- on C code efficiency. Unlike earlier strategy is to compile the code with
mize code size, make sure the –Os CPUs with just one or two accumulators and without the function call to see
option is included on the command for manipulating data, the AVR fami- what effect it has on code size. In cer-
line. In the WinAVR environment, the ly RISC CPU has 32 general-purpose, tain circumstances, it might be better
optimization level passed to the avr- memory-mapped working registers to write your own specialized code
gcc compiler is controlled by the (R0 to R31). The avr-gcc compiler rather than use a highly generalized
value assigned to the OPT variable in uses many of these, but some (R2 to library routine.
the makefile. R17) are available for the program- So, is all of this extra bother worth
At the end of compilation, avr-gcc mer. They can be used as ordinary C the effort? To quantify the potential
prints a list of statistics showing char variables if declared with the for code size reduction, the Pong-like
code size and RAM usage so you can compiler register directive. Here is game software was compiled using
easily monitor memory consump- an example declaration: avr-gcc at each available level of opti-
tion. The assembly language pro- mization, both with and without the
duced by the compiler can be register unsigned char game_state use of register variables (see Table 1).
inspected by looking at the listing asm("r9"); For the default scenario without com-
file (.LST). WinAVR also produces an piler optimizations and all variables
extended listing file (.LSS), which The declaration causes the compiler to stored in RAM, the code size was
conveniently shows lines of C code treat register R9 as the unsigned char 3,550 bytes—much too big to fit in
interspersed with the assembler variable game_state. Declaring fre- the target microcontroller. By opti-
statements they generate. The C-to- quently used variables as register vari- mizing compilation for size and allo-
assembler correlation can also be ables can reduce code size dramatical- cating 15 char variables to registers,
observed by opening the ELF format ly. This is because normal variables the code size shrank 42% to 2,044
debugging file produced by WinAVR must be moved first from RAM to a bytes. This fits in the target microcon-
in AVR Studio 4. Although we are working register where they can be troller with 4 bytes to spare! Clearly, in
not coding in assembler, it’s impor- manipulated and then moved back to this case, the code size reduction was
tant to understand the “cost” of each RAM, if changed. Using register vari- crucial to a successful outcome. Note
C statement in terms of assembler ables avoids the need for the compiler that Table 1 emphasizes compiler behav-
instructions generated. Any C code to generate the extra assembler ior and does not emphasize the gains
that produces reams of assembly lan- instructions needed to move the vari- achieved from following the coding
guage may need to be reworked. able back and forth because the vari- style recommendations given earlier.
I will now focus on coding tech- able is permanently in a register. Typi-
niques. The first efficiency “rule” is to cally, it won’t be possible to store all CONSTRUCTION & PROGRAMMING
use small data types wherever possible. variables in registers, so careful Artwork for the double-sided PCB is
Because the AT90S2313 is an 8-bit thought and experimentation will be available in PDF and Gerber formats
microcontroller, use char variables needed to select the best combination on the Circuit Cellar FTP site.
instead of int. There are two rea- for the smallest code size. While regis- Because only through-hole compo-
sons for this. First, 8-bit char vari- ter variables are feasible on the AVR nents are used, assembly is generally
ables take up just 1 byte of RAM with its large register file, CPU archi- straightforward. Just use the Part-
storage, while 16-bit int variables tectures with few machine registers slist.doc and Componentoverlay.pdf
take up 2 bytes. Second, assigning will not benefit as much from this files posted on the Circuit Cellar
values to a char variable requires technique. FTP site. When mounting LED1 to
fewer bytes of code than the same As I’ve mentioned, using large data LED4, make sure they are perfectly
assignment for int variables because types implicitly causes supporting straight and level. When soldering
int variables have to be processed in library routines to be compiled in, Q1 to Q14, press them down firmly
two steps: first the least significant which bloats the code. The program- to ensure they are below the display
byte and then the most significant mer may also explicitly call library surface. Note that U2 and U3 face in
byte. If multiplication and division is functions, which poses a similar risk different directions. The piezoelec-
required within a loop, consider of inflating code size. Although tric speaker is attached to the under-
whether the calculation can be rewrit- library routines are normally coded side of the PCB with a dab of hot
ten using iterative addition or subtrac- efficiently, more complicated library melt glue after the finished board has
tion to avoid compiling in lengthy functions should be used with care. been tested.
math subroutines. Take particular For example, the formatted print The programming file UPONG.HEX
care when using float data types. function printf is supported by a is available on the Circuit Cellar FTP
They not only take up many bytes of raft of formatting routines, such as site. Although the AT90S2313 can be
RAM, but also require memory-hun- conversion of integer binary numbers loaded on a dedicated programmer unit
gry library routines to manipulate to decimal, hexadecimal, and octal before it is soldered down, a conven-
them. representations, which can take up ient feature is its in-system program-
CPU architecture has a great bearing more code space than desired. A good mability. The avrdude programming

60 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


Compiler optimization Code size (bytes)
Level Type RAM Variables[1] Percent change Register variables[2] Percent change
0 No optimizations 3,550 0% 3,224 –9%
1 Speed, size, compile time 2,548 –28% 2,246 –37%
2 Speed, size 2,414 –32% 2,102 –41%
3 Speed 3,682 4% 3,114 –12%
s Size 2,340 –34% 2,044 –42%

Notes: The compiler is avr-gcc version 3.4.3. The shaded cell is baseline for percentage comparisons.
[1] Variable (data) storage = 51 bytes of RAM only
[2] Variable (data) storage = 15 char variables in registers plus 36 bytes of RAM

Table 1—The table shows how code size is affected by the various compiler optimization levels, as well as the impact of putting variables in registers.

utility supplied with the WinAVR when power is restored. If you want to explore the topic fur-
package works nicely under Windows Achieving C coding efficiency ther, David Spuler’s book, C++ and C
98 with the simple printer port cable comes at the cost of programmer effi- Efficiency, is worthwhile—and, come
shown in Figure 5. (Note that some ciency because more care (and time) to think of it, so is a happy 12-year-
versions of Windows do not allow has to be taken to monitor the com- old! I
direct access to the printer port.) To piler’s output and adjust your coding
program the AT90S2313, temporarily style to achieve the smallest code size. Andrew March (amarch@three.com.au)
solder the cable wires to the five Like any skill, this gets easier with is a systems engineer at Silverbrook
specified test points at the base of practice. For some projects, it might Research in Sydney, Australia, where
push button S1 on the underside of be easier to migrate to a microcon- he works on next-generation inkjet
the PCB, apply power, connect the troller with more code memory. How- printing technologies. He holds a
cable to the PC, and invoke avrdude ever, there will often be situations Bachelor’s degree in Computer Engi-
with the following command line: where the hardware design is fixed neering from the University of Wol-
and new features or bug fixes have to longong (New South Wales, Australia)
avrdude -p at90S2313 -P lpt1 -c fit in the available memory. In other and an MBA from Curtin University
bascom -U flash:w:upong.hex:i cases, production volumes may be so (Perth, Australia).
high that the hardware cost savings of
Programming takes only a few sec- using a part with a smaller memory
onds. When finished, disconnect the justifies the one-off programmer effort PROJECT FILES
cable from the PC, remove power, to minimize code size. Under these To download code, go to ftp://ftp.circuit
and desolder the temporary connec- circumstances, C coding efficiency is cellar.com/pub/Circuit_Cellar/2008/215.
tions. The game should spring to life paramount.

REFERENCE
[1] Atmel Corp., “AT90S2313: 8-bit AVR
J1
1 Microcontroller with 2K Bytes of In-
14
2 R1 PB5 (MOSI) System Programmable Flash,” Rev.
15
3
330 0839I, 2002, www.atmel.com/dyn/
16
R2 resources/prod_documents/DOC0839.
4 RST
17 330 PDF.
5
18
6 R3 PB7 (SCK)
19
7
330
RESOURCE
20
Solder flying leads to marked test points
8 D. Spuler, C++ and C Efficiency: How
under S1 from solder side of PCB
21
9 to Improve Program Speed and Mem-
22
10 ory Usage, Prentice Hall, Upper Sad-
23
11 PB6 (MISO) dle River, NJ, 1992.
24
12
25
13 SOURCE
DB25-M GND
AVR Studio 4 IDE and AT90S2313
microcontroller
Figure 5—The flying leads are temporarily soldered to test points on the bottom of the PCB under S1. They are Atmel Corp.
removed after programming. www.atmel.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 61


FROM THE BENCH by Jeff Bachiochi

Self-Destructive Behavior
Processor Action Requires Power Supply Removal
Fed up with corrosion? Eliminate the contacts. Jeff replaced his old doorbell switch with a
capacitive touch pad using only the pair of wires available at the door. If you are not in the
market for a new doorbell, this solution could work well in a different project.

I was frustrated for the last time. If I


hadn’t been walking by the door, I
no-brainer, there are other aspects to
this project that add some intrigue.
the previous solenoid allows for only
a “ding.”
never would have known that my Take a look at the doorbell circuit to This project is not designed to
neighbor was standing outside patient- get a better idea of the problems replace the old solenoid-based doorbell
ly waiting for me to show. When I involved. Most doorbells consist of with an electronic one, but it is
asked why he hadn’t rung the door- solenoids that run off of a low-volt- designed to use only the pair of wires
bell, he assured me he had. This was- age 14-VAC transformer handling up available at each door. Now it should
n’t the first time contact corrosion had to 1 A of current. When energized, be clear that not only does this project
affected my ding-a-ling. What could I the solenoid’s plunger whacks a bar use low-voltage AC, but when a door-
do besides replace the oxidized con- of metal. Like a note on a xylophone, bell button is pushed, it creates a
tacts again? the bar vibrates when struck. A nor- short across the pair of wires and can
Sure, I could just go to the hardware mally open (NO) push button at the no longer provide power. So, this proj-
store and buy another replacement, door energizes the solenoid in the ect must be powered from AC, control
but what fun is there in that? I’ve house by completing the circuit. AC, store some power, and provide a
played around with a number of touch Some doorbells have a second bar of a contactless input.
projects in the last few years, so using different length that is whacked on
a capacitive sensor isn’t new. My past the return of a second solenoid’s RC OSCILLATOR
projects have included devices that plunger. The solenoid’s circuit gives The basic premise for this circuit is
were developed specifically for capaci- the “ding-dong” for one door, while a resistor/capacitor oscillator, where
tive front ends. The Quantum
Research Group built its company
around QProx devices. You may have
noticed a number of companies that R1 = R2 = R3
have recently realized the impact that
this technology has made on product VDD CP0A
design. While some manufacturers R1
R4 R2 CP0 +
such as Atmel, NXP Semiconductors,
R3
Renesas Technology, and STMicro- CP0 -
Comp

electronics have licensed the Qprox


patented technology, others like
Switch
Cypress Semiconductor, Microchip
MCU
Technology, and Silicon Laboratories
demonstrate how to harness capaci-
tive touch technology using standard
Figure 1—The RC network charges and discharges (via a comparator’s output) are providing continuous oscilla-
I/Os on a microcontroller.
tion. When RC charges above a 2/3-VCC reference, the comparator’s output goes low, removing the charging volt-
While using a touchpad to replace age and effectively changing the reference voltage to 1/3 VCC. When RC discharges below the new reference, the
a doorbell switch may seem like a comparator’s output goes high, which begins a new charging cycle with a reference of 2/3 VCC.

62 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


Figure 2—The circuit here must continue to run when its AC source is shorted out by the TRIAC across its AC input. Stored power in C1 will enable the microcontroller to exe-
cute even when it gates the TRIAC to turn ON for 0.5 s. C5 is a capacitor formed by PCB traces that act as the touch sensor input that will initiate the TRIAC shorting the AC.

the resistor and capacitor are fixed plates. Parallel capacitors look like The RC junction hangs on the nega-
and produce a fixed frequency. The an increase in the plate size so the tive input to the comparator, with the
capacitor is made up of two fixed capacitance goes up. free end of the capacitor connected to
plates (usually PC traces) that have Although there are ways to make ground, while the free end of the
an inherent value. The fixed value of an oscillator without a microcon- resistor is connected to the compara-
a capacitor will be affected by an troller, some standard peripherals can tor’s output. The comparator’s output
object (usually a finger) that comes in simplify the circuitry. The most sim- can swing between ground and VCC.
close proximity to the plates. The ple circuit uses a comparator as the The positive input to the comparator
object looks like additional capaci- active part of the oscillator. Figure 1 is connected to the midpoint of equal
tance in parallel with the fixed shows how the circuit is configured. resistors (R2/R3), creating a voltage

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 63


divider of 0.5 VCC. Howev-
er, an additional resistor
of equal value (R4) is con-
nected between the com-
parator’s positive input
and its output. When the
comparator’s output is
high (VCC), the resistor
(R4) is in parallel with the
upper resistor (R2), caus-
ing the divider to create
2/3 VCC at the positive
input to the comparator.
When the comparator’s
output is low (ground),
the resistor (R4) is parallel
to the lower resistor (R3),
causing the divider to cre-
ate 1/3 VCC at the positive
input to the comparator.
The comparator’s output
remains high until the
voltage on capacitor C
exceeds 2/3 VCC. C is
charged via R from VCC. It
takes only about one
time constant (τ) to rise Photo 1—This photo shows the relative sizes of the input capacitor C1 necessary to provide 15 mA of current for the circuit when the
to 2/3 VCC, so use τ for AC is available (100 µF) versus unavailable (3,300 µF).

64 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


Photo 2—The corroded contacts of this standard doorbell switch suggested this circuit, which produces the same result, shorted out 14 VAC (applied power to the doorbell
solenoid inside the house). The required capacitor’s size resulted in a larger enclosure for the button.

your calculations. That’s τ = R × C. cycle consists of one charge and one or 50 kHz.
Using friendly values of R = 100k discharge time, the oscillator period Once the oscillator is running, it
and C = 10 pF, τ = 1 × 106 × 1 × 10–11 will be 2 × 10 µs. The oscillator fre- will charge and discharge between 1/3
or 1 × 10 –5 s (10 µs). Because one quency is therefore 1/period = 1/20 µs, and 2/3 VCC. The frequency will be

66 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


higher than the initial time from change in period will be easy to and the jumper enables the idle sen-
ground (power up) to 2/3 VCC. In fact, detect. While the capacitor will be in sor’s count to be measured and the
my circuit runs at about a 100-kHz the picofarad (pF) range, the actual span value to be calculated based on
rate. Because instruction cycles are 1 µs, value on the capacitor will depend on the differences. You will most likely
that’s only 10 instructions per period. many factors. want this value to be saved into non-
It would be tough to see a small Silicon Laboratories’s application volatile memory, so span will be a
change in frequency because the res- note titled “Capacitive Touch Sense semi-permanent value.
olution is 1 µs or 10%. Instead of Solution” (AN338, 2008) shows the
looking for changes in frequency, results of using different trace pat- MAIN
count periods over a longer period of terns and spacing as a capacitance Now that you have access to a flag
time. Assuming that the period of sensor on a PCB. The effective capaci- that indicates the state of a capacitive
one cycle is 20 µs, if you count peri- tance (in the range of 1 to 9 pF) is larg- sensor, what do you need to do?
ods for 20 ms, you can increase the er as the trace-to-trace spacing is Although there is only one require-
resolution from 10% to 0.01%. This reduced, or the total length of the ment—control of a TRIAC to short
is a trade-off of time for resolution. traces increases. This is what you’d out the two wires—you may want to
In this project, you don’t need expect from analyzing how a fixed make this distinctive. Although out-
microsecond response time so this is capacitor is constructed. (The capaci- put devices will require additional
a good trade-off. tance increases as the surface area of currents (covered later), they can
This application will use a timer the capacitor’s plates increase or as make the project unique. Sound and
for generating the counting periods the inter-plate spacing decreases.) The light are the outputs of choice here.
and a second timer (in the Count bare PCB has air between traces. To But, start with the TRIAC gate signal.
mode) to keep track of the number of keep objects from coming into physi- The main loop has two tests. The
periods (comparator toggles). The cal contact with the sensor, insulation first test checks the CFG input and
timer must be long enough to give may be added on top of the sensor. runs a calibration routine if you
adequate resolution but short enough The thickness and makeup of this request it (by shorting the CFG input
so the associated counter will not material will affect how the object can to ground). The second test checks
overflow. In this case, the counter is interplay with the sensor. As you the Flags register for the Button bit.
16 bits, so based on a 20-µs period, it might think, the thinner the material, A logic 1 indicates that an object has
will take over 1 s to overflow, which the larger the influence an object will been sensed and the button pushed
fits the requirements. have on the sensor’s capacitance. routine is executed. The main rou-
When the timer overflows (I’m Interestingly, a covering of glass and tine loops endlessly 99% of the time
using 64 µs), two things happen with- plastic can be twice as thick as FR4 (except for the Timer0 interrupt that
in the interrupt. The period count is (the material used in most PCBs) records the sensor periods and deter-
compared to an average period count without having a significantly differ- mines object proximity).
to determine if the difference is ent impact. The calibration routine turns on
greater than a predefined value (vari- However you design your sensor, it the red LED, indicating that you
able span). A flag is set if the new will need to be calibrated in some should place your finger on the sensor.
value (plus span) is less than the aver- way. The calibration determines After about 3 s (allowing you time to
age value (extra capacitance increases what the variable span will be. The cover the sensor), an average period
the period, reducing the total count). value will be more critical if the value is saved as ButtonONH/L. The
The flag is cleared if the new value capacitive difference between idle red LED is turned off and you should
(minus span) is greater than the aver- (no object) and loading (object pres- remove your finger from the sensor.
age value (removing the extra capaci- ent) is a smaller number. A small After about 3 s (allowing you time to
tance decreases the period, increasing span may false trigger, while a large clear the sensor), an average period
the total count). span may have a problem triggering. value is saved as ButtonOFFH/L. The
The average value is calculated by The value can be determined empiri- difference between the two values is
adding a number of past count values cally if you have an in-circuit emula- the amount the period counter
saved in a ring buffer. Small count tor. This enables you to see what changes. This value, or a fraction of it,
changes, due to environmental effects, kinds of count values the circuit will will be used as the SpanH/L variable
will be adjusted for by this moving ref- see during idle and loading by halt- that is saved in EEPROM for future
erence (average). Larger changes will ing execution and checking vari- use in determining if a threshold has
be seen as an object at the sensor. ables. Otherwise, you can build in been crossed and the Flags.Button
Therefore, the variable span is critical calibration routines based on a pro- bit must be set or reset. When the cal-
to enabling the application to deter- cedure using an input pin. If you culation is finished, the calibration is
mine an object’s presence at the capac- place an object (finger) on the sensor complete and the red LED is flashed to
itive sensor. Naturally, you would like and short out an input pin, the spe- let you know that execution is now
the total capacitance of the sensor to cial count can be stored as a loaded looping, ready for something else to
change as much as possible, so the reference count. Removing the object do.

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 67


Back in the main loop, if the about as close as you can get to the When half-wave rectification is used
Flags.Button bit has been set, you actual doorbell chime. However, if (as in this circuit), the charging is
get to perform your lot in life. For you want to personalize your ring further limited to every other half
this project, it’s not a lot. You will tone, be my guest. cycle. The formula for determining
turn on a TRIAC for 0.5 s. This is how big the capacitor should be is
sufficient time for the AC to drive POWER based on the current required by the
the solenoid in the doorbell and alert The Microchip Technology load I, the time for a charge cycle, dt,
anyone within earshot that someone PIC16F610 microcontroller I used for and the amount of ripple (the differ-
requires assistance at the front door. this project has a cousin, the ence between the maximum voltage
The STMicroelectronics Z0405DE PIC16HV61x. The HV device has an during charging) and the minimum
TRIAC is a 400-V 4-A device capable internal voltage regulator, but because voltage (during no charging), dv:
of being driven directly from a micro- I didn’t have one of those handy, I had
dt (seconds)
controller. In this circuit, all of the cir- to add an external regulator. I used a C ( farads) = I ( amps) × [1]
dv ( volts)
cuitry is insulated from the user, so an 78L05, which has 5 mA of quiescent
optoisolated gate driver is not neces- current. (That’s the current used by the In this circuit, you need to supply
sary (see Figure 2). regulator to do its job even with no 0.015 A (I). The charging period is
Note: Although all of the circuitry output load.) Because this circuit is 0.017 s (dt at 60 Hz) and the mini-
is powered by low-voltage AC and iso- going to be totally cut off from the mum voltage must remain higher
lated by the doorbell transformer, source for a minimum of 0.5 s (the than the minimum input voltage to
some caution should be exercised time the TRIAC is shorting out the the regulator (in this case 7 V). So
when working with the circuitry. feed wires), every drop of wasted power with a rectified peak of approximately
Some insulation must be used will come back to haunt me later. 14 V, that would be a difference of
between the sensor element and any Referring back to Figure 2, the 14-VAC approximately 7 V. This leaves no
object used to sensor proximity. This power is rectified and charges capacitor wiggle room for conditions such as
is an important consideration because C1. The amount of current necessary lower-than-normal AC voltage, so you
it will most likely be the weather- for the circuit to continue to run with might want to use a factor of two or
proofing barrier as well. the AC shorted out by the TRIAC will four to improve the performance. I’ll
You might see a few doorbell come from this capacitor. So, its size use a 2-V dv for this example:
switches with lights on them. For will be dependent on the circuit’s cur-
0.017 0.000255
the most part, that’s as extravagant rent draw. C = 0.015 × = =
2 2 [2]
as these devices get. A couple of By adding a two-pin jumper between
0.00012275 = ~100 μF
LEDs will not only light up this proj- C1 and the regulator’s input, I could
ect, but also give some feedback to measure various currents in the circuit. At 60 Hz, a good rule of thumb is
the user. A red LED is used as a With no microcontroller installed, I 6,000 µF/A for half-wave circuits and
power or idle indicator (and used in measured less than 3 mA. With the 3,000 µF/A for full-wave circuits. In
the calibration routine). The LED can microcontroller installed and execut- this circuit, a 100-µF capacitor is
be turned off when a button push is ing code, this rose to 5 mA. An LED required to allow operation while AC
recognized. I decided to add a green adds 2.5 mA and the TRIAC’s gate is being applied to the input.
LED that turns on during the button drive adds another 6.5 mA. That’s What happens when the TRIAC is
pushed routine. This will stay on approximately 15 mA of total load cur- turned on, shorting out the input to
during the TRIAC firing and for an rent required to run the circuit. When the circuit and leaving nothing to
additional few seconds to indicate the TRIAC turns on for 0.5 s, C1 needs charge up the capacitor? With your
that something has happened. (With to supply 15 mA of current for at least 15-mA draw on the capacitor, it will
no physical button to push, there 0.5 s. not get charged during the next dt so it
isn’t any mechanical feedback.) If you’ve ever designed a linear will continue to discharge from 14 to
Note: No feedback is a big disadvan- power supply, you know that recti- 12 V. The next dt it will discharge fur-
tage of nonmechanical switches. fied AC charges up the capacitor and ther from 12 to 10 V, and then 10 to 8 V,
To make this project standout, I the load discharges it. If there is no and 8 to 6 V. In just four periods, the
implemented a piezoelectric beeper load, the capacitor will charge up and regulator will fail to regulate and the
to give you additional feedback. remain charged. A load will dis- circuit will shut down (providing the
Although most piezoelectric devices charge the capacitor. Because AC is regulator’s output falls below the reset
have a sweet spot (i.e., some frequen- only charging the capacitor when its voltage of the microcontroller). Four
cy that will produce a maximum out- voltage exceeds the voltage on the periods is only 67 ms. You need to
put level) they can be used to pro- capacitor, while the load is continu- operate a minimum of 500 ms before
duce a variety of output tones. You ously trying to discharge it, the power is restored (the TRIAC is turned
must drive the devices with a fre- capacitor’s job is to charge fast so it off).
quency, so you get to be as clever as can sustain sufficient charge and The same formula is used to solve
you want. A two-toned beep-boop is allow the regulator to do its job. this new dilemma. Now the dt is 0.5 s,

68 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


assuming you want to remain at the the capacitance into multiple (smaller)
2-V ripple level: capacitors. While I could probably
reduce the current by one-third by
0.5 0.0075
C = 0.015 × = = selecting an alternate regulator and
2 2 [3] using modulation on the LED, I’ll set-
0.00375 = ~ 3,300 μF tle for a slightly larger button housing.
You might look at this and say, “Yah, I found an enclosure in a box of odds
so.” Remember that you’re only asking and ends that will work well and does-
for 15 mA of current and you need to n’t look too bad. It already has a cutout
keep everything as small as possible to area or almost 1 sq. inch that will be
fit into the space available for this proj- perfect for a touch sensor. The large
ect, a doorbell button. Let’s take a look sensor area can also provide room for
at the size difference between a 100-µF LEDs behind the label, environmental-
25-V capacitor and a 3,300-µF capacitor ly sealing the front surface.
(see Photo 1). The 3,300-µF capacitor has Even if you find replacing your inex-
33 times the capacitance of the 100-µF pensive button with this circuit a bit
capacitor. Volume wise, it is approxi- outlandish, there are a number of
mately 50 times greater: technologies and methods used here,
which I believe you can store away for
V = π × r2 × h a rainy day. Sometimes a proposed solu-
2
⎛ 6.5 mm ⎞ tion will offer insight that far exceeds
V = 3.14 × ⎜ × 18 mm =
⎝ 2 ⎟⎠ its usefulness or practicality in that
0.190 cm3 (100 μF) solution. That’s why there are no stupid
2 ideas in brainstorming sessions. I
⎛ 18 mm ⎞
V = 3.14 × ⎜ × 38 mm = [4]
⎝ 2 ⎟⎠
9.7 cm3 (3,300 μF) Jeff Bachiochi (pronounced BAH-key-AH-
That’s about as big as all of the key) has been writing for Circuit Cellar
other components combined! When I since 1988. His background includes
substituted a 2,200-µF capacitor for product design and manufacturing. He
the original 100 µF, the measured may be reached through the magazine
voltage on C1 was 12.5 V with rough- (jeff.bachiochi@circuitcellar.com) or his
ly 0.1 V of ripple (the dv improved web site (www.imaginethatnow.com).
because C increased). When the
TRIAC shorted, I saw the 12 V dis-
PROJECT FILES
charge to 10 V over the 0.5 s the
TRIAC was shorting the input. To download code, go to ftp://ftp.circuit
Because the program execution calls cellar.com/pub/Circuit_Cellar/2008/215.
for a few additional seconds of wait-
ing and beeping, C1 has a chance to
charge back up before the button can
RESOURCES
be pushed again. This prevents dis- T. Perme, “AN1103: Software Handling
charging C1 further due to repeated for Capacitive Sensing,” DS01103A,
requests for the TRIAC to remain or Microchip Technology, Inc., 2007.
retrigger for additional periods.
Silicon Laboratories, Inc., “AN338:
PUT 10 lb INTO A 5-lb SACK? Capacitive Touch Sense Solution,”
I made my prototype with through- 2008.
hole parts. With the increased size in
C1, I can’t fit this circuit into the origi-
nal doorbell’s enclosure. Photo 2 shows SOURCES
the original doorbell switch, the PIC16F610 Microcontroller
through-hole prototype, and an alter- Microchip Technology, Inc.
nate enclosure. Even going to surface- www.microchip.com
mount parts won’t allow this to fit into
the original doorbell button enclosure. Z0405DE TRIAC
C1 is too large. There are two alterna- STMicroelectronics
tives: reduce the load current or split www.st.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 69


THE DARKER SIDE by Robert Lacoste

Let’s Be Crystal Clear


Many electronic devices are enhanced by crystals, but do you know why? Robert
explains why there are usually small capacitors around a crystal, the difference
between “series” and “parallel” crystals, and more.

W elcome to the Darker Side. I still


consider myself reasonably young, but
and explained in Paris, France, in
1880 by Pierre and Jacques Curie.
oscillators for its transmitters![1]
The piezoelectric phenomenon is at
I remember when my dad bought one (The former became the husband of microscopic scales. Unfortunately, you
of the first inexpensive electronic Marie Curie, and they later discov- will never see a crystal size change
watches. The display was made of ered small things like radioactivity, when it is electrically excited. A few
seven-segment red LEDs, so I had to but that’s another story.) The under- volts on a quartz crystal corresponds to
press a button to read it. Although the lying physical principle is quite sim- an electricity charge of a couple of pico-
batteries drained after a couple of ple (see Figure 1). As usual, the first coulombs, which translates into forces
weeks, it was still a great innovation. real-life application was for the mili- in the Newton range (100 g), which
As you know, such a watch is based tary. Paul Langevin used it as a trans- translates into displacements of a few
on a crystal oscillator. ducer to create ultrasound for the first micrometers only. Quartz manufactur-
Crystals remain important. Many of sonar system during World War I. ers know how to cut a crystal to opti-
the electronics that you use on a daily According to the Encyclopedia Univer- mize its performances for a given appli-
basis, from MP3 players to wireless salis, the first quartz-based oscillator cation. The cuts are normalized in
devices, probably wouldn’t be possible was built in 1918 by Walter G. Cady, regard to the crystal structure (named
without the time stability of crystals. and that was the first of many. During X-cut, Y-cut, CT-cut, AT-cut, and
Although they are very common, they World War II, the United States built more). But you usually won’t need to go
are often misunderstood. For example, more than 50 million quartz-based into this level of detail because you are
do you know why there are usually
small capacitors around a crystal? Do
you understand the difference Pressure applied

between a “series” and a “parallel” Nonsymetrical crystal

crystal?
This month, I will try to answer
these questions and a couple of others.
Follow me into the magical world of
crystal oscillators.

PIEZOELECTRICITY
Some crystals, quartz in particular,
are piezoelectric devices. Piezoelec-
tricity is on the border between elec- Equilibrium
tricity and mechanics: If you press a
piezoelectric device, a voltage will More << + >> on left:
Voltage appears
appear between its sides. Conversely,
if you apply a voltage between two of
Figure 1—Piezoelectricity appears when a crystal is not fully symmetrical. Look at the simplified figure on the left. With-
its faces, its physical size will
out any pressure, these atoms are centered and the overall electrical field is null. If you press vertically on the crystal,
change. you will slightly change its shape (right), the electrical charges will no longer be symmetrical, the left side will be a little
Piezoelectricity was first demonstrated more positive than the right, and a voltage will appear. Conversely, if you apply a voltage, the crystal will distort itself.

70 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


on the electrical side.
Crystal
X1

THE ELECTRICAL MODEL


Quartz shrinks or inflates depending
on the voltage. So, if you apply an AC
Equivalent circuit
voltage with a specific frequency to its
two terminals, you will enable the L1 C1
R1
crystal to reach its mechanical reso-
nance (either longitudinal vibration
resonance or a more complex shearing
C2
resonance depending on the crystal
cut). At that precise frequency, the
current flowing through the crystal
will be in phase with the excitation
signal and the crystal will electrically Simplified, at serial resonance
behave as a small resistor, R1. If you
move the frequency around the reso- L1 C1
R1 1
FSERIES =
nance frequency, the crystal will 2π × L1 × C1

behave as a series R1/L1/C1 network,


in parallel with a loading capacitor C2
(see Figure 2). C1 is called the motion-
Simplified, at parallel resonance
al capacitance, and it models the
behavior of the quartz at resonance L2
R1
with L1. C2 is nothing more than the
parasitic capacitance between the two ⎛ C ⎞
FPARALLEL = FSERIES ⎜ 1 ⎟
⎝ 2C2 ⎠
terminals of the quartz.
C2
The values of these equivalent com-
ponents make quartz a very uncom-
mon RLC network. Most megahertz-
range crystals have an inductance (L), Figure 2—The equivalent circuit of a crystal is a series L1/C1/R1 resonant circuit in parallel with a parasitic capaci-
tance C2. Such a network has a minimum impedance when the L1/C1 network is at resonance (series resonance)
not in nanohenries, but from 0.1 to 1 H.
and at a maximum impedance when L1/C1 behaves as a large inductance L2, which oscillates with the parasitic
The series resistance (R) is hundreds of capacitance C2 (parallel resonance).
ohms, and the motional capacitance
(C) is in femtoFarads (yes, 0.001 pF),
providing a quality factor of more than oscillators. That also explains why Finally, the parasitic capacitor C2 is a
100,000. Because the quality factor of you can’t replace quartz with equiva- more usual value, a couple of pico-
a network is equal to the bandwidth lent discrete components. Just try to Farads.
divided by the central frequency, this buy a 1-H inductor with parasitic For low or high frequencies, the
helps to build precise and stable capacitance below 1 femtoFarad. crystal is equivalent to the capacitor

a) b)

Photo 1—This is the transmission response of an 8-MHz crystal oscillator (a), as grabbed on a Hewlett-Packard 3585 spectrum/network analyzer (b). The minimum impedance
corresponds to the maximum transmission, here at 8,000,250 Hz. This point is followed by a minimal transmission (maximal impedance) a couple of kilohertz higher and then several spurious
resonances are visible.

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 71


C2, because the impedance amplitudes. These reso-
of C1/L1/R1 is high. How- nances are parasitic reso-
ever, when you increase the nances generated by other
frequency, you will reach vibration modes of the crys-
the resonant frequency of tal often linked to mechani-
L1 and C1 (FSERIES) at some cal discontinuities. These
point. At this frequency, usually can be disregarded
the crystal will behave like because your oscillator will
a simple low-value resistor be designed to lock on the
R1: this is its minimum main resonances.
impedance. If you continue
to increase the frequency, PARALLEL OR SERIES?
the crystal will behave like This simple experiment
a larger inductor, up to a highlights an extremely
virtual open circuit. It will important concept: there are
finally reach the behavior two usable resonance fre-
of the capacitor C2 (see quencies for a given crystal.
Photo 2—The addition of a 20-pF capacitor in parallel to the crystal (bottom curve)
Figure 2). It’s easier to see doesn’t change the frequency of the series resonance compared to the quartz alone The first one, the series res-
it rather than describe it, (top curve). However, the parallel resonance is now far closer to the series one, 500 Hz onant frequency FSERIES, is
so I hooked my Hewlett- away compared to 12 kHz. This is clear with the formula provided in Figure 2. If C2 the intrinsic resonance fre-
Packard 3585 network ana- gets higher, both frequencies get closer. quency of the crystal L1/C1
lyzer on a standard 8-MHz and it corresponds to a min-
crystal. The plot is shown in Photo 1. series resonance (minimal impedance) imal impedance. The second resonant
You can do the same with a good at 8.000250 MHz. It then has a maxi- frequency, FPARALLEL, is a little higher in
and stable sweeper generator and an mum impedance at a frequency frequency and corresponds to a maxi-
oscilloscope, but an actual network around 12 kHz higher. Some tens of mum impedance. This is the reso-
analyzer makes life easier. As you can kilohertz higher, the crystal shows nance of the R1/L1/C1 network,
see, my test crystal shows a clear other resonances, but with lower which behaves here as a high-value
inductor, close to an open circuit,
with the parasitic capacitor C2 (see
Figure 2). There isn’t a “series cut” or
“parallel cut” crystal; all crystals are
the same. However, a crystal built to
be used at its parallel resonant fre-
quency is adjusted a little below to
compensate for the small difference
between FSERIES and FPARALLEL.
There is another fundamental differ-
ence between Series and Parallel Reso-
nance mode. As shown in the formu-
las provided in Figure 2, the series res-
onant frequency is independent from
the value of the parasitic capacitor C2.

Figure 3—Here is the basic HC-mos gate-based oscil-


lator that I built on a small protoboard for the experi-
ments provided in this article. A Parallel mode crystal
oscillator can’t be simpler.

72 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


You can still adjust the fre- 8-MHz crystal and a pair of
quency of a series-made crys- 74HC00 gates (see Figure 3).
tal oscillator by adding series Let’s go through each compo-
inductors or capacitors, nent around the crystal.
which will slightly change First, the ubiquitous C1
L1 or C1, respectively. How- and C2. The two capacitors
ever, for the Parallel mode, form the external loading
the value of the parasitic capacitor I just described.
capacitor C2 is influencing Rather than use a single
FPARALLEL, as shown in the capacitor across the termi-
equations. Moreover, nals of the crystal, it is more
because this capacitor is stable to use two capacitors
between the two terminals each between a terminal and
of the quartz, any external the ground. They act as a sin-
loading capacitor is also gle capacitor because they are
influencing it because both connected in series, at least
capacitors will be in parallel. from the point of view of the
Photo 3—This screenshot is a bit blurry, but I think you’ll still find it useful. The top
Thus, the oscillation fre- curve is the output of the oscillator (8 MHz as planned). The two bottom curves crystal, and stabilize the
quency should be unstable show signals measured on both ends of the crystal. It’s clearly 180° out of phase oscillation more efficiently
depending on external cir- or so, as expected. than a single floating capaci-
cuits. However, there is a tor. Their value must be
trick. Why? Because a series mode means twice the loading capacitor that is
Look again at the equations in Figure 2. very low impedances and CMOS oscil- specified for the crystal you are using,
If C2 becomes higher and higher, then lators are happier with large imped- usually around 20 pF each, because
FPARALLEL frequency becomes closer and ances. Moreover, series resonance is the overall capacitance of two C
closer to FSERIES. It is easy to show this more sensitive to temperature and capacitors in series is C/2. The value
with the network analyzer. component variations. I built an oscil- of the capacitors must also be trimmed
Refer to Photo 2. The addition of a lator on a prototyping board around an to account for all of the parasitic
20-pF capacitor in parallel with the
crystal doesn’t change the series reso-
nant frequency. However, the parallel
resonance is reduced from 12 kHz to
500 Hz away from FSERIES, making it
more resistant to external variations.
We Listen. Think. And Create.
That’s why a crystal in Parallel mode
is always used with an external paral-
lel loading capacitor. And that’s why a
Distributed Digital Serial Industrial HMI
I/O I/O Computing
I/O
crystal manufacturer always indicates
the value of the external capacitor if
the given crystal is designed to be SeaLINK Ethernet Serial Servers Offer:
used in Parallel mode in its specifica- SeaLINK Ethernet serial • 1, 2, 4, 8, and 16-Port Models
tions. If you load it with a capacitor of servers are the fastest, • RS-232, RS-422, RS-485, and Optically
a different value, your oscillator sim- Isolated Versions
most reliable way to • Included Software Enables Virtual COM
ply won’t oscillate exactly at the value Port Operation
stamped on the crystal body. connect serial devices
• Easy Installation and Configuration
By the way, the experimental setup to your network. • DIN Rail or Table Mount Design
used for Photo 2 is also a good way to • Extended Temperature Option Available
calculate the C1 motional capacitor of
a crystal: measure the frequency varia- F CUS
tion of the parallel resonance with a
On Success
given external capacitor and deduce
C1 from the equation in Figure 2. This
is called the pullability method.

HCMOS PIERCE OSCILLATOR


Now let’s examine a classic quartz-
based oscillator. Nearly all CMOS-
based oscillators use parallel resonance.

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 73


Finally, the resistor R1 is just help-
ing to keep the NAND gate in its lin-
ear region: the logic gate is used as
an inverting analog amplifier and not
as a pure logic gate. The value of R1
is not critical, but it should be high
enough to reduce power require-
ments (and because the input imped-
ance of a CMOS gate is very high),
usually between 100 kΩ and a couple
of megaohms.
Photo 3 shows the waveforms meas-
ured on the output of this oscillator as
well as on the two terminals of the crys-
tal. As expected, there is nearly a 180°
phase shift between the two terminals
of the crystal. The output frequency
was measured at 8.0021348 MHz. Why
not exactly 8 MHz? Because I have
wired it on a protoboard, long wires
are connecting the crystal and the
Photo 4—If you capture the start-up behavior of my test crystal oscillator with an oscilloscope, you may conclude logic gates, adding parasitic capacitors
that it is stabilized after about 12 µs. This is true regarding amplitude but not frequency. Horizontal scale is 2 µs/div,
the top curve is the quartz output, and the bottom is the logic gate output. and inductors everywhere. Starting
from this basic schematic, what hap-
pens if you change a component’s
capacitors because you need to get input impedance of the crystal to a value? As expected, increasing C1 or
exactly 8 MHz. higher value and then shifts its oper- C2 decreases the oscillating frequency.
Because you are in Parallel Reso- ating point to a frequency where its For example, adding 10 pF reduces the
nance mode, the crystal will show phase shift is 180°. R2 also helps frequency to 8.0016469 MHz. The
maximal impedance and a phase shift reduce the risk of spurious oscilla- resistor R2 also has an effect on the
around 90°. The HCMOS inverter pro- tions. As a starting point, the value of frequency. Increasing it to 10 kΩ
vides a phase shift around 180°, plus the resistor should be close to the reduces the oscillating frequency to
some propagation delay through the impedance of the loading capacitor at 8.0017738 MHz. However, this
HCMOS gate. An oscillating loop the working frequency (1/(2π × F × C), change degrades the stability of the
must provide a 360° phase shift giving around 2 kΩ. The resistor also output. The standard deviation of the
through the loop, so a little more avoids loading the output of the logic output frequency increased from
phase shift should be added. The gate with a strange load as a crystal 0.249 to 1.678 Hz, but this is more
resistor R2 helps here. It adapts the directly connected would. difficult to see without an exotic

a) b)

Photo 5a—A Hewlett-Packard 5372A time interval analyzer enables you to capture the frequency behavior of the crystal at start up. b—Here the frequency first jumps to 40 MHz or so
and gets down and locks to 8 MHz after only 241 µs (marker position). Time is on the horizontal axis and frequency is on the vertical axis from 0 to 100 MHz. A nice instrument, isn’t it?

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 75


measurement tool. I will good idea for a future proj-
cover this later. ect around your preferred
microcontroller.) By the
OSCILLATOR STARTUP way, you can find inexpen-
It is also interesting to sive TCXO-integrated prod-
check the behavior of the ucts if you need a low-fre-
oscillator when its power quency oscillator like a
supply is switched on. It is standard 32-kHz-based
easy to do. Simply hook RTC. Look at chips such as
an oscilloscope on its out- the Maxim Integrated Prod-
put, trigger it on the rais- ucts DS32B35, which pro-
ing front of the power sup- vides a 2PPM stability from
ply, and voila, you have 0° to 40°C for a couple of
the screenshot shown in bucks.
Photo 4. The startup If you need an even
behavior is a little chaotic, greater stability over tem-
but after around 12 µs the perature, you must go with
output signal amplitude is Photo 6—This is what happens if a 50-mV/1-Hz “noise” is added to a 5-V power supply: the more expensive one:
stabilized. So, you will the frequency of the crystal oscillator is gently following the same shape as the power sup- oven-controlled crystal
conclude that the startup ply voltage. Don’t be confused by the graph. This is not a time domain oscillograph but the oscillators (OCXOs). The
time of the oscillator is 12 output frequency of the oscillator over time. Each vertical division is a 2-Hz variation. idea is simple. Heat the
µs. You will be wrong, but crystal to a fixed tempera-
it is not easy to see why with an delay will never be a couple of ture so it will no longer drift if the
oscilloscope. microseconds. Be prepared to wait, or ambient temperature changes. That is
I am a lucky engineer. My consult- use something other than a crystal. easy to say, but it is more difficult to
ing company has some pretty cool test (RC oscillators or even ceramic res- do, especially for power or cost-
equipment. In particular, I have a onators are orders of magnitude quick- restricted applications.
Hewlett-Packard 5372A frequency and er to start.) But temperature is not the only fac-
time interval analyzer (see Photo 5). tor that could impact your frequency.
The unusual box is a powerful univer- IS IT STABLE? Do you want another cool experi-
sal counter. It can obtain frequency or Now the crystal oscillator is started ment? I’ve added a little noise on the
time measurements quickly and up to and stays on 8.000 MHz. You know clean 5-V powering logic gates-based
millions of measurements per second that this is also a little false, don’t 8-MHz oscillator. That is not a lot of
(and display either their variation over you? noise, just a 50-mVPP,1-Hz sine added
time or their statistics). First, its actual frequency will drift to the 5 V, so a power supply moving
Let’s connect it to the oscillator out- with the ambient temperature. The slowly from 4.95 to 5.05 V. Is there a
put and trigger it when VCC is shape of the temperature to frequency visible impact on the output frequen-
switched on. The result is the plot in curve is not the same for different cy? Time to switch on my 5372A ana-
Photo 5, which shows the output fre- crystal cuts, but manufacturers ensure lyzer again. It generates what you see
quency of the oscillator on the vertical that the variation is minimized in Photo 6. The output frequency
axis and time horizontally. At the around the ambient temperature. In a closely follows the power voltage sine
right of the graph, around 240 µs after nutshell, you can expect variations curve, with a ±3-Hz variation! Not a
start up, the oscillator is well settled around 1 to 10 PPM when the ambient large error, but this can still be a
at 8.000 MHz; but during these 240 µs, temperature changes by 10°C.
the oscillator output went anywhere There are two solutions if you need
from 0 to 40 MHz! This is the intrin- a far more stable oscillator. The first
sic stabilization time of the oscillator. one is to add a circuit that will meas-
The conclusion is that you shouldn’t ure the actual ambient temperature,
use the output of a crystal oscillator and slightly tune the quartz oscillator
during a couple hundred microsec- with external components like varicap
onds. And this is why microcon- diodes, based on some knowledge of
trollers usually include oscillator the theoretical temperature to fre-
startup timers, just to be sure not to quency error. Such oscillators—which
overclock the silicon during this stabi- are called temperature-compensated
lization time. crystal oscillators (TCXOs)—will pro-
The oscillator design can be opti- vide stabilities of 0.1 to 0.5PPM per
Figure 4—The addition of a 24-MHz band-pass filter
mized with a good selection of exter- 10°C. The correcting circuitry can be made with C1 and L1 transforms the 8-MHz oscillator
nal components, but this mandatory either analog or digital. (DTCXO is a shown in Figure 3 into a 24-MHz overtone oscillator.

76 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


it is close. That’s also Crystal oscillators are fun. They
why you can buy are not black magic, even if they are
crystals specifically sometimes on the darker side. I
built to operate in
overtone. First, their Robert Lacoste lives near Paris, France.
construction is opti- He has 18 years of experience working
mized to enhance the on embedded systems, analog designs,
overtone resonances, and wireless telecommunications. He
but they are also has won prizes in more than 15 inter-
tuned to provide the national design contests. In 2003,
exact desired fre- Robert started a consulting company,
quency in the over- ALCIOM, to share his passion for inno-
tone mode. vative mixed-signal designs. You can
Building an over- reach him at rlacoste@alciom.com.
tone oscillator is theo- Don’t forget to write “Darker Side” in
retically simple, but the subject line to bypass his spam filters.
Photo 7—A cystal can also be used in Overtone Resonance modes. Using
the same test setup as the one used for Photo 1, this is what happens when it is usually a little
you look at the crystal impedance significantly higher than its fundamental fre- tricky on the bench.
quency. A third-order resonance is clearly visible around 24 MHz, three times Let’s look at the theo- REFERENCE
8 MHz. ry first. Just add a
[1] P. Voyelle, “Piezoélectricité,” Ency-
band-pass filter circuit
clopedia Universalis, Corpus 14, 1985.
problem for some applications. in series with the crystal that will damp
Temperature and supply voltage are the fundamental frequency. Refer to
usually the first contributors to oscil- Figure 4 where my dear logic-gated oscil- RESOURCES
lator problems, but they are not lator is modified to oscillate on the third Dove Electronic Components, Inc.,
alone. Remember that quartz is a overtone (more or less 3 × 8 = 24 MHz). “Crystal Oscillator Reference,”
piezoelectric device. If you stress it The C1/L1 network acts as a resonant www.doveonline.com/oscillator/more-
mechanically (e.g., with vibrations), band-pass filter with a center frequency on-crystal-oscillators.php.
there could be a visible change in the of 25 MHz (i.e., 1/(2π × √(L1 × C1)). The
output frequency. On some RF actual measured frequency was Fairchild Semiconductor Corp., “Applica-
designs, even sound waves can gener- 23.95966 MHz—as expected, close but tion Note 340: HCMOS Crystal Oscilla-
ate visible spurious modulations of not equal to three times the funda- tors,” AN005347, 1983, www.fairchild
the output (the so-called “nasty mental. What makes an overtone semi.com/an/AN/AN-340.pdf.
microphonic effect”). So, high-g oscillator tricky are the parasitic com- M. Haque and E. Cox, “Use of the
designs usually have some concerns ponents, which are increasingly diffi- CMOS Unbuffered Inverter in Oscilla-
with crystals. cult to manage. Here I had to remove tor Circuits,” Application Report,
the 20-pF capacitors to help it oscillate SZZA043, Texas Instruments, Inc.,
LET’S OVERTONE where I wanted as the parasitic com- 2004, http://focus.ti.com/lit/an/szza043/
Finally, the impedance of a crystal ponents started to be significant as szza043.pdf.
over frequency, as shown in Photo 2, such a high frequency. Anyway, with a
gives a beautiful resonance. But what couple of experimentations you should Hewlett-Packard, “Fundamentals of
happens at higher frequencies? The get it right. Quartz Oscillators,” 200-2, 1997,
answer is in Photo 7. A crystal also http://cp.literature.agilent.com/litweb/
has overtone resonance frequencies, WRAPPING UP pdf/5965-7662E.pdf.
usually close to three times, five Here we are. I hope that your ideas Wikipedia, “Crystal oscillator,” http://en.
times, or even seven times its basic are now clearer on crystals, parallel wikipedia.org/wiki/Crystal_oscillator.
frequencies. It is possible to use a versus series modes, overtones, and
crystal in such an overtone mode to more. You should now understand T. Williamson, “Oscillators for Micro-
build higher-frequency oscillators. It why you shouldn’t forget to put these controllers,” AP-155, Intel Corp., 1983,
is important to understand that the two capacitors around your crystal, ftp://download.intel.nl/design/mcs51/
overtone modes are not electrical har- why you should minimize wirings, applnots/23065901.pdf.
monics of either FSERIES or FPARALLEL; and why you should have a clean
they are mechanical overtones where power supply.
the crystal is oscillating in more com- Don’t hesitate to read through the SOURCE
plex mechanical ways. The conse- documents and articles listed in the 5372A Frequency and time interval
quence is that the third overtone fre- Resources section of this article. analyzer and 3585 network analyzer
quency is not exactly three times They will provide you with addition- Hewlett-Packard
higher than its base frequency, even if al details about these topics. www.hp.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 77


SILICON UPDATE by Tom Cantrell

Touch Me
If you haven’t used touch sensors in your designs, you will soon.Tom explores the new touch
sensors from Cypress Semiconductor and Silicon Laboratories. Traditional keypads and
touchscreens beware!

L ast year, during my visit to the


Sensors Expo, I concluded that touch
to acquire the entire company![2] limitations and then just assume it’s
When it comes to placing bets, I’d good for everything else.
sensing was one of the hotter topics say the $130 million ($88 million up Mechanical switches have funda-
on the show floor (“I Sense, Therefore front, up to $42 million later) that mental advantages over a touch
I Am,” Circuit Cellar 207, 2007). Atmel is paying is definitely upping switch that will never go away, start-
Over my years covering the high- the ante. I imagine that’s an opinion ing with the fact that they are pas-
tech sector, I’ve noticed that where shared by Quantum’s other licensees, sive and require no power for opera-
there’s smoke, there’s either mirrors such as Renesas Technology and tion—no “electrical” power that is, a
or a fire, and the touch sensing mar- STMicroelectronics. point brought home by the EnOcean
ket is definitely the latter. “energy harvesting” (i.e., mechani-
How hot is touch? You really don’t IF THE CAP FITS cal-to-electrical energy conversion)
have to look further than Apple. What applications is touch good self-powered switch technology I
They not only designed touch sens- for? The generic answer, “human covered a while back (“Harvest
ing into their popular iPods, but with interface,” is so all-encompassing Time,” Circuit Cellar 209, 2007).
their new “iTouch” products, they’re that it’s easier to identify touch’s When it comes to energy, there’s no
even designing it into their brand.
Capacitive sensing works for both
keypads and touchscreens, so predic-
tions call for it to find its way into
just about every portable road-war-
rior gadget (phones, PDAs, and
more).[1]
The touch sensing parts from
Freescale Semiconductor and Analog
Devices that I covered back in Issue
207 were just the start. At this point,
virtually everyone in the MCU busi-
ness is in the game and putting new
touch chips on the table.
The action has even moved from
the fab to the boardroom. Back in
September 2007, Atmel made a deal
to license technology from capacitive
touch sensing specialist Quantum
Research Group (see Photo 1). I guess
Atmel liked what they saw because I
just came across a press release Photo 1—You can get hands-on—err, make that fingers-on—with new touch sense gadgets from (left to right)
announcing that they’ve now decided Quantum Research, Silicon Labs, and Cypress Semiconductor.

78 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


a) Photo 2—Express is a simple way to develop simple applica-
b)
tions. Just (a) “draw” your program, (b) define object proper-
ties, (c) transfer functions, (d) debug with a simulator, and
download to flash memory when you’re done.

d)

c)

free lunch, just different ways to


divvy it up.
On the other hand (no pun intend-
No other PCB-design tool gives you ed), the ostensible “passive” advan-
tage for a mechanical switch does
more value per dollar come with a bit of a catch-22. If
Boards designed under EAGLE are developed in one-man there isn’t enough juice left in the
businesses or in large industrial companies. Most of the top
companies are our customers. The crucial reason for selecting battery to monitor a touch switch,
EAGLE is not usually the low price, but rather the high-end there likely isn’t enough to do any-
functionality along with the ease of use. And EAGLE users thing useful anyway.
appreciate the outstanding level of support, which at
CadSoft is always free of charge, and is available New Version A touch switch also can’t serve as an
without restriction to every customer.
These are the real cost killers! EAGLE 5.0 a)
Version 5.0 is even easier to use, especially for Schematic Capture • Board Layout
beginners, due to an enhanced user interface. Autorouter

Windows Linux Mac


® ® ®
for
Version 5.0 Highlights
>
Stand-alone schematic editor available.
>
Automatic signal/contact cross
references using frame coordinates.
>
Right-mouse click for more consistent
Windows UI. b)
>
User-definable attributes for parts.
>
Schematic sheet management.
>
Hiding approved DRC and ERC errors.
>
PRINT preview and text-searchable
PDF output.
>
Improved search engine for help.
>
And much, much more.

Pick the level that is right for you — c)


pay only the difference for upgrades!
Light Standard Professional
Max. number of Standard and Light Editions
1 99 999
schematic sheets have full functionality except
Max. board size 4x3.2 inch 6.4x4 inch 64x64 inch for the limitations mentioned
Max. # of signal layers 2 4 16 in the table.
Layout or
Schematic Editor $249 $498 You can use EAGLE Light for
evaluation and non-commercial
Layout and
$498 $996 applications without charge.
Schematic Editor
Download it from our web site. Photo 3—A touch sensor’s baseline adaptation algorithm
Layout Editor and $498 $996
Autorouter is key for dealing with vagaries of the application and the
Layout Editor and environment, so expect to spend some time fine-tuning.
Schematic Editor
and Autorouter
$49 $747 $1494 www.cadsoftusa.com You can see adaptation in action in this photo sequence
800-858-8355 using the Cypress proximity. With the object (ruler) out of
range, the LED glows red (a). It then turns green when the
CadSoft Computer, Inc., 19620 Pines Blvd., Suite 217, Pembroke Pines, FL 33029 object moves close enough (b). But wait a few seconds
Hotline (954) 237 0932, Fax (954) 237 0968, E-Mail: info@cadsoftusa.com and the adaptation algorithm, which expects to deal with a
Windows / Linux / Mac are registered trademarks of Microsoft Corp. / Linus Torvalds / Apple Computer, Inc. quick touch, will increase the baseline and “un-detect” the
object, turning the LED red again (c).

82 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


electrical link, at least in the conven- the passive (i.e., no power required) Boardroom and legal machinations
tional sense. If you want to connect a capabilities of a low-tech DIP switch. aside, Cypress makes it super easy to
signal from here to there, a mechani- You would also need relays to estab- give touch a try with their new
cal switch is the way to go. lish a true electromechanical connec- “PSoC FirstTouch” starter kit. You
Similarly, a mechanical switch has tion. Preferably, you would use relays can hardly go wrong considering the
the ability to “remember” its state that enable visible determination of kit is only $29.95 and includes
while a touch switch is just the on/off state. Otherwise, you’d everything you need to give touch
“momentary.” need to add LEDs or some such as a (and other applications like tempera-
Better yet, said state of a mechani- visible indicator. ture and light sensing) a whirl.
cal switch can be determined by tac- So, if your grand plan is a new-age The kit also includes the novel
tile or visual means. By contrast, a DIP switch, touch sensing isn’t for PSoC Express “visual programming”
separate mechanism (e.g., a screen you (but maybe psychiatric care is). tool, which I’ve covered before
update, an audio click, or a blinking Otherwise, read on. (“Code Like the Wind World Tour,”
LED) is required with a touch switch Circuit Cellar 200, 2007). Let’s get
to provide feedback and confirmation EXPRESS YOURSELF one thing straight: Express is by no
to a user that their input has been Let’s start by taking a look at the means the Holy Grail of program-
recognized. latest touch sense offering from ming, some kind of World-Beyond-C
Let’s use a bad example to make a Cypress Semiconductor. They were nirvana. It can handle neither big
good point by considering a hypo- among the first to target the touch projects nor those that require blaz-
thetical application where “touch” market with their flash-programma- ing real-time performance. Of course,
and (makes) “sense” don’t go togeth- ble and analog-capable PSoC chips. the same could be said of the PSoC
er. Herewith for your consideration As an aside, I notice Quantum (now chip itself, which can hardly be
is my brainstorm for a high-tech DIP Atmel) is suing Apple over their lat- described as “big” or “high-perform-
switch. est iPod touch technology that is ance” in this era of multi-core 64-bit
The touch contacts and a chip to said to utilize Cypress chips.[3] There uber-silicon. Both Express and the
monitor them are just the start. You is no better proof that you and your PSoC recognize the reality that it’s
need a battery or an otherwise un- technology have arrived than when econoboxes and pickup trucks, not
interruptible power source to match you start getting sued. Ferraris, that make the embedded

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 83


world go round. specifying the “parameterizable” niques. CSD uses more PSoC
Anyway, there’s no doubt that aspects of their operation with point- resources than CSA (i.e., it generally
Express gets you on the air fast. If you and-click forms. The only real calls for a higher-end PSoC), but it has
haven’t done it before, installation of “thought” required to create an a couple of advantages (moisture and
the software is a little clunky because Express program involves defining the temperature tolerance) that may prove
it relies on Microsoft .NET, which control and data linkages between the compelling in harsh/outdoor environ-
adds a layer of complexity. The fact predefined objects. ment applications.[4]
that I already had older versions of Let’s go through the “Proximity The next step is simple enough. Just
Express and .NET on my PC caused a Detector” demo program that comes define the “transfer function” that
little head scratching during the with the FirstTouch starter kit. The connects the proximity detector to the
install since my PC gyrations didn’t Express “program” is as simple as the LEDs (see Photo 2c).
exactly follow the path outlined in the application itself, which just switches Once your “program” is finished,
rather terse instructions. Lucky for an LED from red to green when an hit the Build button. It takes only a
me, things sorted themselves out. It object gets within striking distance minute or two for Express to generate
wasn’t more than a few minutes (see Photo 2). the PSoC software and hardware con-
before I had the demo setup up and After cutting and pasting the touch figuration, schematic, datasheet, and
running. sensor and LED objects from the even the bill of materials. At that
When it comes to “programming,” library, the next step is to define the point, you can run a simulation if you
Express makes things easy by doing as “properties” for the touch sensor (see like before taking the final step of
much automatically as possible. Photo 2a). They specify various switch flashing the PSoC (see Photo 2d).
Obviously, there’s a trade-off in that tuning parameters such as threshold, Of course, this is just a toy demo. In
ridding yourself of the responsibility noise, hysteresis, debounce, and base- real life, expect to spend time tweak-
of handling the gory details means you line drift (see Photo 2b). ing the touch sense properties and
also give up the freedom to tweak any- The Express library offers alternative hardware (e.g., PCB contact layout).
thing and everything you want. touch sense implementations to The fact is, a touch sensor is not the
Rather, the Express way of doing choose from, including “sigma-delta” same as a mechanical switch, and it’s
things boils down to choosing from a (aka “CSD”) and successive approxi- a challenge to design hardware and soft-
library of predefined “objects” and mation (aka “CSA”) conversion tech- ware that completely hide the difference.

64-KB Flash memory


4-KB RAM

CIP-51 8051 Port I/O configuration


Power on
reset/PMU Controller core
Digital peripherals
Wake 64-KB ISP Flash
program memory UART
Reset Port 0
Timers 0, drivers
C2CK/RST Debug/ 256-byte SRAM 1, 2, 3
programming Priority
hardware 4,096-byte XRAM crossbar
Integrated PCA/ decoder
LDO regulator WDT
C2D
CRC SMBus
Engine
VDD/DC+ VREG SPI 0, 1 Port 1
Analog Digital
power power SYSCLK SFR drivers
Bus Crossbar control
GND/DC- Precision
24.5-MHz Analog peripherals
oscillator
VBAT DC/DC 6-bit
Converter Low-power IREF0
IREF
Integrated 20-MHz
DC/DC boost GND oscillator
Internal External Port 2
converter External VREF VREF drivers
XTAL 1 VDD
oscillator VREF
XTAL 2 circuit 10-bit A
M Temp
300-ksps sensor
XTAL 3 U
smaRTClock ADC X
oscillator GND
XTAL 4
CP0, CP0A
System clock CP1, CP1A Burst mode
configuration 10-bit ADC
Comparators with fast wake-up
internal VREF

Precision 2% 24.5-MHz oscillator Two comparators with up to


Low-power 10% 20-MHz oscillator 23 touch sense inputs
32-kHz smaRTClock oscillator

Figure 1—These plan “.9” parts aren’t from outer space, they’re from Silicon Laboratories, and they pack a big analog punch (up to 23 channels) into a tiny footprint and
power budget.

84 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


For example, you can “trick” the you’ll find features that stretch the
proximity detector baseline adaptation analog mileage you can squeeze from
algorithm by “creeping up on it” (see the chip.
Photos 3a, 3b, and 3c). Other gotchas For example, there’s a sampling
to watch out for include “finger-on mode that accumulates the results of
startup” (i.e., touch contact during up to 64 conversions in a burst. In
baseline establishment) and “stuck essence, it’s an automatic (i.e., no-soft-
on/off” contacts. ware overhead) oversampling capabili-
All of which highlights how Express ty built into the chip. As you may
is ideal for experimenting and proto- recall from DSP class, oversampling
typing. You get to spend your time gives a designer the flexibility to
and brainpower on the fundamentals trade-off speed for higher resolution.
instead of “coding.” Later, you can Using a 16- or 64-conversion burst,
carry your work forward into the con- the ’9xx 10-bit ADC delivers perform-
ventional (i.e., “C,” ASM) PSoC tool- ance as good as or better than 12-bit
chain, taking full advantage of the units on other MCUs.
experience gained working with Behind the scenes, there is an
Express. army of analog servants including
multiple trigger options, precision
PLAN .9 FROM OUTER SPACE Photo 4—Low-voltage and minimal power consump-
voltage and current references, auto-
Look up in the sky—it’s a bird, it’s a tion give designers the flexibility to choose between a matic threshold detection, low-power
plane, it’s a UFO! one-battery cell configuration to reduce cost, size, and wakeup options, a temperature
No, I’m not talking about little and weight or a two-cell configuration for a longer sensor, and two comparators, all
battery life.
green men from Mars. Long-time read- fronted with a 23-channel analog
ers know that “UFO” means mux.
“Unidentified Fifty-One.” Yes, we’re as a ’51, but as with other UFOs, it is The 0.9-V capability has the poten-
talking about yet another incarnation one that’s benefited from 30 years tially compelling benefit of allowing
of the venerable 8051 (aka “The MCU worth of Moore’s Law. Most apparent single-battery operation. It may not
That Wouldn’t Die”). Say hello to our is the fact that raw performance is seem like a big deal, but when you’re
new little friends: the C8051F9xx line- improved by roughly a factor of 10. talking about some inexpensive pock-
up from Silicon Labs, which has been Plan .9 parts execute most instruc- et gadget, the reduction in cost, size,
christened with the marketing tions in one or two clocks compared and weight can be noticeable.
moniker “.9” (see Figure 1). to the dozen clocks or more for the Low voltage also means low power,
Ironically, the march of silicon original. and I mean really low power, as in a
poses a challenge for embedded It’s recognizable as a ’51 alright, fraction of a milliamp per megahertz.
MCUs. Each new generation of fab but only if you bring a magnifying Silabs has a nifty little power estima-
process cuts the core voltage, which is glass. Small has never been more tor utility program that allows you to
great for reducing power consumption, beautiful than when it allows you to plug in various battery configurations
but not for real-world interfacing. To cram so much intelligence into so and application scenarios (clock rate,
address the problem, both the Cypress little board space. Thanks to the lat- sleep/wake duty cycle, and more).
and Silicon Labs parts include on-chip est QFN package, a 32-pin part is a Photo 4 is a screenshot of the simula-
switch mode controllers that turn the mere 5 mm (less than 0.25″) on a tion for a once-per-second data logger
chips into mini-me step-up DC/DC side. If you can get by with a 24-pin application. Over 10 years from a sin-
power supplies. That’s what the part, the QFN footprint shrinks to gle AAA—that’s what I’m talking
Silicon Labs “.9” pitch is all about just 4 mm × 4 mm. Also offered is a about!
(i.e., the chip can run down to 0.9 V traditional 32-pin LQFP package,
by generating its own 1.8-V (core) and which is larger, though hardly impos- STEP UP TO THE PLATE
3.3-V (I/O) supplies). ing at 9 mm × 9 mm. Though quite general-purpose in
Some say Plan 9 From Outer Space The packaging and ones-and-zeros most respects, the new Silicon Labs
is the worst movie every made.[5] features are interesting, but it’s ana- parts have some tweaks under the
Actually, I thought it was bad enough log where the MCU action is. On the hood that are specifically designed to
to be funny, which makes it better surface, the 10-bit, 300-ksps ADC support touch sense applications. The
than a lot of movies, which are just seems pretty middle of the road, same goes for tools, with a touch
bad enough to be bad. But make no especially considering Silicon Labs sense starter kit leading the way. It’s
mistake, I say “Plan .9 From Silicon makes other parts in the high-resolu- $36.90 for a two-piece setup compris-
Labs” delivers some of the best 8-bit tion stratosphere (e.g.,16-, 20-, and ing a USB plug-in toolstick plus a
MCUs ever. even 24-bit converters). But look a touch daughter card or just $19.90 for
The core itself is still recognizable little closer at the datasheet and the daughter card itself which, once

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 85


requires only a few hundred REFERENCES
bytes of code (and that includes
initial calibration) and a frac- [1] Walker Mobile, “The Future of
tion of a percent interrupt Mobile Touch,” 2007, http://walker
overhead. mobile.com/The_Future_of_Mobile_
As for the capacitive switches Touch.pdf.
themselves, what size, layout,
and overlay materials (e.g., glass, [2] Atmel Corp., “Atmel to Acquire
Plexiglas, Mylar, plastic, and Quantum Research Group,” Feb. 6,
FR4) are best? Kudos to Silicon 2008, www.atmel.com/dyn/corporate/
Labs for studying the issue thor- view_detail.asp?ref=&FileName=Quantum
oughly, so the rest of us don’t Announcement_2_6.html&SEC_NAME=.
have to (see Figure 2).[6]
[3] The Macintosh News Network,
ONCE MORE, WITH FEELING “Quantum Sues Apple Over iPod
No doubt capacitive touch Clickwheel,” Jan. 22, 2007, www.macnn.
sense is a major trend that has com/articles/07/01/22/quantum.sues.
a huge impact for traditional apple/.
keypad and touchscreen appli-
cations. It’s coming to a phone, [4] R. Seguine, “Capsensing: CapSense
MP3 player, PDA, and more Device and Method Selection Guide,”
near you soon, if it is not Cypress Semiconductor Corp., 001-14459,
already there. I imagine it 2007.
won’t be long before creative
designers start to explore ideas [5] The Internet Movie Database, Plan
Figure 2—This isn’t some crazy eye chart, but rather a vari-
ety of potential touch switches. Naturally, switch sensitivity that go well beyond the tradi- 9 From Outer Space, www.imdb.com/
increases with size, but layout and packaging also matter. tional. For instance, who says title/tt0052077/.
Measurements performed by Silicon Labs indicate that circu-
all of the “keys” on a gadget
lar layout is far superior. Depending on the specific overlay [6] Silicon Laboratories, Inc., “AN338:
material and thickness, the sensitivity (i.e., percent change in have to be lined up in a flat lit-
capacitance caused by a finger touch) of a circular layout tle square. Form should follow Capacitive Touch Sense Solution,” 2008,
(i.e., row four) is typically two to five times higher than any function, and now it can. www.silabs.com/public/documents/tpub_
grid variant.
Going even further, I’m doc/anote/Microcontrollers/Small_Form
intrigued by the idea that this _Factor/en/AN338.pdf.
programmed, is capable of stand-alone technology gives designers the ability
operation. to gift their applications with a [7] S. Adee, “Dean Kamen’s ‘Luke
The journey from a capacitive touch “sense of touch.” For instance, I Arm’ Prosthesis Readies for Clinical
switch to ones and zeros starts with recently read that Dean Kaman (of Trials,” IEEE Spectrum, February
the pins and front-end to the analog Segway fame) is hard at work creating 2008, http://spectrum.ieee.org/feb08/
multiplexer. There you’ll find a specif- artificial limbs offering hope for the 5957.
ic “touch sense” configuration option future that seems to be quickly evolv-
that includes the resistors, which han- ing from science fiction to science
dle the “R” part of the “RC” relax- fact.[7] So, wouldn’t the ultimate cul- RESOURCE
ation oscillator equation. That’s a very mination of the quest for an artificial Quantum Research Group (Atmel),
welcome feature because it complete- limb include “skin” that could truly “QProx capacitive touch sense tech-
ly eliminates the need for any external “feel”? nology,” www.qprox.com.
components beyond the switches Once again, the challenge and
themselves. opportunity of a new technology
The comparators have features like presents itself. And once again, I’m SOURCES
programmable hysteresis and the sure designers will rise to that chal- CY8C21xxx Microcontroller and
ability to work in concert with the lenge with inventions that will express development tool and
on-chip timers. There’s nothing indeed “touch” our lives in many FirstTouch starter kit
going on here that couldn’t be han- ways. I Cypress Semiconductor Corp.
dled in software, but having the chip www.cypress.com
take care of the grunt work is a luxu- Tom Cantrell has been working on
ry that leaves more MIPS and code chip, board, and systems design and C8051F9xx “.9” MCU and toolstick
space for bigger and better things. marketing for several years. You may with touchsense daughtercard
With the hardware support, adding reach him by e-mail at tom.cantrell@ Silicon Laboratories, Inc.
touch sense to your application circuitcellar.com. www.silabs.com

86 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


IDEA BOX
THE DIRECTORY OF PRODUCTS 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 OTHER ELEMENTS MUST FIT WITHIN A 2" x 3" FORMAT. Call for current rate and deadline information. Send your disk and digital submission sheet
to: IDEA BOX, Circuit Cellar, 4 Park Street, Vernon, CT 06066 or e-mail adcopy@circuitcellar.com. For more information call Shannon Barraclough at (860) 875-2199.

The Suppliers Directory at www.circuitcellar.com/vendor/


is your guide to a variety of engineering products and services.
®

USB
CROSSWARE

ARM
Tools for Embedded Development

8051 Add USB to your next


®

COLDFIRE project—it’s easier than you


Three quality tool suites might think!
G C/C++* v USB-FIFO up to 8 mbps
v USB-UART up to 3 mbps
G Code Wizards
v USB/Microcontroller boards
G Debugging pre-programmed with firmware
G Simulation v 2.4GHz ZigBee™ & 802.15.4
v RFID Reader/Writer
G Support
* Embedded C++ for ARM and Absolutely NO driver software
ColdFire only development required!
Advanced software www.dlpdesign.com
tools since 1984
www.crossware.com
360-812-2397

w
Ne og!
al
Cat

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 87


88 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com
NEW
HI-TECH C® PRO for the Cypress®

PSoC ®
Mixed-Signal Array

C Compiler
FREEWARE
New PRO compiler also operates in
Lite mode with no time or size limits:
cypress.htsoft.com/portal/CC20

Cypress and PSoC are registered trademarks of


Cypress Semiconductor Corp.

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 89


90 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com
Coming Soon!
A Social Networking Site for
You, the Electronics
Enthusiast!

We Need Beta Testers Now


Sign Up At:

www.solderbynumbers.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 91


92 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com
CROSSWORD
1

2 3

6 7

8 9

10

11

12 13 14

15

16

17 18

19

Down Across
1. The “L” of an LC circuit 2. Assigning a “friend” to new employees when they are hired to
3. No affinity for H2O acquaint them to the company
4. Magnetic mineral used for navigation 7. A mobile phone that combines some capabilities of a PC, including
5. 1015 Internet connectivity
6. A long, shallow depression 8. A device that restrains voltage transients
10. A device that periodically reverses current in 9. 10,000 lux
an electric motor and maintains current flow 11. A circuit that mutes a receiver when an input signal is below a
in a generator certain level
13. The place in orbit that is farthest from the 12. The “C” of an LC circuit
Earth 15. Sn
14. A charge for using a mobile phone when 16. 0.001 inches
you’re outside your service area 17. English physicist and inventor (1783–1850) who designed the first
18. A low-pressure sodium lamp electromagnets. Think: electric motor
19. Voltage falls, lights dim
The answers are available at
www.circuitcellar.com/crossword.

www.circuitcellar.com CIRCUIT CELLAR® Issue 215 June 2008 93


INDEX OF ADVERTISERS
The Index of Advertisers with links to their web sites is located at www.circuitcellar.com under the current issue.
Page Page Page Page
87 AAG Electronica, LLC 87 FDI-Future Designs, Inc. 39 Luminary Micro 88 Reach Technology, Inc.

66 AP Circuits 90 FlexiPanel Ltd. 89 MCC (Micro Computer Control) 79 Renesas Technology

92 All Electronics Corp. 92 FlyPCB China Co., Ltd. 90, 91 Micro Digital, Inc. 95 Saelig Co.

88 Apex Embedded Systems 83 Grid Connect, Inc. 92 Micro Digital, Inc. 91 Schmartboard

9 Applied Micro Training 88 Hagstrom Electronics 41 Microchip 73 Sealevel Systems

7 Atmel 89 HI-TECH Software LLC 92 microEngineering Labs, Inc. 11 SEGGER Microcontroller Systems LLC

25 Bitscope Designs 34 HobbyLab LLC 57 Mouser Electronics 5 Spark Fun Electronics

65 CWAV 88 ISP Micro 88 Mylydia, Inc. 1 Sunstone Circuits

82, 88 CadSoft Computer, Inc. 33 IMAGEcraft 23 NKK Switches 91 Systronix

63 Calao Systems 91 Intec Automation, Inc. C2 NetBurner C3 Tech Tools

29 Comfile Technology, Inc. 87 Ironwood Electronics 3 Noritake Co., Inc. 80, 81 Technologic Systems

87 Crossware Products, Inc. 64, 66 JKmicrosystems, Inc. 69 Nurve Networks LLC 90 Technological Arts

87 Custom Computer Services, Inc. 91 JKmicrosystems, Inc. 90 Ontrak Control Systems 89 Tern, Inc.

19 Cypress Microsystems, Inc. 48 Jameco 72 PCB-Pool 56 Tibbo Technology, Inc.

87 DLP Design 69 Jeffrey Kerr LLC C4 Parallax, Inc. 89 Tin Can Tools, LLC

69 Decade Engineering 42 Keil Software 90 Phytec America LLC 13 Total Phase, Inc.

34 Designnotes 58 LPFK Laser & Electronics 2 Pico Technology Ltd. USA 92 Trace Systems, Inc.

83 EMAC, Inc. 34 Lakeview Research 92 Pioneer Hill Software 91 Triangle Research Int’l, Inc.

89 Earth Computer Technologies 88 Lawicel AB 40 Pololu Corp. 64 WCSC (Willies Computer Software Co.)

90 Embedded Developer 9, 88 Lemos International 91 Pulsar, Inc. 50 Wiznet

49 ExpressPCB 63 Linx Technologies 47, 74 Rabbit, A Digi International Brand

47 ezPCB 89 Loadstar Sensors, Inc. 89 Rabbit, A Digi International Brand

Preview of July Issue 216 ATTENTION ADVERTISERS


Theme: Internet & Connectivity August Issue 217
Internet-Enabled Alarm Clock Deadlines
Internet Information Retrieval: A Design For Targeting And Displaying Web Site Content Space Close: June 11
PSoC Design Techniques (Part 1): Advanced Analog Routing Material Close: June 20
Card Reader USB Theme:
Create A Modbus Slave Embedded Development
Launch Control: Build A Coil Gun Controller And Launcher BONUS DISTRIBUTION:
Sound Effects Processing Hot Chips; Flash Memory Summit

LESSONS FROM THE TRENCHES Living & Working Off The Grid (Part 1): Planning & Design Call Shannon Barraclough
now to reserve your space!
FROM THE BENCH Electric Motor Technology: Theory, Construction, And Usage 860.875.2199
SILICON UPDATE MIPS For The Masses: A Look At The PIC32 e-mail: shannon@circuitcellar.com

94 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com


UNIQUE PRODUCTS & SUPPORT
www.saelig.com
Bargain MSO 100/200/300MHz DSO S c o p e + A n a l y z e r 15/20MHz Wfm Gen 1/2GHz RF Generators EMC Spectrum Analyzer
!

GO !
GO !
EW

RI EW
RI EW

L
L

L
GO
N

N
N
RI

25MHz 100 MS/s 2/16ch scope/ 100/200/300MHz 2 ch, 2000 wfm/s 100MHz 2-ch /16 logic scope and 15/20MHz USB 14-bit Function/ High accuracy/stability, wide Handheld Palm PC-based 2.7GHz
logic-analyzer 5ns-5s/div with refresh rate. FreeCase! logic analyzer. 2000 wfm/s refresh Arbitrary wfm Generators. 10 built-in range, low phase noise/leakage,
Spectrum Analyzer. Multiple
complex triggering. See wfm + DS1102C (400MS/s) $999 rate. See waveforms and logic wfms; FM, AM, PM, FSK, serial control. Keypad/rotary setting. sweep settings – store wfms,
data lines. 7.8” TFT Color LCD. DS1102A (2GS/s) $1295 data simultaneously. Trigger on SWEEP and BURST; 6 digit TGR1040: 10MHz-1GHz, FM int/ext set-ups, etc. Use WiFi PC for
USB-connected. 4MS buffer. DS1202A (2GS/s) $1595 data or signal edge. 200MHz frequency counter. TGR2050: 150kHz-2GHzAM/FM/PM email, reports, calculations.
MSO5022 SALE! $799 $899 DS1302A (2GS/s) $1995 DS1102CD FreeCase! $1499 DG1011 / DG1021 $650 / $795 $2498/4558 PSA2701T $1990
Color LCD Scope Low-Cost Scope 50MHz USB Scope Logic Analyzer World’s Fastest 60/100/120MHz AWG
lle t

GO !
RI EW
Se Bes

L
r

N
Winner!
O w o n - 2 5 M H z 2-ch + 2-ch 40/100/200MS/s 8-bit scope PS3206 - Is an impressive 2-ch ZeroPlus - Intuitive full-featured 16-ch PS5204 - 2-ch 250MHz Scope with 60/100/120MHz USB 14-bit ARB
trigger standalone USB bench range with 5/10/25MHz bandwidth 200MS/s 8-bit PC scope adapter 4MB 200MHz sampling memory. 128 MS/s and real-time sampling of w. USB RS-232, LAN/GPIB. 10
scope with 7.8” color LCD. and USB2.0 for fast screen - 10GS/s for repetitive signals! Sophistcated triggering. I2C, SPI, 1GS/s. Adv triggering. 250MHz spec. built-in wfms; 6 digit 200MHz
Te s t g e a r

Battery powered optional. updates. Inc. scope/FFT/logging No power supply needed, simple and UART monitoring. Includes analyzer and 125MS/s waveform gen. frequency counter; opt. 16-ch
PDS5022S (25MHz) $325 software, case, probes. USB 2.0 connection clipleads, USB cable and software. PS5203 32MS buffer $2237 gen. DG3061A $1895
PDS6062T (60MHz) $599 PS2203/4/5 from $318 PS3206 Bundle $1574 LAP-16128U $299 PS5204 128MS buffer $3360 DG3101A/DG3121A $2795/$3995

6 in 1 Scope Automotive Testing Mixed -Signal PC Oscilloscope Handheld Scope Pen Scope
100 MHz Scope and Logic Analyzer
lets you do complex triggering to find
hard-to-get-at glitches, spikes, etc.
Huge 4 or 8 MS buffer for deep data
drilling and zooming. Optional built-in
6-in-1 USB scope adapter! 200kHz 2-ch swept signal generator. 2 Analog 20MHz or 60MHz rugged PS2105 - 25MHz USB powered
10-bit scope, 2-ch spectrum analyzer, Auto Diagnostics - Award-winning channels x 10, 12, 14 bit with more handheld USB scope with 3.8” scope-in-a-probe! Up to
than 60 dB dynamic range. 8 digital
2-ch chart recorder, 16-ch 8MHz logic kits turn yours into vehicle-electrics color LCD. Built-in meter - 100MS/s, 24kS buffer C/VB/
inputs for mixed signal display/trigger.
analyzer, 5-ch signal gen, 8-ch pattern diagnostic tool. PS3423 kit $2293 CS328A-4 (4MS Buffer) $1259 great for your tool kit. Delphi/LabView/VEE drivers.
gen. SPI/I2C/1-w/UART decoding. 3-ch logger for 16-bit current/voltage/ CS328A-8 (8MS Buffer) $1474 HDS1022M (20MHz) $499 PS2105 (25MHz, 100MS/s) $372
PoScope with probes $199 temp msmt. KLARI-MOD MC $1500 CS700A (signal generator) $299 HDS2062M (60MHz) $699 PS2104 (10MHz, 50MS/s) $234

RF Testing Electronic DC Load DMM USB Bus Analyzers SPI Bus Analyzer GPS Logger
GO !

!
RI EW

EW
L
N

SPI Bus Analyzer - SPI protocol


Economical, portable RF test For testing dc power/battery sources 6 1/2 digit 50KS/s, 2MS mem. Opt. USB1.1/2.0/WiMedia analyzers exerciser and analyzer for standard TrackStick II - Pocket-sized logger
enclosures, for initial compliance Const. current, resistance, 16-ch mux. Automeasure DC/AC, and now - EX260 can test SPI and non-standard 4-wire and tracks position data for vehicles,
testing. from $1295 conductance, voltage and power 2/4-wire R, C, Continuity, Diode, USB3.0 5Gbps too! Emulate 3-wire serial protocol interfaces up personnel, etc. Records date, time,
Shielding Tents with external modes 0 to 80 V and 0 to 80 A 300W Frequency, Period, Ratio, Temp, host/device, verify compliance. to 50 Mbps. PC control via free GUI location, route and speed. Shows
frame, instant up/down for Transient generator. Variable drop-out. Sensor, High/Low Limit Math. TR110 / EX200 / EX260 8Pl Control Panel Software. data on Google maps! $175
emissions-free room. from $3500 LD300 $1555 DM3061 $795 $999 / $2999 / CALL SPI Xpress $699 Super TrackStick II $239
Serial-Ethernet Cable Instant Ethernet Ethernet-IO Multiparameter Loggers Serial Server Temp/RH Sensors

Mini-logger with built-in temp/humidity/


Network your serial product easily 10/100 Ethernet controller on a chip! Ether-IO - UDP/IP-controlled 24 pressure/3-axis accel sensors.
RS232/422/485 device server for UPSICAP™- novel ambient sensors
without a PC using this 28” cable. Fully hardwired TCP/IP core. No digital I/O board 3 x 8-bit TTL Customize msmt/record parameters;network-enabling legacy serial and modules accurately measure
Provides an instant IP address. OS required. TCP offload improves ports each independently send data to PC after or during logging. devices. 1/2/4/8/16/32 ports temp/RH. Amazing range/response:
RS-232 port compatible with most system performance. PCB too! programmable. Connects to any Synchronize multiple loggers, 10/100Mbps-230kbps. Static 0% to 100% RH, -90 to +85degC;
Misc

10/100mpbs Ethernet hubs. W5100 (integrated PHY) $5.58 TCP/IP Ethernet network. merge data to single record IP/DHCP/PPPoE. 0.25s! Interchangeable without
eCOV-110-P $89 WIZ110SR $30 Ether-IO 24 $119 MSR145S from $468 Portbase-3010/RS232 from $149 recalibration. from $3 / $40
USB to I2C I2C for PCs RF Modules Wireless Modules 1/2/4/8/16 x RS232 Saelig
Alan Lowne
says: "I started
Saelig as an
engineer - for
engineers!
PCI93LV: industry-standard I2C card Saelig - an
Devasys - Provides a simple for PCs. WINI2C/PCI software RF TX/RX Modules - simultaneously Easily create mesh networks at Add COMports via your PC’s Olde English
“drop-in” solution for connecting gives windows-interface to develop transmit composite video and 910MHz - like Zigbee only better! USB Port. USB-COM-S $20 word meaning 'happy, prosperous,
blessed' - which is what I want for
your PC to 90kHz I2C + 20 I/O and debug I2C bus systems. stereo audio signals. 2.4 GHz Complete RF solution for fast & USB-2COM $48
my customers, my staff, and
lines. Free software. Use multiple UCA93LV is USB version. ISM band. 4-ch RF, 5V operation reliable data transmission. USB-4COM $105 myself! See my blog for behind-
boards for more I2C/IO. Transparently monitor at AWM630TX $16 B915FHtiny-plus/40-SMD-WA $64 USB-8COM $195 the-scenes company details,
business hints, kudos, etc. "
USB I2C/IO $89 400kHz! $499 AWM634RX $27 B915FHtiny-plus/40-DIP-EA $804 USB-16COM-RM (rackmount) $459

We search the world for unique, time-saving products - see our website for 100s more: volt/temp data loggers,
wireless boards, LCD display kits, Ethernet/IO, USB/RS232/485, USB-OTG, instant Ethernet-serial,
CAN/LINbus, USB cables/extenders, line testers, logic analyzers, color sensors, motion controllers,
eng. software, wireless boards, SMD adapters, I2C adapters, FPGA kits, GPS loggers, automotive testing,
security dongles, video motion detectors, crystals/oscillators, custom switches, barcode scanners,
robots, DSP filters, PLCs, Remote MP3 players, etc. Don’t forget to ask for your FREE Starbucks card
with your order! Check w w w . s a e l i g . c o m often for special offers, bargains, business hints, blog, etc.
PRIORITY INTERRUPT
by Steve Ciarcia, Founder and Editorial Director

It’s All In The Whiskers


S peaking as someone who has been on both sides of the fence and still intimately involved in electronics, let me just say that I certainly find it a lot
easier to talk about embedded technology than wade through the muck and mire of compliance and certification that electronics manufacturers deal with
today. When I used to own a manufacturing business (sold nine years ago), my one certification/testing nightmare with conductive spray coatings for
EMI/RFI shielding convinced me that dealing with government edicts can be a real pain in the tush.
Twenty years ago, electronic manufacturing success simply involved a good product idea, some production samples, and lots of advertising luck. All
it took were a few large production orders and yet another flourishing company was born. Unfortunately, for today’s entrepreneur, the global economy has
changed both the dynamics of producing a product and the logistics of marketing it. The concept of a single entrepreneur personally soldering boards
together for shipment to a customer in the next town and transitioning that U.S.-compliant product to a mass-produced item serving the global economy
has gotten a whole lot more complicated. All the other countries have their fingers in the compliance-and-regulation soup now, too.
Presented in February 2003 by the European Union (EU) and mandatory as of July 2006 (China instituted a similar but stricter version in March 2007),
suppliers of electronic materials have been making significant changes to their products to comply with the Restriction of Hazardous Substances (RoHS)
Directive. The regulation restricts the use of six materials: cadmium (Cd), hexavalent chromium (Cr (VI)), lead (Pb), mercury (Hg), polybrominated
biphenyls (PBB), and polybrominated diphenyl ethers (PBDE). Basically, you can’t ship products to these countries that include more than a prescribed
amount of these substances.
A few minutes on the search engines will tell you all the materials and products affected by these restrictions, but the most significant one affecting
the embedded control community has to be lead solder—or, more importantly, lead-free solder. I have a bit of manufacturing experience, so when I say
that arbitrarily replacing good old 60-40 tin-lead with lead-free solder has a whole lot of problems, believe it. Certainly, the regulations were conceived for
environmental concerns, but there was a fundamental misconception that the electronics industry could easily switch from tin-lead solder chemistry to
pure tin (or alloys of tin, silver, and copper) with the only difference between classic solder and lead-free solder being the melting point. Bad idea!
Replacing tin-lead with pure tin appears to have been a big mistake and the environmental motivation may have faulty logic. First of all, avoiding lead
because it leaches into our environment may be true for paint and gasoline, but there is little evidence that the lead in solid form on PCBs migrates into
the ground the same way. Also, the added resources necessary for increased tin, silver, and copper mining and smelting are a poor trade when compared
to the fact that most lead solder is derived from recycled products.
Toxicity issues aside, the real problem with lead-free solder is that it just plain doesn’t work as good as tin-lead solder. Regardless of the multitude of
substitute alloys that have been tested so far, current lead-free tin solder chemistry has this nasty propensity to spontaneously grow tin “whiskers” that
can become long enough to short adjacent traces. Typically microscopic in size, some whiskers have been almost as long as a centimeter and, at 30 mA
current capacity, disastrous to digital circuitry. If you think problems from whisker shorts are irrelevant or inconsequential, ask the Swiss watch company
Swatch about the $1 billion they spent in 2006 recalling short-circuited watches. Or research what happens when a nuclear power plant shuts down
because a steam pressure monitor shorts out, which is what happened at the Connecticut-based Millstone 2 nuclear power plant in April 2005. Lead-free
solder is also considerably more brittle and therefore susceptible to fractures and open connections, too. As a company owner, these are certainly not
“features” you want in a “parts and labor” warranted product that is shipped to the other side of the world.
To my knowledge, the U.S. hasn’t specifically outlawed the use of lead solder (a quick check over at www.jameco.com shows a variety of lead and lead-
free solders available), but like BMW and Mercedes making cars that meet California emissions and U.S. crash test regulations, the desire to participate in
the global market ultimately dictates product ingredients that meet everyone’s regulations. If you’ve bought a car, a TV, or a computer since 2006, regard-
less of nationality, it most assuredly uses lead-free solder. And, of course, we all got extended warranties because we expect a lower MTBF. ;-)
Seriously, the issues with lead-free solder are both a goal for future chemical research as well as a logical motivation for reassessing a bad regula-
tion. The irony of the situation is that the European Union has already exempted military hardware and critical communications gear from using lead-free
solder because they know it affects reliability. Even Swatch has received an exemption that allows it to go back to using lead solder.
The path for small businesses and entrepreneurs is a bit grayer. Certainly, developing a product that becomes a mass-market item is every engineer’s
goal, but be careful that you design and manufacture it to meet the intended customer destination. To add insult to injury, if making the PCB isn’t enough
aggravation, try shipping it to China. There, even the packing materials have to meet stringent RoHS certification. As for me, I’m just going to stay down
in the Circuit Cellar making Sn-Pb soldered prototypes and not even think about all the directives, certifications, and regulations. ;-)

steve.ciarcia@circuitcellar.com

96 Issue 215 June 2008 CIRCUIT CELLAR® www.circuitcellar.com

You might also like