Está en la página 1de 100

CIRCUIT

#201 April 2007

www.circuitcellar.com

CELLAR
®

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

EMBEDDED PROGRAMMING
MCU-Based Keyboard Interface

Reverse-Engineered
ECP Bus

Create a Modbus Master

Embedded RF
Communication

0 4>

7 25274 75349 9
$4.95 U.S. ($5.95 Canada)
Real
Mixed-Signal
Programmability.
Get PSoC ®. Because change happens. GET STARTED WITH PSoC NOW.

PSoC flexibility enables changes anytime: at concept, through


Download our “Change Happens” White Paper
production, in the field. Specifications change constantly. Yet and get 50% off a PSoC development kit:
pressures to differentiate, minimize costs, and speed time-to-market www.cypress.com/changepaper
remain the same. To stay ahead of the cur ve, you need flexibility, Download free PSoC Express™ visual embedded
programmability, and scalability. PSoC’s unique programmable software: www.cypress.com/changesoft
architecture delivers this and more. Futureproof your design; make Request free PSoC device samples:
PSoC your agent of change. www.cypress.com/changechip
Free online training:
PSoC delivers: www.cypress.com/changetrain
The configurability of an FPGA, the mixed-signal integration
Purchase PSoC development tools:
of an ASIC, and the familiarity of an MCU. www.cypress.com/changetools

Reusable IP, compatible device families and variable


resource options ensure you can optimize design efforts
and accommodate changes.

The industr y’s first visual embedded design tool, PSoC Express™,
speeds design time, enabling you to generate a complete
design without writing a single line of 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).

© 2007 Cypress Semiconductor Corporation. All rights reserved. PSoC is a registered trademark and PSoC Express is a trademark of Cypress Semiconductor Corporation. All other trademarks are properties of their respective owners.
Link Instruments
PC-Based Test Equipment

Digital Oscilloscopes
• 2 Channel Digital Oscilloscope

NEW!
• 500 MSa/s max single shot rate
• 1Mpt sample memory
250 MSa/S (Dual channel) 512 Kpts
500 MSa/S (Single channel) 1 Mpts
• Advanced Triggering
• Only 9 oz and 7” x 3.5” x 1.5”
• Portable and Battery powered
• USB 2.0
• Advanced Math
• FFT Spectrum Analyzer
• $950 (DSO, Probes, Software & power supply)

a/s
500M
S
1Mpts

Logic Analyzers
• 40 to 160 channels
• up to 500 MSa/s
• Variable Threshold
• 8 External Clocks
• 16 Level Triggering
• up to 512K samples/ch
• USB 2.0 and Parallel Interface
• Pattern Generator option
LA5240 (200MHz, 40CH) $1700
LA5280 (200MHz, 80CH) $2350
LA5540 (500MHz, 40CH) $2500
LA5580 (500MHz, 80CH) $3500
LA55160 (500MHz, 160CH) $7500

Link Instruments (973) 808-8990


17A Daniel Road East · Fairfield, NJ 07004 · Fax (973) 808-8786

www.Linkins4.com
For The Premium Application
that took years to develop and must be instantly read under
all lighting, temperature, and viewing angle conditions:

256 x 128 format


now available in
three sizes

Multiple Built-in Windows Multiple Interfaces


Many International Fonts Highest Brightness
Font Magnification Extended Temperature Range
Large Memory Widest Viewing Angles
High Density Pixels Choose From 11 Models

www.noritake-elec.com/52
Over 300 standard VFD modules available
TASK MANAGER
The Cruelest Month? FOUNDER/EDITORIAL DIRECTOR CHIEF FINANCIAL OFFICER
Steve Ciarcia Jeannette Ciarcia
E ven if you spent your college years working with circuit boards and
writing code, you’re probably familiar with the famous first sentence of
MANAGING EDITOR
C.J. Abate
MEDIA CONSULTANT
Dan Rodrigues
the poet T.S. Eliot’s modernist masterpiece, The Waste Land (1922): WEST COAST EDITOR CUSTOMER SERVICE
Tom Cantrell Debbie Lavoie
“April is the cruelest month—”
CONTRIBUTING EDITORS CONTROLLER
You may have heard a few exhausted bookkeepers and accountants Jeff Bachiochi Jeff Yanco
Ingo Cyliax
mumble that line a few times too. Tax season, right? Fred Eady ART DIRECTOR
Well, we here at Circuit Cellar have a different take on April. It’s a George Martin KC Prescott
great month. Not only are we now past the days of sleet, snow, and Ed Nisley GRAPHIC DESIGNER
dark commutes to and from the office, we have a lot of exciting things NEW PRODUCTS EDITOR Mary (Turek) Sobuta
on our plate—which is your plate too, of course. John Gorsky STAFF ENGINEER
PROJECT EDITORS John Gorsky
This month we’re off to the Embedded Systems Conference in San
Jose, where we plan to spend the entire week talking everything Steve Bedford
Ken Davidson
embedded with our readers and advertisers. Look for our booth. We David Tweed
hope to see you there!
ASSOCIATE EDITOR
The Microchip 16-Bit Embedded Control Design Contest also kicks Jesse Smolin
off this month. As you know, we’ve brought you a lot of amazing con-
tests over the years. This one is sure to create a lot of buzz in the design
ADVERTISING
community. With a handful of amazing eligible parts to choose from, this 860.875.2199 • Fax: 860.871.0411 • www.circuitcellar.com/advertise
contest is going to get competitive quick. Ready to hit the workbench? PUBLISHER
On the editorial front, we’re excited about the articles in this issue. Sean Donnelly
On page 12, we begin with an article about Steven Savage’s award-win- Direct: 860.872.3064, Cell: 860.930.4326, E-mail: sean@circuitcellar.com
ning ATir keyboard interface design. This project won him First Prize in ADVERTISING REPRESENTATIVE
the Atmel AVR Design Contest 2006. If you’re preparing a project for the Shannon Barraclough
Direct: 860.872.3064, E-mail: shannon@circuitcellar.com
new Microchip contest, be sure to check out this article. Steven shows
ADVERTISING COORDINATOR
what it takes to put together a winning project.
Valerie Luster
Another project-inspiring design is Tom Kibalo’s Java-based 1-Wire E-mail: val.luster@circuitcellar.com
distributed watering system (p. 20). Tom used his hardware and soft-
ware skills to build a handy system to water plants in six EarthBoxes. Cover photography by Chris Rakoczy—Rakoczy Photography
Even if gardening isn’t your thing, you can use the principles he covers www.rakoczyphoto.com
to design and program a multiple-module system for other purposes. PRINTED IN THE UNITED STATES
At the end of his article about the watering system, Tom writes that
CONTACTS
he plans to use ZigBee technology to extend the system’s range SUBSCRIPTIONS
Information: www.circuitcellar.com/subscribe, E-mail: subscribe@circuitcellar.com
beyond its 1-Wire limitations. Well, you don’t need to wait until Tom Subscribe: 800.269.6301, www.circuitcellar.com/subscribe, Circuit Cellar Subscriptions, P.O. Box 5650,
upgrades his system and writes another article. Why not take Fred Hanover, NH 03755-5650
Address Changes/Problems: E-mail: subscribe@circuitcellar.com
Eady’s advice and implement the technology in a system of your own? GENERAL INFORMATION
In “Uncomplicated RF Communication” (p. 45), Fred shows you how to 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
get your system on the air. New Products: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: newproducts@circuitcellar.com
AUTHORIZED REPRINTS INFORMATION
On page 28, Gordon Dick describes how he designed and built a three- 860.875.2199, E-mail: reprints@circuitcellar.com
axis CNC mill machine. The easy-to-move machine is a great project for AUTHORS
Authors’ e-mail addresses (when available) are included at the end of each article.
anyone who loves design and woodworking. It features an old laptop, an
intelligent motion controller, and an old X-ray machine.
CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) is published monthly by Circuit Cellar
Have you tried Visual Basic 2005 yet? As you know, Aubrey has been Incorporated, 4 Park Street, Vernon, CT 06066. Periodical rates paid at Vernon, CT and additional offices. One-year (12 issues)
subscription rate USA and possessions $23.95, Canada/Mexico $34.95, all other countries $49.95.Two-year (24 issues) sub-
putting it to use for some time now. This month, he finishes up his series scription rate USA and possessions $43.95, Canada/Mexico $59.95, all other countries $85. All subscription orders payable in
about a generic Modbus simulator (p. 60). To put you on the right track, 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
he explains how he created the generic interface to gain access to any 800.269.6301.

Modbus slave via an Excel workbook. As Aubrey explains, the application Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650.

simply pulls the information from Excel, presents it on the UI, formats it, 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-
and sends and receives Modbus messages. 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®.
With projects like these to keep you occupied, it’s going to be a pro- 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
ductive month. 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 © 2007 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 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


ILLUMINATED SOLUTIONS
IMPROVE PROJECT TIMELINES

Your production efficiency will shine with our brightly


illuminated solutions. NKK’s SmartSwitch™ allows
you to improve your processes by providing simple
solutions to complex procedures. Our series of
LCD programmable switches and displays
feature high-contrast and wide viewing
angles to simplify and accelerate
your project timelines.

IS Dev Kit-2

Power your designs with NKK.


Visit us online to:
Get Your FREE
3D CAD Model at: • ORDER Dev Kits to drive your creativity

• DOWNLOAD software to expedite your design process

http://cc.nkksmartswitch.com • PROTOTYPE and test new design ideas cost effectively


April 2007: Embedded Programming
FEATURES
12 ATir Keyboard Interface 38 Reverse-Engineered ECP Bus
Steven Savage Miguel Sanchez
First Prize Atmel AVR Design Contest 2006
45 Uncomplicated RF Communication
20 Java-Based EarthBox Watering System Fred Eady
Tom Kibalo
60 Generic Modbus Simulator (Part 2)
28 Build a Three-Axis CNC Mill Machine Create a Modbus Master Using Visual Basic 2005
Gordon Dick Aubrey Kagan

ATtiny45-Based Keyboard Electronic Watering System (p. 20) Computer-Controlled Mill


Interface (p. 12) Machine (p. 28)

COLUMNS
56 ABOVE THE GROUND PLANE
Battery Capacity
Charge USB Unplugged? (p. 78)
Ed Nisley

70 FROM THE BENCH


Local Interconnect Network
Jeff Bachiochi

78 SILICON UPDATE What’s on the LIN Bus? (p. 70)


USB: (Wire)Less is More
Tom Cantrell

DEPARTMENTS
4 TASK MANAGER 94 INDEX OF ADVERTISERS
The Cruelest Month? May Preview
C.J. Abate
96 PRIORITY INTERRUPT
8 NEW PRODUCT NEWS Only Real Events Lead to Real Trends
edited by John Gorsky Steve Ciarcia
93 CROSSWORD

6 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


Dream of Darkness,
Wasteman!

What can AVR picoPower • True 1.8V supply voltage enabling operation of all features and core down to 1.8V
do for your design? • Minimized leakage current enabling 100 nA Power Down sleep consumption
• Sleeping brown-out detector enabling full protection with no power penalty
• Ultra low power 32 kHz crystal oscillator enabling operation at only 650 nA
Edited by John Gorsky
NEW PRODUCT NEWS
RS08 C COMPILER
The C6808 Code Development System that supports Freescale
Semiconductor’s advanced 8-bit RS08 microcontroller architecture
is now shipping. The C6808 is one of the first C compilers for
RS08. It allows easy migration of programs written for Freescale
Semiconductor’s HC05 and HC08 to the high-volume 8-bit micro-
controller platform. The C6808 supports all HC08, HCS08, and
now RS08 parts in its optimizing C compiler and tools.
The C6808 Code Development System includes an optimizing C
cross-compiler with an inline macro-assembler, support libraries,
full program optimization with the BClink optimizing linker, and
the BCLIDE. The compiler produces industry-standard executables
and code files, including the Byte Craft Limited .COD file format
and ELF/DWARF. The .COD file and ELF/DWARF contain every-
thing an emulator needs for C-source-level debugging.
The C6808 supports ISO TR 18037 named address spaces and
fixed-point math. It implements the full C language within the tion than conventional asynchronous program-
limits of the hardware: Any potential application can be imple- ming.
mented in C with greater ease and optimization than in assembly. The C6808 costs $1,750.
Thread support in C complements the RS08 interrupt architecture
and threads can model hardware interrupt arbitration in software. Byte Craft Limited
They typically allow faster, smaller code and less RAM consump- www.bytecraft.com

MODULAR KICKSTART KIT TARGETS R8C, M16C, AND M32C VGA CONTROLLERS FOR EMBEDDED APPLICATIONS
The new IAR0018 KickStart kit contains all the necessary The ezVGA Graphics Controller and ezVGA Serial
tools for initial evaluation and prototyping on the Module are two new display controllers from Multilabs.
R8C/M16C/M32C microcontroller range, giving developers The ezVGA Graphics Controller is an embedded graph-
the opportunity to test 8-, 16-, and 32-bit microcontrollers ics controller
within the same core family. It also provides the flexibility to that can be
change the microcontroller during the course of the evalua- interfaced to
tion. Using the same fully featured tools, which will be used any design via
when real product development starts, makes it possible to an 8-bit data
avoid the delays and errors that can be caused by changing bus and four
tools and the development environment after the evaluation addressable
proof-of-concept milestone is reached. control lines.
The kit includes code-limited versions of the Embedded Through the
Workbench for the M16C, the M32C, and the R8C. An applica- ezVGA Graph-
tion baseboard fitted with a microcontroller from one of seven ics Controller,
available device families such as the R8C, the M16C, or the your embedded
M32C is also included. The board is fitted with three serial controller or
interfaces: two MAX232s and one TTL along with a USB-to- processor will easily generate color VGA graphics. It
serial interface, CAN with a transceiver, user LEDs, a 16 × 2 provides all the circuitry necessary for a host interface,
character LCD module with an LED backlight, an LDR and video memory control, and generating color VGA
potentiometer connected to the A/D-channel, an encoder graphics with high screen resolution.
switch with a push button, a MMC/SD card interface, and The ezVGA Serial Module takes it one step further.
other features. With the ezVGA Graphics Controller and an on-board
The kit also includes microcontroller, it scales high-resolution color VGA
a Renesas Technology graphics down to two serial communication lines and
E8-USB debugger, with a handful of graphics and text commands. This makes
all the necessary cables the ezVGA Serial Module a ready-to-use serial-con-
and documentation. It trolled VGA video card that will deliver VGA func-
works for all the rele- tionality to your design. The nine easy-to-learn com-
vant microcontrollers mands give any embedded controller or processor the
and can be driven from ability to draw high-resolution color, VGA text, and
within an IAR Embed- graphics.
ded Workbench. The The ezVGA starts at $24.95 and the ezVGA Serial
IAR0018 costs $495. Module is $64.95.

IAR Systems Multilabs


www.iar.com www.multilabs.net
8 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com
NEW PRODUCT NEWS
RTOS SUPPORT FOR THE ARM RealView DEVELOPMENT KIT
embOS, the popular, small footprint embOS provides the benefits of a tions. embOS also provides, at no
RTOS, now supports the ARM fully featured multitasking system additional costs, a viewer that allows
RealView Microcontroller Develop- by offering 100% identical API on all you to look into the system from the
ment Kit (MDK) feature-rich develop- of its 8-, 16-, and 32-bit CPUs. Its PC (including profiling).
ment environment. This development small memory footprint also makes Note that embOS, which is avail-
gives customers a complete solution. it suitable for single-chip applica- able in object and source code form,
embOS, which is well comes with a single
known as a small and developer license with
efficient real-time ker- no project limitations.
nel, has become one of embOS is royalty-free
the most popular kernels and comes with six
for ARM processor-based months of technical
microcontroller develop- support and free
ment over recent years. updates.
The RealView MDK, The object code for
which features the ARM the embOS-ARM7,
RealView compilation ARM9, and KEIL MDK
tools and the Keil μVi- is available for $3,100
sion 3 IDE, provides a and the source code is
complete development available for $6,225.
environment for users of
standard microcon- SEGGER Microcontroller
trollers based on the Systems, LLC
ARM7, ARM9, and the www.segger.com
ARM Cortex-M3 fami-
lies of processors.

10 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


NEW PRODUCT NEWS Visit www.circuitcellar.com/npn
for more New Product News.

CONTROLLER WITH EASY-TO-USE SEQUENCING SOFTWARE


The new techFX controller is based on the Microchip log inputs, up to two PWM outputs, and digital I/O.
Technology PIC18F4550 running at 48 MHz. It is feature The techFX controller board costs around $60 and
filled enough to be used as a stand-alone controller board includes the board, cables, and a CD containing the tech-
in most applications. Adding new functionality is as easy FX tools.
as connecting the new module and updating the configu-
ration and commands. New modules include PWM, The Silicon Horizon
expanded I/O with a relay board, audio record/playback, www.thesiliconhorizon.com
and motor-control functionality.
Programming options are geared at both the
veteran programmer and the customer who does
not want to write one line of code. You can easily
configure and create control sequences using the
Windows-based controller software, or you can
program the board using prewritten firmware
code that already contains the backbone func-
tions of USB, I2C, PWM, ADC, and many more
functions. Use state-of-the-art tools such as
Microchip’s MPLAB IDE and MCC18 C compiler
to quickly produce efficient code. Also, there are
other options such as PICBASIC, HI-TECH C,
and ASM. Then use the included bootloader to
easily transfer your firmware to the board.
The board features full-speed USB 2.0 commu-
nications and eight high-current outputs through
a Darlington array. Also available are 17 config-
urable I/O lines featuring up to eight 10-bit ana-

w
Ne g/
alo
Cat D!
C

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 11


FEATURE ARTICLE by Steven Savage

FIRST PRIZE
ATir Keyboard Interface
Steven’s well-designed ATtiny45-based ATir interface device is a convenient cross-platform
solution to interface an IR remote control to type keyboard macros to a PC. The system fea-
tures an infrared receiver/demodulator and a few discrete components.

A t an early age, my son took a


great interest in the “Thomas the
SYSTEM OVERVIEW a)
Small on pins does not necessarily
Tank Engine” series. A good deal of mean small on performance. Take the
his playtime was spent pushing those Atmel ATtiny series. These tiny
little wooden trains around the track. microcontrollers can do a lot more
Part of the experience was to watch than act as a programmable 555 timer
the videos, and as such, Dad often got or implement some simple logic func-
invited to watch as well. “Little tion. In this project, the microcon-
engines can do big things” is one of troller is used to decode and encode
Thomas’s favorite mottos. But what PS2 keyboard signals and perform data
about little microcontrollers, can compression and storage in real time.
they do big things? They sure can. It can also be used to decode signals b)
My Atmel ATtiny45-based ATir from an IR remote, with a few exter-
interface device can emulate the nal components to get the job done. If
function of a PC “AT” keyboard (see you’re more of a software person and
Photo 1 and Figure 1). With an IR less of a hardware designer, this may be
remote control, the compact system the project for you. I admit that Figure 1
(2″ × 2″ × 0.6″) connects in series is rather simple, but isn’t there a cer-
with an existing keyboard. If the tain elegance in simplicity? Another
portable device is already pro- advantage of this simple design is its
grammed, you can use the ATir with- ease to implement on a budget. Photo 1a—The ATir has an attached cord set salvaged
out a keyboard (see Figure 2). The human interface to most PCs from a combination keyboard-trackball device. The
remote control is an inexpensive surplus unit, but the
consists of a keyboard and a
ATir is designed to work with other remote controls as
mouse. While this is con- well. b—Here is what it looks like inside. Not much to it,
venient for many tasks con- is there? The ATtiny45 is on the left, the IR receiver is
ducted with a PC, some on the right, and there are a couple passive compo-
nents to glue it together. Even with the through-hole
applications warrant remote
construction, there is no problem getting things to fit.
operation. For example,
when conducting a
Microsoft Power Point slide trial systems use PCs running a cus-
presentation, it is nice to be tom software application that may
able to advance the slides only require a small set of keyboard
without having to operate commands to operate, while most of
the keyboard. For PCs dedi- the time the keyboard remains unuti-
cated to running multimedia lized, collecting dust. Those are just
applications in a home the- some of the applications that could
ater environment, it is easier benefit from the use of the ATir key-
Figure 1—As you can see, most of the passive components are for
to press the Play button on a board interface.
the Sharp IR receiver. Power comes from the PS2 port on the PC. No
crystals or external clock components here. It uses the internal, cali- remote control than to oper- Using a keyboard, the ATir is pro-
brated RC oscillator with good results. ate a keyboard. Some indus- grammed to respond to a key press on

12 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


ment a bidirectional synchro- series from 36 to 40 kHz. With no sig-
Optional nous serial bus. The bidirec- nal, the device outputs a high value
tional nature of the bus allows and it will drive the input low with
Keyboard ATir PC
the PC to send select messages the presence of a modulated IR signal.
to the keyboard such as, For the remote control, a logical 1 is
retransmit the last byte, or represented by a short pulse of approx-
Remote turn on the Caps Lock LED, as imately 540 µs. A logical 0 is repre-
control well as the normal traffic from sented by a long pulse of 1,640 µs,
the keyboard to the PC. with a 570-µs delay between pulses.
Key press information is Most of the discrete components used
Figure 2—The ATir connects a PC and a PS2-style keyboard. After
the ATir is programmed, the keyboard can be removed, if desired. transmitted in the form of a in this project comprise the low-pass
With no keyboard attached, the ATir takes care of initialization during scan code. For example, the A filter recommended in the Sharp
the PC boot sequence. It is operated by an IR remote control. key sends a code of 0x1C when GP1UM27XK datasheet.
pressed and 0xF0 0x1C when The ATir was designed to support a
a remote control and output a block of released. The key press and key variety of remote controls by reading
keyboard data. For example, the ATir release are coded separately to allow remote control commands at run time
could be programmed to work with multiple keys to be pressed simultane- and not relying on particular com-
Power Point by entering Program ously (such as when using the Shift mands from a particular remote. The
mode, selecting a button on the key to type a capital letter). The for- remote used was a surplus unit from
remote control (say your remote has a mat for a scan code is an 11-bit frame, All Electronics (a TEAC model
“Play” button), pressing the F5 key, consisting of a start bit, 8-bit code, odd RC505), but other remote controls
and saving the keyboard macro by parity bit, and stop bit. The frame-tim- could also be made to work. Although
pressing the same button on the ing diagram for keyboard to PC (host) the 16-bit address field is decoded by
remote. Now, with Power Point start- communication is shown in Figure 3a. the ATir, it is ignored so other remotes
ed, when you press the Play button on PC-to-keyboard communications is with different ID values can be used
the remote, ATir sends the codes for initiated by the PC by placing the bus with no modification to the code. A
the press and release of the F5 key and in a “request to send condition,” universal remote control can be con-
the Power Point presentation starts. which signals the keyboard to clock in figured to work with the ATir, as well
To go to the first slide in the presenta- the command. This communication is as extra remote controls that you may
tion, the keyboard shortcut 1 + Enter shown in Figure 3b. have that are not being used (that
can be used. This keyboard macro modulate at the same frequency and
could also be linked with another IR REMOTE OPERATION use a common 32-bit frame format).
remote control push button. The infrared remote used for this
Key sequences of up to 64 keys can project transmits a 32-bit packet con- ATir HARDWARE
be stored in an individual macro. sisting of a 16-bit address field, an 8-bit The ATir is used to interface an
These macros are stored in the EEP- command field, and an 8-bit command infrared remote control to a PS2 key-
ROM section of the microcontroller, complemented field for error detection. board port, where a key on the remote
so the data is retained after power is The IR signal is modulated by the IR corresponds to a programmable key-
removed. After macros are defined, the remote at approximately 38 kHz. Other board macro. The device has male and
ATir can be connected to a PC without modulation frequency receivers are female mini-DIN connectors that are
a keyboard and it will perform the nec- available in the Sharp GP1UM27XK intended to be connected inline with a
essary handshaking during PS2 keyboard, but using a
boot up to enable operation. A a) keyboard is optional. I was
keyboard can also be connect- Idle able to harvest a cable from a
ed to the ATir after the sys- Clock Keyboard broken keyboard/trackball
tem boots and the ATir will Idle Host
combination keyboard and
relay information between Data Start 0 1 2 3 4 5 6 7 P Stop change one of the six-pin
the keyboard and PC. male mini-DIN connectors to
b)
a female connector. When a
KEYBOARD Idle keyboard is attached to the
The AT keyboard is config- Clock
Keyboard
device, the device relays scan
ured with a five-pin DIN con- Idle codes and command informa-
nector or a six-pin mini-DIN Data 0 1 2 3 4 5 6 7 P ACK Host tion to and from the PC and
(commonly referred to as PS2) the attached keyboard. If a
connector. The interface Figure 3a—As you may expect, the majority of communication is from the key- keyboard is not connected,
board to the PC. The keyboard generates the clock signal and data is sent in an
comprises four wires (i.e., 5 V the device will perform the
11-bit frame. b—Yes, the PC can actually send data to the keyboard (such as
ground, clock, and data). The turning on the Caps Lock LED). The keyboard generates the clock signal regard- required handshaking with
clock and data lines imple- less of the direction of dataflow. the PC simulating the

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 13


response of a keyboard. Without this mand that is linked to a valid key- the adapter transmitted its response.
capability, the PC BIOS would deter- board macro is received and sent to Even engineers grow weary of con-
mine that a keyboard is not connected the PC. Indicator connection is possi- stantly flickering LEDs at some point.
and either present with a keyboard ble because the ATir always generates The system doesn’t have too much
error message and halt or turn off the the clock signal, and the ATtiny45 has hardware, so it’s fairly easy to build.
port to save power (with the response no trouble driving LEDs directly from The internal, calibrated eight-MHz
being dependent upon how the BIOS is an I/O pin. clock was used as a clock source for
configured). Ultimately, I did not include the the ATir. This source proved to be sur-
The device hardware, as assembled, LED because of a peculiarity in the prisingly accurate, as the timing
includes an IR-13 case from All Elec- PS2-to-USB adapter, which I purchased requirements for the AT keyboard data
tronics, an ATtiny45 microcontroller, to extend the functionality of the ATir communication and IR pulse length
a Sharp infrared receiver/demodulator to PCs, with no PS2 keyboard/mouse timing require a consistent and accu-
and a few discreet components con- ports. It turns out that the adapter rate system clock.
sisting of low- pass filter components periodically sends an invalid AT scan Most of the digital resources of the
and pull-up resistors. Originally, the code that the keyboard responds to per ATtiny45 are used in this project.
intention was to have a circuit board the AT keyboard protocol. Maybe this Timer0 is used to time the pulses
manufactured, but in the end, the cir- is done to detect if the keyboard has from the IR receiver. Timer1 is used to
cuit was constructed on a 0.1″ center- been removed, and I don’t know if all implement a timeout condition during
perforated board. The ATtiny45 micro- the adapters operate in this manner. transmit and receive to ensure that
controller IC1 is an eight-pin device The result of this periodic handshake synchronous communications remain
that contains 4 KB of flash memory, (about every second or so) would cause synchronized. The EEPROM section is
256 bytes of SRAM, and 256 bytes of the LED to constantly flicker while used to store IR commands and the
EEPROM. The microcontroller also
contains two 8-bit timer/counters, a
universal serial interface, and a 10-bit Listing 1—How can a keyboard create a user interface? Just “type” it out. This algorithm takes an ASCII char-
successive approximation ADC. For acter input and converts it into an appropriate key down, key release, and shift key press (if necessary) scan
code stream. Anyone for a speed-typing contest?
this project, I used the ATtiny45
because the ATtiny85 was not yet //This function “types” the character argument via output of
available. The ATtiny85 has twice as //keypress scancodes
much memory (flash memory, SRAM, void kbd_putchar(char ch){
and EEPROM) in the same pin-com- uint8_t index;
uint8_t keyCode;
patible package, allowing for twice as bool shift = false;
much keyboard macro data to be switch (ch){
saved, as well as an enhanced user case (‘\n’):
interface. This will be discussed more keyPress(KEY_ENTER);
break;
in the software section. case (‘\t’):
The keyboard clock line is connect- keyPress(KEY_TAB);
ed to the external interrupt pin and break;
the interrupt is configured for falling- default:
edge detection. The output of the IR index=ch-32; //subtract 32 from ascii value to obtain index
detector IC2 is sensed using the pin- if (index>63){ //lower case letters and supported symbols
change interrupt with a mask config- //greater than 63
ured to sense only the IR detector out- index-=32; // are equiv to value - 32 but with shift inverted
shift = true; //after xor, shift is inverted
put. To save space and components, }
the internal pull-up feature is used keyCode=pgm_read_byte(codeTable + index);
instead of the external pull-up resis- if bit_test(keyCode,7){
tors for the required PC clock and data shift^=true; //set shift or invert if already 1
bit_clear(keyCode,7);
lines. A high-resistance pull-up R5 is }
used on the keyboard clock line to if (shift){ //this section presses the shift key for every character
allow operation with a keyboard dis- keyDown(KEY_SHIFT);
connected while being able to sense keyPress(keyCode);
keyRelease(KEY_SHIFT);
and operate a keyboard when connect- }
ed. Resistors R4 and LED1 were used else
during development. They give a visu- keyPress(keyCode); //non shift keypress
al indication whenever the ATir is
break;
transmitting data to the PC. This }//end switch
occurs when a key is pressed on an }
attached keyboard or when an IR com-

14 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


associated macro data. Program mem- Listing 2—This algorithm reads the stream of scan codes and extracts the essentials. The ATtiny45 has a 256-byte
ory utilization is a few bytes short of EEPROM to store all macro data. Conservation is “key.”
the ATtiny45’s 4-KB capacity. All of
the I/O pins are used. The RESET pin void encode(uint8_t scancode){
static bool ext = false; //extended key flag
has the capability of being reconfig-
static bool rel = false; //key release flag
ured as a general-purpose I/O, but this static bool lwc = false; //last (input) was a code byte (not ext or rel)
feature was not implemented because
reprogramming the chip would then static uint8_t lastcode = 0;
require a high-voltage programmer switch (scancode){
case 0xE0:
versus the inexpensive parallel port if (lastcode && !ext){
programmer that was used. addKeyDown(lastcode);
The microcontroller source code lastcode = 0;
was developed in C using AVR GCC }
ext = true;
in the AVR Studio 4 development
lwc = false;
environment. Working on a budget, I break;
thoroughly enjoyed working with the case 0xF0:
free AVR GCC compiler that integrates rel = true;
nicely with AVR Studio. Initially, code lwc = false;
break;
was written and tested using the built- default:
in simulation tools in AVR Studio for a if (scancode==lastcode){
40-pin ATmega32 as the target. if(rel){ //if release, its a keypress
Next, the application was pro- rel=false;
if(ext){
grammed into the ATmega32 for in-
ext = false;
circuit debugging. This allowed for addKeyPressExt(lastcode);
easy programming and debugging by }
using a JTAG ICE and a built-in else{
addKeyPress(lastcode);
UART to send scan code information
}
to and from the device to a PC run- lastcode = 0;
ning a terminal program. The }
ATmega32 also had plenty of spare I/O else{
lines to run an LCD and output signals if(ext && lwc){
addKeyDownExt(lastcode);
to capture events on an oscilloscope.
ext = false;
After the application was running }
on the ATmega32, some minor archi- }
tectural changes allowed the applica- }
else{//scancode != lastcode
tion to be ported on the ATtiny45
if(lastcode){ //a key was pressed pending
using the same compiler and develop- if(rel){
ment environment. Another debug- rel=false;
ging option is debugWIRE, the one- f(ext){
wire-debugging feature of the ext = false;
addKeyDownExt(lastcode);
ATtiny45, but this requires a JTAGICE addKeyReleaseExt(scancode);
mkII, which didn’t fit into the budget. }
The original plan was to port the else{
application to the ATtiny85, which is addKeyDown(lastcode);
addKeyRelease(scancode);
physically the same chip with double
}
the memory (flash memory, SRAM, and lastcode=0;
EEPROM) of the ATtiny45. Unfortu- }
nately, this chip was not available dur- else{
ing development, requiring a lot of cut- if(ext){
addKeyDownExt(lastcode);
ting (and almost hammering) to get the
application to fit. With an ATtiny85, if(lwc)
the user interface and programming ext = false;
functionality can be improved signifi- }
else{
cantly. I have a few suggestions.
addKeyDown(lastcode);
Function argument validation can be }
added. When entering Programming lastcode=scancode;
mode, show a listing of macros that } (Continued)
have already been programmed. Indi-

16 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


Fully Contained MCU Development System Buy Online
Not only did Silicon Labs introduce the worlds’ first USB ToolStick evaluation www.silabs.com

platform, we continued the evolution with a family of interchangeable


ToolStick modules including base adapters, daughtercards and debug
adapters. Now, software and hardware MCU development is easier than
ever. Using only a PC with a USB port, designers can fully experience the
software development environment in conjunction with the MCU on-chip
debugging hardware that allows full, non-intrusive access to the target CPU,
peripherals and memory. The software development environment consists of
the Integrated Development Environment (IDE), editor, debugger, Flash Complete Evaluation

programmer and a demonstration version of the Keil compiler. System for $10.99

Description Price • Development Tools


ToolStick Starter Kit (includes C8051F330 Daughter Card) $24.99 • Source Code Examples
ToolStick Evaluation Kit $10.99
ToolStick Base Adapter $17.50 • Documentation
ToolStick C8051F330 Daughter Card $9.90 • 2K Limited C Compiler
ToolStick C8051F360 Daughter Card $9.90
ToolStick C8051F530 Daughter Card $9.90
ToolStick Debug Adapter $8.90

Product details: www.silabs.com/ToolStick

MCUs TIMING POWER BROADCAST WIRELINE WIRELESS www.silabs.com


cate the currently used and available Listing 2—Continued
space remaining for programming
macro data. Allow the last macro pro- }
grammed to be deleted (easy), or any else{ //key not pressed pending
if(rel){
macro programmed (more difficult). rel = false;
So, how do you make a user interface if(ext){
with a device that emulates a keyboard? ext = false;
Simply start your favorite text editor and addKeyReleaseExt(scancode);
}
let the keyboard type the interface text. else{
To simplify this process, the ATir addKeyRelease(scancode);
implements a putchar and puts func- }
tion that includes all letters, numbers, lastcode=0;
and many of the special characters found }
on the keyboard (ASCII codes 32–125) else{
using a 64-byte look-up table. Keyboard
scan codes don’t follow a logical encod- lastcode=scancode;
}
ing scheme that could be derived numer- }
ically; therefore, characters are translat- }
ed into scan codes via the look-up table. lwc=true;
Both uppercase and lowercase characters }//end switch
can be sent, because the algorithm }
inserts the Shift key into the scan code
stream when a capital letter or a special
character like those printed on the num- sequence is represented by storing 1 byte ist, text should be scrolling onto the
ber keys (e.g., !@#$%^) is required. in EEPROM. In addition, if a character screen prompting you to press a but-
The scan codes for keys associated key is held down in an application ton on the remote. If the key sequence
with printable characters can be (such as a word processor), the charac- above is reentered at this stage, the
expressed with 7 bits. The eighth bit ter repeats until it is released. This is EEPROM is cleared.
is encoded in the look-up table value because the keyboard resends the key To program a macro, point your
to indicate if the Shift key should be down scan code at a configurable peri- compatible remote control at ATir and
pressed to output the character. odic rate, which is referred to as the press a button. If decoded successfully,
ASCII codes below 33 are not print- typematic rate. This typematic data is the command byte is displayed and
able, so no table entries are necessary filtered and therefore does not con- you are prompted to enter a macro and
for them. For ASCII codes above 96, tribute to storage requirements. List- press the same button to record. Type
the table is offset by 32 and the shift ing 2 is the compression algorithm. in your macro. When you’re finished,
bit state is inverted. By using this press the same button on the remote
scheme, the lowercase characters OPERATION control to confirm the macro and record
beginning at ASCII code 97 do not To program keyboard macros using it. If a macro does not exist for the com-
have to be encoded into the look-up the ATir, simply plug the male con- mand selected, a prompt will indicate
table. The table was created in nector into the PS2 keyboard port of that the macro was recorded successful-
Microsoft Excel, which assisted in the PC, plug your keyboard into the ly. When you press the Remote Control
converting numbering systems and female connector of the ATir, and boot button, the keyboard macro sequence is
calculating for the shift bit and for- your computer. Open your favorite sent to the PC. Reenter Program mode
matting the data in columns that text editor. For Windows operating to set up additional macros for other
could then be copied and pasted direct- systems, Notepad is sufficient. To keys on the remote. Listing 3 is a pro-
ly into the header file (see Listing 1). enter Programming mode, a key gramming session.
The application places some real- sequence is entered on the keyboard.
time signal processing demands on the To prevent the ATir from going into NICE SOLUTION
microcontroller. Reception of data Program mode during normal typing The ATir keyboard interface offers a
from the keyboard must be processed tasks, I chose a keyboard sequence convenient cross-platform solution to
and retransmitted to the PC. Keyboard that is somewhat abstract. Type the interface an IR remote control to type
data is processed by a filtering and following sequence: hold down the keyboard macros to a PC. The inter-
compression algorithm when record- right Shift key, press and release the face plugs into a PS2 keyboard port on
ing macros to conserve EEPROM left Shift key, and then release the the PC and accepts commands from an
memory. A key press and release right Shift key. Hopefully, you have infrared remote. The device can be con-
sequence causes the keyboard to trans- never used that sequence before with figured to operate with common remote
mit three or five scan code frames normal computing tasks. Now, as if by controls with little or no change in
comprising 11 bits per frame. This some extremely fast magic speed typ- code. For those of you with laptops or

18 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


Listing 3—This is an example of a programming session creating a “Hello World” macro. The ATir “types” the first
line after entering Programming mode. I press a button on the remote that is decoded as “EF.” The ATir prompts me
to type in a macro. I type “Hello World” <Enter> and then press the same button on the remote. The ATir responds
“OK.” I press the Programmed button on the remote twice and “Hello World” is printed on the screen twice.

Press button on remote to program

Command = EF
Type in macro now
Press the same button on remote to accept
Hello World

Command = EF
IR command match
Macro write OK
Hello World
Hello World

new computers without PS2 ports, do University of Akron, especially Dr.


not despair. USB-to-PS2 adapters are Grover). Steven works for Daimler
inexpensive and allow the ATir to be Chrysler as a welder repair technician.
used within USB environments. He is also working on a technology
Another option would be to bypass startup business called Vigilant Tech-
the adapter and design the ATir with a nology. He enjoys playing trains with
USB connection. Directly implement- his son, archery, working with the
ing a USB interface is not trivial. Atmel media team at his church, and adding
has a family of microcontrollers with blinking LEDs to fishing lures. You can
hardware support of the USB protocol reach him at stevensavage@nls.net.
that would be more appropriate for that
kind of project (compared to the
ATtiny45 used in this project). Of PROJECT FILES
course, if you want to connect your To download code, go to ftp://ftp.
USB device to an older PC with only circuitcellar.com/pub/Circuit_Cellar
PS2 ports, you’ll need an adapter. The /2007/201.
ATir worked well with the USB adapter,
which is nice for Power Point presenta-
tions from your laptop on the road. The RESOURCES
adapters are readily available on the
Atmel Corp., “ATtiny datasheet,
’Net for less than $10, including ship-
2586-AVR,” 2586J-AVR, 2006,
ping. Just don’t forget to program it
www.atmel.com/dyn/resources/prod_
before you leave, unless you have time
documents/doc2586.pdf.
and access to a PS2 keyboard.
Other remote controls for PCs are C. Peacock, “Beyond Logic: Interfacing
available, but the ones I have seen the AT Keyboard,” 2005, www.beyond
require using the supplied remote and logic.org/keyboard/keybrd.htm.
installing drivers. With the ATir, you
Sharp Corp., “Sharp GP1UM27XK series
can recycle that old working remote
datasheet,” ED-01052A GP1Um27XK
control, even after the device it con-
series, 2001, http:// rocky.digikey.com/
trolled has passed away. The system
WebLib/Sharp/Web%20Data/GP1UM
will work with any PC operating sys-
27XK_Series.pdf.
tem that recognizes a keyboard. As
constructed, it costs about $10. I
SOURCES
Steven Savage holds a Computer Engi-
ATtiny45 Microcontroller
neering degree from the University of
Atmel Corp.
Akron. He is currently pursuing a
www.atmel.com
Master’s degree in Electrical Engineer-
ing (special thanks to the faculty and GP1UM27XK IR Remote receiver unit
staff in the department of Electrical Sharp Corp.
and Computer Engineering at the www.sharpusa.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 19


FEATURES by Tom Kibalo

Java-Based EarthBox Watering System


Tom was tired of watering his plants by hand, so he built a Java-based 1-Wire distributed
watering system. The expandable system can water six EarthBoxes.

S ome time ago, I became interested


in EarthBoxes. “EarthBox” is the trade
matures and bears vegetables, water-
ing is extremely important. Water lev-
name for a commercially available gar- els must be maintained (at least daily) Staking system
dening box. The boxes have been to yield a reasonably sized fruit. The Water tube
Fertilizer band
growing in popularity. They are ideal internal water reservoir, which is Mulch cover
for folks like me, who have limited close to the soil just above it, allows Potting mix
access to sunlight. (I live at the edge of the soil under the plant to access
Aeration screen
a forest.) They are also ideal for people water as needed. To facilitate the Water reservoir
Container
who want the conveniences of a pro- watering process, each EarthBox has a
ductive garden without having to watering tube that empties into the Seepage port

devote too much time and real estate internal reservoir. As the internal
(garden area) to one. reservoir fills to capacity, a seepage
The boxes are self-contained and hole in the side of the box releases Figure 1—A cut-away illustration of an EarthBox.
engineered with soil containers, an water to ensure that you do not over-
internal water reservoir, and fertilizer water the plant. This is good engineer- hole released water. I would then
reserves to yield hearty vegetable gar- ing. move on to the next box and repeat
dens from a modest scattering of 2″ When I started growing plants in the process. I eventually had six
seedlings. Newer EarthBox designs are EarthBoxes, I would slip a garden hose boxes. (I do like my fresh vegetables!)
equipped with casters for mobility and into the watering tube of each box, let Watering all six boxes every day can
an integral staking system (see Figure 1). it fill, and then note when the seepage be a chore. That’s why I developed an
In this article, I will automatic distributed water-
describe how I designed and ing system that sustains the
built a Java-based 1-Wire dis- reservoir levels with a pro-
tributed watering system for grammable watering cycle. I
an EarthBox. The compact also wanted to be able to
system is shown in Photo 1. monitor (on a per-box basis)
the amount of time the sys-
EARTHBOXES tem spends watering each
When I started using box. I thought the monitor
EarthBoxes, I was amazed at would give me a good indica-
the number of tomatoes and tion of whether the EarthBox-
eggplants harvested from es were functioning and the
just four plants (two plants plants were growing. The sys-
per box). To keep the plants tem needed to be distributed
healthy, the boxes require to allow me to judiciously
regular watering to sustain situate the boxes where they
their internal reservoir lev- could benefit from maximum
els, because the plants sun exposure and not “crowd
steadily soak up water. up” in any one area around
Photo 1—An LCD and a keypad are in the center. The Javelin Stamp is on the
Watering is pretty infrequent the house. I envisioned a
right. The RJ-45 connections are in the rear of the box. A dual-color LED flash-
to start with when the plant es to indicate the system’s overall status. Green indicates proper operation totally hands-off gardening
is small. However, as it (otherwise, it flashes red). system that would require lit-

20 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


tle more than planting, fertil- extensibility to larger plat-
izing, and harvesting. forms. Microcontrollers are
Luckily, the watering tech- available in all shapes and
nology exists; it is most sizes, but there are limitations
prevalent in lawn irrigation on what is easily available for
systems. Garden hoses are embedded Java. I chose the
inexpensive, and water distri- Parallax Javelin Stamp, which
bution is easily accomplished is a flash memory reprogram-
with lengths of a hose and mable SBC (about the size of a
garden hose manifold distri- postage stamp) with 32 KB of
bution fixtures. Watering RAM/program memory and
control can be accomplished support for a host of virtual
with inexpensive lawn water- peripherals: UART, timer,
ing solenoid-controlled ADC, DAC, ports, and buttons.
valves. The valves can con- The Javelin is programmable
nect to garden hoses with in a Java language subset using
PVC pipe and the proper hose Photo 2—The remote box supplies water to each EarthBox via black hoses. It the Parallax IDE. It has debug
fittings. To control these contains an internal waterproof box for the electronics, as well as a PVC mani- capabilities and Java library
valves and monitor water lev- fold and valves. The white water sensor wires are coupled to the hose and classes to easily deal with 1-
feed back to the remote box.
els, I used Maxim Integrated Wire and embedded Java appli-
Products’s 1-Wire technology. cations in general.
I had recently completed a larger proj- type, and terminations, total cable
ect using the technology and I was lengths of 300 m are possible. Such a SYSTEM OVERVIEW
impressed by its simplicity and relia- setup can accommodate more than Each EarthBox can be a maximum
bility. I knew that using 1-Wire would 100 1-Wire devices (that’s about 50 of about 100′ from the Javelin-based
allow me to uniquely address, moni- EarthBoxes in my setup). controller box, which contains the
tor, and control all of the valve con- The other key element was the Javelin controller, the 1-Wire inter-
trols and watering levels for each microcontroller. I wanted to use Java face, a 1-Wire distribution hub, system
remote box with a single location. I language. Again, I had just completed power, a time-of-day chip, a watchdog
also knew that 1-Wire technology a project with Java and I was timer, a solid-state relay for solenoid
would support several EarthBoxes. impressed with its object-oriented fea- power on/off, an LCD with a keypad
Given the right 1-Wire driver, cable tures, its reuse capability, and its for operator detail status/control, and
a dual-color LED for gen-
eral status indication (see
Figure 2). The entire
EarthBox EarthBox
assembly is housed in a
Remote 1-Wire
clear box (see Photo 1).
Time of day Watchdog Solenoid
water level The box is not water-
Battery monitoring Solenoid
clock timer valve and valve proof, but I keep it out-
value control doors, under my porch,
1-Wire
PVC Pipe Garden hose for easier connection to
LCD Javelin Remote watering box
Keypad Stamp interface the remote EarthBoxes.
EarthBox EarthBox The system also
includes remote watering
RJ-45 Distribution

Wall
transformer
Remote 1-Wire boxes (see Photo 2). Each
Green/red water level
status blinking Solenoid monitoring Solenoid remote box is connected
valve valve
Power strip

LED and Water


value control source
to the controller box for
12-VDC
Supply
Relay control/status reporting
PVC
PVCPipe
Pipe Garden hose Garden hose
Remote watering box
and power via a modified
RJ-45 cable connector
5-VDC Controller box
Supply EarthBox EarthBox scheme. The same type
of clear box that is used
AC in Remote 1-Wire for the controller is
Each run of water level
RJ-45 wire is
Solenoid monitoring Solenoid reused for the remote
Figure 2—Check out the entire water- approximately 100´ valve and valve
ing system. This diagram shows the value control box (see Photo 3). In the
controller box and the remote watering PVCPipe
PVC Pipe
larger remote box, a
Garden hose
boxes with associated EarthBoxes. Remote watering box small plastic waterproof
box is incorporated for

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 21


Photo 3—The placement of the remote and PVC manifold construction are
box’s major internal components is clear-
ly depicted. I opened the remote box’s also in the larger box. For each mani-
cover so you can see the location of the fold, a garden hose must be connected
remote electronics box, the hose, the for the water supply. I mounted a 0.5″
valves, the PVC manifold, and the feeder garden hose adapter to the water entry
connections. What do you think? You can
also see the sensor wires within the for each manifold.
remote box. The solenoid relay I chose was the
54048 0.75″ in-line valve from Lawn
Genie, which is available at most
hardware stores. To weigh down the
the 1-Wire valve control and remote box, I used crushed white rock
water-sensing electronics. (see Photo 3).
The solenoid irrigation valves The controller monitors the water
level in each EarthBox. With this data,
it also supervises the watering process
for each EarthBox through its solenoid
water valve. Each valve and water sen-
sor is uniquely addressed using 1-
Wire. The watering scheme can be
implemented automatically or manu-
ally; it is just a matter of software. I
used both automatic and manual
schemes. In Automatic mode, you can
set the frequency of the watering cycle
(from 1 h up to every 16 h) and the
maximum valve/watering on time
(from 1 min. to up to 20 min.). The
maximum on time is a preventive
measure to ensure that each valve
does not stay on too long to achieve
the desired water level (especially if
water is shut off or if it is not connect-
ed to the remote box). The controller
logs the accumulated watering times
for each EarthBox and notes if a maxi-
mum on time has been exceeded. If a
maximum on time has been exceeded,
the controller will bypass this valve
for the next watering cycle and period-
ically flash the dual-color LED (red).
Otherwise, if all conditions are satis-
fied, the LED will blink green. You
can also change the scheme to per-
form various other tasks because I
designed it to be inherently flexible
and expandable.

HARDWARE OVERVIEW
Power comes from a number of
sources: a wall transformer to the
Stamp, a 5-VDC power supply to all
remote box electronics, and finally a
12-VDC power source to the valves.
Individual returns for the 5 and 12 VDC
were required to ensure noise-free
operation. The 12 VDC is switched
using a Kytech Electronics KF0604D
KYOTTO solid-state relay. I realized

22 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


that 12 VDC should only be
applied once it has been decided to
switch the solenoid relay. Note
that 12 V at 0.5 mA is sufficient.
The wall transformer (9 VDC) is
used with a Stamp prototype board
and its internal regulator (National
Semiconductor’s LM2940) regulates
the 5-VDC required by the Stamp.
Because of the remote box’s 5 VDC
requirement (in comparison to what
the Stamp prototype board could
deliver), I used a separate 5-VDC sup-
ply. Both the 5 VDC and the 12 VDC
of power are distributed to the Earth-
Boxes via pair 2 and pairs 3 and 4 of
the RJ-45 connection respectively.
Two pairs are assigned to the 12 V
because of the larger current
requirement. In addition, all ground
returns are separated and connect-
ed to a “Mecca ground” in the con-
troller box to minimize noise. The
remaining RJ-45 pair is connected
to the 1-Wire electronics.
The Javelin Stamp reports on the
Figure 3—The Javelin Stamp is connected to all of the peripherals. The RJ-45 cables exit the box through the RJ-45 system with a blinking red/green
distribution to the associated remotes and their EarthBoxes. LED. More detailed status and con-

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 23


trol information is available via the Listing 1—Within the MAINTESTER class is a continuous-loop state machine. The code for one state within the
Matrix Orbital LK204-25 LCD and its loop is shown. Each individual valve and its associated water sensor represents a state. The system exits a state
associated keypad. To support this and goes to the next state once all of the conditions are satisfied relative to the valve operation and water level.
LCD/keypad interface, an RS-232 switch (state) {
interface to the Javelin Stamp’s virtual //start of automatic process
case 1:
peripheral UART is required. This address =switch1;
interface is accomplished with the use valve_on = valve_state1;
of a Sipex SP232ACP RS-232 driver //Test 1-if valve in error condition just bypass
if (valve1_error){ state++; break; }
chip. The controller maintains the water_ok =read_DS2406();
time of day, its watering cycles, and //Test 2-if water ok and valve is not on just move on to next state
the elapsed time using the Maxim if (water_ok && !valve_on){state++;break;}
//Test 3-if valve isn’t on and water is low, turn on valve start time
Integrated Products DS1302 TOD chip. //return to same stat
The chip is backed up with a 3.3-V if (!valve_on&& !water_ok) {
lithium cell battery. Again, the inter- on_valve(1);
captureStartime();
face is well supported. The Javelin t_run =0; //start timer
Stamp library can incorporate a //display valve on-stay in same state
DS1302 object for application reuse. d.valve_Status (1,valve1_ontime,true,valve1_error);
d.outTimetoDisplay(t.readTime(true)); break; }
Finally, I used Maxim Integrated //Test 4 -if valve is on and water is ok -turn off valve
Products’s 6301watchdog timer chip. // and display time or error
Watchdogs are an important part for if (valve_on && water_ok) {
off_valve(1);
ensuring reliability within embedded captureStoptime();
designs by providing an external (non- t_run= time_accum(0) ; //t_run =diference of stop-start\
software) reset to the controller on a valve1_ontime= time_accum(valve1_ontime) ;
if ( t_run> delta ) valve1_error =true;
periodic basis. If the controller is fully d.valve_Status (1,valve1_ontime,false,valve1_error);
functional and operating within its d.outTimetoDisplay(t.readTime(true));
code sequence, a provision is made t_run =0;
state++;
within each code segment to provide a break;
“reset” to this watchdog timer prior to }

24 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


The remote’s
electronics are
based on Maxim
Integrated Prod-
ucts’s 1-Wire
DS2405 and
DS2406 switches.
Both switches have
an open-drain PIO
pin that can be con-
trolled remotely.
The DS2406 also
has integral EEP-
ROM (not used in
this design). The
DS2405 is used
with the valves,
and the DS2406 is
for the water sense
level. I used the
DS2406 for water
Figure 4—The electronics are duplicated for each EarthBox, water control, and sensor. The entire box connects to a single 1-Wire interface. level sensing
The DS2405 1-Wire device is used for valve control, while the DS2406 1-Wire device is used for water sensing. A red LED is connected to because its com-
each valve control to indicate activity. A green LED is connected to each water sensor.
mand structure
allows for the direct
its own timeout (whereby it sends a ensuring the reliable operation of an reading of the PIO pin state. The
reset to the controller). Watchdogs are embedded controller. In this case, a 6-s DS2405 can be read only once the
generally recognized in the industry for watchdog timeout is used (see Figure 3). command to change it has been

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 25


issued. It is an oddity, but Main tester
with a green LED indi-
it is also much less expen- cates the water condition
Main() DS2408 Class
sive than the DS2406. So, Initializes and runs at the remote box.
state machine loop
in a roundabout way, you 1-Wire bus instance

need to command the init() reset() SOFTWARE OVERVIEW


on_valve(int) message()
DS2405 switch in order to off_valve(int) getBit() The system’s software
read_Ds2405(int)
access the PIO state and reset_AllDs2405()
is flash programmed into
DS1302 Class
then possibly command it reset_AIIDS2406() the Javelin Stamp (see
resetWatchDog()
again to change it to its captureStartime() t instance Listing 1). There are five
desired state. I used these Int Time_accum(int)
turnOffLed() write Time() distinct classes: Main
for the valve control. turnOnGreenLed() Read TD()
UART
Tester, Display Key,
turnOnGreenLed()
Figure 3 shows dual turnOnRedLed() txUART instance
DS2408 Class, DS1302
DisplayKey
DS2405 and DS2406 pairs longPause()
ledHandler()
Class, and UART. The
d instance sendSting(string)
for the remote box and processkey() sendByte(byte) first two classes are new
two EarthBoxes. The outTimeto Display(time)
UART for this design. The
outcycletoDisplay(cycle_time)
DS2405 has a 1-kΩ pull- outModeto Display(mode) remaining three are
outOntimetoDisplay(on_time) rxUART instance
up resistor to its PIO pin, read_key()
reused from available
byteAvailabe()
which drives a 2N222A get_key()
receiveByte() Javelin Stamp libraries.
for a red LED on indica- The DS2408 class is
tion for the valve as well Figure 5—The controller box’s Javelin Stamp used this software structure and these Java used in an instance called
as a control input to a classes. 1-WireBus. The support-
MOSFET used to control ing methods (reset(),
the solenoid for the valve. The wired internally to the EarthBox to message(), and getBit()) are all
DS2406 is used to read the input from indicate the proper water level in the that you need to deal with both the
the water sensor. This sensor is sim- EarthBox. When the water touches DS2406 and DS2405 once their indi-
ply an open base through 10 kΩ to 1 both leads, the transistor is saturated vidual addresses and command
MΩ to ground to a 2N222A transis- and the condition is read by the sequences are known (see Figure 4).
tor. Both the base and 5 VDC are DS2406. In addition, a PNP transistor Each device has a unique factory-set
64-bit address. The addresses can be
uncovered in one of two ways. One
option is to write a simple Java rou-

We Listen. Think. And Create. tine using the DS2408 class with your
DS2408 adapter to pool the address of
each part and display it so you can
incorporate it in the code. The other is
to use Maxim’s downloadable iButton-
Distributed Digital Serial Industrial HMI
I/O I/O I/O Computing TIMEX software utility. It has a nice
GUI for 1-Wire reading and control. It
works with Maxim’s DS2408 RS-232-
SeaLINK USB Serial Adapters Provide: to-1-Wire adapter.
SeaLINK USB serial
• 1, 2, 4, 8, and 16-Port Models The DS1302 class is used in an
adapters are the fastest, instance called tinstance. Its associ-
most reliable way to • RS-232, RS-422, and RS-485
ated methods are all you need to set
Serial Interfaces
connect peripherals to any and read the clock. The first custom
• Data Rates to 921.6K bps class, displayKey, is simply “d.” The
USB-equipped computer.
• State Machine Architecture to function of this class is to build up the
Reduce Host Processor Overhead display contents, update the mode of
• Operation as Standard COM Ports operation, time, and status and on
to the Host Computer times for each valve. This class also
• Lifetime Warranty reads the associated keypad for opera-
tor-requested changes.
Communication to the LCD and key-
F CUS pad is essentially via RS-232. Two
On Success instances of UART classes are used: one
for transmit and the other for receive.
The Main Tester class is for the main
routine for initialization and system
operation. The main tester has methods

26 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


for controlling individual DS2405s and ZigBee in this application to extend
SOURCES
DS2406s. It processes recovered key- the EarthBox’s range beyond its 1-
strokes from displayKey and takes Wire limitation. In the meantime, I EarthBox gardening system
appropriate action with display updates, hope to enjoy my vegetable bounty! I EarthBox
mode changes, and individual valve www.earthbox.com
Tom Kibalo (tkibalo@gmail.com)
control. The main tester also manages holds an M.S. in Electrical Engineer- KF0604D KYOTTO Solid-state relay
the watchdog timer and the controller ing. He has been a practicing engineer Kytech Electronics
box’s red/green LED indicator. In Auto- for over 33 years in the Washington, www.kyotto.com
matic mode, the main tester functions DC area. In addition to engineering,
in a continuous loop (see Figure 5). he’s an adjunct faculty member at a LK204-25 LCD
local community college, where he Matrix Orbital
LESSONS LEARNED teaches courses on microcontroller www. matrixorbital.com
I quickly made a prototype of the technology. Tom enjoys reading, bik-
system using the Javelin Stamp and its DS1302 TOD chip, DS2405 and DS2406
ing, gardening, and bonsai.
libraries and capabilities. This tech- switches, and DS2408 1-Wire chip
nology, as well as 1-Wire, was well PROJECT FILES Maxim Integrated Products
suited for the EarthBox application. www.maxim-ic.com
To download code, go to ftp://ftp.
The system worked well during the circuitcellar.com/pub/Circuit_Cellar/ LM2940 Regulator
growing season and alleviated the pain 2007/201. National Semiconductor Corp.
of having to water my boxes. In the
www.national.com
future, I plan to switch power to the RESOURCES
water sensor prior to water measure- Javelin Stamp module
Parallax, “Getting Started with 1-
ment. This will minimize any materi- Parallax, Inc.
Wire,” 2002, www.parallax.com/dl/
al buildup on the sensor probe due to www.parallax.com
appnt/jav1/appnote1a.pdf.
the 5 VDC. Another alternative is to
use an alternating source rather than ———, “Getting started with the SP232ACP Driver/receiver
DC for the water sensor. DS1302,” 2002, www.parallax.com/dl/ Sipex Corp.
Finally, I plan to explore the use of appnt/jav2/appnote2.pdf. www.sipex.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 27


FEATURE ARTICLE by Gordon Dick

Build a Three-Axis CNC Mill Machine


Gordon shows you how to design and build a computer-controlled wood mill machine. The
system includes an old medical X-ray machine, a Galil DMC-2133 three-axis intelligent
motion controller, and an old 386 laptop.

I built my first computer-controlled


XYZ router machine about 12 years
smaller machine.
At about the same time, during one
storage for several years while I pur-
sued a variety of other projects and
ago (“Designing an Industrial Grade of my frequent visits to a government before I got serious about building the
XYZ Router,” Circuit Cellar 62, 1995). surplus outlet, I found a medical X-ray second machine. Now, about a year
My intention at the time was to create machine that had two motion stages after starting, I have a finished system.
signage using wood or acrylic. As a that could be modified for use in my
result, the large machine had a 50″ × 50″ second appliance. One stage even had DESIGN CONCEPT
workspace. For various reasons, my a lead screw in it. I don’t remember When building for myself, my
attempt to get into the sign business the exact price of the unit at auction, designs are influenced strongly by the
failed, and I was left with a huge but it was less than $50. And I knew materials and parts that I have on
machine that took up nearly half of that it would save so much work hand. For this project, I had servo
my once-spacious shop. It was certainly when it came time to build my newer, motors (4″ D × 7″ L with a 0.625″
a valuable tool, but it was not mak- smaller machine. So, it was soon shaft) from some mainframe tape
ing me rich. So, I decided that I need- stripped down to only the parts that I drives. I also had linear servo ampli-
ed to sell it to make room for a much could use and put in storage. It sat in fiers for the motors (from the same

a) b)
Z-axis Z-axis

Y-axis

Laptop Joystick
and Tool Y-axis
buttons

X-axis

41˝ Electronics and


Tool 15˝
power supplies 30˝ 62˝
Storage

X-axis

54˝

Storage Storage
26˝

Figure 1a—Here is a side view of the design. The X-ray machine becomes the y-
and z-axes. b—This is the front view of the design. It is about 5′ tall and wide
enough so that it’s not “tippy.” 39˝

28 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


that evolved after a few iter-
ations is shown in Figure 1.
Some dimensions were
included to allow for a cor-
rect overall size impression.
I initially planned to make
the frame of the cabinet out
of thin wall-square tubing
and then cover the frame
with sheet metal. A few
things stopped me from doing
this. I didn’t have a MIG
welder to build a metal cabi-
net, and I didn’t want to con-
tract the job out. In addition,
I believed the metal version
would be more difficult and
expensive to change. So, the
cabinet was built out of
Figure 2—This is a simplified schematic of the tape drive servo amplifier. Without the original schematic and manuals, I probably 0.75″ birch plywood and
wouldn’t have used these amplifiers.
designed to be as mechani-
cally rigid as it is practical.
tape drives), a power supply with an tomer and the vendor, I could change
aluminum enclosure for the parts, two the specifications. The travel on what DESIGN & CONSTRUCTION
motion stages from a medical X-ray would become the z-axis is 9″, which With the conceptual design final-
machine, several 386 laptops, sprock- is just fine for this machine. Since the ized, I began the detailed design. Sev-
ets and a chain from another motion- X-ray machine provided only two eral areas needed to be addressed and
control machine, and casters from a axes, the x-axis had to be designed and it’s probably not appropriate for me to
printer or a mainframe. built from scratch. show you drawings of all the parts.
In addition to incorporating the It was also during this time that I Rather, let me list the areas that
aforementioned parts, I had other discovered that the motion stage for required detailed design. The z-axis
design criteria. The machine had to the y-axis would need more modifica- motion stage was not driven before, so
occupy as small a footprint in my tions than I first thought. Some cru- a lead screw, a bearing support struc-
shop as possible and it had to be mod- cial bearings and bearing tracks that ture for the lead screw and chain
ular enough that it could be moved to weren’t necessary on the X-ray drive, and a motor-mounting plate
another shop in the event I moved or machine had to be added. Without were required. A means of attaching a
sold it. In other words, the modules going into detail here, let me just say tool to the z-axis was also needed. The
had to be able to pass through a typi- that this added considerable time and y-axis motion stage needed a different
cal door. The workspace had to be effort to make the motion stage as lead screw and a motor-mounting
about 20″ × 20″. Incremental optical useful as the y-
encoders had to be attached to the axis. However,
motors. A joystick had to be part of the work on this
the control panel. The machine had to part proceeded
be on casters and also have screw feet. simultaneously
And lastly, the machine had to use a with the overall
Galil Motion Control DMC-2133 machine design.
intelligent motion controller. (I had So, when I got
used these before and was familiar tired of working
with them. More on this later.) with the CAD
With these criteria in mind, I set package on the
about designing my computer-con- conceptual and
trolled wood mill. First, I needed to detailed design, I
take some measurements of the X-ray went out to the
machine’s parts. I found at that point shop and worked
that the motion stage travel distance on the motion-
of what would eventually be the y-axis stage modifica-
was 18″. This was a little shorter than tions. The con- Photo 1—Operation of the machine would normally be done from this side. The podi-
I wanted, but since I was both the cus- ceptual design um is sized to put the laptop screen close to eye level.

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 29


Photo 2—Here’s a view from the opposite side. The come up however. When changing the
controlled AC outlet and the arm to support the moving
cable are shown. y-axis lead screw, I discovered a large
amount of backlash in the existing nut
assembly. The amount wasn’t meas-
plate. I had to build an x-axis motion ured, but I’m guessing now that it was
stage and the motors needed encoders close to 0.125″. With a minor redesign
mounted on them. of the nut-restraining mechanism, the
After many hours (days, weeks) in backlash was reduced to an acceptable
front of the computer building parts level. (Actual backlash measurements
on virtual paper, construction could will be given later.)
finally begin. And construction pro- Since the backlash has been men-
ceeded with no major difficulties to tioned here, I should also point out
completion. One minor issue did that toothed drive belts would have
less backlash than the chains I used.
Had I built this machine with all new
parts, toothed belts would’ve been my
choice. I knew that the intelligent
motion-control card was going to cost
me over $2,300, so I was trying to
keep other costs down wherever possi-
ble. This machine has no travel limit
switches or home switches. Those fea-
tures were included on my first
machine, but I found them to be of lit-
tle use. However, some provisions
have been made so they could be
installed later on this machine.

MOTION CONTROLLERS
The DMC-2133 motion controller
has nonvolatile memory that enables
it to store motion programs that can
be executed on power-up. So, no desk-
top computer is required, other than
for initial programming. Of course, if
the machine is to be used in applica-

Photo 3—When viewed from the front, you can see the
ample storage area. The x-axis is one of its travel limits.

30 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


tions where the motion program nately, you don’t have to learn all the
changes frequently, such as the wood commands, but a dozen or so need to
mill described here, it makes sense for be learned, and you need to be aware
a computer to be permanently of what is possible with the others.
attached to the controller. Since the Simple tool paths can be programmed
function of the computer used in con- manually, but complicated parts
junction with an intelligent motion require a different approach. (More on
controller is usually only for commu- this later.)
nication (i.e., transferring and execut-
ing motion programs), its capabilities MODIFICATIONS
need only be minimal. I used an old With construction complete, the
386 laptop that ran DOS, something last phase could begin: the wiring. Photo 4—I removed the worktable! The x-axis drive
most folks would have thrown out One area that always requires special motor is partly visible in the rectangular cutout.
long ago.
In addition to providing the “brains”
to perform the calculations necessary
to implement a digital control loop,
the intelligent motion controllers pro-
vide digital I/O. Digital outputs are
useful to control a cutting tool or a
dust collector. Digital inputs are help-
ful for providing signals to the con-
troller (e.g., starting a motion program
on a button press). Intelligent motion
controllers can also be supplied with
ADCs. This makes controlling a
machine with a joystick very easy to
implement. Galil’s family of con-
trollers is programmed using a lan-
guage specific to them, very similar to
assembler. This language is extensive
in terms of how the behavior of the
controller can be changed. The one I
used has a separate, rather thick com-
mand summary manual, containing
the syntax for 192 commands. Fortu-

Photo 5—This is the back of the machine. Digital panel


meters monitor the system DC voltages.

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 31


consideration is the cables in motion. hardware. A spring-loaded arm mount-
They must be allowed to move, but ed on a pivot plays out or takes up
they must move in such a way that cable as required.
the copper doesn’t fatigue and fail. I doubt I would’ve used the servo
And, of course, the cables must be amplifiers from the magnetic tape
protected from physical damage. The drive if I didn’t also have the schemat-
advantage of this design is that only ics. Reverse engineering a circuit
the z-axis cables are in motion. board to obtain a schematic is a
Commercial machines use a variety daunting task, and without a schemat-
of clever techniques. Most require spe- ic there’s no way to know how to con-
cial hardware to guide and protect the nect the amplifier. Because I had
cables. The method I chose to use is schematics, I was able to make several
effective and didn’t require buying any modifications to the servo amplifiers

Photo 6—With the front panel removed, the inside of


the electronics cabinet can be examined. Who would
guess that this aluminum box used to be the home of a
magnetic tape drive?

to better suit them to this application.


The original servo-amplifier
schematic is considerably “busier”
than what you see in Figure 2; howev-
er, this simplified version is better for
explanation. The original photocell
circuit that produced input to the
servo amplifiers from dancer-arm
motion must have introduced some
offset, because both the supply and the
take-up reel amplifiers had an offset
introduced via R3. I removed R3
because I didn’t want the offset here.
Switch S2 is a JFET, which is con-
trolled by some circuitry external to
the servo amp. When S2 is open, U1
has voltage-shunt feedback applied to
it via R5/R6 with the voltage on the
right-hand side of R6 determined by
the R7/R8 voltage divider. This makes
the servo amp a transvoltage amplifi-
er, and as the 2-kΩ part of R8 varies
through its range, the grain varies
from –9 to –17. When S2 is closed, the
voltage on the right-hand side of R6 is
determined by the voltage across the
current-sampling resistor, R9.
Although the R7/R8 divider is still
present, the voltage dominates it
across R9. Since the voltage driving
the R5/R6 resistor is derived from a
current, U1 now has current-shunt
feedback applied to it. The servo amp
is best described as a transconductance
amplifier with a gain of –8 A/V. I hard-

32 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


wired a jumper across S2 to make the The motion controller can be pro-
amplifier permanently transconductant. grammed to remove the drive to the
A relay, such as RLY1, is often used servo amps if a significant position
between a servo amp and the motor it error develops, which is extremely
drives. When the relay is deenergized, helpful when powering up a system
the NC contacts place a short across the for the first time. In addition, if the
motor terminals, providing very effective sense of the feedback loop is incorrect,
braking. When the motor is to be driv- there are commands to invert the
en, the relay is energized and the motor sense of the feedback from the
is connected to the amplifier. I like this encoders and invert the behavior of
kind of control to be activated by the motor. It is likely that no wiring
Photo 7—Check out what this machine can do. The
limit switches or, in my case, manual- changes will be necessary to correct a
metal ruler on the bottom is for a size reference (12″).
ly by a switch on the control panel. Finding vector-based fonts for letters and numbers was runaway situation.
The original servo-amp PCB had a problem in the past. Even when the sense of the feedback
some components that interconnected is correct, the control system may be
the AMP ENABLE and MOTOR control system for the first time must dynamically unstable. This was the
ENABLE circuits. I removed some be done carefully. There are many case with my machine. When a feed-
components and added R11 to separate places where signal inversions can be back system involving mechanical
their functions. The AMP ENABLE introduced when the wiring is being components oscillates, it often mani-
input is driven by a signal from the done, so there’s a good possibility that fests as a high-pitched “whine.” Other
Galil board. When the circuitry associ- the system will initially run away. If behaviors are possible, including the
ated with S1 is driven, a short is the motors used are large and can pro- classic large-amplitude sinusoidal
applied to the output of U1 through a duce significant motion-stage velocity, oscillation. So, when I heard the
1-kΩ limiting resistor. This disables machine damage is a distinct possibili- whine coming from my motors, I was-
the power stage. ty. Intelligent motion controllers have n’t happy. The connection of an oscil-
features that allow the initial power- loscope confirmed there were large
COMMISSIONING up to be done without any scary amplitude oscillations in the motor-
Powering up a closed-loop motion machine runaway. drive signal, which got worse at the

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 33


2900 Spafford Street, Davis, CA 95616 Tel 530.757.8400
start and end of a move. x-axis y-axis z-axis The intelligent motion controller
Initial machine power-up is usually Repeatability error 0 0 0 controls (through a solid-state relay)
done with the controller set for a low Accuracy 0.003″ 0.001″ –0.003″ the AC outlet in the middle of the
value of Kp and no Ki or Kd. (Kp is pro- Backlash 0.005″ 0.018″ 0.008″ cabinet. I have used a similar approach
portional gain. Ki is the integral gain. to control a shop vacuum for dust col-
Table 1—The machine’s performance is respectable. The
Kd is the derivative gain.) Reducing Kp y-axis backlash could be improved, but that would lection. The dust-collection approach on
didn’t have much of an effect on the require significant disassembly just to get at the source. this machine is still under development.
oscillations, which was strange. After Unless it becomes a problem, it will remain as is. To prevent the system from over-
some head scratching, I went back to heating, a rectangular hole was
the servo-amplifier schematic and Since the joystick produces only installed to the right of the outlet
found the problem I should’ve seen two analog signals, it can’t control the with the aluminum mesh to cool the
before. Resistor R1 has a capacitor z-axis using the same method. It may electronics cabinet behind it. There is
across it (see Figure 2). This drastically not be obvious in the photo, but the a similar ventilation hole on the oper-
increases the high-frequency gain of joystick has a push button on the top ator side. There are also two holes in
the servo amp, not usually desirable of it. Pressing the button makes the z- the bottom of the cabinet with screens
from a stability point of view. When axis move at a fixed velocity in a to allow air convection.
C1 was removed, the system was fair- direction established by a nearby tog- A blank for a part is attached to the
ly well behaved. At this point, I also gle switch. worktable using a collection of shop-
hardwired a jumper across R5 to The red button in the upper-left cor- made clamps (and blocks sometimes)
reduce servo-amp gain to –4 A/V, which ner of the control panel is the master fixed via 0.25″ cap screws and captive
further improved system behavior. Reset for the controller. It could also nuts on the back. The worktable can
With the changes to the servo function as an Emergency Stop button. be replaced should it get eroded by the
amplifier feedback network complete A toggle switch on the control panel is tool, but with care, that can be avoid-
on all three axes, the system was well the actual Emergency Stop. It controls ed. The area under the x-axis is stor-
behaved. I finally had a working a set of relays that are part of the age space for clamps and manuals. I
machine! servo amps that can disconnect the might add doors on the front to keep
motors. Also, there is a momentary out dust. Note that the top shelf under
FINISHED MACHINE toggle switch that is used as a Start the right-hand side of the x-axis is
The laptop sits on a podium to bring signal. I try not to let any motion pro- smaller than the others because the
the screen to eye level and to slant the gram execute directly from the key- drive motor hangs down under the
keyboard (see Photo 1). A small con- board. Having to push a Start button stage (see Photo 3).
trol panel containing the joystick and allows for one last check to make sure The design of the motion stage is
switches also sits on the podium. To all is well before a motion program conventional with one minor excep-
make the joystick operate the begins. The arm to deal with the mov- tion. Usually, you would find hard-
machine, I had to write a motion-con- ing cable pivots slightly to allow the ened steel rails with recirculating ball
trol program. This is an example of stage to move out. bearings. But those are rather expen-
why it is necessary to be familiar with Wooden covers enclose the chains sive, and I didn’t think they were nec-
some of the intelligent controller com- and sprockets on all three stages. In essary for this machine, because the
mands. When the joystick program addition to being a safety feature, the accuracy requirements for wood parts
runs, moving the joystick from side to covers also keep out dust. They pro- are more relaxed. So, the rails are ordi-
side controls the y-axis and moving it tect the sprockets during transporta- nary cold-rolled steel and the bearings
back and forth controls the x-axis. tion as well (see Photo 2). are bronze bushings with oiling wicks.
Short movements of the joystick move A riser box elevates the y- and z- The lead screw is a 0.625″ acme-type
the corresponding stage slowly, where- axes. There are several stiffeners thread rod sold in 3′ lengths and
as long joystick movements increase inside the box to make it resistant to selected for straightness. (It isn’t actual-
the speed of the stage. The joystick is racking and twisting. The box is not ly intended to be used as a lead screw.)
an expensive, well-built military sur- permanently attached to the lower The x-axis motion stage is surpris-
plus part. part of the cabinet. When the system ingly easy to move despite the lack of
Being able to move the machine was almost complete, I decided the y- recirculating ball bearings. Initial indi-
about the workspace using a joystick and z-axes weren’t quite high enough, cations are that the bushings seem to
is a significant feature. Previously, get- so I added an additional 2.25″ riser by be quite tolerant of small amounts of
ting the machine into the proper start- sandwiching three layers of 0.75″ ply- dust, although my intent is to keep as
ing position was tedious. All machine wood. (I did this to avoid making a much dust off them as possible. (More
motion was initiated from the key- new riser box.) Note that the z-axis on that later.) Elevating the worktable
board. And on the predecessor, the cables have been retracted by the piv- so it clears the sides of the cabinet
keyboard was several steps from the oting arm. The gray aluminum panel when nearing the travel limits is
machine. Just getting the tool into the under the outlet is where the main AC accomplished with the wood risers
starting position was time consuming. power for the machine is connected. attached to the motion stage. The

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 35


wood risers touch the bronze bushings encoder signals to it. was done as a demonstration of the
so there is some oil staining, which There is a servo amplifier assembly machine’s capability. When I was
might be visible (see Photo 4). mounted on each side of the cabinet, making these letters, I ruined a few
Just below the motion stage, near with the side of the cabinet becoming before I realized I had to leave “tabs”
the front, there is a slot cut in the cab- part of the servo-amp heatsink. There connecting the letter to the blank.
inet. This slot will accommodate the are actually two servo amps in each Otherwise, when the letter came free
installation of the x-axis limit and assembly, so one amplifier is unused. at the end of the cutting, it would
home switches. A finger will extend The solid-state relay for the controlled shift and be caught by the bit, always
from the motion stage through the outlet is on the left side of the cabinet causing fatal damage to the letter.
slot and the switches will mount on above the servo amp. There is a sec- Since I was using them as samples for
the underside of the slot. ond solid-state relay behind it for a mail out, they had to be flawless.
The machine’s cabinet is designed future use. The very top left-hand cor-
as two closed boxes. One is the riser ner is where an AC power distribution MOTION PROGRAM DEVELOPMENT
block; the other is the lower cabinet. terminal block is located. The lower Galil has produced a utility package
However, to install the electronics third of the cabinet is occupied by the that allows motion control programs
cabinet, there had to be a large hole in power supply. Since the power supply to be produced in a highly automated
the back of the lower box. In order to provides the logic power for a rather fashion. It’s called CADTODMC. This
retain as much strength as possible, expensive intelligent motion control utility allows the tool path from a
the electronics cabinet’s cover panel card, I am pleased that it has output drawing package to be converted to
also doubles as one side of the lower over-voltage protection. That’s a fairly Galil motion control commands with
box. To that end, there are five screws common, but necessary, feature here. a desktop computer. The drawing
(1.5″ long) on each side of the alu- I’m not particularly proud of the package needs to have the ability to
minum panel that extend through the wiring inside of the electronics cabi- produce a DXF version of the tool path.
plywood into a hardwood backing net, some of it would be called “point- The motion-program-development
plate to try to retain the integrity of to-point,” as opposed to being nicely steps are: create the drawing of the
the face of the lower box (see Photo 5). bundled into cables and clamped. At tool path using a suitable CAD pack-
Digital panel meters monitor the the time I thought no one would ever age, convert the tool path drawing to a
DC voltages produced by the power see it, so why fuss with it? I guess I DXF file, and use CADTODMC on
supply from the magnetic tape drive. was wrong. The cable on the bottom the DXF file to create the motion pro-
The machine is powered up from here. left in Photo 6 goes to the On/Off gram. This process appears simple and
The power supply produces 5 V for switch for cabinet power. The bundle eventually it is. But, initially, there is
powering the intelligent motion con- of cables above it goes to the digital a lot to learn, and while learning is
troller, ±12 V for the joystick and the panel meters. happening, mistakes are being made
intelligent motion controller, and ±20 V I produced a collection of items on that can be frustrating to correct.
for the servo amplifiers. This power the first machine. They include the
supply can also deliver ±40 V to the number “2” done in cedar (about PERFORMANCE MEASUREMENTS
servo amps under logic control, but at 0.625″ thick), a gray letter “M,” a tan How good is this machine? The
the moment I haven’t made use of cutting template from countertop measurements I’ll describe next are
that feature. Although I’m not expect- plastic laminate, the letter “A” in the first I’ve done on a machine that
ing a power supply failure, it’s com- smoked Plexiglas (0.125″ thick), a I’ve built. Earlier, there was no reason
forting to see the correct DC voltages business card holder with a 0.3125″ for measurements because the
displayed when the machine is pow- deep pocket, a plaque showing a curl- machines adequately did what I want-
ered up. The main machine’s On/Off ing rock, and a floppy disk holder with ed. Most parts didn’t require absolute
switch is in the lower-right corner of 0.25″ deep slots (see Photo 7). The accuracy; however, good repeatability
the aluminum front panel. floppy disk holder is done in walnut, was often important when making
There is still a lot of empty space in which is dark, so the slots are not multiples of the same part. For exam-
the electronics cabinet. Had there clearly visible. The second machine is ple, I have stacked up multiples many
been a shortage of space, I would’ve still so new that I haven’t made any- times and I have been pleased at the
repackaged the power supply and thing of note yet. excellent repeatability. Before present-
servo amps. But in order to get the The optimum depth of cut for the ing a summary of the performance
worktable at a suitable height, the router was 0.125″. Any time more specs, let me explain how the data
cabinet had to be large, which meant depth was required it was done in was obtained. All measurements were
the electronics cabinet from the mag- multiple passes. This machine has made using a dial indicator capable of
netic tape drive could be used “as is.” superb repeatability, so that wasn’t a measuring just over 1″ of total travel,
This saved me a significant amount of problem. The feed rate I use most of having a scale calibrated in 0.001″ and
work (see Photo 6). The intelligent the time is 0.5″ per second. which can be interpolated sensibly to
motion controller is mounted on the In the letter “A,” a piece is inserted distinguish units of 0.0005″.
back of the cabinet and cables bring where there is normally a cutout. This You should also appreciate that per-

36 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


formance is largely dictated by the would be appropriate for this machine. tion sensors per axis. One is usually
mechanical system and not the digital I have years of experience building on the motor shaft and it is usually an
control system. This machine uses things out of metal and wood. So, gen- optical encoder. The other is on the
optical encoders with 128 pulses per erally my intuition about what will be motion stage and it is usually a trans-
revolution. The Galil board introduces strong is pretty good. However, when I lational transducer. The controller
a revolution improvement by a factor chose 0.75″ cold-rolled metal for the then uses the rotary optical encoder
of four. When the lead-screw pitch and rails of the x-axis, that wasn’t strong for “rough” positioning and the trans-
chain drive ratio are taken into enough. It probably isn’t important in lation transducer for “final” position-
account, this translates into 5,120 this application, but the x-axis stage ing. Since the final position is deter-
quadrature counts (QC) per inch or has more “give” for vertical loads than mined by the actual position of the
195 µinches/QC of basic system reso- I would like. Certainly, I would use motion stage, the error due to back-
lution. Unless some Ki is used, there heavier rails in another version. lash is eliminated.
will be some steady-state positioning At the moment there is no means of These translational transducers tend
that’s error-dependent on forward gain. dust collection. That’s rather important to be expensive. But I was recently given
In this case ±2 QC, or an error of 390 for a machine like this because the three resolvers taken from an old NC
µinches, which is slightly less than my dust produced is very fine, and there is mill that was being scrapped. With a lit-
measurement capability of 0.0005″. lots of it. Previously, I used a shop vac- tle work and some cables and pulleys,
To measure repeatability, moves to uum with its hose attached to a shroud they can be made into translational
the same location were repeated and around the base of the router. This units. Here’s the best part: the DMC-
the dial indicator reading was noted. machine doesn’t use the base of the 2133 was designed to implement dual-
Different dial indictor readings indi- router, so something different needs to loop control. I plan to modify this
cated a lack of repeatability. It came as be done. My first attempt at collecting machine for dual-loop control, but I
no surprise to me when I wasn’t able dust on this machine was unsuccessful. have not set a target date. There is
to measure any deviation from perfect There is more work to do in this area. another aspect to using resolvers with
repeatability. To measure accuracy, a My original design called for all of intelligent motion controllers. In gen-
move of exactly 1″ was executed from the critical parts of the motion stages eral, they don’t accept resolver signals
a zero (on the dial indicator) position. to be completely enclosed with accor- as inputs. They are designed for optical
This move was done several times dion-like jackets. Bearings rolling on encoders. The resolver signals must be
with the measured error being the even small amounts of dust soon accu- converted, so they are similar to optical
same on the respective axis. I expected mulate lumps of packed dust. Making encoder signals in order to use them. I
these errors to be larger than they these jackets is somewhat difficult, so
were, just because the lead screws I opted for “dust skirts” on the x-axis Gordon Dick (P. Eng.) is an instructor in
weren’t actual “lead screw” quality. only. These are attached to the sides Computer Engineering Technology at
Some errors in cutting the lead screw of the worktable with some weight at the Northern Alberta Institute of Tech-
threads would easily account for this the ends. (The photos were all taken nology in Edmonton. Occasionally, he
positioning error. before the dust skirts were installed.) consults in intelligent motion control.
My first attempt at measuring the So any dust not caught by the dust-col- Gordon is usually working on microcon-
backlash gave poor results. My best lection scheme will fall on the skirt troller-based projects (often involving
results were obtained when I physical- rather than on the x-axis rails. The y- machining of metal parts). You may
ly pushed a stage back and forth and axis and (the z-axis to a lesser extent) contact him at gordond@nait.ab.ca.
noted the dial indicator reading. Since will still be subject to airborne dust,
the method of trapping the lead screw which I know will be a minor problem.
nut is different on the y-axis, I expect- I have not spent much time “tun- PROJECT FILES
ed the backlash to be larger there. But ing” the controller. Some adjustment To download code, go to ftp://ftp.
on all three axes, the backlash was of the controller parameters had to be circuitcellar.com/pub/Circuit_Cellar
lower than I expected. Overall, I’m done when the system was first pow- /2007/201.
very pleased with the performance of ered up just to get the system stable
my machine (see Table 1). from a dynamic point of view. I
haven’t gone beyond that, but I RESOURCE
IMPROVEMENTS should. Galil has some slick software Galil Motion Control, Inc., “CAD-to-
It seems to be a human trait to look to help with the tuning process, which DMC User Manual,” www.galilmc.com/
for ways to improve machines. My I will likely use. support/manuals/cadman.pdf.
second machine is better than the first The last improvement I’ll talk about
in many ways. Since you don’t have is the most interesting. System back-
intimate knowledge of the first lash can be compensated for by using SOURCE
machine, I won’t talk about those what’s called “dual-loop control.” This DMC-2133 Motion controller
improvements. But, I will talk about means there are two position feedback Galil Motion Control, Inc.
improvements and enhancements that loops per axis and therefore two posi- www.galilmc.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 37


FEATURE ARTICLE by Miguel Sanchez

Reverse-Engineered ECP Bus


Miguel wanted to build a system to simulate strokes on a keypad so he could trigger modes
on an alarm system. But first he had to learn about ECP buses. In this article, he explains
what he learned.

W hen trying to gather information


about a new chip, protocol, or device,
communication you want to emulate
can help you figure out how it works.
sonal computers. The best informa-
tion I found on the Internet was that
a search engine can often be your I continued to write more Java code to the ECP bus consists of four wire
friend. Just knowing the name of a decode the captured data once I knew interconnects: power, ground, data
given system may be enough to find what the format was. Finally, I wrote transmit, and data receive. The infor-
all of the information you need. When some Perl code to allow a PC to emu- mation, while true, did not help
you are lucky, searching on the Inter- late the communication that I was much. Because I was not finding use-
net can lead you to a variety of docu- asked to perform. Later on, I turned ful information on the Internet, I had
ments and useful information. Howev- that into a small C program for a Rab- to resort to other sources. So, I talked
er, this is not always the case. It was bit core. You will find all of these pro- to some of the people who install
definitely not true this time. Some- grams and some of the sampled data these security systems.
times you need to interface with sys- on the Circuit Cellar FTP site. Now I A security company representative
tems that are poorly documented or will show you how I did it. told me that ECP buses serve to inter-
not documented at all. Whether the face several security panels, consisting
lack of documentation is anybody’s ECP BUS of a keypad and a display, to an alarm
fault or it is the true will of the manu- I am sure that most of you have motherboard. An ECP bus is a mul-
facturer, you may be in for a big dose heard of an extended capabilities port tidrop network that also provides the
of guesswork. (ECP) interface. The ECP was designed power supply for the panels. An alarm
In my project, the goal was to sim- by Hewlett-Packard and Microsoft to motherboard can be operated from sev-
ulate keystrokes on a keypad so I provide a new high-speed version of eral remote panels. For example, a
could trigger the desired operational the standard parallel port (also known house may have one panel in the
mode on an alarm system. The prob- as Centronics) found in early PCs. garage and another one near the main
lem was that I knew nothing about The bus in my project was a serial door. If you watch someone typing a
the proprietary bus that the system bus, and it had nothing to do with per- code in a home security system in a
used, and I had only a movie, chances are it is
sample working system one of the panels that I
to play with. I decided to am talking about.
look for a PC-based data Some people on
capture system. With the USENET news also
system, I obtained samples asked about details on
of the communication. the ECP bus protocol,
Next, I created a way to but no answers were pro-
display the long list of vided. I contacted two
samples I received by com- people that showed inter-
bining a small piece of est in the topic, but I
Java code with a fantastic obtained no information.
piece of vector-graphics I even found U.S. patent
software. I also learned a #6868493 that referenced
bit about scalable vector the ECP bus, but it did
graphic (SVG) language not give specific details.
during the process. While I am sure there
Having samples of the Photo 1—USB Instruments’s Stingray consists of two input channels and one signal generator. has to be a way to pull

38 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


the bus specification from the manu-
facturer, I did not envision a fast,
straightforward method at the begin-
ning of the project. I just had to figure
it out from scratch. I started by look-
ing at signals I could pick up from the
bus while operating my sample sys-
tem. Later on, I figured out how the
system works by looking at the cap-
tured information.

GATHERING DATA
I do not perform reverse engineering
for a living, so I was not well equipped
to carry out this task. I was dealing
with 30-year-old equipment and I
assumed data transmission speeds
would not be very high. I needed to
obtain a good sample of the signals
over the transmit and receive wires of
the ECP bus so I could start figuring
things out. Photo 2—EasyLog software comes with the Stingray. I used part of a captured signal here.
A sample oscilloscope would be all
right, but only for very basic tasks. It
was also not clear if a PC serial port glad to learn that the unit could also baseband digital signals using non-
could handle serial communication be used under the Linux OS and that return-to-zero (NRZ) encoding. How-
over the bus. Using an old oscillo- the Windows-based software would ever, it was not clear whether asyn-
scope, I could observe that bus signals run on top of Wine too. chronous serial communication was
ranged from approximately 0.8 to 11 V, The Stingray came with two pro- used or not. Signal polarity might be
while the power signal was 12 VDC. grams: a sampling oscilloscope and a inverted too.
Using my analog oscilloscope, I was data logger. The latter was designed to I first needed to know the signal’s
not getting a good idea of the bus’s capture long sampling sessions (see data rate. For an NRZ-encoded bit
data rate or format, so I needed a new Photo 2). It allowed me to view and stream, you need to look for the short-
gadget to get the signals properly sam- save gathered data to a file. It would est length of a signal element to dis-
pled and stored for further analysis. I also allow me to save the sampled cover the bit time. In my case, the bit
thought a PC-based signal-capture data to a text file. It seemed quite time was around 200 μs. I knew that
board would be appropriate, but after a appropriate to pass the gathered data because it was a value between 10 and
quick search on the Internet, I learned on to another application for further 11 samples. However, most of the
that the USB Instruments DS1M12 processing. time, serial communication uses cer-
Stingray dual 12-bit oscilloscope was Once transmit and receive signals tain data rates that can be easily gen-
available from a local seller at a good had been gathered while operating the erated from a crystal oscillator. These
price, so I bought it (see Photo 1). keyboard, I turned to the process of are values like 300, 1,200, 2,400,
Besides the Windows software pro- finding out how it works. I had my 4,800, 9,600, 19,200, or 38,400 bps.
vided with the unit, there is a DLL text file with a table-like format with Assuming the bus’s data rate was one
you can use to gather data from your measured voltage for each signal sam- of them, I just needed to calculate the
own software. (By the time I learned pled at 20-μs intervals. Just looking at inverse of these values to know the bit
about this it was too late because I the captured signal, it became obvious time for each one. It turns out that
had created a workaround first.) I was that both transmit and receive were 1/4,800 is 208 μs, so it would be just
this value. Once I guessed the bus’s bit
2) Addressing
rate, the next step was to find the data
format. Is asynchronous serial trans-
1) Poll
mission being used? If yes, what is the
number of data and stop bits? What
4) Key transmission parity, if any, is being used?
Asynchronous serial communica-
3) Go ahead 5) Acknowledgement
tion keeps the line idling to a high
level while no data is available and it
Figure 1—Check out the details on the protocol associated with the transmission of a key press. inserts a zero bit to begin transmitting

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 39


3URXGO\GLVWULEXWHV

Intel® Pentium® M 745 1.8GHz, 2MBL2, ATX

EPIC
/PM

Based on Intel® Pentium/Celeron® M processor.

Intel 855GME / ICH4 chipset with integrated Intel®


Extreme Graphics 2 engine 2x32 MB VRAM UMA.

2x DDR-RAM-SODIMM for up to 2GByte.

Photo 3—The Inkscape program shows part of the drawing generated by the Draw.java program.

IDE Flash Drive Carrier Board with Micro SD Interface a character. However, by scrolling the Because samples were numeric values
captured signals back and forth using expressed in millivolts, I used a suit-
the data logger software, it was not able threshold to convert each sam-
clear whether they were even the pled value to a digital value of 1 or 0.
same in terms of polarity. It would be
SD
nice to have all that printed onto a VECTOR GRAPHICS
-ID
E -40
/
paper page; however, the print func- Some of the most popular graphics
44
tion of that software only prints what formats like BMP, JPEG, and GIF are
Available in 40 and 44 pin header configuration you can see on the screen. Zooming bitmap graphics. They represent the
Support PIO 0-4 and Ultra DMA 3 mode. out to get the entire sampled interval image matrix of picture elements (pix-
Bootable from Transflash/micro SD. did not help. That made it impossible els), each one a given color. There are
Low power consumption. to see the signal details. different code libraries for you to read
I just saved the captured data as a and write such file formats. However, I
text file to end up with a 25-MB file was more inclined for a solution that
from a 20-s capture at a 20-μs sample was as self-contained as possible.
rate. A quick look at the file with Because I was using Java, interfacing
Fanless Intel® 852GM Celeron® M 600 MHz Micro PC
Notepad showed that lines starting with an external library was not easy.
with a space contained data arranged Vector graphics create a representa-
as three columns: sample time, chan- tion of the drawing actions, instead of
nel A, and channel B. I connected the the color of each pixel. It is like the
RECEIVE signal to channel A and the set of commands to create the image.
3
72 transmit signal to channel B. There are different file formats for
S-3
EE
The next step was to figure out a vector graphics. Most of them are pro-
Onboard Intel® Celeron® M 600 MHz good way to turn this data into a real- prietary, but the World Wide Web
with 512K L2 Cache CPU. ly long graph that could be printed. Consortium developed the SVG mark-
Intel® 82852GM Chipset.

Scalable with Evalue EPIC SBC.

One SODIMM up to 1 GB DDR SDRAM.

www.tri-m.com info@tri-m.com

1.800.665.5600
HEAD OFFICE: VANCOUVER
tel: 604.945.9565 fax: 604.945.9566
Figure 2—The top and bottom signals are the same but inverted. The circles show when there is a violation of the
stop bit.

40 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


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

DSO
2.0

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.
up language standard signal, then the last line
in 1998 to provide a does seem to break
standardized alterna- FF FD because characters do
0
tive. I had learned 0 0 not seem to fit to either
about SVG several 8 data bits without pari-
years ago, but I was ty or to 8 data bits plus
89 2 4 71
never interested in F6 9 0 a parity bit.
that file format before. Figure 2 shows the
One year ago, I started bus-transmit signal
using Inkscape graphics (below) and the same
software and it turns signal inverted (above)
out that it uses the against a data format of
SVG file format to save Figure 3—The decode.java program adds the decoded values to the drawing. 8 bits, no parity
its designs. SVG files (below), and 8 data bits
are human-readable files like HTML to show the results (see Photo 3). plus 1 parity bit (above). I have located
(although you may prefer a browser the patterns starting at the first falling
program to do the processing). For GETTING THE BYTES OUT edge of the signal (that it marks the
example, the following command will I did several captures using different beginning of a start bit). It is expected
create a diagonal red line: <line address codes (2, 7, 9, 15, and 18) in that after transmitting the data bits
x1=”5” y1=”5” x2=”45” y2=”45” the keyboard of a user typing the code (and maybe parity) there has to be a
stroke=”red”/>. There are several 1,2,3, and 4. A sequence of events stop bit (a red block in the figure) that
other commands like circle, polyline, associated with each keystroke has to be a 1 bit. The signal on the
polygon, and ellipse. became apparent (see Figure 1). The bottom of the figure is the only one
It is quite simple for a program to bus transmit signal, commanded by that it is consistent with an asynchro-
print the sequence of commands to the alarm motherboard, appears as a nous transmission of 8 data bits plus
create the graphical representation of a red line. After a long pulse, much parity bits. So the transmit signal has
digitized signal. In my case, I wrote longer than a character, the keyboard the right logic polarity but it violates
some code to draw the two signals I starts transmitting some pulses (a blue the idle condition, so when no data is
had previously digitized, as if they line) triggered by the fall edges of the being sent, the line is kept low and it
were the lines of a book. Since page transmit signal. I guessed this was is raised to the high level some mil-
width is limited, I drew from left to some kind of polling action. Later, liseconds before the beginning of a
right, creating a line and then moved after about a 50-ms pause, the trans- data transmission or as a polling
down a bit to start from the left of the mit signal transmitted some bytes and action (line high for more than some
next fragment of the signal. I repeated then the keyboard panel transmitted milliseconds without transmitting
the process until all the captured data what appeared as a keystroke message. data). If a poll is detected, the keyboard
was drawn. A different color for each Finally, the bus transmit signal sent will initiate its own addressing phase.
signal helped me differentiate them. I what might be an acknowledgment of We are almost done, but some
wrote the Stat.java program to get an the keystroke message. understanding of the message’s con-
idea of the maximum, average, and It was not clear what type of trans- tent is still required. To do this, I
minimum values of the captured data mission was used or the polarity of needed to simulate a UART, because it
and to solve the details about properly the signals. A standard RS-232 data is a pain to manually decode each byte
parsing the data file. For some weird signal stays at negative voltage while from the already generated graphs.
reason, the data file contained both idle, which is the opposite polarity of Because the capture sampling rate was
commas and dots as decimal separa- the logical level high (positive voltage) approximately 10 times the bit time, I
tors used interchangeably, so I took it represents. An asynchronous trans- used this information in the decoding
care of that before converting the data mission will start with a 0 bit (start routine. SVG format allows text labels
into a number. I guess this problem bit), but the line will remain high on the document, so I added them in
might have been caused by a comput- until then. the last Java program: Decode.java.
er’s regional configuration. Here you see a signal that mostly This program creates an SVG file,
Draw.java created an SVG file repre- remains at a low level
senting the captured data as a set of (red) and another one
lines using two colors (blue and red) to that mostly remains Address Values (hexadecimal) Binary (least significant bit first)
represent channels A and B. This way at a high level (blue). 2 FB 1101 1111
you can print it out or study the signal At first sight, it might 7 7F 1111 1110
on-screen while viewing several sec- look like we need to 9 FF, FD 1111 1111 1011 1111
onds of captured signals. Then it is invert the transmit 18 FF, FF, FB 1111 1111 1111 1111 1101 1111
much easier to look for patterns of signal (red). However, Table 1—Want to know how addresses are made? It is all clear when you look
activity. I used free Inkscape software if we invert the red at the binary pattern.

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 43


Observing different keystroke mes- While I am not providing the com-
sages allowed me to discover the plete details of how the protocol
details of the first byte of the message works in the text, you will find them
and the checksum calculation. Mes- in the article’s source code. I hope that
sages also include a sequence number you might consider using the SVG file
to detect duplicated messages that can format in your future projects when
happen in case of a transmission error. you need to create some graphics from
The second byte was just a counter of your programs. If you do, you will find
the number of bytes to follow, but it that Inkscape software will help you
was always two unless I typed really display, modify, and print your graphs.
fast and then two different keystrokes The drawing and decoding code I pro-
would be sent in a single message, but vided here may be adapted for a simi-
1 byte longer. lar project, but using a different data
rate or format. I will be glad if you can
TRYING THINGS OUT use it and I hope you will be inspired
My goal was to be able to simulate the next time you have to deal with
keystrokes on the ECP bus. I thought I an undocumented bus. I
knew how everything worked, but you
are never sure until you can fool the Miguel Sanchez holds a B.S., an M.S.,
real system. So, I decided I needed to and a Ph.D. in Computer Science. He
check if my understanding of the pro- has taught computer networks courses
tocol was good enough. The simplest at the Technical University of Valen-
way of getting things done was to use cia, Spain since 1989. Miguel’s inter-
a PC serial port to simulate the com- est in electronics and microprocessors
plete dialog. But there were one or two sparked his career in computer sci-
Figure 4—I connected a Rabbit core to the ECP bus. problems. I was not sure if I could get ence, but his solder is always at hand.
good time measurements in Java and I His research is currently focused on
drawing the signals and adding the had never used Java for serial port pro- vehicle energy efficiency. He also
values of each decoded byte as a hexa- gramming. works as a consultant. You may con-
decimal value. After searching the Internet for a tact him at misan@disca.upv.es.
Once the data decoding is printed minute, I decided to use Perl for this
over the graph, it is much simpler and task. I knew I could use the “select”
PROJECT FILES
convenient to figure things out. So, system call to get quite accurate time
the addressing scheme shows differ- delays. I could also transmit and To download code, go to ftp://ftp.
ences depending on the address value receive over the serial port. Once my circuitcellar.com/pub/Circuit_Cellar
used. In Figure 3, address nine turns code was working properly, I learned /2007/201.
into the sequence FF, FD. Table 1 that my guesswork was a success.
shows you other address values too. With the inverted nature of the bus RESOURCES
You just need to put these values in signals, I just needed a diode to con-
CPAN Search, “Win32::SerialPort Perl
binary form (using the serial-transmis- nect to the computer. I connected the
package,” http://search.cpan.org/dist/
sion order of sending the least signifi- bus transmit signal to both the RXD
Win32-SerialPort/.
cant bit first) to see how addressing and CTS signals. I connected the bus
works in the bus. (The address is the receive to the TXD signal of the PC Inkscape, “SVG Graphics Editor,”
number of consecutive bits before a serial port. www.inkscape.org.
zero is found. Multiple bytes are used I have to admit that results were not
as needed.) A “GO AHEAD” message perfect due to the fact that millisec- Kevin Lindsey Software Development,
is formed by a fixed F6 data byte plus ond precision under Windows is not “Basic SVG shapes,” 2003,
the address number in the next byte. always achieved (at least not with my www.kevlindev.com/tutorials/basics/
Each keystroke message is preceded by Perl code). For my second attempt, I shapes/svg/index.htm.
2 bytes, then the actual number used a Rabbit Semiconductor
pressed represented in binary (not RCM3710 core. I used a small circuit SOURCES
ASCII), and then a fourth byte (a to invert and adapt the signal levels. A
DS1M12 Stingray oscilloscope
checksum byte). Acknowledgment is a couple of op-amps were used in this
USB Instruments
single byte matching the first byte of case, as shown in Figure 4. The logic
www.usb-instruments.com
the keystroke message. If that is miss- of keypress.c code is the same as Perl
ing, the keyboard will attempt to code, but here the timing is just per- RCM3710 Core
retransmit the message when the next fect because there are no other tasks Rabbit Semiconductor
poll happens. to interfere with. www.rabbitsemiconductor.com

44 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


FEATURE ARTICLE by Fred Eady

Uncomplicated RF Communication
You don’t have to build or run an official ZigBee stack to use the new 900-MHz and 2.4-GHz
transceiver ICs. However, knowing what the radio is capable of and how to use its features
will enable you to easily understand what a ZigBee stack is doing.This month, Fred teaches
you all about ZigBee stacks.

I t’s rather easy to get caught up in


the hype and find yourself standing
cracked the hard outer shell of
the 802.11b nut. If you recall,
CC2420 Microcontroller

FIFO GIO0
lost amongst the trees in the forest. we didn’t have very much
One of today’s biggest hypes is ZigBee. 802.11b technical information FIFOP INTERRUPT

Don’t get me wrong, I’m not bashing to support us. The lack of tech- CCA GIO1
ZigBee. I’m simply bringing to your nical documentation is not a SFD TIMER CAPTURE
attention the amount of interest factor in the IEEE 802.15.4
ZigBee is getting these days. world, where datasheets and ref- CSn GI02
When I initially signed up for erence design Gerber files are SI MOSI
ZigBee school, I was totally over- standard handouts. One of the
SO MISO
whelmed by the complexity of the most prolific 2.4-GHz transceiv-
SCLK SCLK
ZigBee specification. I was equally er ICs out there right now is the
befuddled by the seemingly complex Texas Instruments CC2420. If
RF side of ZigBee. What I should have you come to understand the Figure 1—This represents a typical interconnect between the
done was back off of the high-level CC2420, you will find that CC2420’s digital I/O pins and a generic host microcontroller.
ZigBee stuff and establish a ground- many of its competitors walk in Note that although the physical connection is there, the
CC2420 driver firmware does not employ the services of the
plane understanding of the hardware the trails blazed by its tank
CC2420’s CCA pin.
that makes ZigBee possible. The hard tracks.
fact is that ZigBee is simply an exten-
sion of the IEEE 802.15.4-2003 specifi- CC2420 OVERVIEW trum (DSSS) is another technique you
cation, and the specification can’t Like many of the IEEE 802.15.4- will find that is common to radios,
exist without low-power 900-MHz and compliant transceiver ICs, the aimed at IEEE 802.15.4 use within the
2.4-GHz transceiver hardware. CC2420 uses SPI to communicate industrial, scientific, and medical
An elegantly written ZigBee stack is with a host, which is usually a micro- (ISM) frequency domain. Naturally,
a beautiful thing. However, the most controller equipped with its own inte- the CC2420 includes a digital DSSS
complicated and feature-rich of ZigBee grated hardware SPI interface. The baseband modem that provides a
stacks still has to cater to the RF hard- whole idea behind IEEE 802.15.4 is spreading gain of 9 dB. The popularity
ware that supports it. low-power (20 mA) operation coupled of the CC2420 stems from its interna-
What I’m driving at here is that you with low data rates (250 KBps). The tional flavor. The CC2420 complies
don’t have to build and run an official CC2420 was designed with all of that with all of the regulations put forth by
ZigBee stack to use the current crop of in mind. Direct-sequence spread spec- the United States (FCC CFR47 Part
900-MHz and 2.4-GHz trans- 15), Europe (ETSI EN 300 328
ceiver ICs. However, knowing and EN 300 440 class 2), and
what the radio is capable of Register Read Japan (ARIB STD-T66).
0 1 A5 A4 A3 A2 A1 A0 16 bits of data returned D15–D0
and how to access its capabili- The CC2420 is not just a
ties makes for an easier under- Register Write means of temporarily bending
standing of what a ZigBee 0 0 A5 A4 A3 A2 A1 A0 D15...D0 the Earth’s magnetic field. Lots
stack is doing, if your applica- of things are done within the
tion requires a stack. Figure 2—This is typical of a SPI command/data transfer sequence.You’ve CC2420 to reduce the work-
A couple of years ago, we got all of the essential ingredients: a command, an address, and data. load of the host microcon-

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 45


XOSC16M_STABLE Bit 6 register is addressed with 6 bits. The Bank 0 TXFIFO 0xb00
TX_UNDERFLOW Bit 5 value of the most significant bit of the Bank 1 RXFIFO 0xb01
ENC_BUSY Bit 4 address byte determines if a RAM(1) Bank 2 Security 0xb10
TX_ACTIVE Bit 3 or a Register(0) operation is about
Table 2—Absolutely no rocket science here.
LOCK Bit 2 to take place. Bit 6 of the address
RSSI_VALID Bit 1 byte, acts as the Read/Write(1/0)
signal. The actual 6-bit register Bit six of the CC2420’s status byte
Table 1—Short and sweet. One look is all it takes to
get a complete status. address begins with bit 5, which is the informs you about the state of the
most significant bit of the 6-bit address CC2420’s 16-MHz oscillator. If a FIFO
value. In the case of the 33 16-bit con- underflow occurs during a transmis-
troller. Packet-handling chores, such figuration and status registers, 24 bits sion, the TX_UNDERFLOW bit is set. Bit
as data buffering and data authentica- are clocked across the SPI for any read 5 must be cleared using a SFLUSHTX
tion, are handled by the internals of or write operation when the CC2420’s command strobe. The ENC in bit 4 of
the CC2420. The CC2420 can also chip select (CSN) pin is held logically the CC2420 status byte is short for
assist in the transmission and recep- low. Figure 2 is what the Read/Write encryption. The CC2420 has an inter-
tion phases of operation by perform- SPI binary bit stream looks like. nal encryption module if you care to
ing clear channel assessment (CCA) Accessing the CC2420’s 15 com- use it. The only remaining CC2420
and providing link quality informa- mand-strobe registers is akin to issu- status bit that may not be obvious as
tion (LQI). ing a single-byte write instruction to to its usage is the LOCK bit, which
the CC2420. Command-strobe regis- simply reports if the CC2420’s PLL is
ACCESS THE CC2420 INTERNALS ters are used to do things like enable locked or not. The collection and
Everything you will do with the the crystal oscillator or flush the interpretation of the CC2420 status
CC2420 will depend heavily on the transmit FIFO. There’s also a no oper- byte is very important.
SPI connection between the host ation (SNOP) command-strobe register All but one command strobe will
microcontroller and the CC2420. The that allows reading of the status bits not be accepted when the CC2420’s
CC2420 is always configured as a SPI by way of the SPI. A CC2420 status crystal oscillator is not running. Only
slave and connects to the host using a byte is returned on the CC2420’s SO the SXOSCON command strobe will be
standard SPI hookup like the one pin when a command strobe is issued recognized by the CC2420 when the
shown in Figure 1. and during a transfer of the register- CC2420’s crystal oscillator is inactive.
The CC2420’s register farm is com- access byte. CC2420 status bytes are The remaining CC2420 command
posed of 33 16-bit configuration and also clocked onto the CC2420’s SO strobes are accepted only after the
status registers, 15 command-strobe pin, while clocking the first RAM XOSC16M_STABLE status bit is set.
registers, and a pair of 8-bit registers address byte and during a transfer to While you’re on the subject of com-
that act as portals to the independent the CC2420’s TXFIFO. The status mand strobes, a command-strobe reg-
transmit and receive FIFOs. The byte’s most significant bit and least ister is accessed by issuing a register-
addressing scheme associated with read- significant bit are reserved, leaving write operation. No data is written to
ing and writing the CC2420’s set of 50 only 6 bits of status information (see the command-strobe register. Only
registers is very efficient. Each CC2420 Table 1). the RAM/Register bit, the Read/Write

Figure 3—This is textbook CC2420 implementation. Texas Instruments doesn’t recommend you deviate too much from this design and the layout you see in Photo 1.

46 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


bit (both set to 0), and the 6-bit com- Photo 1—You can’t get this CC2420 radio com-
mercially anymore. But, if you’re resourceful, you
mand strobe-register address values can build your own. The specifications and PCB
are transferred on the SPI. files are available on the Texas Instruments web
The CC2420 houses 368 bytes of site. You can also get CC2420 reference design
RAM in addition to its 50 configura- evaluation boards from Texas Instruments in its
CC2420 development kits.
tion and status registers. Only a single
byte of RAM data can be read or writ-
ten at a time. The CC2420 programmer
must submit only the beginning address process: SFD, FIFO, and FIFOP.
when initiating a read or write because A complete RF transmission con-
the CC2420 hardware will automatical- sists of a preamble (4 bytes of 0x00)
ly increment the address with succes- followed by a start of frame delim-
sive RAM read/write operations. iter (SFD), 0xA7 the length (least sig-
The RAM address consists of 2 bytes.
The most significant bit of the most
significant byte is the RAM/Register
bit, which must be set logically high
to access the CC2420’s RAM area.
The 7-bit RAM address follows the
RAM/Register bit. The CC2420’s
RAM area is partitioned into three
banks (see Table 2).
The second address byte begins with
the binary bank value followed by the
Read/Write bit. The rest of the second
address byte is ignored by the
CC2420. From the SPI’s point of view,
the RAM addressing scheme looks
like this:

1 A6 A5 A4 A3 A2 A1 A0 B1 B0
RW X X X X X

It is not recommended to do direct


reads and writes to the FIFO RAM
area because the automatic FIFO
counter will not be in the loop. The
TXFIFO and RXFIFO RAM areas can
be accessed instead through the
TXFIFO and RXFIFO registers. FIFO
access using the TXFIFO and RXFIFO
registers is byte-by-byte. Issuing a
SFLUSHTX command strobe will clear
the TXFIFO, while an SFLUSHRX
(issued twice by recommendation of
the CC2420 datasheet) will flush the
RXFIFO.

CC2420 RECEIVE MODE


Now that you know how to access
the CC2420’s internal registers and
RAM areas, there should be no prob-
lem coding up the necessary initializa-
tion routine. However, we still need
to obtain more information before
attempting to code the receive and
transmit routines. The CC2420 uses
three I/O pins to assist in the receive

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 47


PC/104 Single Board Computers

Low Price, Low Power, High Reliability


200 MHz ARM9
using Linux development tools Power as low as 1/4 Watt

5 boards, over
2000 configurations
$ 99
qty 100
Fanless, no heat sink

SDRAM - up to 128MB
$ 129
qty 1
Flash - up to 128MB onboard

TS-7200 10/100 Ethernet - up to 2


shown with
optional A/D converter,
Compact Flash and RS-485 DIO lines - up to 55
NEW!
2 USB ports SD card
option
COM ports- up to 10
options include:
onboard temperature sensor, A/D Converter 8 channel 12 bit, Extended Temperature, Programmable FPGAs VGA video
Battery Backed Real Time Clock, USB Flash 256 M (with ARM Tool Chain), USB WiFi
Linux, Real Time extension, NetBSD

Off-the-Shelf Solutions ready to design into 133 MHz 586


your project using DOS development tools
Power as low as 800mA $ 229
qty 100
Fanless, no heat sink

SDRAM - up to 64MB
$ 259
qty 1
COM Ports - up to 4 ports

Ethernet Ports

DIO Channels - up to 40

TS-5600 Shown with


optional flash modules,
PCMCIA II adaptor
A/D, RS-485 and
Merlin cellular modem
Compact Flash adaptor

options include: USB Ports (Except on TS-5300)


RS-485 Half and Full Duplex, A/D Converter up to 8 Channels at
12 bits, DAC up to 2 Channels at 12 bits, Extended Temperature
see our website for 33 MHz 386 configurations

Over 20 years in business Custom configurations and designs w/


Open Source Vision excellent pricing and turn-around time
Never discontinued a product
Most products stocked and available
Engineers on Tech Support for next day shipping

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


New Products and PC/104 Peripherals

Tiny WiFi Controller Intelligent Battery Back-up


boots Linux in 1.1 seconds

200 MHz ARM9


$ 119
qty 1
$ 249
qty 1 Up to 128MB Flash
Run your system for days
with no external power source

Up to 128M SDRAM

802.11g WiFi

SD Flash Card socket

1 external USB port

1 10/100 Ethernet

Rugged aluminum enclosure 3 TTL serial ports


measures 1.1” x 4.9” x 3.1”

ZigBee Wireless low power wireless, simple serial interface, range up to 1 mile

33.6K baud, 56K baud, AT commands, caller ID, cellular using


Modems GSM and CDMA technologies

Non-volatile Memory up to 2MB, 10 year lithium battery

Serial Ports up to 4 serial ports with optional RS-485, opto-isolated available

8 channel 12-bit A/D converter, optional 2 channel 12-bit DAC,


12 bit A/D, DAC A/D jumpered for 0-2.5V, 0-10V or 0-20mA

Philips SJA1000, opto-isolated, up to 1 megabit/sec


CAN Bus Controller selectable termination resistor, Ocera Linux driver

32 inputs, 32 outputs, 200 mA drive, optional 512 Kbyte or 1 MB


64 Digital I/O battery-backed SRAM, stack up to four boards, RoHS compliant

see our website for more boards and option details

Technologic
S Y S T E M S
We use our stuff.
Visit our TS-7200 powered website at
www.embeddedARM.com
WIN
Every week, Jameco is
giving extra discounts on
major brands like these:
• AlcoSwitch • AMP/Tyco

BIG
• Dallas Semiconductor
• Intersil • Maxim
• Microchip • Molex
• Panasonic • AVX
• Fairchild Semiconductor
• Tyco • Aromat
E AN
TAK

E X T R%A
• Aavid Thermalloy
• Atmel • ST Micro

And that’s in

15
addition to the

OFF
industry-best
pricing you
already get

EW at Jameco
ON 2 N

M A J ODRS
every day!

You already
know about

BRAN W E E K
Jameco’s
! best-in-the-
EVERY business
low pricing...
Now we’re
out to get a new
message across:
Major Brands—at
Jameco pricing!
To dramatize the
point, we’re giving

EVERY
• T.I. Semiconductor
you an additional 15% discount on two
different major brands each week. From
• Augat/Tyco • Bourns
now through the end of May!
• CTS • Cypress
And that’s on top of our

SEE
• C&K Switches
everyday discounted pricing!
• Comair Rotron UP
O’S We wanted to make this

THIS WEEK
WH
• Condor • Grayhill so good a deal that you just
• Intel • Micron O couldn’t pass it up.
GO T I T E So... Want to know which

WEEK
• Philips • Power-One B S
• Raychem/Tyco THE WE two major brands you can
• Renesas • SanDisk save extra-big on this week? Just head

— —
• Toshiba to the website...
• Vishay Siliconix
AT www.Jameco.com/CCW

Great Products.
Awesome Prices.

JAMECO
nificant 7 bits of 1 byte) of the the CSMA-CA process. By issu-
MAC protocol data unit ing a STXONCCA strobe command
(MPDU), and the MPDU itself. instead of the STXON strobe com-
The CC2420’s SFD pin will go mand, transmission will only
logically high upon the detec- occur if the channel is clear. The
tion of a valid IEEE 802.15.4 TX_ACTIVE status bit can then
SFD sequence. The SFD pin will be used to detect the result of
go low again after the reception the CCA instead of reading the
of the last byte of the MPDU. logic level of the CCA pin. CCA
The SFD pin will also go low has three modes, which are
immediately if address recogni- mutually exclusive and deter-
tion fails. mined by a register setting.
To aid in identifying an Mode 1 clears the channel when
address recognition failure, the received energy is below the
CC2420 employs the services of threshold. Mode 2 clears the
the FIFO pin. The FIFO pin will channel when it is not receiving
go logically high following the valid IEEE 802.15.4 data. Mode 3
reception of the length byte, clears the channel when energy
which will be the first byte is below the threshold and it is
stored in the RXFIFO. If address not receiving valid IEEE 802.15.4
recognition fails, both the SFD data.
and FIFO pins will go logically The FIFO and FIFOP pins are
low. As long as the FIFO pin not considered during Transmit
remains logically high, there are mode because they only relate to
data bytes in the RXFIFO. The the RXFIFO. However, the SFD
FIFO pin will take a logically pin is active during Transmit
low state when the RXFIFO is mode and goes logically high
empty. Thus, when address when the SFD field has been
Photo 2—It doesn’t take much computer power to put a CC2420
recognition completes success- completely transmitted. When
radio on the air. In many ways, using a PIC18LF4620 here is overkill.
fully, the FIFO pin will remain As usual, I used 0805 SMT passives on the other side of this point- the number of bytes designated
high as the SFD pin goes low to to-point wired board. by the length byte have been
indicate the end of MPDU transmitted, the MPDU is con-
reception. sidered to be fully transmitted
Another CC2420 I/O pin, FIFOP, is signal the receipt of a complete frame and the SFD goes logically low at that
also used to verify MPDU reception. by interrupting the host microcon- time. The CC2420’s SFD pin will also
The FIFOP pin will go high when the troller. If multiple frames are buffered take on a logically low level on a
number of unread bytes in the RXFI- in the RXFIFO, the FIFO pin can be TXFIFO underflow. The TXFIFO
FO exceeds the threshold programmed used to interrogate the RXFIFO for the underflow condition is verified by
into the 7 FIFOP_THR bits of the presence of unread bytes. And, if reading the state of the TX_UNDER-
IOCFG0 register. Also, the FIFOP pin frame timing is important to you, the FLOW status bit.
will not go high until address recogni- timing window created by the SFD
tion completes successfully, even if pulse width can be captured by a host PLINKING A CC2420 MESSAGE
the number of bytes in the RXFIFO microcontroller capture input. The CC2420 is remarkable, but it
exceeds the programmed threshold. A needs a supporting cast of its own in
successful MPDU reception is sig- CC2420 TRANSMIT MODE addition to the host microcontroller
naled by the SFD pin going low and We can take or leave the functional- circuitry. Figure 3 is a graphic repre-
the FIFOP line going high, as the ity offered to us by the clear channel sentation of the components necessary
FIFOP line will go logically high and assessment (CCA) pin. The CCA sig- to immediately support the CC2420.
the SFD pin will take on a logical low nal is based on the measured receive The circuit you see can be assembled
when the last byte of the MPDU is signal strength indicator (RSSI) and a on a small double-sided PCB. The
received, regardless of the RXFIFO programmable threshold value located CC2420 reference design PCB art and
threshold. in the RSSI and CCA status and con- Gerber files can be obtained from
Figure 1 should be a bit clearer to trol register. The CCA function is Texas Instruments. As you can see in
you now. In a standard IEEE 802.15.4- used to implement the carrier sense Photo 1, I “bogarted” my CC2420
compliant configuration, and provided multiple access with collision avoid- radio and supporting electronics from
the FIFOP threshold value is set to ance (CSMA-CA) functionality. an old Microchip Technology PIC-
127 (the maximum value of the length Issuing the STXONCCA strobe com- DEM Z development kit. As you
byte), the FIFOP pin can be used to mand is the easiest way to kick-off know, Microchip now ships its own

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 51


Listing 1—This is the main function of the test version of my CC2420 driver firmware. The real meat of the
CC2420 driver lies in the supporting functions that fill and empty the CC2420’s internal registers and RAM
areas.

void main(void)void main(void)


{
unsigned int timer,x;

CC2420_Enable();
sequence_byte = 0x00;
do{
CC2420_CSn_0();
SPI_OUT(REG_TXFIFO);
SPI_OUT(0x1A); //length (not counting this byte)

SPI_OUT(0x01); //frame control LSB


SPI_OUT(0x88); //frame control MSB

SPI_OUT(sequence_byte++); //sequence byte

SPI_OUT(0xAA); //destination PAN ID LSB


SPI_OUT(0xAA); //destination PAN ID MSB

SPI_OUT(0xBB); //destination addr LSB


SPI_OUT(0xBB); //destination addr MSB

SPI_OUT(0xCC); //source PAN ID LSB


SPI_OUT(0xCC); //source PAN ID MSB

SPI_OUT(0xDD); //source addr LSB


SPI_OUT(0xDD); //source addr MSB

SPI_OUT('C'); //data
SPI_OUT('I');
SPI_OUT('R');
SPI_OUT('C');
SPI_OUT('U');
SPI_OUT('T');
SPI_OUT(0x20);
SPI_OUT('C');
SPI_OUT('E');
SPI_OUT('L');
SPI_OUT('L');
SPI_OUT('A');
SPI_OUT('R');
CC2420_CSn_1();
Transmit_Frame();
for(timer=0;timer<0xFFFF;++timer)
{
++x;

}
}while(1);
}

MRF24J40 radio card with the new 4. Most of the work is done in
PICDEM Z development kits. firmware. All you really need the PIC
The host microcontroller board, for, in addition to its program execu-
shown in Photo 2, is based on a tion core, is its hardware SPI port and
Microchip Technology PIC18LF4620 interrupt capabilities.
and wired in accordance with Figure The firmware needed to drive the

52 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


within the hardware initialization
portion of the CC2420 driver
firmware. First, the PIC18LF4620’s
CC2420 general-purpose I/O pins are
initialized. Then the PIC18LF4620’s
SPI is initialized. The PIC18LF4620’s
hardware initialization processes con-
sist of configuring general-purpose
I/O pin directions (input/output) and
setting their initial states, which put
the CC2420 into an unselected and
powered-down state. Once the
PIC18LF4620 is configured, you can
turn your attention to initializing the
CC2420’s PHY. That entails several
steps (see Figure 5).
The remaining steps that pertain to
getting the CC2420 ready to receive
and transmit involve selecting a trans-
mit power level and flushing both the
RXFIFO and TXFIFO. The transmit
Photo 3—I am able to do lots of “what ifs” with the CC2420 firmware by using Daintree Networks’s SNA Sniffer as power level is selected according to
a catcher’s mitt. I used this shot to verify the correct transmission of my hand-made IEEE 802.15.4-compliant frame. how much current you wish to add to
your overall current-consumption
budget. In the course of all of this
CC2420 is not complex, but it is a TECH Software PICC-18 C source action, the FIFOP threshold is set to
bit more than I can show in print code on the Circuit Cellar FTP site. 127 and the CC2420 MAC security
form right now. So, I posted the HI- Let’s take a look at what happens feature is disabled.

Figure 4—Any microcontroller with hardware-SPI capability and a good interrupt engine can be inserted into this picture. All you really need is to be able to communicate with
the CC2420 via a SPI and have the ability to manipulate the CC2420’s internal registers and RAM areas.

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 53


The next step in the
CC2420 initialization 1. Issuing a hard CC2420 reset-pin-associated reset
2. Enabling the CC2420’s internal 1.8-V regulator
process involves loading 3. Enable the CC2420’s 16-MHz oscillator via an SXOSCON
address information into command strobe
the CC2420’s address reg- 4. Polling the status byte until X0SC16M_STABLE is set
5. Set modem control registers to:
isters. This is done to
a. Enable address decoding
ensure that the CC2420’s b. Set CCA mode to 1
address recognition c. Enable automatic CRC
engine has valid address- d. Enable automatic ACK generation
e. Set the preamble length for IEEE compliancy
ing information to work
with. CC2420 RAM Figure 5—This is standard stuff. The PHY is very important. Everything
address space is reserved passes through the PHY.
for addresses (16 bits), a
PAN identifier (16-bit
address), and a 64-bit IEEE address. The services of the SPI and the CC2420’s
addressing information is sent to each RXFIFO. I’ve included the receive
of the address-bearing CC2420 RAM interrupt handler details in the
locations with simple SPI transfers. CC2420 driver source code. However,
The operating channel (11) is loaded before I can do the receive firmware
into the FSCTRL register just before testing, I’ve got to build up another
the CC2420 driver firmware sets up host microcontroller board like the one
the capture interrupt, which is multi- you see in Photo 2.
plexed to general-purpose I/O RB3, Once you download the CC2420 driv-
and configures the PIC18LF4620 for er source code, you’ll see that is doesn’t
PORT B interrupt on change. The take very much to get a CC2420-based
final initialization step enables all of transceiver on the air. I’m really begin-
the PIC18LF4620 interrupts. ning to like this pointy hat stuff. With
You really need to make sure you’re the CC2420, RF communication isn’t
sending what you think you’re send- complicated, it’s embedded. I
ing before trying to receive. So,
instead of getting fancy, I kept low to
Fred Eady (fred@edtp.com) has more
the ground and chinked out the code
than 20 years of experience as a sys-
you see in Listing 1. All of the
tems engineer. He has worked with
CC2420 and PIC18LF4620 hardware
computers and communication sys-
initialization code is contained within
tems large and small, simple and
the braces of the CC2420_Enable
complex. His forte is embedded-sys-
function.
tems design and communications.
Rather than bore you with play-by-
play rhetoric, I put my money where
my mouth was and produced the
Daintree Networks’s SNA Sniffer
PROJECT FILES
shot in Photo 3 from the code snip- To download code, go to ftp://ftp.
pet you see in Listing 1. I basically circuitcellar.com/pub/Circuit_Cellar/
hand-assembled an IEEE 802.15.4- 2007/201.
2003 data frame, loaded it into the
CC2420’s TXFIFO, and initiated a
transmit with an STXONCCA com- SOURCES
mand strobe from within the PICC-18 C Compiler
Transmit_Frame function. Since HI-TECH Software
this is a test shot, I decided to www.htsoft.com
demark all of the address fields so
PIC18LF4620 and PICDEM Z
you can see how they would be laid
Development kit
out in the transmission of the frame.
Microchip Technology, Inc.
www.microchip.com
IT TAKES TWO TO TANGO
All that’s left is to test the receive CC2420 Transceiver
firmware, which is nothing more than Texas Instruments, Inc.
an interrupt handler that employs the www.ti.com

54 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


ABOVE THE GROUND PLANE by Ed Nisley

Battery Capacity
Charge
Occasionally, paying attention to datasheet footnotes can make the difference between a
successful charger and a fire hazard. This month, Ed takes a look at why NiCD and NiMH
automatic battery chargers occasionally goof up.

T he battery discharge
characteristics you saw in
voltage reaches a peak
and then decreases slight-
my February column cor- ly after a full charge for
respond directly to gadget both NiCd and NiMH
performance: higher bat- cells. Depending on tem-
tery capacity means perature and the charging
longer run time, higher current, which must be
current means more over about C/2, the
torque, and higher volt- decrease is about 10 to
age means lower current 20 mV/cell for NiCd and
for a given power, unless half that for NiMH. That’s
you’re using throw-away less than a 1% variation,
alkalines. However, so your measurements
recharging those batteries must have sufficient reso-
poses an entirely different Figure 1—NiCd cells have two full-charge indications: voltage drop and temperature rise. lution to unambiguously
set of problems that you This cell’s first charge took such a long time that it would probably fool an automatic charger. detect the peak.
must solve properly to The cell temperature
get maximum battery life at the low- directly affects the cell’s efficiency and increases during charging and rises
est overall cost. longevity. dramatically at full charge, at least for
In this column I’ll explore how Because cells produce a reasonably currents over C/4 in an ordinary shirt-
NiCD and NiMH batteries behave constant voltage during discharge, a sleeve environment. Your charger
during charging, with particular battery’s voltage does not correlate must cease charging when it detects
emphasis on misbehaviors that can well with its remaining charge. It does cell-damaging temperatures, a difficult
fool automatic chargers. In most cases behave some-
chargers work fine, but you’ll see why what more pre-
paying attention to datasheet foot- dictably during
notes can be the difference between a charging, rising
successful charger and a fire hazard. monotonically
as the cell’s
CHARGING BASICS chemistry recov-
NiCd and NiMH cells produce elec- ers. As we’ll see,
trical current from a chemical reac- though, a bat-
tion that liberates electrons. Unlike tery’s terminal
nonrechargeable primary cells, a voltage need not
reverse electrical current reverses that correlate with
reaction by supplying electrons and what’s going on
(more or less) restoring the cell to its within individ-
original condition. Determining exact- ual cells.
Figure 2—NiMH cells display a much smaller voltage drop and a much faster tempera-
ly when that reaction reaches its end- As charging ture increase at full charge.You can see why NiCd chargers are not compatible with
point during charging and discharging continues, the NiMH cells.

56 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


task in extreme envi- rated capacity, starting from
ronments. a completely discharged
All of these effects state. For this 1.6-A⋅h cell,
are, as you’d expect, that’s 1.9 A⋅h, about 2.4 h
directly related to at the C/2 rate. I terminat-
chemical conditions ed the first charge after
inside the cell. The nearly 4 h, far longer than
charging reaction that any automatic charger
absorbs external elec- would allow.
trons is endothermic:
it absorbs heat energy THE HEAT GOES ON
and the cell tempera- Nickel-metal hydride
ture would drop in the cells have a lower voltage
absence of resistive temperature coefficient
losses. That reaction than NiCd cells. This is a
ceases as the cell Figure 3—Charging an eight-cell NiCd pack shows how the pack’s external temperature lags its Good Thing because the
state of charge. For best results, the thermal sensor must be in close contact with the cells.
reaches full charge, the output voltage varies less
cell stops absorbing with temperature, but a Bad
heat, and the temperature begins ris- meter reported voltage drops in the Thing because the end-of-charge volt-
ing. The cell voltage has a negative wiring, while the DVM had a Kelvin age decrease due to cell heating is
temperature coefficient, so it decreas- connection at the cell. much smaller. In fact, some sources
es as the cell heats up. That cell reached a peak voltage just say that you simply cannot (or should
Unfortunately, because the voltage over 1.7 V and simply hung there. The not) depend on the voltage decrease to
depends on temperature, you can’t use power supply meter can’t resolve the terminate the charge. Instead, you
absolute temperature or voltage limits expected 10- to 20-mV decrease, but I must measure the cell temperature
to determine the charge state. What’s was looking for a temperature increase relative to ambient and terminate at a
important is the temperature increase that didn’t happen. specific increase.
over the ambient and the relative volt- The temperature (shown in the The blue traces in Figure 2 show a
age change from the peak. Of course, lower blue trace, with dots) did four-cell 1.1-A⋅h NiMH battery pack
you should take ambient changes into increase, but not as dramatically as I charged at C/1. The final two data points
account, but nearly all chargers expected. Eventually the cell voltage show that the temperature rose nearly
assume that room temperature declined and the temperature began 30°F in 10 min. as the pack passed
remains constant. increasing, so I concluded the cell was through full charge, while the voltage
For the purposes of this column, I’ll as charged as it was going to get and dropped 220 mV, about 50 mV/cell.
be pushing cells well past full charge proceeded to test it. As you saw last Cell temperatures exceeding 120°F
to show what happens. Don’t try this time, it recovered completely. or 50°C reduce the battery’s useful
with cells you care about! The other traces show that it lifetime, so this is as hot as it should
behaved normally during successive ever get. However, because I taped the
NEAR-DEATH EXPERIENCE charges, with 20-mV voltage decreases thermocouple to the outside of the
In my last column I showed the last that correspond
gasp of a 10-cell NiCd battery. The with the abrupt
pack’s integrated charger was unable temperature
to fully recharge the weakest cell, increases at full
which suffered reverse charging, while charge. The
the rest of the pack discharged. That peak on the red
cell wasn’t permanently damaged, curve shows the
most likely because I caught the prob- effect of charg-
lem and didn’t further abuse it. I ing at C/1; you
extracted the two weak cells for fur- can see the need
ther testing. for temperature
The blue traces in Figure 1 show monitoring and
the weakest cell’s first recharge. I did- a high-temp
n’t expect what was about to happen, cutout.
so I began recording the cell voltage Note that full
directly from the power supply’s charge occurs
Figure 4—Well-matched cells charge nicely together and the pack voltage represents
meter and only later used a DVM for after the cell has
the individual cell charge state reasonably well. Because my four-channel data logger
higher resolution. The top two traces absorbed about has 20-mV resolution, I eliminated the jitter in the single-cell traces with Gnuplot’s Bezi-
don’t overlap because the supply’s 120% of its er smoothing.

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 57


pack, the internal tempera- before delivering enough
ture was certainly too high! charging current.
A charger designed to Figure 3 gives a better
terminate at a drop of 10 picture of the relation
mV/cell would have between charging cur-
caught this pack before rent, voltage drop, and
the temperature rose temperature increase,
quite so high. A charger using the eight best cells
that depends only on of that 10-cell NiCd pack
time would severely dam- in their original waterproof
age this pack, because it plastic container. I taped
started from a half- the thermocouple to the
charged state. outside of the pack, where
The purple traces in it was insulated from the
Figure 2 show why volt- cells by both an internal
Figure 5—I discharged Cell 4 more than the others in this pack to show the eventual effect
age monitoring generally of automatic under-charging. Terminating the charge based on pack voltage or temperature air gap and a few millime-
doesn’t work for NiMH will always under-charge that cell, further weakening it. The thermocouples indicate individ- ters of plastic.
cells, even though these ual cell temperatures. The C/2 charge, shown
cells seemed to have a in blue, heats the pack
nice voltage drop. temperature. slowly enough that the temperature
I charged three hulking 9-A⋅h NiMH Charging the cells at C/2 would passes through 90°F just as the volt-
D cells in series at 3 A, a C/3 rate that increase the voltage drop, but it’s age drops. The C/1 charge, however,
is the most my constant-current obvious that the drop depends on fac- is well past full before the heat reach-
charger can manage. The overall volt- tors that aren’t completely under es the thermocouple: it’s heating at
age dropped 10 mV, only 3 mV/cell, your control. Your charger must about twice the rate, so the external
while the temperature increased detect the temperature rise and ter- temperature lags the charge state by a
through the same 30°F. In this case, minate charging soon enough to pre- greater margin. The temperature will
the thermocouple read the actual cell vent damage, while not terminating rise even faster under fault condi-

58 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


tions, which emphasizes the need for The raw data behind Figure 4 shows one dead cell in each.
much closer thermal contact than that all four cells have, indeed,
you see here. reached full charge when the pack’s CONTACT RELEASE
voltage reached the plateau. Figure 5 I used a power supply with manually
PACK MATCHING in the February column showed that’s controlled voltage and current regula-
Low-voltage circuitry allows many not always the case, though, with one tion to produce the data for this col-
low-power devices to run from a single cell lagging far behind the others. umn. This type of supply is particularly
alkaline or NiMH cell. High-power This month’s Figure 5 shows what well suited to NiCd and NiMH charg-
devices generally require several cells happens inside a deliberately sabo- ing because both chemistries respond
in series in a pack, but, inevitably, one taged four-cell pack undergoing a mod- well to constant-current charging.
cell must be weaker than the others. erate charge. I drained the pack by a However, I had to closely monitor the
There’s also one cell that’s stronger quarter of its nominal capacity, dis- charging process to terminate it at the
than the others, but that’s never a charged Cell 4 almost completely, and right moment (or a bit later!) and
problem! then charged the pack at C/3 while ensure nothing went wrong.
Figure 4 shows a quartet of new 2.5- monitoring all four-cell voltages and One pack, alas, got away from me.
A⋅h NiMH AA cells charging at C/4. the temperatures for Cells 1 and 4. The power supply turns on in con-
The overall pack voltage (in red, right As expected, after charging for 35% of stant-voltage mode with the current
y-axis) accurately indicates the overall capacity, Cells 1 through 3 are fully limited to 3.0 A, after which a button
charge state of all four cells (various charged, as shown by the flattening pack press activates constant-current
colors, left y-axis). I didn’t record the voltage (red trace) and Cell 1’s rapidly mode at the preset value. I set a C/1
temperatures during this cycle, but the increasing temperature (blue trace). I rate of 650 mA, set my PDA to beep
C/4 rate just barely warmed them up then disconnected the fully charged cells in half an hour, and went off to do
by the time I reduced the current to and continued charging Cell 4 at the other things. Some time later the
C/10. same rate. All that fiddling caused the utility power blinked and reset the
I used a four-channel, ±10-V data blips in Cell 4’s purple trace. supply to 3 A.
logger with 10-bit (20-mV) resolution Also as expected, Cell 4 required As you might expect, ramming 3 A
and subtracted to find the differential twice as much energy to become into a 650-mA⋅h battery pack causes
voltage across each cell. That means fully charged, at which point I both quick charging and severe over-
the traces have up to 40-mV jitter due switched to a C/10 trickle. Notice heating. I caught this one in time, but
to sampling error alone, so I applied that the fully charged voltage for this I now charge the cells on a ceramic
Gnuplot’s Bezier smoothing to those cell is much higher than the others, tile and run the charging supply from
four traces. The unsmoothed pack which indicates that it’s not in such a UPS. Charge safely! I
voltage has a larger scale that sup- good condition; it had been showing
presses the small variations. signs of weakness in my earlier tests, Ed Nisley is an EE and author in Pough-
The two vertical red lines indicate which is why I picked it for this mis- keepsie, NY. Contact him at
times when an automatic charger might treatment. ed.nisley@ieee.org with “Circuit Cellar”
reasonably stop charging based on volt- An automatic charger that would in the subject to avoid spam filters.
age readings. The first marks the start have terminated the charge at one of
of the upper voltage plateau, after the the times shows the red and blue ver- PROJECT FILES
final steep increase. The second marks tical lines: voltage plateau, voltage
the voltage drop after the peak. drop, or temperature rise. At that To download graphs, gnuplot scripts,
In retrospect, those times are easy to point, Cell 4 was only half-charged, so etc., go to ftp://ftp.circuitcellar.com/
identify while looking at the graph. it would have gone into reverse charg- pub/Circuit_Cellar/2007/201.
An automatic charger must interpret ing during the next discharge and
charging’s signs and portents in real- accumulated further damage. RESOURCES
time running without any look ahead, As nearly as I can tell, this is what Battery protection,
which poses a significant challenge. kills most packs: the weakest cell suf- www.mpoweruk.com/protection.htm
The plateau in Figure 4 lasts about fers consistently under- and reverse-
7% of nominal capacity: 17 min. at charging, which makes it even weak- Charging overview, www.buchmann.
C/4, 8 min. at C/2, and just 4 min. at er, which eventually renders the pack ca/article18-page1.asp
C for these cells. A typical fast charger useless.
samples the battery voltage every For example, one of my amateur GnuPlot, http://gnuplot.info
minute or two and, when the differ- radio HTs has a fixed low-voltage cut- Logging with Dataq DI-194,
ence between two successive samples off that works fine for its standard users.sdsc.edu/~hubbard/neesgrid/
indicates a plateau or a decline, it ter- four-cell packs, but severely over-dis- dataq/index.html
minates the charge. If all the cells charges its eight-cell “high-power”
have reached full charge at that time, packs. Despite my best efforts, I’m the Radio Shack 22-182 DMM,
the charger has done its job. proud owner of two 9.6-V packs with www.home.pages.at/linux/

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 59


FEATURE ARTICLE by Aubrey Kagan

Generic Modbus Simulator (Part 2)


Create a Modbus Master Using Visual Basic 2005
This month, Aubrey continues with the topic of a Modbus implementation on a PC. He cov-
ers creating the user interface to realize communication with Modbus slave units.

I hope I managed to whet your


appetite last month when I introduced
order to allow Visual Basic to achieve
early binding (discussed in my previ-
driven. The easy way to follow the
project is to right click on a control in
the topic of a Modbus implementation ous article) with Excel. In technical the user form and review the proper-
on a PC. To date, I have covered the terms, this is called adding an automa- ties. Double clicking on the control
Modbus protocol and an approach to tion client. In Visual Basic, open or mostly will take you to the associated
documenting the register set of a Mod- create a project, and then click Project code. (I don’t intend to discuss every
bus slave and even a family of Modbus and Add References. Next, click the control since the topic is dry enough. I
slaves in Microsoft Excel. This month, COM tab. Scroll down until you see will point out only matters that you
I will show you how to use that infor- the Microsoft Excel x.x object library. may find interesting.)
mation to create a Modbus master on Select the latest one (I used 9.0) and
a PC. The software for the Modbus click OK. This will be fine if you are SERIAL PORT PARAMETERS
master is written in Visual Basic 2005 not working with my project. If you are The user interface is a tab control
Express, which I described in my arti- going to open this project, you will with three tabs (see Photo 1). The
cle “Visual Basic 2005 and the Serial probably end up with an error message, Settings tab is based on the serial
Port,” (Circuit Cellar 197, 2006). so here is what you should do. First, port parameter selection and was
I created a generic interface to allow load this project. Next, click Project described in my article on Visual
for access to any Modbus slave via an Modbus and Test Properties. Then Basic and the serial port. The major
Excel workbook as the container of click the References tab. In the Refer- difference is that when the applica-
the register set in each slave. My ences window, select the Excel and tion loads, it checks to see if there is
application extracts the information Office Object Library entries and then a file that contains the stored param-
stored in the Excel workbook, presents click Remove. Then add the automa- eters. Listing 1 is added to the
it on a user interface, formats it, and tion client as above. Form1.Load event.
sends and receives Modbus messages. Documenting a Visual Basic project The file save is initiated when you
The entire application is written in is quite difficult because it is all event click on any of the other two tabs.
Visual Basic Express. That is when it leaves the
Settings tab. The code in
USER INTERFACE Listing 2 is placed in the
Despite the fact that tabSettings.Leave
Visual Basic 2005 Express event.
is available for free and is
very easy to use, it is an FILE LOAD
incredibly powerful pro- The user needs to select
gramming environment.[1] an Excel worksheet, open
Of course, nothing is per- it, and access the informa-
fect, so you can imagine tion that it contains. This
that there are flaws, some is initiated from the File
of which I will point out. Selection tab in Photo 2.
This is in addition to the In order to use the gener-
shortcomings that I cov- ic access to files, you must
ered in my article on the have the OpenFileDialog
Photo 1— The Settings tab shows the parameters that can be modified on the serial
serial port. control that you dragged
port when the application is run. Except for the port selection, the other boxes have to be
First, you need to do enabled in order to change the values. This is done by clicking on the Parameter Change from the toolbox and
some housekeeping in button and entering “password.” dropped on the user form.

60 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


Clicking on the Load File button triggers Listing 1—This code is added to load serial port settings from a file that is stored in the same directory as
the code in Listing 3. You may have the application. If it fails (i.e., the file does not exist), it forces the user to the Setup tab to review the default
noted that the file name in Listing 2 is settings.
also stored with the serial port param-
sPath = Application.StartupPath & "\mod.cfg"
eters so the last accessed file name is
'start in the same directory as the application
restored when the application is rerun. Try
sLines = System.IO.File.ReadAllLines(sPath)
LOADING FROM EXCEL sJigPort = sLines(0)
sJigBaud = sLines(1)
In this application, a new instance
sJigBit = sLines(2)
of the Excel file is opened, even if an sJigStop = sLines(3)
instance is already open. It does not sJigParity = sLines(4)
pay attention to any subsequent Target.sFileString = sLines(5)
changes to the file. Although it is ListBox1.Text = sJigPort
lstJigParity.Text = sJigParity
open, it is invisible, and you have no
lstJigData.Text = sJigBit
visible knowledge that the file or lstJigBaud.Text = sJigBaud
application is running. GenerateJustFileName()
In Listing 4, the worksheet names, Me.SelfTest.SelectedTab = tabFileSelection
which we decided would be the OpenPorts()
Catch ex As Exception
product names, are loaded into the
'failed to open file
lstWorksheetSelect list box and MsgBox(ex.Message & vbCrLf & "Please set up parameters", _
sets the default selection to the first MsgBoxStyle.Exclamation, "First Time Setup")
worksheet. The selection of this work- Me.SelfTest.SelectedTab = tabSettings
'force to settings tab
sheet in the code, and any subsequent
End Try
selection of any worksheet, will exe-
cute the code in Listing 5.
Let me pause for a moment and
return to a few details about Excel, or well. It stands to reason that program- tional transformation to a string. The
rather Visual Basic within Excel. matically the cells approach would be irony is that in the Visual Basic Excel
Accessing a cell from Visual Basic easier. I have no idea if it was Visual help file (GetObject Function),
code can be done in two ways. You Basic 2005, Excel 2002, or that I didn’t Microsoft explicitly frowns upon
can use the range method that quite create the right object (although doing it this way. But for me, it was
involves accessing a string (e.g., Range I suspect the latter), but I could not the only way that worked.
(“B5”)). There is a second technique get the cells method to be exposed. As Loading the profile names to the
using the cells method, where the two a result, all the arithmetic manipula- lstProfileItems list box can be
parameters refer to the row and col- tions that had to be done to access a seen in Listing 6. It will give you a
umn. Cells (5,2) refer to cell B5 as particular cell had to undergo an addi- taste of the string manipulation that I
am talking about.
The listing for LoadAddresses
FromExcel is rather long and boring.
If you have managed to read to this
point, I am sure you have opened the
Visual Basic project where you can see
it in all its glory. It only differs from
Listing 6 in that it reads two columns
and merges them to create a line includ-
ing the address and the location name.
It also looks for blank addresses. If it
finds them, it inserts a line of dashes to
indicate the compression. This list box
is the heart of all the actions and infor-
mation in it is used in a number of pro-
cedures and in the interchanges with
Excel. I decided to centralize the infor-
mation by creating a class (see Listing 7).
It is instantiated as an object named
User. Two look-up tables allow for a
Photo 2—To access an Excel file, click on the Load File button. Using the standard OpenFileDialog, locate the speedy cross-reference between Excel
desired file. Note the COM and Dialog controls that have been placed on the form. and the application. They are stored in

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 61


two arrays, iExcelToIndex() and Listing 2—Write serial port parameters to a file when leaving the Settings tab. Note that in order to change the
iIndexToExcel(), which cross-refer- parameters, you need to enable the associated boxes using the EnableParameters procedure, which
ence the line index in the lstAddrEnvir requires a password: “password.” Not very original! Every time the Settings tab is selected, the boxes will be
initially disabled.
list box to the rows in the Excel work-
sheet. I will discuss the other mem- Private Sub TabPage5_Leave(ByVal sender As Object, _
bers of the class in due time. ByVal e As System.EventArgs) Handles tabSettings.Leave
'updating the parameters to the new settings
sJigPort = ListBox1.Text
THE APPLICATION USER INTERFACE sJigBaud = lstJigBaud.Text
In order to access a Modbus location sJigBit = lstJigData.Text
sJigStop = lstJigStop.Text
once the Modbus device has been select- sJigParity = lstJigParity.Text
ed (by selecting the worksheet), you WriteConfigurationFile()
need to decide several things. You 'write to file
OpenPorts()
must decide whether you want a single End Sub
or multiple location access, the start Public Sub WriteConfigurationFile()
address in either event, and the num- Dim sPath As String
Dim sLines(NUMBER_OF_PARAMETERS) As String
ber of locations in the latter case. Two
sPath = Application.StartupPath & "\mod.cfg"
radio buttons allow for single or multi- sLines(0) = sJigPort
ple selections. The rest of the choices sLines(1) = sJigBaud
sLines(2) = sJigBit
are handled in the list box with the
sLines(3) = sJigStop
location names and addresses. sLines(4) = sJigParity
Despite similarity in appearance to sLines(5) = Target.sFileString
Windows controls, I found that the System.IO.File.WriteAllLines(sPath, sLines)
End Sub
list box control lacks the methods to Private Sub TabPage5_Enter(ByVal sender As Object, _
do certain things that appear to be ByVal e As System.EventArgs) Handles tabSettings.Enter DisableParameters()
standard in Windows. My original ClosePorts()
End Sub
intention was to click on an address Sub DisableParameters()
and then Shift-click on the end lstJigBaud.Enabled = False
address so all the lines would be lstJigData.Enabled = False
lstJigParity.Enabled = False
selected. It may be possible to do, but lstJigStop.Enabled = False
you will see that it and other desirable End Sub
features (at least to my way of think- Sub EnableParameters()
lstJigBaud.Enabled = True
ing) are not built in. For instance, I am lstJigData.Enabled = True
still not sure how to change the font lstJigParity.Enabled = True
and color of a sub string within an lstJigStop.Enabled = True
End Sub
entry. Modifying a line requires you to
read back the line, delete it, and re-
insert the modified line. Changing the
color of individual lines requires you Listing 3—Find a file using the generic OpenFile procedure. Only the file name (without path) is displayed
in the list box.
to write a handler that runs each time
the list box is redrawn. Enough of the Private Sub Button1_Click(ByVal sender As System.Object, _
griping, let’s see how I tackled this. ByVal e As System.EventArgs) Handles btnLoadFile.Click
I decided that right-clicking in the OpenFileDialog1.InitialDirectory = Application.StartupPath
OpenFileDialog1.Title = "Select an Excel file..."
lstAddrEnvir list box and choosing OpenFileDialog1.Filter = "Excel files | *.xls"
from a drop-down menu would realize OpenFileDialog1.FilterIndex = 1
most of the control I wanted. I first OpenFileDialog1.FileName = ""
If OpenFileDialog1.ShowDialog() <> Windows.Forms.DialogResult.Cancel Then
needed to drag a ContextMenuStrip Target.sFileString = OpenFileDialog1.FileName
control from the toolbox, drop it on 'create file name without path for display
the form , and name it. The next step GenerateJustFileName()
Else
was to bind the menu control to the
txtLoadedFile.Text = ""
associated list box. In the properties End If
for the lstAddrEnvir list box, I End Sub
inserted the name of the menu control Public Sub GenerateJustFileName()
Dim iI As Integer
in the ContextMenuStrip property. I Dim iJ As Integer
then added the following options to iI = InStrRev(Target.sFileString, "\")
the menu: Set Start Address, Set End iJ = Microsoft.VisualBasic.Len(Target.sFileString)
txtLoadedFile.Text = _
Address, Clear All Addresses, Clear
Microsoft.VisualBasic.Right(Target.sFileString, iJ - iI)
All Data, and Set Data. Each one of End Sub
these leads to associated code. The Set

62 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


Turn Digital Power
into Real Power
The Microchip name and logo, the Microchip logo and dsPIC are registered trademarks of Microchip Technology Incorporated in the USA and in other countries. dsPICDEM is a trademark of Microchip Technology Incorporated in the U.S.A. and other countries.
© 2007 Microchip Technology Incorporated. All rights reserved.

Looking to bring the benefits of digital power conversion – including higher


power density, lower cost features and accelerated innovation – to your product?
Microchip’s dsPIC®Digital Signal Controllers (DSCs) for Switch Mode Power Supplies (SMPS) and digital power
conversion are designed for applications in AC/DC power supplies, power factor correction, DC/DC converters,
uninterruptible power supplies, power inverters, digital lighting and advanced battery chargers.

GOING DIGITAL THE EASY WAY!


1. Educate yourself
Purchase and program your
16-bit dsPIC® DSCs
microchip
Learn the technical aspects of digital power
conversion and SMPS design with hands-
and related development tools at.... DIRECT
www.microchipdirect.com

on training and FREE web seminars from High


Microchip. 10-bit, Speed Analog
Flash 2 MSPS PWM Compar-
2. Accelerate your development Device Pins (KB) (CH) (CH) ators
Speed up your design
dsPIC30F1010 28 6 6 4 2
time with tools targeting
digital power such as dsPIC30F2020 28 12 8 8 4
the dsPICDEM™ Buck dsPIC30F2023 44 12 12 8 4
Development Board.
Visit our web site for more information about additional
3. Win stuff in our Digital Power Contest 16-bit devices supporting power conversion!
Visit our web site and get coupons for
discounted development tools when you
REGISTER TO WIN a dsPIC DSC SMPS
Development System. We are also giving
away an Apple® iPod® mobile digital media
player to one lucky winner! Visit our web site
for complete contest information.

w ww.microchip.com/SMPS

Microcontrollers • Digital Signal Controllers • Analog • Serial EEPROMs


Start Address option is Aside from load-
self explanatory, setting ing profiles, as we
the User.iStart saw earlier, it is also
AddressIndex and possible to insert
User.bStartSetUp values to be written
variables. The Set End to a register. The Set
Address acts similarly, Data brings up an
but it is only needed for Inbox to enter
multiple register access- numerical data.
es. Obviously, the Clear When this is
All Addresses resets the entered, the selected
above settings. There line must be updated
are, of course, checks to by reading, deleting,
make sure that the start and inserting, as I
address precedes the complained about
end address, that the earlier. The Clear All
grouping is only of like Data goes through all
registers, and so on. the lines clearing all
The normal color of data, whether it was
the text in the user box set by the Load Pro-
is orange, which shows Photo 3—Take a look at the construction details of the tab. files, Set Data, or
up well against the dark even data read back
blue of the reverse video selection indi- line up. To achieve the color change, I from a Modbus slave. It too must go
cator. The color of the text of any line needed to change the DrawMode prop- through the same update procedure.
selected between the start and end erty of the lstAddrEnvir list box to
address is turned to red. I also chose OwnerDrawFixed. Look at the MODBUS
the Courier font to ensure equal spac- lstAddrEnvir_DrawItem procedure I have now come full circle. Let’s
ing of any character so that the entries to see the code that is needed. take a look at the interactions over

64 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


the serial port. Clicking on Write To created. I daresay that it is possible to unpack (in bitReadMultipleBits)
Location starts a process that fetches create a single function that handles the bit format into bytes and to gen-
the function codes to be used from the all the write functions and the read erate the CRC (done in the function
Excel worksheet (from columns G, H, functions, but I decided to be modern cGenerateChecksum). As an aside,
and I). It also makes sure that the loca- for once in my life and I didn’t care you may have already noted a num-
tions can be modified by testing that about the amount of memory that it ber of modifications and additions to
the function code is applicable. The would chew up. Please forgive my lack the Visual Basic language that resem-
data to be written to the slave is of programming elegance. ble C. At long last, it is possible to
extracted from the lstAddrEnvir dis- Creating the message to send as the shift/rotate data instead of multiply-
play. If there is no entry, the data master is trivial. Simply fetch the ing or dividing by two. The notation
value is set to zero. For digital (coil) required information and plug it into is identical in both languages using
outputs, any nonzero value will be the frame format described in Part 1 of the “<< “ and “>>” symbols.
sent as a set command. Depending on this series of articles (Circuit Cellar Once the actual message has been
the decision to access single or multi- 200, 2007). The only pause is to pack created, it is written to the Tx text
ple locations, different messages are (in boolControlMultipleBits) and box at the bottom of the form before
it is transmitted from the serial port.
Once the frame has been sent, the
Listing 4—When the user clicks on the Modbus tab, the file selected in the OpenFile dialog is opened as an process starts the bytReceiveMod-
Excel application. When the Modbus tab is deselected by selecting another tab, the Excel application is termi-
nated. Note how to create the different objects to access Excel.
bus function that waits for the
return message. Modbus uses vari-
Private Sub tabModbus_Enter(ByVal sender As Object, _ able-length messages, so the software
ByVal e As System.EventArgs) Handles tabModbus.Enter has to dynamically extract the mes-
StartExcelApplication()
ClearModbusMessages()
sage length from the frame as it is
End Sub received. The function returns an
Public Sub StartExcelApplication() array where the first byte contains
Dim iI As Integer the status, as you can see in the
Dim iNumberOfSheets As Integer comments in Listing 8. Although I
Dim sSheetName(100) As String
could have put the CRC check in
Target.oXL = CType(CreateObject("Excel.Application"), Excel.Application)
this function, I chose not to because
Target.oWB = Target.oXL.Workbooks.Open(Target.sFileString, , True)
For iI = 1 To 100 I wanted the whole stream to be
'finding the number iof sheets and their names returned so that it could be reported
Try to the Rx text box on the user inter-
Target.oSheet = Target.oWB.Worksheets(iI)
face. My concept was that this should
sSheetName(iI - 1) = Target.oSheet.Name
Catch ex As Exception be updated outside of the byte-recep-
Exit For tion function.
End Try Once the software process returns
Next
from the byte-receive function, the
iNumberOfSheets = iI – 1
'using this information to create options in a list box datastream is written to the Rx box.
For iI = 0 To iNumberOfSheets - 1 Next, the process checks for an error
lstWorksheetSelect.Items.Add(sSheetName(iI)) return in the first byte of the array
Next
and then it checks to see if the CRC
'select the first one
lstWorksheetSelect.Text = sSheetName(0) of the message is consistent with the
Target.oSheet = Target.oWB.Worksheets(1) expected value. Several other checks
'index of ssheetname and worksheets are offset by 1 may also be done on the byte stream,
Target.oSheet.Activate()
depending on the function being per-
ClearUserSettings()
End Sub formed. The analysis of all these
Public Sub EndExcelApplication() checks is presented as Label 7 at the
Target.oXL.Workbooks.Close() bottom of the form. These could
Target.oXL.Workbooks.Application.Quit() include messages, such as “Response
Target.oRng = Nothing
received correctly” or “CRC error
Target.oSheet = Nothing
Target.oWB = Nothing detected,” to help with the under-
Target.oXL = Nothing standing of the Modbus interaction
ClearUserSettings() since this application is intended to
End Sub
be a development tool. If there is
Private Sub tabModbus_Leave(ByVal sender As Object, _
returned data, it is then updated in
ByVal e As System.EventArgs) Handles tabModbus.Leave
EndExcelApplication() the associated data field in the
End Sub lstAddrEnvir list box overwriting
any data that may have been there

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 67


from reads or preset data. by Visual Basic, and an external serial Aubrey Kagan (antediluvian@sympatico.
protocol, the Modbus. Convergence ca) is a professional engineer with a
PUBLISHING THE PROJECT with a vengeance! I hope this series B.S.E.E. from the Technion—Israel Insti-
Creating an executable to run out- has proved informative. I tute of Technology and an M.B.A. from
side of the Visual Basic environment
is termed “publishing,” and it is sim-
Listing 5—This code is run any time the Excel worksheet selection is changed by clicking on an item in the
ple in the extreme, both to generate lstWorksheetSelect box. It calls the LoadAddressesFromExcel procedure, which fetches
and to install. First, you need to set the addresses, compresses, and displays them in the lstAddrEnvir box, which is shown in Photo 3. It
the project properties, especially the also loads the profiles to the lstProfile box.
assembly information under the
Private Sub lstWorksheetSelect_SelectedIndexChanged _
Application tab. This sets up the revi- (ByVal sender As System.Object, ByVal e As System.EventArgs) _
sion and copyright details. You may Handles lstWorksheetSelect.SelectedIndexChanged
notice an option to set the “splash Dim iI As Integer
screen.” Depending on your operating iI = lstWorksheetSelect.SelectedIndex
'iI = lstWorksheetSelect.SelectedItem
system and some other details, the Target.oSheet = Target.oWB.Worksheets(iI + 1)
splash (start-up) screen option may 'index of ssheetname and worksheets are offset by 1
create run-time errors. It certainly did Target.oSheet.Activate()
on mine (with Microsoft acknowledg- LoadAddressesFromExcel()
LoadProfileNames()
ing the problem), so I will hold off on lstAddrEnvir.Focus() 'make sure that if the scroll
even trying to describe the process. 'button is the next control after setting the page,
You then click on Build, Publish Pro- 'the page selection does not scroll.
jectName, and follow the prompts in radMultiple.Checked = True'set by default to multiple addresses
ClearUserSettings()
the Publish wizard. Then, publish it to ClearModbusMessages()
a CD-ROM. Create a folder and the End Sub
application will be placed in the fold-
er. Distribution of the application
merely involves transferring this fold- Listing 6—Initially, iTemp gets the number of profiles from the location D5 on the active sheet. The active
sheet was set in Listing 5. The procedure then accesses row 7 column by column, starting at column J. It does
er. A setup.exe file is in the folder
this by converting the ASCII representation of J to an integer Asc “J,” adds an offset to it, converts it back
that you can rename to any other to ASCII, and then concatenates it with row “7” to create the variable sString. sString is then used as
name, with an .exe file extender. the parameter in the Range method. CStr casts the value returned from Excel to a string to add as an item in
Installation is very simple. Copy the the list box.
folder to wherever you want it and
Private Sub LoadProfileNames()
double click on the setup.exe (or its Dim iI As Integer
new name) file. The first time you do Dim sString As String
this it will be installed to your startup Dim iTemp As Integer
menu and the program will run. In 'first clear the entries
this application, you will see the error lstProfile.Items.Clear()
message that there is no set-up file iTemp = Target.oSheet.Range("D5").Value
If iTemp <> 0 Then
and one must be created. All of the
For iI = 0 To iTemp - 1 'NUMBER_OF_PROFILES - 1
subdirectories are hidden within the 'create a string incluidng address of cell
folder. It is possible to run the applica- sString = Chr(Asc("J") + iI) & "7" 'creating string j, k, l...
tion at any time after that by double lstProfile.Items.Add(CStr(Target.oSheet.Range(sString).Value))
Next iI
clicking the self-same file or by using
lstProfile.SetSelected(0, True) 'by default set the first
the entry on the Start menu. Of End If
course, you could copy a shortcut End Sub
onto the desktop.
Uninstalling is a cinch. Use the Listing 7—The UserSelection class is instantiated as the object User, using a dim statement at the
uninstall option. Go to My Computer, start of the Form1 class (see the project itself).
Control Panel, and then Add/Remove
Programs. Public Class UserSelection
Public bStartSetUp As Boolean
Public bEndSetUp As Boolean
CONVERGENCE Public iStartAddressIndex As Integer
In this series of articles, I covered Public iStopAddressIndex As Integer
many aspects of electrical engineering: Public iExcelToIndex() As Integer
'should allow for quick lookup from one to the other
hardware and hardware interfacing 'especially since there are lines of --- which could cause a problem
through the serial port, an approach to Public iIndexToExcel() As Integer
operating Excel as an external object, End Class
the programming environment created

68 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


the University of the Witwatersrand. articles for Circuit Cellar and having
PROJECT FILES
He works at Emphatec, a Toronto- ideas published in other periodicals,
based design house of industrial-con- Aubrey wrote Excel by Example: A To download the code, go to ftp://ftp.
trol interfaces and switch-mode power Microsoft Excel Cookbook for Electron- circuitcellar.com/pub/Circuit_Cellar
supplies. In addition to writing several ics Engineers (Newnes, 2004). /2007/201.

Listing 8—The byte reception is modified from the original code in my first article. The number of bytes expect- REFERENCE
ed depends initially on the received function code (including the Modbus exception). In some cases, the num-
ber of bytes is explicitly embedded in the message and must be extracted. [1] Microsoft Corp., “The Microsoft
Developer Network,” 2006,
Function bytReceiveModbus _
(ByVal bySentAddress As Byte) As Array
http://msdn.microsoft.com/
'start timer vstudio/express/vb.
Dim iRx(255) As Byte
Dim iI As Integer = 0
Dim iNumberOfBytes = 250 RESOURCES
bTimeout = False
Timer1.Interval = 1000 '1 sec delay F. Balena, Programming Microsoft
Timer1.Start() Visual Basic 2005: The Language,
iRx(0) = 0 'set return flag for OK Microsoft Press, 2006.
'on return
'if iRx(0)=0 ->OK J. Foxall, Visual Basic 2005 in 24
'if iRx(0)=1 ->Timeout Hours, SAMS Publishing, 2006.
'if iRx(0)=2 ->Modbus error
'if iRx(0)=3 ->Address mismatch
M. Halvorson, Microsoft Visual Basic
While (iI < iNumberOfBytes) And (bTimeout = False) 2005 Step by Step, Microsoft Press,
'so don't overflow buffer
2006.
'only while timing out
Application.DoEvents() Microsoft Corp., “How to Automate
If SerialPort1.BytesToRead > 0 Then
iRx(iI + 1) = SerialPort1.ReadByte Microsoft Excel from Visual Basic .NET,”
'now checking on the numebr of bytes 301982, http://support.microsoft.com/kb
If iI = 1 Then /301982.
'this is the 2nd byte-> if bit 8 is set then fault
'and length is 5
———, “How to Transfer Data to an
If (iRx(2) And &H80) = &H80 Then
iNumberOfBytes = 5 Excel Workbook Using Visual Basic
iRx(0) = 2 .NET,” 306022, http://support.microsoft.
End If com/kb/306022.
End If
If (iI = 2) And ((iRx(2) And &H80) = 0) Then
'no error, and enough bytes to get number of bytes ———, “How to Use MFC to Auto-
Select Case iRx(2) mate Excel 2000 and Excel 2002 and
Case 5, 6, 15, 16 Obtain an Array From a Range in
iNumberOfBytes = 8
Excel 2000 and Excel 2002,” 186122,
Case 1, 2, 3, 4, 12, 17, 23
iNumberOfBytes = iRx(3) + (5) http://support.microsoft.com/kb/186122.
Case 7
iNumberOfBytes = 5 Modbus-IDA, “MODBUS Over Serial
Case 11
iNumberOfBytes = 8 Line, Specification & Implementation
Case Else '8 Guide V1.1,” 2002, www.modbus.org/
End Select docs/Modbus_over_serial_line_V1.pdf.
End If
iI = iI + 1
———, “MODBUS Application Proto-
End If
End While col Specification V1.1a,” 2004, www.
If bTimeout = True Then modbus.org/docs/Modbus_Application
iRx(0) = 1 _Protocol_V1_1a.pdf.
iI = 0
Else
If (iRx(1) <> bySentAddress) Then ———, “Modicon Modbus Protocol
iRx(0) = 3 'use address as fault indicator Reference Guide Rev J,” PI-MBUS-
iI = 0 300, 1996, www.modbus.org/docs/PI_
End If
MBUS_300.pdf.
End If
ReDim Preserve iRx(iI)
bytReceiveModbus = iRx P. Pelland, Build a Program Now!
End Function Microsoft Visual Basic 2005 Express
Edition, Microsoft Press, 2006.

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 69


FROM THE BENCH by Jeff Bachiochi

Local Interconnect Network


Instead of a controller area network (CAN), try a local interconnect network (LIN) the next
time you need to control a limited area within a machine. Jeff gets you working with a low-
cost LIN system.

I n an attempt to steer my focus back


toward an exploration of electric vehi-
will be true, the LIN consortium was
formed in 2000 to oversee the stan-
node capability file (NCF) that can be
used with a plug-and-play tool to auto-
cles and their subsystems, I want to dardization of this serial low-cost matically create an LDF.
start investigating a communication communication concept, including a Prior to the release of V2.0, there
medium that’s becoming popular in development environment. Original was little flexibility in the slave node.
the automotive world: the local inter- members include Audi, BMW, Daim- Each slave was hard-coded with its
connect network (LIN) bus. Although lerChrysler, Volvo, and Volkswagen, choice of identity. You can imagine
the LIN is thought of as a lower-band- along with communications specialist that with a limited number of identi-
width medium, it seems plenty ade- Volcano Communications Technolo- fiers (60), it wouldn’t take long for
quate for my project. This column gies and the semiconductor manufac- someone to use two nodes pro-
will cover uses of the LIN in distrib- turer Motorola. grammed with identical identifiers.
uted control. My plan involves a small The open-standard LIN specification Even though a master node is in
cluster of LIN modules, consisting of a package (V2.0) consists of several charge, there was little it could do
master and at least two slaves at this parts. The LIN’s physical layer specifi- before V2.0 about slaves with conflict-
point. cation describes the physical layer, ing NADs or message_IDs.
LIN is used as a low-cost and low- including the bit rate, clock toler- The consortium’s steering group
end solution for distributed control in ances, etc. The LIN protocol specifica- solved many shortcomings in the previ-
the automotive industry (see Figure 1). tion describes the data-link layer of ous release by designating a develop-
Its UART-based single-wire bus is the LIN. The LIN diagnostic and con- ment workflow that not only included
about as simple as it gets. LIN is not figuration specifications describe the input from slave nodes (NCF), but also
meant to be a replacement for the con- service that can be layered on top of allowed conflicts to be mediated prior to
troller area network (CAN), but it’s an the data-link layer to provide diagnos- assembly of the cluster (LPF). With this
alternative where requirements are not tic messages and node configuration. release, nodes must be reconfigurable
as stringent. LIN’s bandwidth is present- The LIN API specification describes (i.e., it gets its frame identifiers assigned
ly limited to approximately 20 kbps. It the interface between the network and by the master node according to the
is often used within a specific area, the application program, including the LPF). The block diagram in Figure 2
such as a door assembly. While a man- diagnostic module. The LIN configura- shows how the cluster design phase
ufacturer might use a CAN bus to tion language specification describes uses all NCFs to create the LDF. The
connect various components of an the format of the LIN descriptor file master is created from the LDF and
automobile, it may make more sense (LDF). The LDF is used to configure passes this configuration information
to use local control within those com- the complete network and serve as a on to all of the slaves.
ponents. For instance, within a door, a common interface between the origi-
side mirror, a window system, a lock, nal component manufacturer (OEM) START AT THE END
and user controls. and suppliers of the different network To see how this all works, it makes
Manufacturers of individual compo- nodes. It is also used as an input to sense to start at the end of the LIN
nents are more likely to invest in this development and analysis tools. The specification list. Before you take con-
approach if they can be assured that LIN node capability language specifi- trol of something, you have to know
their equipment will “plug and play” cation describes a format used to what its capabilities are. The manu-
well with others. To ensure that this describe off-the-shelf slave nodes in a facturer of any LIN-compatible node

70 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


must provide an NCF doc- frames, it knows that only
Roof:
umenting the node’s abili- Rain sensor, light sensor, Steering Wheel: those frames with protected
ties. This file’s ASCII light control, and sunroof Cruise control, wipers, identifier’s associated with
and turning light
structure makes it possible one of its subscribed
Optional: Climate
for the file to be read by control, radio, and phone frames contains data that
technicians and LIN tools it can use.
developed to help LIN The LIN bus transfers
Seat:
managers eliminate errors Seat position motors, data using frames. The
occupancy sensor, and
(and even produce code.) control panel
diagnostic frame was dis-
The NCF is a list of node cussed as a way for the
definitions including areas Door: master node of a LIN clus-
for general, diagnostic, Mirror, central ECU,
mirror switch, window
Climate: Engine: ter to have a dialog with
Small motors
frame, status_manage- lift, seat control switch, Control panel
Sensors
Small motors
individual slave nodes.
door lock, etc.
ment, and free_text def- Once all nodes have been
initions (see Listing 1). Figure 1—This diagram shows a number of typical areas where using individual LIN initialized (received their
The supplier is a member buses makes sense. individual assignments),
of the LIN consortium. the master can move into
You can find its respective supplier_id The first area of concern is with the an Operational mode, where required
on www.lin-subbus.com. Suppliers are NAD chosen by each node. Every communication is scheduled based on
responsible for issuing a function_id node within the cluster must have a the information requested by the indi-
for each product manufactured under unique NAD. If multiple nodes vidual NCFs. Using the max_period
their supplier_id. When a product declare identical NADs in their NCF, and min_period declared by each
undergoes revision, which does not the master must reassign a new NAD. frame and a time_base declared by
affect the existing function, the manu- It will do this via a diagnostic frame, the master, a schedule of frames is
facturer increments the variant_id. Con- using the protected identifier 0x3C created (in the LDF) that satisfies the
formance testing is available to assure (60). The master node is able to com- requirements of all the declared
adherence to the LIN specification. municate with each of the slaves diag- frames. The schedule is a list of
The frame definitions can have mul- nostically, via the declared or assigned frames (and delay times) that will be
tiple entries with optional parameters NAD. repeated. The delay times are based on
for each message_id entry. The pub- Cluster communication is normally the maximum time necessary to
lish frame declares the information it handled by protected identifiers, 0- transmit the frame and receive the
has available to others. The cluster’s 0x3B (0–59). The master must assign a frame’s response. Although this is
master will use this frame to gather unique protected identifier to each fixed, it can be different for each pro-
information, the slave will respond, published and subscribed frame of tected identifier, based on the number
and any node (including the master) every node. Each node has already of data bytes in the response. The
can use the data. A subscribe frame declared a message_ID for each of its delay time for that frame is the maxi-
describes a function that it can per- own published and subscribed mum frame time rounded up to the
form. In this case, a cluster master frames. The master uses a slave’s next even increment of the
will use this frame to produce this NAD and its mes-
information, a slave will reply (it sage_ID to assign the Node capability files Design
could in fact be the master), and any unique protected iden-
node can use it. The master always tifier to each slave. System
initiates a frame as guided by the LDF. Each published defining tool

In most cases, only one slave (or the frame and all those
master itself) will respond. subscribed frames
(with matching data) System LIN Description
generator
LIN DESCRIPTION FILE will receive the same file

With all cluster nodes defined in sepa- protected identifier. A


System
rate NCFs, these documents become the slave will only Debugging
input to the master node’s LDF. The respond (with data) to
LDF is similar to the NCF. It contains those frames sent by
Bus analyzer and
sections describing the cluster node, the master that Slave 1 Slave 2 Slave 3 Master
emulator
signal, frame, node_attributes, include a protected
LIN
and schedule_table. While most of identifier associated
the information is garnered from the with one of its pub-
Figure 2—This block diagram shows the LIN cluster split into three areas of
NCFs, the LDF must reconcile con- lished frames. Even
design. The design phase begins with documentation. The system phase
flicts and create a communication though a slave node includes the actual cluster hardware. The debugging phase uses the docu-
schedule. will listen to all mentation to test the actual hardware.

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 71


time_base. In many configurations,
Listing 1—The NCF consists of the basic information necessary to describe a slave node. Its ASCII-based for-
this will simply be a list of the pro- mat allows it to be used to input to either a manual or an automatic LDF design process. Note that blue =
tected identifiers of all published choice and bold = optional.
frames. It may be necessary in larger
node_capability_file;
clusters for some frames to be includ-
LIN_language_version = (ASCII string); (0.01-99.99)
ed more than once in a schedule list
to assure that they meet their maxi- node (ASCII string) { (node name)
mum and minimum requirements. To general {
LIN_protocol_version = (ASCII string); (0.01-99.99)
make scheduling a bit more flexible,
supplier = (integer); (supplier id)
multiple schedules can coexist, but function = (integer); (function id)
only one can be active at any particu- variant = (byte); (variant id)
lar time. bitrate = (integer); (1000-20000 bps)
or select (integer), (integer); (acceptable rates)
I want to mention one of the zingers
or automatic min (integer) max (integer);(acceptable rate)
introduced into this otherwise volt_range = (real), (real); (integer or decimal)
straightforward protocol. It seems that temp_range = (real), (real); (integer or decimal)
if your cluster has data that is not conformance = (ASCII string); (LIN2.0 or none)
}
expected to change very often, the
diagnostic {
frames will just continue exchanging NAD = (integer), (integer); (1-127)
this unchanging data. This is a waste, P2_min = (integer) ms;
so let’s complicate the protocol by ST_min = (integer) ms;
support_sid { (byte), (byte)}; (supported sids)
allowing responses from multiple
max_message_length = (integer); (buffer size)
slaves at the same time, thoroughly }
destroying the original premise that frames {
only one slave can respond. The idea publish (ASCII string) { (frame name)
or subscribe (ASCII string) { (frame name)
here is that a master can send a spe-
message_id = (integer); (0-0xFFFF)
cial frame that allows select slaves to length = (byte); (1-8)
respond and if no one responds, it can min_period = (integer) ms;
assume nothing has changed (and max_period = (integer) ms;
event_triggered_message_id = (integer);
maybe go to sleep for a while). The
signals {
problem now is that if multiple slaves (ASCII string) { (signal name)
respond, a bus conflict arises, and the init_value = (interger);
response frame is useless. The master size = (interger);
offset = (interger);
can then switch schedules using
encode (ASCII string) { (encoding name)
frames that guarantee a single logical_value, (integer), (signal value)
response from each frame. (ASCII string); (label)
These special frames are called physical_value (integer), (min value)
(integer), (max value)
event_triggered_frames. Assigning
(real), (scale)
the same protected identifier to multi- (real), (offset)
ple slaves creates them. Look back at (ASCII string); (label)
the NCF in Listing 1. In the frames bcd_value, (bcd); (signal value)
ascii_value, (byte); (signal value)
section, you will see an optional entry
}
for event_triggered_message_ID. }
When a slave declares one of these, it }
allows the LDF to assign it a protected }
}
identifier that may be assigned to
status_management {
multiple slaves. (Only slaves with error_response = (ASC string);
identical response lengths will be (signal name)
assigned the same protected identifier.) }
free_text {
(ASCII string); (description)
API }
Specifications for the LIN 2.0 are }
based on tools presently available to
help the LIN bus designer achieve a
working system with minimal effort. tines written in C to handle the mas- The LIN 2.0 API provides a driver that
Figure 3 shows how these high-end ter and slave processes necessary for is implemented by the LIN tools to
tools manage the development LIN 2.0 conformance. Depending on maintain standardization. API func-
process. The application program implementation, a node may not tions can be used as guidelines if you
interface (API) is a collection of rou- require a LIN software device driver. will be programming in a language

72 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


Only 4 Steps... Keil Microcontroller Development Tools
help you create embedded applications quickly
and accurately. Keil tools are easy to learn and
...are required to generate efficient, reliable use, yet powerful enough for the most
applications with the μVision IDE and demanding microcontroller projects.
development tools from Keil.

Step 1. Select Microcontroller and


Specify Target Hardware
Use the Keil Device Database (www.keil.com/dd) to find the
optimum microcontroller for your application.
In μVision, select the microcontroller to pre-configure tools and
obtain CPU startup code.

Step 2. Configure the Device and


Create Application Code
The μVision Configuration Wizard helps you tailor startup code
to match your target hardware and application requirements.
Extensive program examples and project templates help you
jump-start your designs.

Step 3. Verify Program Execution with Components of Keil Microcontroller Development Kits
Device Simulation
High-speed simulation enables testing
before hardware is available and helps you Keil makes C compilers, macro assemblers,
with features like instruction trace, code real-time kernels, debuggers, simulators,
coverage, and logic analysis.
evaluation boards, and emulators.

Over 1,200 MCU devices are supported for:


Step 4. Download to Flash and n 8-bit - 8051 and extended 8051 variants
Test Application n 16-bit - C166, XC166, and ST10
Once your application is runs n 32-bit - ARM7, ARM9, and Cortex-M3
in simulation, use the Keil
ULINK USB-JTAG Adapter for
Flash programming and final Download an evaluation version from
application testing. www.keil.com/demo

800-348-8051 www.keil.com
other than C. and synch is detected.
Database
A separate diagnostic manager
Now the node is looking
Database
API is included (not to be for a protected identifier
confused with the diag- User-provided
that it recognizes. If none
LIN
nostic frames mentioned Configuration information is found or the parity is
description file (target hardware
above). These functions information) incorrect, the slave will
make the LIN bus accessi- go back to a dormant
LIN
ble via a CAN-to-LIN LIN LIN
Configuration state. If the protected
Bus emulator Bus analyzer
interface running on a tool identifier matches a pub-
LIN API
CAN bus. lished frame, the slave
LIN Application
ECU Application will transmit its data and
and configuration
code
DIAGNOSTICS code
checksum. If the protect-
The diagnostic frames LIN Bus ed identifier matches a
described earlier, which Compiler/linker
subscribed frame, the
are used to configure Target
slave will receive the
ECU ECU ECU
NAD and assign protected image data and checksum, using
identifiers, are covered the data if the checksum
under node configuration Figure 3—The tool’s environment (developed to support the LIN standard) can automati- is correct. There has been
in this section. The diag- cally produce code based on your design documentation to help automate the entire only one mandatory error
nostics having to do with design process. flag (bit) that must be
the CAN-to-LIN bus are made available to the
not thoroughly discussed here and do bits, and a stop bit except for break. master. The response_error status
not directly pertain to nodes (or clus- The break has at least 13 dominant bit indicates that an error in the
ters for that mater) that are by them- bits (including the start bit) followed response field is detected by the
selves separate entities. So, I leave by the break delimiter (stop bit). The slave (read back).
this up to you to investigate if you are protected identifier is actually a 6-
interested. LSBit identifier with a 2-MSBit-pari- PHYSICAL LAYER
You’re down to the frame structures ty protection. Exclusive ORing bits A master’s clock must be accurate
themselves now. The master uses a 0, 1, 2, and 4 form bit 6. Taking the to 0.5% of the nominal data rate being
schedule list to determine which complement of the exclusive ORing used. Slave nodes can use less expen-
frame will be transmitted and delayed of bits 1, 3, 4, and 5 forms bit 7. A sive (accurate) system clocks (up to
until the next frame (frame slot). protected identifier of 0x01 trans- 14% error) as long as they can self-
Thus, the frame being sent is shorter lates to a byte field of 0xC1 and a adjust based on the synch byte trans-
than the actual frame slot. The frame protected identifier of 0x03 trans- mitted following a break. Since the
contains a header, a response space, lates to a byte field of 0x03. So, the synch byte must be a 0x55, the result-
and a response (see Figure 4). The byte value used to transmit a pro- ing pattern is alternating dominant
master provides the header consisting tected identifier is actually where (beginning with the start bit) and
of a break, a synch byte, and the pro- the protection comes in. recessive states can be timed by a
tected identifier. The response space is Although a master has network slave node. By measuring the time
dead time, where the master has fin- configuration tasks, its main task is to between the first falling edge and the
ished sending the header and the slave manage network communication. The fifth falling edge and then dividing by
has not yet begun its response. The behavior for this task is to wait for eight to get bit time, a slave can
slave’s response is fixed (declared by the next time slot and then issue a adjust its data-rate generator to
the NCF) at 1 to 8 data bytes. The break, synch, and protected
slave also includes a checksum byte. identifier of the next frame
LIN 1.3 specifies that the checksum on the schedule. If by Message header Message header
include only the data bytes. LIN 2.0 chance the master also has Synch break Synch field Identifier 2,4, or, 8 Data fields Checksum
specifies that the protected identifier an internal slave node (as ≥ 13 bit

be included along with the data bytes many do), it must also
in calculating the checksum. (That’s behave like a slave node;
one reason the NDF includes the pro- otherwise, it merely waits. Byte field
SCI/UART format
tocol version number.) The checksum A slave’s behavior is
0 1 2 3 4 5 6 7
is calculated by adding individual much more complicated. It Start LSB Stop
bytes. If any sum produces a carry, the may be dormant (asleep) or
carry is added to the sum. The final active (awake). Even in a Figure 4—The LIN frame structure contains a header provided by the
master node and a response provided by a single slave node. All of the
byte is complimented. dormant state, a node’s
frame data (except the break) takes on the familiar 10-bit serial format of
All bytes are transmitted as a seri- receiver is active and will 8 data bits, surrounded by a start and stop bit. All of the bits are sent
al 10-bit word with a start bit, 8 data wakeup the node if a break least significant bit first. All data is sent least significant byte first.

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 75


improve accuracy. The data to be passed by using
EUSART peripheral in the LIN bus protocol (see
Voltage VBAT
some Microchip Technol- regulator Figure 6). The circuit can
ogy PIC microcontrollers Ratiometric be used as either a master
reference
has auto baud and or a slave node. I began by
Wake-up
send/recognize break VREG logic creating an NCF for a
functions. Internal circuits slave node and an NCF for
The LIN bus consists of –
the slave portion of a mas-
a +V (battery), ground, and RXD ter (that’s right, the master
+
a single bidirectional can also serve as a slave
communication path. A CS/WAKE
Approx. node). This allowed me to
30 kΩ
LIN transmitter/receiver put together an LDF for
isolates itself using pro- TXD OC LIN the project. Since I was not
tection diodes, so the bus using off-the-shelf prod-
voltage or node voltage VSS
ucts, I was able to write
*FAULT/SLPS
cannot feed back onto the the application code in
LIN bus’s power if the bat- Slope Thermal such a way that no nodes
POR
tery is lost (see Figure 5). control protection needed reassignment. In
Therefore, the internal other words, I didn’t need
supply voltage (VSUP) and to include those functions
communication voltage Figure 5—The Microchip Technology MCP201 LIN transmitter/receiver protects the LIN to reassign NADs, assign
swing will be somewhat bus by disconnecting the transmitter if a problem exists. In Low-Power mode, LIN trans- frame_IDs, or any other
less than the LIN bus bat- ceivers continue to monitor the LIN bus for minimum-power designs. configuration overhead.
tery voltage. The domi- The code is therefore
nant (falling to 40% of VSUP) and reces- teristics limit the LIN bus length to straightforward and just has to deal
sive (rising to 60% of VSUP) thresholds 40 m and 16 nodes. with sending and receiving actual
are based on the internal supply data. The schedule has two uncondi-
(which is based on the LIN bus’s bat- IMPLEMENTATION tional frame_IDs, 0x00 and 0x01.
tery voltage). The LIN 2.0 line charac- I designed a small circuit to allow Frame_ID 0x00 requests 3 bytes of

Figure 6—This simple node can act as a master


or a slave. Plenty of LEDs show application sta-
tus and both analog and digital inputs are avail-
able for connecting external devices. The
PIC18F2455 even has USB support so this cir-
cuit can be used as a snooper/emulator.

76 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


data from the master’s slave Available demo software (a LIN
portion, while frame_ID 0x01 snooper application) can be
requests 4 bytes of data from downloaded to the Stick. The
the slave node. LIN snooper application uses a
The long-range project will PC to display information
include at least one more slave about LIN bus traffic (see
node. This node will be some Photo 2).
kind of display that will make
use of the data transmitted by REALITY
the first two nodes used in this You have to search hard for
project. Presently, there is no manufacturers that have adopt-
reason why adding this third ed the LIN bus in their automo-
node would necessarily change biles. Certainly the Europeans
the programming of the first are well ahead of U.S. automak-
two nodes, because it will only ers embracing the whole LIN-
be listening to the network bus idea. You won’t find the
(much like a LIN snooper node LIN bus listed in the specifica-
might). However, under LIN tions of vehicles. What con-
specifications, its NCF would sumer cares about the skeletal
be included in the creation of design of their car? Mainte-
the cluster’s LDF because the nance-free is what we desire
master would need to assign it and we don’t care how it’s done.
frame_IDs to watch for. In Gone are the days of tinkering
reality, since I am in control, I with an engine on weekends.
can write the application for Photo 1—I configured identical PCBs as master and slave nodes. I then Today, if you don’t have the
daisy-chained a ToolStick to the cluster to monitor LIN traffic.
this node using the frame_IDs diagnostic tools, forget it. Auto-
0x00 and 0x01, and everything motive problems have become
will work well. Although communica- Photo 1 shows the prototype PCBs just a number dumped by some com-
tion between nodes follows the LIN (a master node and a slave) daisy- puter. This means that whatever bus
2.0 specifications, this project’s appli- chained to a third node. This third is being used is useless without the
cation does not need or support recon- node is a Silicon Laboratories Tool- documentation that defines the data.
figuration and diagnostic functions. Stick with a LIN DC daughter board. How nice is it for that documentation
to begin with the original design and
to be an integral part of it right
through production? I

Jeff Bachiochi (pronounced BAH-key-


AH-key) has been writing for Circuit
Cellar since 1988. His background
includes product design and manu-
facturing. He may be reached at
jeff.bachiochi@circuitcellar.com.

RESOURCE
LIN Consortium, www.lin-subbus.org
/frontend/stylesheets/request_doc.htm.

SOURCES
MCP201 LIN transceiver and
PIC18F2xxx Microcontrollers
Microchip Technology, Inc.
www.microchip.com
Photo 2—The Silicon Laboratories ToolStick has a demo application for monitoring the LIN bus. The ToolStick Ter-
ToolStick
minal will display what it sees on the LIN bus. In this case, the master asks for frame_ID 0x00 and it responds
with 3 bytes of data (actually 4 bytes are transmitted: the 3 data bytes and a checksum). The master then asks for Silicon Laboratories, Inc.
the frame_ID 0x01 and the slave node responds with 4 bytes of data. www.silabs.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 77


SILICON UPDATE by Tom Cantrell

USB: (Wire)Less is More


Tom covers new developments in wireless power technology, tells the story of ultra-wide-
band technology, and cuts through all of the “wireless” USB hoopla. Will you be the next
designer to bring wireless power to the masses?

I n last month’s column about the


Cypress Semiconductor Express visual
that many of us use with our PCs. A
typical setup puts a radio transmitter
This type of “Lesswire USB” lashup
is pretty much limited to simple, low-
programming language for PSoCs, I in the I/O device (i.e., keyboard and/or speed devices. Walk the aisles at your
mentioned their “Wireless USB” offer- mouse), which communicates wire- local PC shop and you’ll find plenty of
ing. Subsequently, I received some lessly to a receiver that’s a standard wireless keyboards and mice, but you
wireless USB hardware courtesy of a USB device connected by cable to the won’t find wireless disks, printers,
third-party supplier, Artaflex. Their PC’s USB port. cameras, MP3 players, and so on.
Falcon module is based on the Cypress The beauty of this approach is that That’s because upping the ante in
CYRF6936, a complete 2.4-GHz radio the PC doesn’t know or care that the terms of performance and device com-
on a chip. Though it didn’t make the keyboard or mouse is wireless, since plexity stresses the differences
deadline for last month’s story, I do at the end of the line there is indeed a between a radio and a wire to the
want to report that I checked out the wire (or dongle) plugged into the PC’s point that they become obvious and
gear with a simple, but personally use- USB port. Thus, it’s all blissfully problematic.
ful, application. transparent to the OS and application There are a lot of wired versus wire-
The way my house is laid out, you software. Another thing to note is that less issues, such as ease-of-use, securi-
have to either go up and down a flight the particular details of the radio used ty, and reliability, that we’ll get into a
of stairs or step outside to see if the don’t matter at all. Since the transmitter little later. In terms of the “Lesswire
garage door is open. Kind of a pain in (in the I/O device) and receiver (plugged USB” approach typified by today’s
the keister, right? Using Express and into the PC) are sold as a matched pair, wireless mouse or keyboard, there’s
the Artaflex board, it is easy to whip any radio scheme that gets the bits only one issue that matters—speed, or
together a wireless door position sen- from here to there works fine. rather a lack of it—and it’s a show-
sor (see Photo 1). One unit mounted stopper.
on the garage door uses a low-g a) For instance, the Cypress solution is
accelerometer as a tilt indicator to only good for 1 Mbps with a tailwind
radio that information to another unit and lowlier keyless remote-class (e.g.,
in the living quarters that lights a red 27 MHz) radios deliver even less. That
LED for “open” and a green LED for works for a mouse or keyboard (or a
“closed.” simple application like my garage door
The follow-up serves as a segue to position sensor), but not much else.
this month’s column which isn’t b)
about “wireless USB.” It’s about GO WIDE YOUNG MAN
“wireless USB.” Needless to say, a lit- Ultra-wideband (UWB) is a topic
tle explanation is in order. that’s been around for some time, but
frankly until now it has been more
USB UNPLUGGED? sizzle than steak. That’s all about to
Cypress may call their proprietary change, with real UWB chips and
radio scheme “wireless USB,” but I’d boxes hitting the shelves even as we
Photo 1—A two-line program usually can’t do much.
say it’s more like “lesswire” rather speak (see Photo 2).
But using a low-g accelerometer and a radio module
than “wireless.” Consider the exam- from Artaflex (a), all it takes is a “two-object” Express From 50,000′, the UWB concept is
ple of the wireless keyboard or mouse program (b) to implement a wireless tilt sensor. pretty simple. Instead of hitching a

78 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


a) b)

Photo 2—The market for wireless USB gadgets is poised for takeoff in 2007. Belkin false-started with a “Cablefree” USB hub (a), but they will be switching to Certified Wireless
USB using Intel silicon shortly. Booming business prospects are also enticing new players into the fray, such as Staccato Communications, who offers Certified Wireless USB refer-
ence designs based on their “Ripcord” UWB chipset (b).

ride on sine waves, like a typical “car- (PANs) with range measured in ones Beginning in early spring, (Updated 10/06:
rier-based” radio, UWB uses discrete to tens of meters. For PAN applica- Ship date change to mid-December 2006*),
pulses to pass information. There are tions, limited range is, in fact, a virtue Belkin will offer…
a lot of ways to do that, for instance that emphasizes the “personal” part of …*Because the original chipset manufac-
by varying the pulse timing, ampli- the equation by minimizing interfer- turer for our CableFree USB Hub has stepped
tude, polarity, and so on. But the UWB ence between your PAN and mine. away from the CableFree USB business, we’ve
bottom line is pulses instead of waves. Not to mention all the other LANs, had to change to a different chipset. This has
The good news is that UWB can WANs, etc. crowding the spectrum. caused us to push back the availability of the
deliver a lot of throughput, even using Hub to September. Please look out for more
conventional (i.e., complementary PHY VS. PHY details in a coming press release.
metal-oxide-semiconductor (CMOS)) FOR IMMEDIATE RELEASE —Belkin Press Release, January 3, 2006
technology. The bad news is the short Belkin CableFree USB Hub Enables Instant
and frequent pulses generate harmon- Wireless Connectivity of USB Devices The UWB story gets weird at this
ics that almost literally cover the Powered by Freescale’s Ultra-Wideband point. About five years ago (December
spectrum, raising the prospect of technology, Belkin brings the world’s first 2002), the IEEE decided the time was
drowning out every other wireless wireless USB Product to the market right for UWB and authorized a stan-
gadget out there. What to do? dard effort (IEEE 802.15.3a), fulfilling
The answer, as blessed by the FCC, (Los Angeles, CA)—Jan. 3, 2006—Belkin their traditional role as mediator of all
is pretty simple: limit the allowed announces its new CableFree USB Hub, the things networking. Err, “mediator”
power such that a UWB radio is no industry’s first USB Hub that does not may be optimistic. I’d say “marriage
more obnoxious than the typical unin- require a cable to connect to the computer…. counselor” is more like it.
tentional emitter (i.e., the Sure enough, the
familiar FCC Part 15 limit). 802.15.3a effort quickly
Bluetooth
The combination of low 802.11b WLAN
devolved into a “War of the
power spread across a huge Cordless phones Roses” between two camps,
Microwave ovens
spectrum means that within respectively led by historic
the relatively narrow bands 802.11a WLAN
archrivals Intel and
PCS

Emitted
used by existing (i.e., carrier- signal
Cordless phones Freescale Semiconductor
based) radios, a UWB signal power (then Motorola).
U-NII Band

appears as little more than a On the surface, the argu-


slight increase in back- ment was ostensibly about
ISM Band

ground noise (see Figure 1). arcane aspects of the modu-


GPS

While UWB, like all com- lation scheme, namely


FCC Part 15 Limit
munication schemes, can –41 dBm/MHz
UWB Spectrum
Direct-Sequence (DS) cham-
make trade-offs between pioned by Freescale and
1.6 1.9 2.4 3.1 5 10.6
speed (i.e., bandwidth) and Note: Not to scale Frequency (GHz) Orthogonal Frequency
distance (i.e., SNR), the low- Division Multiplexing
Figure 1—According to the FCC, anything that hogs more than 500 MHz of spec-
power limitation makes (OFDM) by Intel. Technical
trum qualifies as ultra-wideband (UWB). To prevent interference, the rules limit UWB
UWB a good fit for so-called transmit power to a level so low (the familiar FCC Part 15) as to go unnoticed by issues provided the excuse
personal area networks existing spectrum users.[1] for arguing, but it was

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 79


Photo 3—The great UWB modulation always really about NIH and trying to
war between direct-sequence (DS,
preemptively seize high ground in the
backed by the UWB Forum) and
orthogonal frequency division multi- marketplace.
plexing (OFDM, backed by the The jockeying for position and bad-
WiMedia Alliance and the USB mouthing went on and on for years,
Implementers Forum) is finally over,
finally reaching a bitter deadlock.
and DS lost.
Ultimately, in January 2006 the two
camps finally found something to
agree on, namely that they would
never agree, and voted to dissolve the
UWB standard. At this point, I think
another thing everyone can probably
agree on is that the IEEE standards
process, held hostage to ballot stuffing
and paralysis-by-analysis, probably
needs some work.
Anyway, the saga continues. The
corpse of 802.15.3a wasn’t even cold
before the Freescale and Intel camps
split into their own consortia under
the banners of the “UWB Forum” (DS)
and “WiMedia Alliance” (OFDM),
respectively. With no more fussy IEEE
details (like “rules” and “voting”) in
the way, the battle became more tacti-
cal. Instead of speechifying about
technical trinkets and backroom arm-
twisting, each side quickly mobilized
its forces for a double-time march to
market.
Here’s where USB comes back into
the picture. Keep in mind that UWB is
about a future that goes beyond USB
and PCs, including everything from
entertainment systems in the living
room (i.e., wireless A/V) to vehicular
radar on the road (“Look Ma, no
hands—on the wheel”). But these
bluer-sky apps will take time to
emerge and those markets have a lot
of inertia to overcome.
By contrast, USB probably repre-
sents the first, and fastest, way for
UWB to break out of the lab and onto
shelves. Compared to the living room
or road, the PC market evolves and
adopts new technology at a decently
fast pace. Everyone has seen how
quickly the wired-USB market was
able to migrate from USB 1.0 to 2.0.
Wireless USB was understood to be
the first “killer” UWB application,
and thus became the proxy UWB bat-
tleground.
As a founder of the original USB
consortium, Intel naturally aligned
with the “certified” wireless USB ini-
tiative. That left the Freescale camp to

80 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


We search the world for time-saving,
easy-to-use state-of-the-art products!
LCD Scope Handheld Scope Mixed-Signal PC Oscilloscope PenScope Logic Analyzer
100 MHz Scope and Logic Analyzer
w- W

EW
EW
!
st
Te s t i n g

lets you do complex triggering to find


Lo N E
Co

N
N
hard-to-get-at glitches, spikes, etc.
Huge 4 or 8 MS buffer for deep data
drilling and zooming. Optional built-in
swept signal generator. 2 Analog
PDS5022S - 25 or 60MHz 2- HDS1022M - 20MHz 2-ch PS2105 - 25MHz USB powered ZeroPlus - Intuitive full-featured
channels x 10, 12, 14 bit with more
ch + trigger standalone bench standalone scope and DMM than 60 dB dynamic range. 8 digital
s c o p e - i n - a - p r o b e ! U p t o 16-channel with 4mb memory.
scope with USB connection with USB connection and 3.8” inputs for mixed signal display/trigger. 100MS/s, 24kS buffer C/VB/ Sophistcated triggering. I2C, SPI,
and 7.8” color LCD. color LCD. Delphi/LabView/VEE drivers. and UART monitoring. Includes
PDS5022S Sale! $329 CS328A $1149 PP315 $349 clipleads, USB cable and software.
CS700 (signal generator) $249
PDS6062T Sale! $579 HDS1022M Sale! $499 PP317 (10MHz, 50MS/s) $199 LAP-16128U $399
USB to I2C Ethernet to I2C I2C for PCs FREE COFFEE Ethernet to I2C
STOP
P THEE PRESS!
- NEW
W PRODUCTS
S ARE
I2C

G EVERY
ARRIVING Y DAY!
Call 1-888-7SAELIG
USB I2C/IO - Provides a simple FMod-TCP - TCP/IP server with I2C, PCI93LV: industry-standard I2C card NM7010A-LF REV 2 - Complete,
Mention Offer# SBW
“drop-in” solution for connecting Pleasee go
o to 19 x digital I/O, 5 x 10-bit A/D for PCs. WINI2C/PCI software hardwired TCP/IP-I2C module. Offloads
gives windows-interface to develop to get a free
your PC to 90kHz I2C + 20 I/O www.saelig.com inputs, and UART serial interface.
and debug I2C bus systems. Starbucks Card
stack for hi-speed Internet-enabling
lines. Free software. Use mul- to
o seee late-breaking Connect I2C devices/sensors with your order! microprocessor systems. Drop-in
UCA93LV is new USB version.
tiple boards for more I2C/IO. to an Ethernet network! NOW - transparently monitor at W3100A-based board for instant
announcements . While supplies last -
USB I2C/IO $79 FMod-TCP from $232 400kHz! $499 not available with any other offers network speeds to 8Mbps. $22

Stepper Motor Signal Wizard USB to 24 x I/O FATfile Storage Easy LCD Touch-Sensing ICs
I/O

Easy-Step 3000- Advanced stepper Signal Wizard - easy-use real-time USBI/O24R - 24 latched I/O lines Micro ALFAT-SD - Ready-made Micro LCD - Easy way to add 2” sq Quantum ICs - World’s best capacitive
motor drive and control system for DSP-based filter board for audio self-powered from USB port. Ubicom way to easily add SD storage 128 x 128 color LCD to your project. sensor ICs for switching & control.
unipolar stepper motors up to bandwidth signals. Design filters SX52 allows individual pin I/O to your product. Serial data Add text/graphics/animations for Patented Adj. Key Suppression,
35V/3A- ideal for robots/industrial in seconds without any DSP programming. I/O control via PCs in - FATfile data out. $39.95 any micro with serial or USB. Spread-spectrum, adj. sensitivity. In
control - turns you into an knowledge! USB port. Or design-in a micro ALFAT IC Micro LCD MK II $81 use worldwide by the world’s largest
instant motor control expert! $119 Signal Wizard v2.5 $699 USBI/O24R $69 for MB storage. $14 ea. Micro LCD-OLED $99 consumer/appliance mfrs $1
Serial-Ethernet Cable Ethernet to Serial Ether-IO Ethernet to I2C TCP/IP IC Motion Control
Ethernet

28” cable links serial devices to EG-SR-7150MJ - Ready-to-go Ether-IO - UDP/IP-controlled 24 FMod-TCP - TCP/IP server with W3150A+ - Hardwired TCP/IP stack PIC-Servo - Motion control boards
network without a PC, providing an serial-to-Ethernet Gateway. Simple X digital I/O board. 3 x 8-bit TTL I2C, 19 x digital I/O, 5 x 10-bit A/D - cheap micros can now have with integrated power amplifiers
instant IP address. RS-232 port set-up for 10/100Mbps Ethernet ports each independently inputs, and UART serial interface. internet capabilities at full speed! for DC-servo/brushless-servo/
compatible with most 10/100mpbs - 230kbps serial. Ethernet/ programmable. Connects to any Connect I2C devices/sensors 10/100 Off-loads TCP/IP burden stepper-motors. Easy connection
Ethernet hubs. Network your serial Internet-enable any serial part. TCP/IP Ethernet network. to an Ethernet network! for fast time-to-market. Ethernet- to std serial ports for powerful
product easily! eCOV-110-P $99 EG-SR-7150MJ $35 Ether-IO 24 from $99 FMod-TCP from $232 enable almost ANYTHING! $7.20 multi-axis, mixed-motor control. $160
Bluetooth RFID Reader IC easyRADIO Wireless Controllers TinyOne Zigbee Data Modem
EW

EW
N

N
RF

Emxys PearlBlue - 100m-Bluetooth RFID Reader Chip - Reads easyRADIO TM Transceiver Owasys - GSM/GPRS/GPS/ TinyOne ZigbeeTM - Complete RF Data Modem - USB-powered
module (UART master/slave bridge). FIVE Int’l Stds ISO14443 A/B, Modules make wireless data Bluetooth/Ethernet wireless solution for fast and reliable data radio transceiver boards add
Easy connection for micro's to PCs, Tag-IT, Felica and ISO15693. transmission simple for USA controllers for M2M - for autos, transmission. Miniaturized OEM wireless RS232 to your device!
PDAs, phones, etc. IceBlue - PIC16F877 Single-chip solution. and Europe! Add wireless capability machines, etc. RS232/485/CAN/ RF module ensures fast and easy Get remote control for your
based emb. dev. system for shortest TRH031M $6.95 to your project today! A/D-I/O. integration into wireless applications. product from PC USB port!
Bluetooth development. $119 RSK-100 Eval Kit $350 ER900TRS from $35 (100) Owasys from $479 TinyOne Zigbee $55 RTM-USA $89
USB in one IC FT232R Module USBwiz Easy USB GPS Logger USB-Serial Adapter
USB

FT232RL - FTDI USB1.1-serial IC with UM232R - FT232RL 24-pin DIP USBwiz - Easily add USB microUSB - Tiny ready-made TrackStick - Pocket-sized logger FTDI - based serial port for
new "security-dongle" feature. Each module - USB-TTL serial convert- peripherals to your system. Includes USB Interface to 1 Mbps 0.7” x tracks position data for vehicles, laptops. Instantly adapts older
IC has unique ID! Internal EEPROM, er for your project. Reference cir- FATfile system for USB thumb & 0.5” based on SiLabs CP2101. personnel, etc. Records date, time, RS232 products to USB! Included
clockgen, pullups, etc. cuit for FT232R. Plug-in module external USB hard drives. No Gnd/RX/TX Suspend, Reset, & location, route and speed. Shows drivers provide virtual COM
FT232RL $4.05 adds USB1.1 instantly! USB knowledge needed. Plug-n-play! 3.3V 100mA source. data on Google maps! $239 port via 45-inch USB cable.
Check out the whole FTDI line! UM232R $19.99 IC $29.95 Demoboard $59.95 microUSB $25 PRO (vehicle powered) $249 USB-COM-S $24.95

www.saelig.com info@saelig.com
1-888-772-3544

1-888-7SAELIG 585-385-1768 fax


sensors expo REGIST
TODAYE! R
& conference
Conference: June 11-13, 2007 • Expo: June 12-13, 2007
Donald E. Stephens Convention Center • Rosemont, IL

Advances in Measurement,
Detection, Monitoring
& Control
The World of Sensing Technology
• Measurement & Detection
• Wireless Sensing
• Systems & Embedded Intelligence
• Emerging Technologies & Applications
• Low-Power Sensing KEYNOTES

Steve Squyres, Ph.D Gregory W. Withee


Roving Mars: Sensing the Health
Spirit, Opportunity of the Planet Through
and the the Global Earth
Exploration of Observation System
Produced by: the Red Planet of Systems (GEOSS)

Official Publication: For more information


or to register, visit
www.sensorsexpo.com
Gold Sponsors:
or call 800-748-5045 and
use source code 303M
come up with their ference from wired USB is
“CableFree” USB flavor. that WUSB uses a star
As with UWB itself, WUSB
point-to-point topology
once again there were Dev versus the “tree” of wired
technical differences to USB-to-WUSB WUSB USB2 version. Thus, with one
Wire adapter Bus Dev
bicker about. “Cablefree USB Host DWA
exception, there is no such
USB,” courtesy of a little (PC) HWA USB2
thing as a WUSB “hub.”
software sleight-of-hand, WUSB-to-USB Mass That exception involves
Wire adapter storage
purported to enable wire- easing the transition from
USB 2.0
less USB without requiring here (i.e., wired USB) to
any software changes on there (i.e., WUSB). A new
Figure 2—The choice between wired and wireless USB isn’t an either-or situation. Both
the PC. Meanwhile, will coexist using a combination of host (HWA) and device (DWA) adapters.
class of device is defined
“Certified Wireless USB” called a “Device Wire
called for more ambitious Adapter” (DWA). It can be
upgrades to the underlying protocols, seize control of USB. It just won’t hap- considered kind of like a conventional
changes that would require new OS pen. They wouldn’t win, and they USB hub with connectors and wires
drivers. know they wouldn’t win, so they on the device side, but using WUSB
And once again, the technical issues won’t even try. Microsoft may not be for the upstream host connection (see
would be rendered semi-moot by a king when it comes to standards, but Figure 2). A DWA allows folks to
shakeup at the top. Preoccupied with they are the kingmakers. migrate their existing wired USB
their own corporate machinations (i.e., With Microsoft, Intel, and a 100- devices into the brave new world of
spinout from Motorola) and perhaps plus-member coalition of the willing WUSB.
just conceding the inevitable, Freescale behind it, I hereby declare “Certified The other half of the upgrade chal-
suddenly decided to hit the Reset Wireless USB” (I’ll just use “WUSB” lenge is addressed with a “host wire
switch on their UWB strategy. Adding as shorthand) the winner. With that adapter” (HWA) that has a wired con-
insult to injury, they quit the UWB decided, let’s see what the future nection on the host side and a WUSB
Forum, the very group they were holds. on the device side. Just plug an HWA
instrumental in creating (see Photo 3). First the basics. The WUSB specs into an existing PC’s USB port to
Thus, ’06 was a year filled with require that all devices deliver at least enable the PC to function as a WUSB
marketing fire drills and U-turns. 200 Mbps, with even higher speed (up host.
There’s Orwellian retro-editing of to 480 Mbps) as an option. Note the Expect HWAs and DWAs to explode
press releases (like the example from implication of the high baseline speed; out of the blocks. It’s going to be quite
Belkin International at the start of this WUSB is overkill for low-end (i.e., a business, since many or even most
section) and “Product of the Year” mouse, keyboard) apps, which presum- existing PCs will end up needing one
awards for products that never were. ably continue to use
Indeed, much of the history, admitted- the “Lesswire USB”
ly not a pretty one, seems to have “dis- approach. USB Client
driver and
appeared” after the fact. Go to the IEEE Like wired USB, TCP/IP Stack
software
standards web site and search for the protocol burden
“802.15.3a” or the Freescale web site is asymmetric with
WiNet Filter USB Core stack System
and search for “UWB.” See what I the “host” doing the driver software
mean? Maybe it was all just a bad heavy lifting to
dream and it never really happened. make things easier WiNet Host UWB Radio CWUSB Host
controller controller controller
(and thus lower cost miniport driver miniport
DIAL “M” FOR MICROSOFT and power) for
As far as I’m concerned, when it “devices.” However,
WiNet Radio Wireless USB
comes to USB there is only one com- it does incorporate UWB Radio
controller host
controller (URCI)
(WiNetRCI) controller (WHCI) UWB PC-side
pany that really matters, and that’s dual-role capabilities Radio
Microsoft. It’s not so much that to enable “no PC” MAC and convergence layer hardware

Microsoft can single-handedly drive a apps, such as direct UWB Radio PHY
particular solution. Surely they need communication
aiding and abetting from the likes of between a digital
Intel and PC suppliers. Rather, it’s the camera and a photo
PEER WiNet CWUSB
recognition that nobody else can drive printer. Device hardware Device hardware
a solution without Microsoft’s bless- A single host in a
ing. For example, consider a scenario WUSB network can Figure 3—Just as a single radio station may deliver, for example, both talk
that has Apple or the Linux crowd (or support up to 127 and rock, a single UWB radio in the PC of the future will support a variety of
both together) trying to redefine and devices. One big dif- interfaces.

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 83


the significant the prominent role given power man-
changes WUSB agement in the spec.
makes to the On the other hand, the rosy scenar-
isochronous device ios call for UWB and WUSB to move
class. lots of bits (MP3s, JPEGs, and so on).
Keep in mind I’ve got an add-on USB-powered disk
the challenge is drive that probably wouldn’t last more
bigger than just than a day or two of typical use on
WUSB. In a PC, a batteries. In any case, even if it ran on
single UWB radio batteries, it would still need a cable
may carry a variety (i.e., a wall wart or plug into a wired
of “programming,” USB port) to charge them.
including WUSB, When it comes to wires, less is bet-
Internet, and ter than more, but it isn’t the same as
future versions of none. I guess that’s why they don’t
other popular call it “Wirefree USB.” What the
Figure 4—The idea behind Nikola Tesla’s turn-of-the-century Wardenclyffe Tower’s interfaces (e.g., world needs now is a new-age Nikola
centralized wireless power delivery was way ahead of its time—and still is. (Source: Bluetooth, 1394) as Tesla to bring wireless power to the
www.teslasociety.ch/info/galerie/bilder/G59.jpg)
well (see Figure 3). masses (see Figure 4).
So, the host Wireless USB will be a winner—but
or both along the way. needs to be able to deal with uncer- I wouldn’t write off wires just yet. I
One “ain’t as simple as it sounds” tainty on both the supply (i.e., radio
aspect of wireless is the basic task of packet error rate) and demand (chan- Tom Cantrell has been working on
establishing a connection. With a wire, nel and load variation) side. That’s not chip, board, and systems design and
it’s as fast and easy (and secure) as easy, and it requires a lot of new capa- marketing for several years. You may
jacking in. The WUSB folks have put a bilities. For instance, the host needs reach him by e-mail at tom.cantrell
lot of effort into delivering “wire- the ability to dynamically change a @circuitcellar.com.
equivalent” out-of-the-box ease of use. device configuration (i.e., packet size
Ironically, one option is to rely on a vs. burst length vs. service interval) as
wired USB port to establish an initial overall circumstances dictate. REFERENCE
wireless connection. At first this Fortunately, most of the complexity [1] B. Hosler, “Certified Wireless USB
sounds goofy, but maybe it’s more resides in the host, so the folks design- Architecture Overview,” 2006,
practical than it seems. Even a WUSB- ing PCs have to do the most head www.usb.org/developers/wusb/docs/
enabled PC is likely to come with scratching. WUSB devices, notably presentations/Taipei06_BH_Archi
wired USB ports for the foreseeable isochronous ones, need to be smarter tecture.pdf.
future. Similarly, I suspect many as well. But it’s still generally the case
devices will come with both USB and that devices tell the host what they
WUSB connectivity. can do and ask for a certain level of RESOURCES
The other approach, wireless-only, service. It’s up to the host to decide USB Implementers Forum, Inc.,
will have users push a button or some yea or nay and, if it is the former, www.usb.org
such to manually initiate a connec- deliver on the promise.
tion, much as with today’s wireless UWB Forum, www.uwbforum.org
keyboards and mice. However, the RETURN OF THE WALL WARTS WiMedia Alliance, 2006, www.wimedia.
WUSB scheme is complicated by the Of course, one irony of all the org
need for bulletproof security. To pre- “wireless” USB hoopla is that it likely
vent pirates from eavesdropping on, or won’t lead to less wires at all.
even hijacking the connection, the One of the best features of wired SOURCES
user supervises and approves an ini- USB is the delivery of power. Take CYRF6936 Radio module
tial key exchange. Subsequently, the away the USB cable and you’re left Artaflex Modules, Inc.
keys are retained in nonvolatile mem- with either battery power or, more www.artaflexmodules.com
ory so authentication and encryption likely, a return of the wall warts (i.e.,
CYRF6936 Radio SoC
of all WUSB traffic is automatic (and AC plug-in power supplies).
Cypress Semiconductor Corp.
mandatory). Fortunately, UWB is relatively
www.cypress.com
But above all, it’s the reliability power efficient (i.e., joules/bit) com-
issue that really separates the wires pared to other wireless schemes (e.g., UWB Chipset and Certified Wireless
from the radios. This is especially 802.11), principally by virtue of the USB modules
true for time-sensitive data (such as limited range. And the WUSB folks Staccato Communications, Inc.
audio and video) and it is reflected in are well aware of the issue judging by www.staccatocommunications.com

84 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


IDEA BOX
THE DIRECTORY OF PRODUCTS AND
AD FORMAT: Advertisers must furnish digital submission sheet and digital files that meet the specifications on the digital submission sheet.
SERVICES
ALL TEXT AND OTHER ELEMENTS MUST FIT WITHIN A 2″ × 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) 872-3064.

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


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

USB
Add USB to your next
phyCORE® OEMable Single Board Computers
XScale: PXA270, PXA255
project—it’s easier than you ARM: LPC3180 (ARM9); LPC22xx, LPC229x, AT91 (ARM7)

Embedded DSP Hands-On might think! PowerPC: MPC5554, MPC5200B, MPC565, MPC555
v USB-FIFO up to 8 mbps ColdFire: MCF5485 x 8 6 : Elan SC520
Workshops CAN
v USB-UART up to 3 mbps C166/XC16x/ST10/8051

v USB/Microcontroller boards Blackfin: BF537


Avoid confusing datasheets.
pre-programmed with firmware Faster-to-Market: Save time by
integrating a PHYTEC Single
Board Computer Module into
Rapidly learn to program, design v 2.4GHz ZigBee™ & 802.15.4 your target circuitry.
Make -or - Buy: Why make
and debug your application. v RFID Reader/Writer your own when you can buy
PHYTEC off-shelf solutions,
Absolutely NO driver software cost-effective to 1000s units/year?

Reinforce course concepts with Integrated Support Services: Let PHYTEC assist you in the design of your

included development tools.


development required! end product: from tools and RTOSes to production. Our hardware is
bundled with leading compilers (Keil, IAR, CodeWarrior), RTOSes (WinCE,
Linux) and debuggers.

www.dlpdesign.com Immediate Support: Talk to PHYTEC technical staff with every call. No
waiting for answers.
Let us help you accelerate your Your OEM solution: With 20 years design, production, and integration
experience, PHYTEC is your OEM partner.
design process. Visit:
PHYTEC America, LLC I 203 Parfitt Way SW, G100 I Bainbridge Island, WA 98110 USA
www.dsp-workshops.com www.phytec.com I (800) 278-9913 I www.phycore.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 85


MOTION CONTROL
Real Time Motion Control Design.
Custom Firmware Design
Device Driver Layer Design
Real Time Operative System
Embeded TCP/IP Stack, USB 2.0
Zigbee, 802.11x, Bluetooth June, Issue #203
Embedded Multi-Axes Motor Control Communications
Data Logger Design ,Home Automation SPORT232ST
Space Close: Apr. 12
STEPPING CO
CONN TROL LER
TROLLER
Control up to 16 STEPPER MOTORS simultaneously BONUS DISTRIBUTIONS:
using a “SINGLE SERIAL PORT”.
NXTcomm; RoboBusiness
Up to 8500 Steps/sec with linear Accel/Decel.
Chopper driver up to 48V/2A for 4,5or 6 wire motors.
Software Winding Current Setup.Shaft encoder input
Internal FIFO for linear, Linear or Spline
Interpolation.
24 digital I/O,Sequential Motion Pivot Controller .
32 bit DLL Windows 95,98,00,NT,Vista; Linux,
LabView FREE SOURCE CODE in C++,VBASIC July Issue #204
Embedded Web-Motion Internet and Connectivity
Space Close: May 11
Stand Allone One
Axis Motion System.
Call: Shannon Barraclough
RMV Electronics Inc.
300-3665 Kingsway
Vancouver, BC, Canada V5R 5W2
(860) 872-3064
Tel: (604) 299-5173 Fax: (604) 299-5174
Web Site : www.rmv.com Shannon@circuitcellar.com

WIRELESS RS-232 Low Cost EDA Software


WCSC (Willies Computer Software Co) For Windows 98, XP, NT, 2000
● Extremely easy to install
and use
v Circuit design package with
● Distances up to 100 schematic entry, circuit board
meters (329 feet)
layout and simulation (SPICE
● Bluetooth Serial Port
Profile
and digital) for only $599
● Communicates with Bluetooth enabled
v Buy modules for as low as
PDAs, Laptops, Smartphones, & Computers $119
● No programming or special software needed v Purchase and download
products instantly from our
Other Products website!
● Professional serial communication
libraries & development tools. v Libraries include latest micros,
● PCI, PCMCIA, USB, Universal PCI,
memories, analog, and others
& ISA multiport RS232, Rs422, &
Rs485 cards, Bluetooth/USB Contact Mental Automation at
Dongles (253) 858-8104
http://CircuitCellar.wcscnet.com http://www.mentala.com
sales@wcscnet.com (281)360-4232

High-speed USB 2.0 + Xilinx FPGA


Complete Software API

75mm x 50mm 3.5“ x 2.0”


$399.95 $199.95

XEM3010-1500P: XEM3001:
Š 1,500,000-gate FPGA Š 400,000-gate FPGA
Š Programmable PLL Š Programmable PLL
Š Over 110 I/Os Š Over 80 I/Os
Š 32 MB SDRAM Š 0.1” expansion headers
Š Configuration PROM Š Business-card size
Š 0.8-mm expansion Š $199.95 / Qty 1
Š $399.95 / Qty 1 Š $174.95 / Qty 10
Š $349.95 / Qty 10
FrontPanel Software API:
Š Windows XP, Mac OS X, Linux Š C/C++, Python, Java
Š Configure FPGA and communicate with your design
Š The easiest way to integrate USB into your product
Š Use for image capture, control, test equipment, etc.
Š Up to 38 MB/s transfer rate!
5% off with Coupon Code: CKTCLR73*
* Valid for first order only. Void 30-days after issue publication.

Opal Kelly Visit us online at:


www.opalkelly.com

86 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 87
New IP Products • $129.95 Low Cost CAN
IP Power USB Adapter
• 4 independent
power outlets Simple configuration & use
• SDK for complete
customization

$
99.95
IP Video Qty 1
• NEW SDK tools
for customization
including telnet access,
busybox utilities, wget, and more
• New simultaneous
4 channel DVR compatibility +1 630-245-1445
Naperville, Illinois USA
www.c-a-n.com
www.ArucaElectronics.com

88 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


www.LinkInstruments.com 973-808-8990
Digital Oscilloscope
500 MSa/s
• 2 Channel Digital Oscilloscope
• 500 MSa/s max single shot rate
250 MSa/S (Dual channel) 512 Kpts
500 MSa/S (Single channel) 1 Mpts
• Advanced Triggering
• Portable and Battery powered
• Only 9 oz and 7” x 3.5” x 1.5”
• FFT Spectrum Analyzer
• USB 2.0
$950

www.LinkInstruments.com 973-808-8990

Net Modules Zigbee Wireless I/O


watchout extend your digital I/O’s

here comes over 100’s of feet up to

Spider
tens of miles - in both
directions - with the
16IO-SSRT RF transceiver

wireless
auto-binding multidrop sensor / actuator
modules

programmable
revolutionary network pods
SAVE 5% enter coupon code CCI at checkout SAVE 5% enter coupon code CCI at checkout SAVE 5% enter coupon code CCI at checkout

ABACOMdirect.com
ABACOMdirect.com ABACOMdirect.com
ABACOMdirect.com ABACOMdirect.com
ABACOMdirect.com
ABACOM tel: +1(416) 236 3858 ABACOM tel: +1(416) 236 3858 ABACOM tel: +1(416) 236 3858
Technologies fax: +1(416) 236 8866 Technologies fax: +1(416) 236 8866 Technologies fax: +1(416) 236 8866

MYLYDIA, INC.
Layout Gerber,
Prototype Making

QUICK TURN
PCB & Turnkey
@
The Best Prices

{Œ“a _WWT]`\T`Z[Y

Sales@mylydia.com

WWW.MYLYDIA.COM

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 89


’“7”•–O—˜™7šG›Q•qœ
!#$%
ZžŸkqž ¡7š¢š£™Zž SpectraPLUS 5.0
Audio Spectrum Analysis
Features
Sound Card based I/O
FFT sizes to 1048576pts, 1/96 Octave
Up to 24 bit, 200kHz sampling rates
3-D Surface and Spectrogram
576#89;:/<-=>?<#@4AB:C 6*D&E F#C 6GE @-H=94=>/6#I Digital Filtering, Signal Generation
J 8K4L8<&IMI6&8N:KO8QPE R8K-RS&E JMTVU >I6&C THD, IMD, SNR, Transfer Functions
PXWZY7=[\=6&8E <&C^]&]&_-`#aPX= Tcb C <4= S DDE, Macros, Data Logging,
_-`#aPX=d[OA-6*e-E Rd6-=XfgE >Sh i Ukj?l WN_-mn7=d[ Vibration Analysis, Acoustic Tools
PXWZY7=[ b _ jNU =[ b _ jNU _-`&aPo=[qp p p r
sQt4u^vxw HQy-@&E zOy*6{C K4LE R|<&@<&C 9}6#8 FREE 30 day trial!
~ so€V‚„ƒoQ† ‡qˆ ‰QŠ-‹OŒ/‹O  Ž*(dŽOŒ‘ ‹O www.spectraplus.com
    
!#" $&%('*) +-,/. $&$*0 )*1 2$43 Pioneer Hill Software

ZZZDVL[WRROVFRP
PHS 360 697-3472 voice
pioneer@telebyte.com

EtherSmart WildcardTM
Network -Enables Your Product

$140/100s
G Standard RJ45 jack hosts
10/100Mbit Ethernet
G HTTP, SMTP, TCP, DHCP, ICMP,
and ARP Protocols
G Email program-controlled messages
to a specified LAN IP address
G Establish a TCP/IP connection to
exchange binary or ASCII data
G Serve software-controlled dynamic
content to your web browser
Mosaic Industries Inc.
tel: 510-790-1255 fax: 510-790-0925
www.mosaic-industries.com

90 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


ANYONE
Can Now Easily
Hand Solder Surface-
Mount Components!
Even A 10
Year Old!
www.schmartboard.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 91


Order online at: microEngineering Labs, Inc. Phone: (719) 520-5323
Fax: (719) 520-1867
www.melabs.com D evelopment Tools for PIC ® Microcontrollers
Box 60039
Colorado Springs, CO 80960

USB Programmer $89.95 LAB-X Experimenter Boards BASIC Compilers for PICmicro®
Pre-Assembled Boards Easy-To-Use BASIC Commands
for PIC® MCUs (as shown)
Available for 8, 14, 18, 28, Windows 9x/Me/2K/XP Interface
RoHS and 40-pin PIC® MCUs
Compliant PICBASIC™ Compiler $99.95
2-line, 20-char LCD Module
BASIC Stamp 1 Compatible
Programs 9-pin Serial Port Supports most 14-bit Core PICs
PIC MCUs Sample Programs Built-In Serial Comm Commands
including Full Schematic Diagram
low-voltage PICBASIC PRO™ Compiler $249.95
(3.3V) devices Pricing from $79.95 to $349.95 Supports Microchip PIC10, PIC12, PIC14,
Includes
PIC16, PIC17, and PIC18 microcontrollers
Direct Access to Internal Registers
Windows PICPROTO™ Prototyping Boards Supports In-Line Assembly Language
98, Me, NT, With Accessories for $119.95: Interrupts in PICBASIC and Assembly
2K, and XP Includes Programmer, Software, USB Cable, Double-Sided with Plate-Thru Holes Built-In USB, I2C, RS-232 and More
Software and Programming Adapter for 8 to 40-pin DIP. Circuitry for Power Supply and Clock Source Level Debugging
Large Prototype Area
Parallel Port Programmer Boards Available for Most PIC® MCUs See our full range of products, including
starting at $59.95 Documentation and Schematic
books, accessories, and components at:
Serial Port Programmer
starting at $79.95 Pricing from $8.95 to $19.95 www.melabs.com
EPIC™

92 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


CROSSWORD
1 2 3 4

7
Down
8 9 10 1. A word or phrase that links
to another document when
clicked with a mouse
3. The British mathematician
11 12
(1791–1871) who designed
13
the first digital computer
4. A signal sent after a program
14 15 has waited a specified length
of time for an event that did
not occur
6. An additional item added to
the end of a datasheet
7. A communications protocol
16 17 18
that allows Modicon-pro-
grammable controllers to
communicate with each
other
10. The type of programming
19 20 featured in Circuit Cellar
this month
11. Noise or incorrect signals
added to a digital signal to
reduce the amount of digital
21 distortion
12. A basin-shaped volcanic
22 crater
13. A device that displays vari-
ous electronic quantities on
Across a screen in the form of volt-
2. An item used to remotely open a car or identify a key ring ages
5. Erasable memory 15. File extension for Photoshop
6. Surrounding; enclosing files
8. A self-service public computer system that is set up for information browsing 16. Supplemental software that
9. An open-source software package used as a digital repository you add to a program to fix
14. An array of frequencies admitted or absorbed by a substance problems
17. A program used to access the Internet 18. What is outdated hardware
19. A signal that must be delivered within a specific set of equal time limits or software?
21. A declaration in C language to give a variable type a new name and make the pro- 20. A break in a planet’s surface
gram more readable
22. A type of metal transistor

Brought to you by:


The answers are available at
www.circuitcellar.com/crossword.

www.circuitcellar.com CIRCUIT CELLAR® Issue 201 April 2007 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
91 AAG Electronica, LLC 85 FDI-Future Designs, Inc. 23 Maxstream 19 Pololu Corp.

86 AP Circuits 90 Front Panel Express, LLC 86 Mental Automation 91 Pulsar, Inc.

90 ASIX 92 Futurlec 87 Merican Made 86 RMV

89 Abacom Technologies 89 General Circuits, Inc. 88, 92 Micro Digital, Inc. 73 R4 Systems

91 All Electronics Corp. 85 Grand Valley State University 63 Microchip 34, 64 Rabbit Semiconductor

87 Apex Embedded Systems 88, 91 Grid Connect 15 Microchip 16-bit Embedded Control 87 Rabbit Semiconductor

24 Arcom Control Systems 66 HI-TECH Software LLC Design Contest 22 Reach Technology, Inc.

88 Aruca Technologies 55 Holmate/Holtek Semiconductor, Inc. 92 microEngineering Labs, Inc. 9 Renesas

7 Atmel 89 IMAGEcraft 90 Mosaic Industries, Inc. 81 Saelig

42 Bitscope Designs 86 Intec Automation, Inc. 95 Mouser Electronics 91 Schmartboard

65 CWAV 88 Intrepid Control Systems 87 Multilabs 87 Scidyne

80 CadSoft Computer, Inc. 11 Ironwood Electronics 89 Mylydia, Inc. 26 Sealevel Systems

90 Conitec 64, 91 JK microsystems, Inc. 5 NKK Switches 82 Sensors Expo & Conf.

90 Custom Computer Services, Inc. 50 Jameco C2 NetBurner 17 Silicon Laboratories, Inc.

91 CyberPak Company, Inc. 54 Jeffrey Kerr, LLC 3 Noritake Co., Inc. 92 Systronix

1 Cypress 74 Keil Software 52 Nurve Networks LLC C3 Tech Tools

85 DLP Design 52 LabJack Corp. 92 Ontrak Control Systems 48, 49 Technologic Systems

85 DSP Workshops 52 Lakeview Research 86 Opal Kelly Inc. 86 Technological Arts

54 Decade Engineering 31 Lantronix 47 P&E Micro 89 Tern, Inc.

88 Designnotes.com 87 Lawicel AB 10 PCB-Pool 58 Tibbo Technology, Inc.

33 EMAC, Inc. 11, 87 Lemos International 85 PTLogica 92 Trace Systems, Inc.

87 Earth Computer Technologies 2, 89 Link Instruments C4 Parallax, Inc. 40 Tri-M Systems, Inc.

88 eMicros 33 Linx Technologies 85 Phytec America LLC 86 Triangle Reasearch Int’l, Inc.

30 ExpressPCB 87 MCC (Micro Computer Control) 27 Pico Technology, Ltd. USA 86 WCSC (Willies Computer Software Co.)

25, 91 ezPCB 41 Matrix Orbital 90 Pioneer Hill Software 90 Zanthic Technologies, Inc.

Preview of May Issue 202 ATTENTION ADVERTISERS


Theme: Measurement & Sensors June Issue 203
Proton Precession Magnetometer Deadlines
Energy and Load Analyzer Space Close: April 12
Being an Embedded USB Host Material Close: April 20

Circuit Board Plotting Theme:


Temperature Calibration System Communications
The Witness Camera: Build a Self-Recording Surveillance Camera BONUS DISTRIBUTION:
NXTcomm, RoboBusiness

Call Shannon Barraclough


LESSONS FROM THE TRENCHES More “Hello World”: C Program Flow
now to reserve your space!
FROM THE BENCH What’s the Slope?: Using an Accelerometer to Measure Slope 860.872.3064
SILICON UPDATE Be All You Can Bee e-mail: shannon@circuitcellar.com

94 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


XBee™ ZigBee OEM RF Module XPort™ AR
ZigBee/IEEE 802.15.4 compliant solution XPort™ AR contains all the essential
that delivers critical data between devices. device computing and networking
Operates within the ISM 2.4GHz-frequency features built into a single RJ45 package,
band, 1mW power output up to 100m range, including a 120Mhz DSTni™ processor,
U.FL.RF connector, -40°C to 85°C temp. range, and 10/100 Base-T/TX Ethernet connection, an
chip or wire options. Supports advanced networking and embedded web server, and a full network
low-power modes. operating system with TCP/IP protocol stack.

mouser.com/maxstream/a mouser.com/lantronix/a

FlashDisk Module
Provides non-volatile,
solid state data and
program storage
for embedded

Embedded Products for applications.


Operating system,

the Latest Technologies application software


compatibility, and portability is ensured by
the module’s True IDE interface. No moving
parts allow for more rugged and reliable
performance than rotation hard drives.

mouser.com/stec/a

4000
High-Performance
Microprocessor
Low EMI
microprocessor for
embedded control, communications, and
Ethernet connectivity. Glueless architecture,
10Base-T Ethernet, C-friendly instruction
set. Up to 60MHz, 8 independent DMA
channels, supports 8 or 16-bit Flash and SRAM
memories, 7 hardware breakpoints, 40+ I/O
lines.

Rabbit Semiconductor BL2600 Wolf™


mouser.com/
rabbitsemi/a

Reduced time to market is critical for new


product designs -- lost time means lost revenue. MOD5282
That’s why engineers depend on Mouser to
deliver a broad selection of embedded products 32-bit
fast! Processor
And because these components have a Module
solution designed in, engineers can utilize
these plug-and-play modules from test through
32-bit 66MHz ColdFire
production - saving time and money.
processor with 10/100 Ethernet, 3 UARTs,
Experience Mouser’s time-to-market
advantage! Our vast selection of the NEWEST 8 10-bit ADC, I2C, SPI, and 50 digital I/O.
products, NEWEST technologies, new catalog Comprehensive software package consists
every 90 days, no minimums, and same-day The Newest Products of uC/OS RTOS, TCP/IP stack, web server,
shipping on most orders, gets you to market For Your Newest Designs NetBurner Eclipse IDE with C/C++ compiler,
faster. We make it easy to do business with and debugger.
Mouser!

mouser.com (800) 346-6873 mouser.com/


netburner/a

The NEWEST Semiconductors | Passives | Interconnects | Power | Electromechanical | Test, Tools & Supplies from Mouser Electronics
Mouser and Mouser Electronics are registered trademarks of Mouser Electronics, Inc. Other products, logos, and company names mentioned herein, may be trademarks of their respective owners.
PRIORITY INTERRUPT
by Steve Ciarcia, Founder and Editorial Director

Only Real Events Lead to Real Trends


T here have been lots of blogs and online articles stipulating that print media is dead, but let’s face it, they are mostly online publishers and have
no particular reason to say otherwise. I’m not swayed by one-sided dialog. Only real events lead to real trends.
Two recent events in particular caught my attention, both at PC Magazine. In the February 6 issue, columnist Michael Miller announced that his
column would no longer be in print, but that he would still write a “columnist’s blog” on the magazine’s web site. Soon after that, Bill Machrone
announced in his column that he too was stepping down. To my knowledge, both of these guys are former editors-in-chief of PC Magazine and should
have influence where it counts. This hardly jibes with Bill’s comment that, “As the technical publishing industry continues trying to find the balance
between print and online media, economic forces weigh against the column's continuance.” (“Wrapping Up,” PC Magazine, January, 31, 2007)
Admittedly, he wasn’t saying print is dead, but it sure leaves a lot of speculation about what he and Michael will really be doing for ZD in the future.
These guys aren’t the only ones. An editorial by Josh Norem at www.hardocp.com is about how he, the former editor-in-chief of Maximum PC
print magazine, is now at HardOCP online magazine because he thinks print magazines like Maximum PC are dying: “These days, readers flock to
their favorite website, and instead of gauging public interest in terms of the number of issues sold, we measure it in page views.” (“Magazines vs.
the Web: End of an Era,” HardOCP, February 5, 2007) Of course, there is also this little thing about being priced out of the housing market where he
lived when he worked for Maximum PC that influenced his decision, but heh….
Seriously, if I tone down his rhetoric a bit, I might agree with Josh to some extent. Magazines that are entirely dependent on breaking news or
up-to-the-minute product reviews in a fast-selling market are in a world of hurt. Print magazines have a lead-time associated with physically printing
and distributing paper that adds up to weeks. Online magazines and news sites can post things online directly from an editor’s desktop. The criti-
cism is that why should you pay for “old” content in a print magazine when you can get it free and quicker online.
The car was supposed to eliminate the horse, television was supposed to eliminate radio, radio was supposed to eliminate newspapers, e-mail
is supposed to eliminate the post office, etc, etc. Give me a break. Technology is evolutionary (and, BTW, I heard a recent statistic that there are
more horses in the U.S. today than there were in 1900). Just because one segment of an industry is discovering intense competition, it doesn’t mean
the whole industry is suddenly dead. It just means that the concept of publishing has hybridized to include a range of being completely online at one
end and all paper and ink at the opposite end.
I like to think that Circuit Cellar is situated correctly on the curve, but it’s always a balancing act to know how far and how fast to move along it.
Print magazines used to simply rely on the convenience of paper as their greatest raison d’etre—high-resolution photos, high physical content, and
little concern about losing paper. This was compared to reading relatively low-resolution, low-capacity content stored on a bulky and expensive lap-
top that you definitely didn’t want to leave on the train. Today, the same is not true. Even though displays don’t yet reach Circuit Cellar’s 2,550 × 3,300
paper page resolution, a cheap super-high resolution OLED or an e-paper with an integrated wireless connection to an infinite amount of download-
able media is only a few development generations away. When that happens, it will just be defined as the new print media for us. Circuit Cellar intends
to be right there on that OLED too.
The point that’s missing in everyone’s dire predictions is that they are confusing the words “print media” with the problems arising from “tradition-
al concepts about print media content.” Online or paper, magazines survive only if people value their content. In a situation when the source infor-
mation is presented in parallel to all media at the same time, such as news events and new products for review, the publisher who gets it to readers
first is the clear winner. The only mitigating factor that eliminates publication timing as an overriding issue is where the content is entirely unique or
there is significant value added to the content by the publisher. In the case of PC Magazine, its future relies on maintaining the quality of its product
reviews, not just doing them quicker.
In the case of Circuit Cellar, we like to think that it is our unique high-quality content that keeps both readers and advertisers coming back for
more. Yes, Circuit Cellar is a print magazine today, but it’s also part of an evolution that is always transforming. A dozen years ago we had no web
site and were strictly print. Today, we are both an online and a print magazine with a very significant web presence.
And, just so you know that I follow my own advice, our hybrid methodology endeavors to dispel the greatest limitation of these traditional print
media publishing concepts: content size. I did a little quick math before writing this editorial and it’s an interesting statistic. As a print magazine, we
publish approximately 750 pages of design articles each year in the print magazine. However, if you want to experience some “value added” and see
a lot more unique content, you should also be on our web site. It turns out that in an average year we typically post about 1,500 pages of complete-
ly new and unpublished design projects and white papers on our web site. Go for it.

steve.ciarcia@circuitcellar.com

96 Issue 201 April 2007 CIRCUIT CELLAR® www.circuitcellar.com


We have lowered our quantity pricing on SX chips. Now you can continue to use SX microcontrollers
in your production projects and enjoy even better pricing. Parallax SX microcontrollers are RoHS
Compliant, RISC architecture, high-speed microcontrollers with flash program memory, in-
system programming and debugging capability.

Part # Pins I/O EE/Flash RAM Qty. 1 Qty. 5 Qty. 100 Qty. 1000
SX20AC/SS-G 20 12 2K bytes 137 bytes $2.79 $2.51 $2.23 $1.89
SX28AC/DP-G 28 20 2K bytes 136 bytes $2.79 $2.51 $2.23 $1.89
SX28AC/SS-G 28 20 2K bytes 136 bytes $2.79 $2.51 $2.23 $1.89
SX48BD-G 48 36 4k x 12 words 262 bytes $2.79 $2.51 $2.23 $1.89

If you have not yet tried programming with an SX, this is the time to get started. Parallax offers free
development software, including SX/B, a BASIC language compiler for the SX microcontroller. The SX/B
compiler speeds the programming of SX chips by providing a simple, yet robust high-level language
familiar to Parallax customers designed to help the transition from high-level programming (ie. BASIC
Stamp®) to low-level programming (assembly language). For beginners we recommend the SX Tech Tool
Kit PLUS (#45181; $99.95) and a 7.5 VDC 1 Amp power supply (#750-00009; $10.95).

Order Parallax SX microcontrollers online


at www.parallax.com or call the Parallax Sales
Department toll-free 888-512-1024 (Mon-Fri,
7am-5pm, PT).
Parallax, and the Parallax logo are trademarks of Parallax, Inc. BASIC Stamp
is a registered trademark of Parallax Inc.

También podría gustarte