0% found this document useful (0 votes)
252 views100 pages

Oscilloscope, Logic Analyzer, Spectrum Analyzer, FFT. (PDFDrive)

About electronic measurement instruments

Uploaded by

Santhosh s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
252 views100 pages

Oscilloscope, Logic Analyzer, Spectrum Analyzer, FFT. (PDFDrive)

About electronic measurement instruments

Uploaded by

Santhosh s
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 100

CIRCUIT

www.circuitcellar.com #144 July 2002

CELLAR
O
®

.R
i2
.H
LE
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
E

GRAPHICS AND VIDEO


M
U
R

Smartswitch Smarts
iU
.G

Stabilize Your Bias


W

An LCD Controller
W
W

Dealing with
Dead Time

0 7>

7 25274 75349 9

$4.95 U.S. ($5.95 Canada)


W
W
W
.G
iU
R
U
M
E
LE
.H
i2
.R
O
W
W
W
.G
iU
R
U
M
E
LE
.H
i2
.R
O
Digital Oscilloscopes

O
.R
• 2 Channel Digital Oscilloscope DSO-2102S $525

i2
• 100 MSa/s max single shot rate DSO-2102M $650
• 32K samples per channel Each includes Oscilloscope,

.H
• Advanced Triggering Probes, Interface Cable, Power
• Only 9 oz and 6.3” x 3.75” x 1.25” Adapter, and software for
• Small, Lightweight, and Portable Win95/98, WinNT, Win2000

LE
• Parallel Port interface to PC and DOS.
• Advanced Math options
• FFT Spectrum Analyzer options
E

Logic Analyzers
M
U
R
iU
.G
W

• 40 to 160 channels • 24 Channel Logic Analyzer


W

• up to 500 MSa/s • 100MSa/S max sample rate


• Variable Threshold • Variable Threshold Voltage
W

• 8 External Clocks • Large 128k Buffer


• 16 Level Triggering • Small, Lightweight and Portable
• up to 512K samples/ch • Only 4 oz and 4.75” x 2.75” x 1”
• Optional Parallel Interface • Parallel Port Interface to PC
• Optional 100 MSa/s Pattern Generator • Trigger Out
• Windows 95/98 Software
LA4240-32K (200MHz, 40CH) $1350
LA4280-32K (200MHz, 80CH) $2000 LA2124-128K (100MSa/s, 24CH)
LA4540-128K (500MHz, 40CH) $1900 Clips, Wires, Interface Cable, AC
LA4580-128K (500MHz, 80CH) $2800 Adapter and Software $800
LA45160-128K (500MHz, 160CH) $7000
All prices include Pods and Software

www.LinkIns4.com
Link Instruments • 369 Passaic Ave • Suite 100 • Fairfield, NJ 07004 • (973) 808-8990 • Fax (973) 808-8786
W
W
W
.G
iU
R
U
M
E
LE
.H
i2
.R
O
check out what’s new at www.saelig.com!

DrDAQ
Educational
PC-based Instruments NEW!!
Datalogger ADC-10 8-bit $85 through ADC-216 16-bit $799—display 12-bit
with built-in scope, spectrum and meter simultaneously. Connect to PC
sensors! parallel port and start 100Ms/S
www.drdaq.com gathering/displaying data dual-ch
immediately!
DrDAQ plugs into a PC for useful scope
• EnviroMon temperature adapter
datalogging at school, college,
logging/alarm system
industry. Built-in sensors for light, standalone or with PC.
sound, temp. or add pH sensor and ADC-212/100
run one of the many suggested
• TH-03 thermistor-
to-PC converter
science experiments! - only $99!
• TC-08 8x thermocouples
$1015!!
Remote control & data acquisition
RS232 to RS422/485 Make PCs
self-pwrd converters BITlink ®
• Plug directly into PC
2 talk I C power & data
on two-wire
— self powered!
• Drive any RS422 easily! control network

or RS485 devices.
• Send control and data Industry-standard card for PC’s NEW! Euroquartz filters/crystals!
100s of feet! ISA/P-port/PCI versions
K422/K485, 25pin > 9pin . . . $69 2-6V I2C bus versions 2-year self-contained
DATALOGGERS for volts, switch-
K2 9pin > 9pin . . . . . . . . . . $69 • Master, Slave or Bus monitor
closures, events, flow, pressure, etc.
Isolate RS232/422/485 signals • Control or program I2C devices See www.abidata.be for details
K4xx-ISOL 25pin ICA90/93LV - PICA90/93LV PCI90/93LV
self-powered . . . . . . . . $139 I2 C”

CANbus Starter Packs


- from $299!
w to
“Ho aelig.com
NEW! 9p-9p K3-ISOL - $129! www.s

! PCI/ISA/PCMCIA/PC104/ by J
WILKE TIGER MODULES
a
W
Sn g VME/cPCI format boards. fo nz

PCMCIA
O com r all
multitasking powerful BASIC building blocks
N Pi Software drivers for most OS’s. pute
Go g g rs

Datalogger TDS2020
L CAN/Ethernet bridges, etc.
BASIC Tigers are
tiny multitasking
computer systems lowpower PCcard logging SMD PCB adapters
for quick project
• Store analog/digital for prototyping
development.
Powerful features and low /GPS or CANbus data
prices make Tigers a number
one choice for developers: super-fast
on FlashATA cards -
read on your own PC! USB ic’s
development cycle, high reliability products, • > 100 customizable USB <> RS232 easily!!
>100,000 instructions/s, up to 38 I/O lines, software modules— US232: USB <> RS232 cable $35
A/D, D/A, I2C, SPI, , text/graphic LCD inter- finish REALLY quickly.
face, up to 50,000 lines of BASIC, RTC/watch-
• 8ch 10bit A/D, 33 I/Os, I2C, 2 x Saelig Company brings you unique,
dog timer. Easy connection and software for
RS232, interrupts, sleepmode, easy-to-use control and instrumentation
Expansion Modules for CANbus, TCP/IP for
net-access, opto-I/O, 64 analog inputs, 64 dig-
pre-emptive multitasking, easy to products to USA, mostly from Europe,
ital outputs, high-current outputs, etc. attach LCD or keypad. but now from worldwide. (Need USA
sales help - overseas companies?)
• CANbus adapter—recompile or log
TIGER Starter Kits start from $159! data over huge network! Our customers comment
on our unrivalled FREE
Customer list inc: Intel, after-sales support.

Saelig Co. Inc. Compaq, Philips, NEC,


Kodak, Nokia, US Military,
Microsoft, Dell, Xerox,
“Hi - I’m Alan
- you can email me at
585-425-3753 • Fax: -3835 Universities, T.I., Dalsa, [email protected] for free
advice for your control or
Harris, Litton, Sony, J&J,
www.saelig.com • [email protected] Thomson, H-P, Agilent, etc.
measurement problem.”
12 Driving the NKK Smartswitch
F E AT U R E S
ISSUE
Part 1: Configuration and Software
Aubrey Kagan

20 Short Solutions
Build a Graphics LCD Bias Supply
AVR MCU-Based AC Phase Controller

144
Brian Millier

24 An 80C31-Controlled Power Supply


Noel Rios

34 Taming the Transients


George Novacek

42 LCD Controller for a PIC


Peter Chia

52
RoCK Specifications
Part 4: Tying Up Loose Ends
Joseph Jones & Ben Wirz

60 Dealing With Motor Control Dead-Time Distortion


Ross Bannatyne & Dave Wilson

66 Starting Down the Pipeline


Part 2: The Long and Short of It
Jim Turley
COLUMNS

6 Task Manager
30 I ROBOTICS CORNER Jennifer Huber
Reliable Information
Extreme OSMC
Part 2: The Modular OSMC Brain
Sonny LIoyd
8 New Product News
edited by John Gorsky
46 I APPLIED PCs
Building a Modular Programming Platform
Part 1: The Program Module 11 Test Your EQ
Fred Eady
94 Advertiser’s Index
70 I FROM THE BENCH
SmartMedia File Storage
August Preview

Part 2: Directory Entries


Jeff Bachiochi 96 Priority Interrupt
Steve Ciarcia
Like Avoiding a Bus
78 I SILICON UPDATE
Eight Isn’t Enough
Tom Cantrell

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 5


TASK MANAGER
EDITORIAL DIRECTOR/PUBLISHER CHIEF FINANCIAL OFFICER
Reliable Information Steve Ciarcia Jeannette Ciarcia
WEB GROUP PUBLISHER ACCOUNTANT
Jack Shandle Howard Geffner

MANAGING EDITOR CUSTOMER SERVICE


Jennifer Huber Elaine Johnston

w here would we be without reliable displays?


Having immediate access to data readouts is not
only useful, it’s crucial in many applications. For
instance, quick and concise messages relayed for medical
SENIOR EDITOR
Rob Walker
TECHNICAL EDITOR
C.J. Abate
WEST COAST EDITOR
ART DIRECTOR
KC Prescott
GRAPHIC DESIGNER
Mary Turek
STAFF ENGINEERS
Jeff Bachiochi
Tom Cantrell John Gorsky
equipment can save lives. The ability to easily check on your home automa- CONTRIBUTING EDITORS QUIZ COORDINATOR
tion system can help you protect your family and home. The benefits of Ingo Cyliax David Tweed
decent graphics displays are obvious in a plethora of applications. Fred Eady
George Martin EDITORIAL ADVISORY BOARD
This issue contains articles about a few that we’re sure you’ll find interest- George Novacek Ingo Cyliax
ing. After seeing the ads, Aubrey Kagan decided it was time to explore the Norman Jackson
NEW PRODUCTS EDITOR David Prutchi
capabilities of the Smartswitch from NKK Switches. He also wanted to make John Gorsky
use of the PSoC from Cypress Microsystems. The Smartswitch is a single- PROJECT EDITORS
pole switch that’s normally open. An LCD activates the switch. The results of Steve Bedford
David Tweed
the project definitely put the Smartswitch as well as the PSoC in favorable
light. Working with Aubrey’s source code, you can test them yourself. Cover photograph Ron Meadows—Meadows Marketing
For further reading on graphics displays, turn to page 42. Keeping tabs on PRINTED IN THE UNITED STATES
systems built with PIC devices can get annoying when you have to rely on
ADVERTISING
either LEDs or seven-segment displays. But, after reading about Peter Chia’s ADVERTISING SALES MANAGER
project, you’ll forget your notion of having to accept the standard way of doing Sean Donnelly Fax: (860) 871-0411
things. What about building an LCD controller for PIC devices? Another plus (860) 872-3064 E-mail: [email protected]
Cell phone: (860) 930-4326
is that Peter’s project uses only a few parts, so expenses are down.
You can save some money with Brian Millier’s suggestions, as well. Using ADVERTISING COORDINATOR
Valerie Luster Fax: (860) 871-0411
an inexpensive microcontroller, he tackles how to maintain desirable display (860) 875-2199 E-mail: [email protected]
contrast over a range of temperatures. The key to success is stabilizing the ADVERTISING CLERK
bias. With an AVR micro, Brian manages to keep the bias stable yet variable. Deborah Lavoie Fax: (860) 871-0411
But, he doesn’t stop there. In addition to the LCD solution, Brian also discuss- (860) 875-2199 E-mail: [email protected]
es an AVR microcontroller-based AC phase controller. CONTACTING CIRCUIT CELLAR
SUBSCRIPTIONS:
So, throughout this issue, you get a healthy dose of display-related materi- INFORMATION: www.circuitcellar.com or [email protected]
al. The articles talk about solutions to typical problems, which are always help- To Subscribe: (800) 269-6301, www.circuitcellar.com/subscribe.htm, or
[email protected]
ful, as well as introduce you to a new LCD module that might pique your inter- PROBLEMS: [email protected]
est. The common thread between Brian and Peter’s applications is giving you GENERAL INFORMATION:
TELEPHONE: (860) 875-2199 Fax: (860) 871-0411
ways to save money, obviously another benefit that’s always welcome. INTERNET: [email protected], [email protected], or www.circuitcellar.com
EDITORIAL OFFICES: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066
In this issue, you’ll also find articles that cover a variety of topics other than NEW PRODUCTS: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066
graphics and video. A frequent contributor, George Novacek, is back with [email protected]
AUTHOR CONTACT:
instruction on how to tame transients. If you’re interested in improving your E-MAIL: Author addresses (when available) included at the end of each article.
motor control, you’ll want to read Ross Bannatyne and Dave Wilson’s expla- For information on authorized reprints of articles,
nation of how to handle distortion caused by dead time. They will impress you contact Jeannette Ciarcia (860) 875-2199 or e-mail [email protected].
with their inexpensive solution that enables a quiet, smooth-running motor. CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) and Circuit Cellar Online are pub-
Also, turn to page 50 for the fourth and final installment of “RoCK lished monthly by Circuit Cellar Incorporated, 4 Park Street, Suite 20, Vernon, CT 06066 (860) 875-2751. Periodical rates paid at
Vernon, CT and additional offices. One-year (12 issues) subscription rate USA and possessions $21.95, Canada/Mexico
Specifications,” by Joseph Jones and Ben Wirz. The series is a step-by-step $31.95, all other countries $49.95. Two-year (24 issues) subscription rate USA and possessions $39.95, Canada/Mexico
$55, all other countries $85. All subscription orders payable in U.S. funds only via VISA, MasterCard, international postal money
analysis of the RoCK, Joseph and Ben’s winning project from the Design 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
Logic 2001 contest sponsored by Atmel. The wrap-up covers the discrete 03755-5650 or call (800) 269-6301.
motor driver, the host interface to the RoCK, and how to create a new user- Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650.

programmed task. 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-
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®.
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
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 © 2001 by Circuit Cellar Incorporated. All rights reserved. Circuit Cellar and Circuit Cellar INK are registered trademarks
[email protected] of Circuit Cellar Inc. Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.

6 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


NEW PRODUCT NEWS
Edited by John Gorsky
PC/104 ETHERNET LAN ADAPTER UNIVERSAL DEVICE PROGRAMMER
The PC104-ELC is a 16-bit high performance The Model 869 is a universal stand-alone programmer
Ethernet LAN card. Its features include –40°C to 85°C designed to program chips while connected to a comput-
extended operation and full compatibility with IEEE er or in the field without the use of a computer. The
802.3 standards. The card delivers full-duplex Ethernet Model 869 uses B&K Precision's device libraries, which
data transmission at speeds up to 10 Mbps. support PROMs, EPROMs, PLDs, and microcontrollers.
The PC104-ELC automatically detects whether it is An extensive line of socket adapters to interface with
connected to an 8- PLCC, SOIC, TSOP, DIP, TQFP, SSOP, PSOP, or QFP
or 16-bit system. devices is also available.
The card has a After its setup, the
built-in RJ-45 con- Model 869 can be
nector, 10Base-T taken into the field
transceiver, and and used as a stand-
optional BNC con- alone device.
nector support The Model 869
10Base-2. It can be comes with a 48-pin
installed under ZIF socket and offers
PnP and jumper- buffer features
less methods or including erase, ran-
jumper selection. dom data fill, fill
This adapter is fully NE2000-compatible. It comes block, copy block, move block, swap block, buffer print,
with drivers that support network operating systems find text, replace text, 8- and 16-bit view modes, go to
OS/2 LAN, Novell NetWare, and Microsoft LAN address, checksum calculator, and a standard parallel
Manager. printer port interface.
The PC104-ELC costs $159. Volume discounts for The Model 869, with a library, costs $995. It comes
OEM and distributors are available. with software, AC adapter, and parallel cable.

Radicom Research, Inc. B&K Precision Corp.


(408) 392-9688 (714) 237-9220
www.radi.com www.bkprecision.com

THERMALLY ENHANCED MOSFETS


The SUM110Nxx and SUM85Nxx TrenchFETs are 42-V Boardnet applications. Additionally, they work in
power MOSFETs in a thermally enhanced D2PAK pack- communications applications, including primary side
age. They enable a low level of thermal resistance and switching in the isolated DC/DC converters used in
are capable of handling 29% more current than the con- servers, routers, and networks.
ventional D2PAK. Compared with conventional D2PAK devices, the
The new n-channel 40- to 200-V TrenchFETs are new SUM series offers up to 29% higher maximum
designed for use in automotive applications, including current (110 A), 75% higher power dissipation (up to
motor control, ABS, electric power steering, and 12- and 437.5 W), and on-resistance as low as 2.3 mW. Thermal
resistance is as low as 0.4°C per watt, which is 33%
lower than in standard D2PAK devices. As a result, the
devices can handle higher current and more power, or
run cooler while handling the same amount of current
and power. Select D2PAK TrenchFETs in the series fea-
ture a maximum junction temperature as high as
200°C, an improvement of as much as 14% over the
standard D2PAK.
The SUM110Nxx and SUM85Nxx cost $2.17 in
100,000-piece quantities.

Vishay Silconix
(408) 988-8000
www.vishay.com

8 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


NEW PRODUCT NEWS
KEYBOARD EMULATOR IC FOUR-AXIS MOTION CONTROL CARD
The Easy Input is an IC designed to allow the transfer The new PPCI7443 is an advanced four-axis motion
of ASCII data into keyboard-based PC programs. control card that allows control of stepper motors or ser-
Incoming data can be sent directly to applications via a vomotors. The unit incorporates a PCL6045 control chip.
USB cable as if the data were being typed on a keyboard. The PPCI7443 offers 32-bit PCI bus plug-and-play
The device uses the standard USB keyboard drivers capability. It features a maximum output frequency of
included with Windows 98 and greater operating systems 6.55 Mpps, trapezoidal and S-curve motion profile capa-
and does not require any special software to operate. bility, and the ability to change speed and position on
The Easy Input was designed for ease of use from an the fly. Any combination of two axes can be used for cir-
engineering perspective. Standard ASCII and supplemen- cular interpolation, or two, three, or four of the axes can
tal characters are placed on an 8-bit bus and clocked be used in linear interpolation.
into the device. On the 24-pin versions, Shift, Alt, and The device offers 13 home return modes, a 28-bit
Ctrl lines are also available. These lines allow you to up/down counter for incremental encoder feedback, and
produce almost any signal that can be created on a key- simultaneous start/stop motion on multiple axes. The
board. The device requires only a resistor, resonator, and software incorporates an MS-DOS C/C++ programming
cable to operate. library, Windows 95/98/ME/NT/2000 DLL, and a test
The device is available in DIP, monitor, and supports a maximum of 12 PPCI7443 cards.
SOIC, and quarter-size outline The PPCI7443 costs $650. For an additional cost, a
packages. The Easy Input is priced 100-pin cable and a junction
at $6.83 in 1000-piece quantities. board are available.

Radovan Robotics Nippon Pulse Motor Co., Ltd.


(805) 375-7059 (540) 633-1674
www.radovan.org www.pulsemotor-usa.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 9


MCU
later.
Customized MCU Design in 20 minutes or less.
Build your custom PSoC™ microcontroller with
programmable analog and digital functions from
our extensive mixed-signal library.

on #8926
Option #1530 8-bit PWM Inverting
g Amplifier
p
Option #625 Low Pass Filter 24-bit Timer
Option #4237 16-bit CRC Notch Filter

Analog 12-bit AC
A
Use the Cypress PSoC™ instead of an MCU for Comparator Incremental A/D 8-bit DAC
on
o
more flexibility, fewer parts and lower cost. Band Pass Filter
12-bit
Incremental A/D
IrDA
The versatile PSoC Programmable System-on-Chip ™ ™
Transmitter Band Pass Filter 8-bit Counter tor
il
microcontroller, winner of EDN magazine’s Innovation
of the Year Award in the 8- and 16-bit microcontroller CPU Programmable
Instrumentation
Amplifier
nnter
category, is the world’s first MCU that lets you custom
Instrumentation
Amplifier CPU Gain Amplifier lle
ffier
Analog
g
configure the exact part you need. 8-bit DAC Comparator
11-bit Analog
Delta Sigma A/D Comparator 16-bit PWM
Graphically select, place, and interconnect
the peripherals you want and adapt the
architecture with PSoC Designer™ software. There are many more blocks to work with—
and thousands of MCU configurations. To learn more
Dynamically reconfigure a single PSoC
chip multiple times—changing functionality about our innovative PSoC solutions and to enter a
on the fly in any application. drawing to win a free PSoC Development Kit
(a $1495 value), visit: www.cypress.com/ad/mcu.
Reduce BOM cost by reducing the number
of external components.

Cypress, PSoC, Programmable-System-on-Chip, and PSoC Designer are trademarks of Cypress Semiconductor Corporation. ©2002 Cypress Semiconductor Corporation. All other trademarks are the property of their respective owners.
Test Your EQ
Problem 1—The circuit shown below is Problem 5—A full adder is a circuit with three
an adjustable output voltage regulator. inputs and two outputs, and the output is a 2-bit
CIRCUIT CELLAR
Assume that the basic op-amp is ideal. binary number that gives the number of ones on
Find the regulated output voltage VO. the inputs. Can you come up with a circuit using
only full adders that can count the number of ones
+V on 15 inputs?
R2 Contributed by Dave Tweed


R1 + VO Problem 6—Now suppose you want to know if
VZ there are more than N ones on the inputs, where
N is presented as a 4-bit binary number. Can you
add this functionality using just full adders (with
Contributed by Naveen PN perhaps some inverters)?
Contributed by Dave Tweed
Problem 2—A dynamic RAM cell that
holds 5 V has to be refreshed every 20 ms
so that the stored voltage does not fall by Problem 7—For the circuit shown below,
more than 0.5 V. If the cell has a constant VCC = 15 V, hFE(min) = 30, and ib = 100 µA.
discharge current of 0.1 pA, what is the Find the minimum value of RL that will ensure
storage capacitance of the cell? saturation operation.
Contributed by Naveen PN
VCC = 15 V

RL
Problem 3—Prove that the basic resis- RB
tor-transistor logic (RTL) gate shown
below is a NOR gate. ib

VCC
Contributed by Dave Tweed
RC
VO
V1 Problem 8—What is “comfort noise”?
Q1 Q2
V2
Contributed by Dave Tweed

Contributed by Naveen PN

Problem 4—In general, what is the


order of gate complexity relative to the What’s your EQ?—The answers and 4 additional
number of inputs to be counted? questions and answers are posted at
Contributed by Naveen PN www.circuitcellar.com/eq.htm
You may contact the quizmasters at
[email protected]

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 11


addressable to allow for the mixture of

FEATURE graphics and text to be placed any-


where on the screen.

CONTEST ENTRY
ARTICLE Obviously, a microcomputer is
needed to drive the display. I wrote
the software so that the user interface
is through a series of RAM locations.
Aubrey Kagan This allows display access to an exter-
nal hardware interface such as a serial
or parallel driver (based on the micro-

Driving the NKK computer’s capabilities) in a stand-


alone application or a concurrent task
resident on the microcomputer.
At this time, I am unaware of any

Smartswitch published projects that use a Cypress


PSoC microcomputer. However, I’m
sure this will change in the near future
as more users begin to appreciate the
Part 1: Configuration and Software advantages of the PSoC. The versatility
of its I/O configuration, the low cost of
its development tools, and the price
and performance of its peripherals
make it an extremely attractive option.

t
In addition, the PSoC is available in
DIP packages, which is great for low-
he NKK volume applications and debugging.
Smartswitch is a And that’s a plus for aging baby
single-pole, normally boomers who have difficulty seeing the
Sure, the NKK open switch with an pins on SMD devices, let alone con-
LCD screen that serves as its activa- necting an oscilloscope probe to one.
Smartswitch looks like tor. I have often looked at the adver-
tisement for the Smartswitch and THE LCD
a cool device, but thought about how cool it would be to The LCD is controlled row by row
use it. But where and how can the with a 40-bit shift register. The first
how can you actually Smartswitch be used? In this series of four bits shifted out are invisible, but
use it? Aubrey found articles, I’ll explain my answer to
those questions.
they must be included in the shifting
process. Each pixel has been allocated
the answer with a little The switch head of the Smartswitch a number so that the software imple-
consists of a 24 × 36 pixel LCD and mentation can address a specific loca-
help from a Cypress some rudimentary driver electronics tion. You can see this allocation in
that drive one row at a time. Control Table 1. The firmware display driver
Microsystems PSoC signals are required to shift out the creates a memory map where each
pixel state for each row, latch the pixel maps to a unique bit in RAM. As
microcomputer. In this pixel states, and synchronize the first you’ll see, the map is continuously
article, Aubrey line. In addition, the display has a
backlight that can be configured as
output to the display by the drivers.
In order to economize on RAM, the
describes the inter- red, green, or yellow. I have tried to memory map is implemented as a 24 ×
make the display interface pixel 5 unsigned character array (cMatrix
face to drive the
Smartswitch. Visible pixels Invisible pixels

Row 0 39 38 37 … 7 6 5 4 3 2 1 0
Row 1 79 78 77 … 47 46 45 44 43 52 41 40
Row 2 119 118 117 … 87 86 85 84 83 82 81 80
… … … … … … … … … … … … …
Row 22 919 918 917 … 887 886 885 884 883 882 881 880
Row 23 959 958 957 … 927 926 925 924 923 922 921 920

Table 1—The numbering of the pixels is arbitrary. Pixels 0, 40, 80, etc. are the first bits shifted out for each row.

12 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


[24][5] in the software). Obviously, the
b)
first index is the row number and the a)
VS VCC VS
ULN2803
second refers to the column number. R1
Port1_1 12
Each bit in a byte is allocated to a 5
pixel as shown in Table 2. NKK 13
NKK VR1
The design of the Smartswitch 14 R2
Port1_0
allows for multiple switches by link- 11
ing the 40-bit shift registers. Because ULN2803
of the processor’s RAM limitations, I
have left room for only one switch Figure 1a—With the backlight drivers, when port1_1 is high and port 1_1 is low, current flows through R1 and
and one controller. I believe the road from pin 5 to pin 14 and turns on the green LED. Note that the current will still flow through R2. The red LED will
be on when port1_0 is high and port 1_1 is low. Toggling at about 550 Hz will produce a yellow color. b—This is
map for the PSoC includes devices
the LCD viewing angle adjustment. I used 9 VDC for VS and 1 KB for VR1.
with up to 1 KB of RAM, so it may
be possible someday to expand the
application. At any rate, the PSoC’s As you can see in Figure 1a, a turn on. The driver also draws current
low cost may allow for a multi- resistor connects each side of the through the resistor on the near side,
processor solution because the LED to the same voltage supply. so it must be capable of sinking the
switch itself is around $50. Different LED colors have different total current. Note that each driver is
efficiencies. You can compensate for connected to a microcomputer output.
HARDWARE INTERFACE this by programming a different cur- In this case, it’s connected to port 1,
The backlight of the LCD consists rent for each direction. bits 0 and 1.
of bicolor LEDs. When current passes The connections to the LEDs are As with all LCDs, it is important
in one direction, the backlight color totally independent of the rest of the to be able to adjust the viewing angle.
is red; when it passes in the reverse control circuitry so this supply need The Smartswitch requires a simple
direction, the color is green. not be VCC. Each side of the LED back- interface with a potentiometer
Toggling from red to green at the cor- light is also connected to an open col- between a supply, as you can see
rect frequency will trick your brain lector driver. When active, the driver demonstrated in Figure 1b. NKK rec-
into thinking the color is yellow. will sink the current through the ommends 9 to 12 VDC.
The backlight is turned off when resistor on the far side of the LED and There are four control lines to set
there is no current. through the LED, causing the LED to the content of the LCD matrix. Data
is presented serially on the DIN line,
and clocked into the shift register on
the negative transition of the clock
Listing 1—An endless loop is a simple form of cooperative multitasking. The project is broken into func-
tions and each function is executed sequentially. The function has total control (except for interrupts) and signal SCP. In other words, for each
must write the yield control back to this routine within a reasonable time. row of pixels, 40 bits are shifted into
the DIN line and clocked on the nega-
while (1) tive edge of SCP.
{
The contents of the shift register are
switch (cPhase)
{ transferred to the pixel drivers on the
case 0: negative edge of the LP signal. The LP
RefreshMatrix(); signal is independent of the SCP sig-
cPhase++; nal, but must occur periodically with
break; minimal jitter or the display’s intensi-
case 1:
ty will vary. NKK specifies a period of
Backlight();
cPhase++; 0.7 to 1.2 ms, but I found that 1 ms
break; works best for this application.
case 2: The Smartswitch has an internal row
ProcessCommand(); pointer that is incremented every LP
cPhase++;
signal. This counter is reset by the
break;
case 3: first line marker (FLM) signal, which
//Process(); must be active (after LP has transferred
cPhase++; the line data) for the data of the first
default: row. There are no restrictions on pump-
cPhase=0; ing the data out (subject to the maxi-
break;
mum 2-MHz clock rate), so it can be
}
} accomplished quickly. This gives the
processor some processing time until
it is necessary to toggle the LP signal.

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 13


cMatrix[n][0] cMatrix[n][1] cMatrix[n][2] cMatrix[n][3] cMatrix[n][4] an on-chip temperature sensor. On
the digital side, there are counters (up
Bit number 7 6 1 0 7 0 7 0 7 0 7 1 0 to 32 bits) and pseudo-random num-
ber generators (up to 32 bits). In addi-
Row 0 39 38 … 33 32 31 … 24 23 … 16 15 … 8 7 … 1 0
tion, there’s pulse width modulation
Row 1 79 78 … 73 72 72 … 64 63 … 56 55 … 48 47 … 41 40
… … … … … … … … … … … … … … (up to 16 bits), UART, SPI, a CRC
generator, and timers (up to 32 bits).
Table 2—In RAM to pixel mapping, for example, the most significant bit of cMatrix[1][0] will map to pixel 79 and Future additions may include an I2C
the least significant bit of cMatrix[0][2] will map to pixel 16. and USB modules.
It’s your job to supervise the alloca-
You can see the timing relation- Designer allows you to choose tion of these functions to the blocks
ships for this project in Figures 2a and between peripherals and allocate them and to choose the I/O pins.
b. Most of the hardware interface is to the analog and digital blocks on the Remember, though, that the number
achieved through peripherals that are chip. The peripherals include multi- of available blocks will limit the num-
implemented on the PSoC. But before channel A/D converters (up to 12 bits), ber of functions you can implement.
I describe the peripherals, I’ll intro- programmable gain amplifiers, com- Keep in mind that the PSoC is like
duce you to the general configuration parators, D/A converters, filters, and any other microcomputer—it’s not a
of the PSoC.
Listing 2—The background routine waits for a signal from the timer interrupt, then it initiates the first byte of
PSoC transmission on the SPI block and prepares the pointer for the interrupt routine for the next four bytes or the
Despite the risk of dampening your row. Every 24 lines the FLM signal is activated.
enthusiasm, I want to make clear that
void InitiateRefresh (void)
this family of devices (and the associ- {
ated tools) is relatively new. As a RAMpnt=&cMatrix[0][1];
result, there are some minor bugs cRowCount=0;
//Initiate the transmission by writing the first byte. The
and certain aspects of the documen- rest get sent in assembler
tation have conflicting information. PRT0DR |= FLM;
All in all, some features of the user cByteCount=4;
//Update the display here
interface and C compiler need //Display();
improvement. However, if you enjoy SPIM_1_SendTxData(cMatrix[0][0]);
the challenge of mastering a new }
void RefreshMatrix (void)
micro, especially one with the fea- {
tures of the PSoC, then you’re going if (cStatus & LP_DONE)
to love this product. {
cStatus &= ~LP_DONE;
Almost every microcomputer on if (cRowCount<23)
the market has a finite peripheral set {
that may include a UART, A/D con- cRowCount++;
RAMpnt=&cMatrix[cRowCount][1];
verter, and timers. But if you want a cByteCount=4; //sending four more bytes
micro without the ADC, you’ll have SPIM_1_SendTxData(cMatrix[cRowCount][0]);
to change the device. Sometimes you //Send first byte
}
can get lucky and the pinout will be else {
the same, but you’ll still have to jug- InitiateRefresh();
gle the features and often pay for ones //Only update here
}
that you don’t need. //Only get here every 1 ms, so you can use as basis of ms
Fortunately, Cypress has taken a dif- timer
ferent approach. The PSoC has eight if (cFlashCount!=0)
{
digital blocks and 12 analog blocks. cFlashCount--;
Like a PLD, these blocks can be con- }
figured to provide different functions, if (cYellowCount!=0)
{
so you can customize the microcom- cYellowCount--;
puter for the exact peripherals you }
need. In fact, the peripherals can be if (cCount!=0)
{
configured dynamically to share the cCount--;
configuration blocks, making them }
something like hardware subroutines. }
}
The user interface, or PSoC
Designer, is available for free on the
company’s web site. The PSoC

14 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


a) b)

Figure 2a—This is a row update. Although difficult to count here, there are 40 SCP pulses in five bursts between
each LP signal. Note the 1-ms update time. b—The FLM extends from before the first data bit to the trailing edge
of the LP signal. FLM becomes active before the first SCP transition for the row. You’ll see later that the LP will
trigger an interrupt that flags the background program. The FLM is set in the background program. The indicated
time is the time for the processor to get to the point in the program where the bit is set. Care must be taken to see
that the last of the 40 bits is shifted in before the next LP signal.

panacea. Before committing to a tings are dynamic registers, so they


design, take time to evaluate the can be overwritten to change the con-
peripherals, especially the analog figuration. And this doesn’t have to be
blocks. The analog blocks are not rail- as simple as changing the gain on an
to-rail, but rather they are 2.5 V (sup- amplifier, in fact, more complex
ply half-rail). That is, the analog zero arrangements could be made.
is considered to be at 2.5 V, and the Suppose you had a converter from
input signal may need to have a DC SPI to UART. It would be possible to
offset applied. interface with an SPI peripheral,
When the function module is gather the data, reconfigure the digi-
placed and graphically configured, tal blocks to perform as a UART,
PSoC Designer creates the code to set and then retransmit the data on dif-
up the registers needed to realize the ferent pins. The reverse would also
function. All of the configuration set- be possible.

Listing 3—The terminal count on the timer module will generate an interrupt and output pulse every mil-
lisecond. A flag is sent in the interrupt routine to indicate to the background routine that the pulse has been
generated so that the next line can be shifted out. Note the software loop that delays the reset of the FLM
line. This happens every interrupt whether or not the FLM is set.

Timer8_1INT:
//place user code here
//set cStatus bit to indicate interrupt has happened
push a
mov a,01h
or [_cStatus],a
//if requested, drop FLM
tst [_cStatus],02h
jz skip1
//delay so FLM goes to negative after LP
mov a,48
skip2:
dec a
jnz skip2

and [_cStatus],0fdh
//clear the bit
and reg[PRT0DR],0feh
//clear the FLM
skip1:

pop a
reti

16 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


352*5$03,&Šª6,1%$6,&
MBasic Software
Whether your just learning or a professional, Programming PICmicro®
MCUs has never been easier ! MBasic is much simpler than C or
Assembly. MBasic creates a one click solution that allows you to
experiment and test code changes on-the-fly! Bring your projects to life
quicker and easier with MBasic for PICmicro® MCUs !

ICD - In Circuit Debugger


Stop wasting time strategically planting debug statements throughout
your entire program. MBasic includes a built-in ICD (In Circuit
Debugger ) FREE. Watch variables, SFRs and RAM values as each
line executes. MBasic’s ICD is so easy to use, even the first time user
can have it up and running in minutes !
MBasic and Assembly Language

PICMICRO MCU TOOLS


Seasoned Assembly programmer or just learning ? MBasic allows an
easy mix of BASIC and Assembly. Instead of spending weeks writing
your program, have it done in days !

Syntax
A complete set of easy to use commands ! Serin, Serout,
Learn to Program PIC Microcontrollers in easy to use BASIC
If..Then..Elseif..Else..Endif, Do..While, While..Wend, OWin, OWout,
ADin, Pulsin, Pulsout, PWM, Xin, Xout and more! Plus easy acces to
all PICmicro built-in hardware peripherals.

Download MBasic Math


MBasic is the only BASIC compiler that supports 32 bit floating point
Lite FREE ! and integer math. This includes 32 x 32 bit divides and multiplies.
Try before you buy ! MBasic Pro Only $229.95
Includes Printed Manual and CD-ROM with MBasic.

3,&0,&52722/6

®
Optional ISP-PRO
Items Available
- Plastic Enclosure
- 40 Pin Zif Adapter
- Universal Adapter

ISP-PRO Programmer Solderless Development Development Kit


- Uses PC Serial port (USB w/ adapter) - Completely Assembled Board Includes:
- Very Simple to use - In Circuit Programmable (ISP) - MBasic Pro Compiler
- Free Software updates - Solderless Bread Board - 2840 Development Board
- Complete with Windows IDE! - Built in RS232 (w/ Max232) - ISP-PRO Programmer
- Easy in-circuit programming - Built in Power Connector - PIC16F876-20
- Supports PIC, Scenix, I2C and more! - Removable Oscillator - 10Mhz Resonator
- Firmware upgrades Free! - Documentation - Serial Cable
- RJ-11 / 10 Pin Header - Auto Disconnect for RB3, RB6, & RB7 - Power Supply
- Includes RJ-11 Cable - Available in several models - CD-ROM and Manual

Only $59.95 Starting At $59.95 Starting At $159.95

Join our on-line PIC forums, information and help FREE!!!

7RRUGHUYLVLWwww.basicmicro.com
RUFDOO
0)$0WR30(67
M i c r o c o n t r o l l e r s M a d e E a s y™
MBASIC is a registered trademark of Basic Micro Inc.
PICmicro is a registered trademark of Microchip Inc.
are two internal prescalers available signal from an 8-bit timer that would
PSoC NKK for clocking functions, 24V1 and interrupt every millisecond. I took
P0_6 27 9 SCP 24V2. The former is the internal 24- the terminal count (TC) output
26 10 DIN
P0_4 MHz oscillator divided by a number directly to an output pin to be used as
P0_2 25 8 LP
P0_0 24 7 FLM from one to 16. The latter will further the LP signal. The width of the TC
divide 24V1 by a number from one to signal is the same as the high period
16. I set 24V1 to 16 and 24V2 to 15 in of the input clock.
Figure 3—The wire interface is simple. Note that the order to generate a clock signal of To drive the data and SCP lines, I
pin numbers for the PSoC are for the 28-pin DIP. 100 KHz with a counter resolution of used an SPI master (SPIM) without the
10 µs. All of these settings are set up receiver function. As expected, it’s pos-
Currently, PSoC Designer does in a graphical user environment, part sible to configure the edge and polarity
nothing to enhance this. It allows for of which is visible in Photo 1. PSoC of the clock signal relative to the data
one configuration and then it’s up to Designer then translates the settings being shifted out. So, I thought I would
you to create alternatives to overlay into code in a process that is transpar- relieve the processor overhead by
these functions. Cypress has decided ent to the user. allowing the hardware to shift eight
that this feature is a competitive I didn’t need many modules for the bits at a time. This called for proces-
advantage, so they have a new version implementation of the hardware sor intervention after every byte
of their PSoC Designer in the wings interface, so I decided to drive the LP under interrupt control. The only
that will simplify this process.
Cypress produces three kinds of
documentation. The first is the stan- Listing 4—The first byte transmitted from the SPIM module is initiated from the background program.
dard datasheet, which at first glance When the transmission is complete, an interrupt will be generated and program execution will be vectored
to this routine. This routine will fetch a further byte and transmit it until four more bytes have been sent.
is somewhat bewildering because of After these five bytes have been transmitted, the routine does not send another byte, so the interrupt will
the variety of configuration options. not occur again until the first byte of a new line is sent from the background routine.
When you select a module in the
user interface, a datasheet for the SPIM_1INT:
//place additional SPIM interrupt level processing here
module appears on the screen. In
push a
addition to samples of the code, the push x
datasheet reading includes all the call bSPIM_1_ReadStatus
relevant registers and I/O points. As ;wait for SPIM done, rather than buffer empty
your product is configured, the PSoC ;because of taking FLM low, after all the data has gone
Designer creates a third datasheet and a,(SPIM_SPI_COMPLETE)
jz SPIM_EXIT
specifically for that particular
//Have we transmitted five bytes (one from C call and four
arrangement so you have complete continuing from there)?
documentation of your product. mov a,[_cByteCount]
All of this is available in an 8- to jnz SPIM1
64-pin package for about $5. A full
development environment that //At this point, all 30 bits have been shifted out, so clear
FLM. reg[PRT0DR],0feh FLM must be high during LP, so set
includes C costs less than $300. And
the request.
you’d think they were paying me to or [_cStatus],02h
say this, but unfortunately they’re not. jmp SPIM_EXIT

MODULE IMPLEMENTATION SPIM1:


//Decrement count
Let’s get back to the project at
dec [_cByteCount]
hand. The PSoC does not need an mov x,[_RAMpnt+1]
external crystal operating to within //Fetch address in matrix from LSB
±2.5% of the intended oscillator mov a,[x+0]
value. This is because the internal //Fetch data from address
oscillator operates to within ±2.5% of // mov a,0ffh
call SPIM_1_SendTxData
the intended value. The base frequen-
inc [_RAMpnt+1]
cy of the unit is 24 MHz, and the //Although this is a two-byte address, it is an address in
timer/counter clock sources can be RAM so it can never be greater than 0xff.
derived from this. In fact, the digital SPIM_EXIT:
modules can work up to 48 MHz. pop x
You can set a number of global pop a
reti
resources, but I only changed three of
them for this particular application. I
set the CPU clock to 12 MHz. There

18 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


loading of the processor because the
LP_DONE flag must be seen with
enough time for the 40 bits to be
transmitted before the next LP signal
(see Figures 2a and b).
Now you know how to configure
the peripherals of the PSoC to imple-
ment the hardware interface to the
NKK Smartswitch. In addition, you’ve
seen the basic software flow to shift
data out of the shift registers con-
tained within the Smartswitch. In
Part 2 of this series, I will show you
how to add functions for a character
generator. I will also describe a user
interface that will allow the display of
graphics and text and the ability to
place them anywhere on the screen. I

Aubrey Kagan (P.E.) has 25 years


of experience in the design of
electronic industrial interfaces.
Photo 1— Pins are allocated either by clicking on the graphic outline of the package or by modifying the table in
the bottom left window. Those pins that are not allocated to the user modules may be used as standard micro-
He has a BSEE from the Technion,
computer I/O. Israel Institute of Technology and
an MBA from University of the
other information you’ll need refers to tested and when it’s greater than 24 Witwatersrand. His diverse design
the connection of the internal signals (number of lines on the screen) the experience ranges from projects
to the output pins (see Photo 1). process is refreshed and the FLM line is that operated two miles under-
Figure 3 depicts the simple wiring set high. In contrast, if it’s not greater ground in a mine to 600 miles
for the microcomputer to the LCD than 24, the counter is merely incre- above the earth in the
interface. The software for this project mented. In either case, the first byte International Space Station. He is
is written in a simple fashion allowing of the line is sent to the SPIM master currently a senior design engineer
multiple tasks. Tasks are identified and a pointer is initiated (RAMpnt) for Weidmuller Canada. You may
and numbered as cPhases. The back- for use in the SPIM interrupt routine reach him at akagan@weid-
ground routine in Listing 1 is included along with the number of bytes left to muller.ca.
in main.c. This extract is the heart of be transmitted (cByteCount = 4). I
the operation. RefreshMatrix is the prefer to do this in C because it RESOURCES
process that maintains the scan of the allows for easy access to the array.
Cypress Microsystems, “CY85C-
display. It’s contained in Matrix.c, you When the SPIM interrupt occurs, the
25xxx/26xxx,” CMS 10002A-R.13.
can see a portion of in Listing 2. processor checks to see if there are any
The interrupt of the 8-bit timer bytes left to transmit (in cByteCount). NKK Switches of America,
occurs every millisecond. The PSoC If a byte remains, the processor fetch- Inc.,“NKK Programmable LCD
Designer cannot implement interrupt es it by RAMpnt, transmits it, and Switch Data Sheet,”
routines in C, so this routine is in decrements cByteCount. If there are www.nkkswitches.com.
assembler module Timer8_1INT.asm no bytes left, the processor exits the
(see Listing 3). Note how the PSoC interrupt. Additional SPIM interrupts SOURCES
Designer has created the routine iden- will not occur until the RefreshMatrix
PSoC and Designer software
tifying where the user code should be routine writes the next byte after the
Cypress Microsystems
placed. When eight bits have been next LP interrupt.
(425) 939-1000
shifted out of the SPI controller an At the next timer interrupt, the
(877) 751-6100
interrupt is generated, vectoring to the routine sets the LP_DONE flag once
Fax: (425) 939-0999
code in SPIM_1INT.asm (see Listing 4). again and clears the FLM line after
www.cypressmicro.com
The software is connected as follows. the output signal becomes low. It
When a timer interrupt occurs, a flag always clears the FLM signal whether NKK Smartswitch
(LP_DONE) is set in cStatus. The or not it’s set. The routine stretches NKK Switches Of America, Inc.
processor tests this flag within Refresh- the point where the FLM signal is (480) 991-0942
Matrix. If set in cStatus, the LCD line cleared through a software timer loop. Fax: (480) 998-1435
pointer (RAM address cRowCount) is Take care when doing the background www.nkkswitches.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 19


member of my favorite microcon-

FEATURE troller family, the Atmel AVR family.


The ATtiny12 microcontroller used

ARTICLE here costs less than $2 in unit quanti-


ties (see Figure 1).
A fly back converter made up of
transistor Q1, inductor L1, Schottky
Brian Millier diode D1, and filter capacitor C2 gen-
erates the negative voltage. The drive
for transistor Q1 is supplied by port

Short Solutions B2 of the ATtiny12 using a pulse-fre-


quency modulation scheme. Basically,
a 10-µs active-low pulse from the
ATtiny12 turns on Q1 and transfers
roughly as much energy into L1 as it
Build a Graphics LCD Bias Supply can absorb. Q1 then is shut off for
about 50 µs, which allows L1 to dump
this energy through D1 into C2. The
AVR MCU-Based AC Phase Controller collapsing magnetic field induces a
voltage opposite to that of the charg-
ing current, so a negative voltage is
generated across C2.
The voltage is regulated with the

g raphic LCD
panels require a
stable negative volt-
help of the ATtiny12’s internal analog
comparator. I’ve configured the analog
comparator to use an internal 1.2-V
band-gap reference as the positive
comparator input. The comparator’s
When Brian proposed age source for bias pur- negative input is connected to port B1.
poses, termed VEE. Depending on the This pin acts as a summing junction
these two straightfor- size of the display, the voltage required made up of the negative bias output
could be between –7 and –15 V, but voltage and the VCC supply, the pro-
ward, simple fixes, we the current draw is miniscule. portions of which are adjustable by
Because this bias sets the contrast of R4, the voltage adjust potentiometer.
thought it was a great the display, it must be stable but vari- For now you should ignore R3.
idea to combine them able over a small range to maintain
good display contrast at various tem-
The ATtiny12 is constantly in loop
checking the analog comparator and
as a section of quick peratures. It’s also useful if the VEE sending a 10-µs pulse (followed by a
source can be varied smoothly under 50-µs rest) whenever it senses that the
solutions. Read on for computer control. Although I’ve used bias voltage is dropping below the
chips designed specifically for this user-specified set point. This action
inexpensive ways to purpose, I thought I could build a less maintains the charge on C2 and keeps
expensive version using the smallest the output well regulated. Because of
control a high-current
resistive load and
how to build a graph-
ics LCD bias supply
with Atmel products.

Figure 1—Here’s the Graphic LCD VEE generator with an Atmel ATtiny12 microcontroller.

20 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


the high switching speed, C2 can be a is sufficient to provide optimum within the ±20% fine-tuning range.
small value capacitor, but it should be contrast over a commercial tempera- Another important feature is the
tantalum for a low noise output. ture range, but you can tailor the delayed turn-on. LCD panels require
To achieve the computer-controlled value of R3 to suit a particular LCD that the VEE supply switch on later
fine-tuning of this bias supply, the application. than VCC. For the LCD panel I was
ATtiny12 also implements an 8-bit The PWM duty cycle is varied in using, this delay was 20 ms or
PWM function at port B4. After fil- response to signals present at the step greater. The program code running in
tering the PWM waveform, a voltage and dir inputs. The Step input pulse the ATtiny12 has a delay loop at the
proportional to the duty cycle of the must be at least 15-µs long to guaran- beginning to accomplish this. The
PWM waveform appears across C4. tee recognition. The high/low value actual delay time could be changed by
Using a high-value resistor for R3 present on the DIRECTION pin at the end user, if necessary, by changing
(680 KΩ) and adding this current into the time of the pulse will determine a program constant.
the summing junction at PB1 allows whether the PWM duty cycle increas- The source and object code for this
fine-tuning of the bias to be achieved. es or decreases. You can specify circuit can be found on the Circuit
Generally a ±20% fine-tuning range 256 discrete PWM duty cycle values Cellar web site. I

AVR MCU-Based AC Phase Controller

AC phase control is a well-estab- is essential to filter out any false trig- and results in a gate pulse being sent to
lished way of controlling high-current gering that might otherwise occur the triac, which turns it on. The triac
resistive loads such as lights and from noise/spikes on the AC line. gate drive is provided by the MOC3009
heaters. You can achieve this under The ’2313 receives a rising-edge optocoupler, which is specifically
computer control by using a simple INT0 interrupt just prior to the zero designed for triac triggering.
AT90S2313 AVR microcontroller to crossing. First, the ISR turns off the A three-pole DIP switch sets the
convert user-specified power levels triac drive by setting the port D4 pin device address for the controller to a
into properly timed trigger pulses to high. It clears Timer1 and loads value between zero and seven, allow-
fire a high-power triac device. Timer1’s Output Capture register with ing up to eight controllers to be inde-
Inexpensive 15-A triacs can easily the necessary delay time to produce pendently controlled using a single
handle power levels of 1800 W. the desired output power. Later in the RS-232 signal.
To accomplish this, the ’2313 AC cycle when Timer1’s value match- Timer1 is clocked by the 4-MHz
microcontroller must sense the power es the Output Capture register, a system clock that is prescaled by 64,
line zero crossing, which occurs at a Timer1 output capture interrupt is which results in it being incremented
120-Hz rate. Power control is achieved executed. The interrupt drops port D4 every 16 µs. Because the INTO inter-
by triggering the triac after some spe-
cific delay from this zero crossing. No
delay would result in full power, and a
delay approaching 8.33 ms (one half-
cycle of the AC line waveform) would
result in little power being delivered
to the load. The exact relationship is
described later.
Accurate triac trigger pulses can be
generated by a ’2313 AVR microcon-
troller using an Interrupt Service
Routine (ISR) prompted by the INT0
interrupt. INT0 is connected to a
MOC5009 optocoupler that’s fed by
the otherwise unused negative half of
the power supply’s bridge rectifier. In
this configuration, the MOC5009’s
output will be low for the entire AC
line cycle time apart from a short
interval surrounding the zero crossing.
The MOC5009 incorporates a Schmitt
trigger in its detection circuit, which Figure 2—This a complete circuit diagram of the AT90S2313.

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 21


g g
100 ting a ramp time to greater than
80 zero adjusts the controller to ramp
from its current power level to a

% Power
60 new power level upon receipt of
— Actual

40
— Fitted subsequent power level commands.
Because the ramp time parameter is
20 defined as the time it takes to ramp
0
from 0% to 100%, proportionately
0 30 60 90 120 150 180 less time is needed for smaller
Phase angle power level changes to occur.
Figure 1—You can see the relationship between the percent- All controllers, regardless of
age of power delivered and the triac firing angle. their device number (as set by the
DIP switch), will respond to com-
rupt occurs just prior to the zero cross- mands sent to device eight. This
ing, I measured that a delay of 29 (of allows you to control numerous lamps
the 16 µs clocks) was needed to pro- simultaneously. The controller’s
duce the gate pulse at the zero crossing. firmware is written using the BAS-
Similarly, the maximum delay needed COM-AVR compiler. The data rate is
for zero power was 578 clocks. Figure 1 set to 9600 bps. If you replaced the
shows the complete circuit diagram. RS-232 level shifter with the standard
The mathematical relationship MIDI optocoupler input circuit and
between a traic’s firing angle and the changed the data rate to 32,500 bps,
percentage of power delivered (0% to you could use this controller for MIDI
100%) is shown in Figure 2. This rela- applications instead of RS-232.
tionship seemed too complex for the You may download the source and
small microcontroller to calculate on object code for this circuit from the
the fly. Therefore, the power range Circuit Cellar web site. As with near-
was broken down into three straight- ly all members of the Atmel AVR fam-
line segments and a simple linear ily, this is a flash memory device and
interpolation routine was performed. is readily programmable. For more
The routine required one multiplica- information, I provided details of a
tion and one subtraction. As you can simple programmer in my previous
see, this does not result in too great article, “My fAVRorite Family of
an error from the ideal firing angle. Micros” (Circuit Cellar 133). I
I patterned the controller’s com-
mands as a subset of the MIDI com- Brian Millier is an instrumentation
mand protocol used by electronic engineer in the Chemistry Department
musical instruments. The two con- of Dalhousie University in Halifax,
troller functions are implemented Canada. He also runs Computer
using commands corresponding to Interface Consultants. You may reach
MIDI Control Change messages. him at [email protected].
BXH 07 pp is the power level, which
corresponds to the volume level in SOFTWARE
MIDI. Here, X is the controller device
To download the code, go to
number (0–8) and pp is a 1-byte value
ftp.circuitcellar.com/pub/Circuit_
representing the percentage of power
Cellar/2002/144/.
delivered (0 to 100 V).
BXH 01 dd is the ramp time, which SOURCES
corresponds to the modulation wheel
AT90S2313 AVR, ATtiny12
in MIDI. Here, X is the controller
Atmel Corp.
device number (0–8). dd is a 1-byte
(408) 441-0311
value representing the ramp time (in
Fax: (408) 436-4200
seconds) for a 0% to 100% power
www.atmel.com
level change (0–127).
Setting the ramp time equal to zero BASCOM-AVR compiler
makes the controller switch power MCS Electronics
levels immediately upon receipt of a 31 75 6148799
power level command. Alternately, set- www.mcselec.com

22 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


The embedded controller that’s out of this world.
When engineers working on NASA’s Space Shuttle imagined the right embedded controller for their critical payload
experiments, they turned to the one supplier with more solutions than any other supplier of embedded controllers in
the world — Micromint.
With over 250,000 controllers in the marketplace, Micromint has been providing innovative, turn-key solutions to the
OEM market for over twenty years- from design through production, as well as packaging and shipping the final product.
Our broad line of embedded controllers and turn-key solutions can turn your imagination into reality.

Visit our website @ www.micromint.com to see our complete line of OEM Solutions.

902 Waterway Place | Longwood, FL 32750 | 800·635·3355 | 407·262·0066 | Fax 407·262·0069


ROM. The 80C31 is a widely available

FEATURE (it’s produced by several manufactur-


ers) and high-quality microcontroller

ARTICLE for embedded design considering its


instruction set and price.
The 80C31 has 128 bytes of RAM,
two external interrupt pins, two
Noel Rios timer/counters, and serial ports (see
Figure 1). It has 32 I/O pins, but does-
n’t have ROM, so some of the ports

An 80C31-Controlled (namely ports 0 and 2) are used for the


address bus and data bus. A few of the
pins of port 3 are also used to inter-

Power Supply
face to other devices like ADCs and
DACs. The pins serve as read and
write signals for proper bus operation
like the read cycle and write cycle. So,
after interfacing the ROM, ADCs, and
DACs, you’re left with 14 I/O pins.
Port 1 is used to interface and read

e
the keypad. Some of the pins in port 3
are used for the Set Voltage and Set
very engineer, Current buttons, while others are used
technician, and to control the relay and analog switch-
hobbyist needs a sta- es to read the voltage and current to
ble power supply to be fed to the ADC.
power up the circuits they’re working U2 74HC373 is a transparent latch
on. However, it would be nice if you (see Figure 2). It’s used to obtain the
Even if you’re a could vary the potential to accommo- address because the address bus and
date many circuits. It also would be data bus are multiplexed on port 0 to
novice, it’s pretty easy pleasant if you could vary the current conserve pins coming out of the IC.
supplied to the circuit, which would The address is obtained after the
to control the power limit the power delivered in case address latch enable, or ALE, is assert-
something is wrong. The circuit fea- ed. U3 is an 8 KB × 8 UV EPROM
supplied to the cir- tured here is an 80C31-controlled (27C64) that stores the program that
cuits you’re working power supply that has voltage and
current limits that you can change to
sets the voltage and current and reads
the ADC. I chose the 27C64 EPROM
on. In this article, suit your needs (see Photo 1). Its volt- because it’s inexpensive, available, and
age ranges from 0 to 22 V, and its cur- the firmware will fit in it. You can
Noel introduces us to rent ranges from 0 to 2.5 A. actually use larger EPROMs like the
In most power supplies, you turn a 27C512, but they’re a waste of space,
a 80C31-controlled knob to adjust the voltage and current. money, and time because you’ll have
The 80C31 CPS, however, has a keypad to wire the added address pins. The
power supply, which for entering the voltage and current, 4K × 8 EPROM can also be used but
is a circuit that as well as Set Voltage and Set Current
buttons so you can change the voltage
it’s hard to obtain.

enables you to moni- and current immediately by moving


through a few menus. Additionally,
tor and alter voltage you can monitor the voltage and cur-
rent delivered by the power supply
and current levels. with the 80C31 CPS’s built-in volt-
meter and ammeter. The voltage and
current is displayed using an LCD.

CIRCUIT DESCRIPTION
The brain of the circuit is the popu-
lar 80C31 microcontroller, which is Photo 1—Take a look at the front panel of the 80C31-
the version of the 80C51 without controlled power supply.

24 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


U4 ADC0820 is a successive approx-
P0.0–PO.7 P2.0–P2.7
imation analog-to-digital converter
that converts an analog input voltage
to an 8-bit equivalent value. It’s fast VCC Port 0 Port 2
drivers drivers
and provides the necessary handshak-
ing pins to interface to the three-bus RAM
VSS Port 0 Port 2
address RAM ROM/EPROM
architecture without glue logic. U4 register
latch latch
8
ADC0820 also converts the analog
voltage to an 8-bit equivalent value.
U7 CD4053 is a triple one-of-two B
ACC
Stack
register pointer Program
switch. It is used to select between the address
register
voltage and current. Wondering why I TMP2 TMP1
said current? Using a high-side current Buffer
detector, the current flowing through a ALU
PC
sense resistor is converted into a suit- increment
able voltage to be read by the ADC. SFRs
timers Program
U5 and U6 AD7524 are digital-to- PSW counter
*PSEN

Instruction
16
analog converters. They convert a dig-

register
ALE*PROG Timing
DPTRs
*EAVPP and
ital value to an equivalent analog cur- RST Control
multiple

rent. They’re chosen because they pro- PD


Port 1 Port 3
latch latch
vide the hardware needed to interface
Oscillator
to the system bus. In addition, they’re Port 1 Port 3
fast and behave like RAM memory. drivers drivers

U9 LM358 and the adjustable resis-


tors form a pair of current-to-voltage XTAL1 XTAL2
P1.0–P1.7 P3.0–P3.7
converters. U8 74HC138 is an address
decoder that’s used to access the ADC, Figure 1—The 80C31 has 128 bytes of RAM, two external interrupt pins, two timer/counters, and serial ports.
DAC, and LCD. The MOVX memory
space is divided into 8 parts of 8 KB write signals whenever it’s executed, to the three-bus system using four
each. I used this scheme so that you so you can read and write to external NAND gates. Because the LCD is
can also insert an 8-KB RAM just in devices connected to the bus. slow, the busy flag is read after an
case it’s needed. Actually, the MOVX LCD1 is an LCD module based on operation to see if it is busy or not.
instruction generates the read and the popular HD44780. It’s interfaced Failing to poll the busy flag will result

Figure 2—In the digital portion of the power supply, U2 74HC373 is a transparent latch used to obtain the address.

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 25


in erratic operation or no display at 79L05 serve as pre-regulators for the
all. In order to interface the LCD voltage references. U2 7805 is the
properly, you’ll often need two signals voltage regulator for the logic circuit.
at one time to perform an operation. Note that the 1-A variety is used
Namely, the decoded signal like a because this also powered the EPROM
chip select signal and the read signal emulator used during development of
for a read operation. The two signals the firmware, which consumed a great
must be turned on at the same time amount of electricity.
for a proper read operation. The same C2, C3, and C6 are filter capacitors
principle applies to the write cycle. used to make the regulators more sta-
C9 and R4 form the RC time delay ble. R5, R27, and D4 LM336-2.5 form
for proper reset. The specifications Photo 2—Here’s a view from above the 80C31-con- the ADC voltage reference. The vari-
require several clock cycles during trolled power supply. The digital part is constructed able resistor R27 trims the voltage to
using point-to-point wiring. I used a ready-made PCB
which the reset is high until the clock 2.55 V. R20 and D14 LM336-2.5 form
for the analog part.
generator is stable. D2 serves to dis- the voltage reference needed by the
charge the capacitor after the power is Zener diode D1, R1, R6, and Q1 pro- DAC ICs. R26 is used to bias the
removed. C5 to C14 serve as an imme- vide a constant current source for the Darlington transistor, which is a
diate source of voltage because the sup- thermal sensor. Q8 serves as a ther- series pass element comprised of Q5
ply rail drops as a result of the internal mal sensor and limits the base current and Q6, which form the Darlington
switching of the transistors. The volt- to the series pass transistor after it transistor. The series pass element
age drop is caused by the inductances reaches a certain temperature. The acts as a variable resistor to change
in the wire or traces of the PCB. And collector current increases as the junc- the output of the power supply.
as you know, the current cannot tion temperature increases even if the R10, R21, R22, R23, R24, and U7
change immediately when there is an base current is constant. This works MC4741 act as a high-side current
inductor present in the circuit. in theory, but it has not been tested detector. Essentially, it’s a subtractor
Rectifier diodes D2, D3, D5, and D7 because I don’t have a themocouple that gives a voltage in proportion to
1N5400 convert alternating current to themometer. I did use, however, a 4″ × the ratio of the resistor and voltage
pulsating DC (see Figure 3). C1 filters 4″ heavy-duty heatsink. difference. The current moving across
the pulsating DC to smooth DC. C7, D12, D13, C4, and C5 form a split R10 produces a voltage drop that’s
C8, D17, and D18 are configured as a supply power source that’s used to detected by the subtractor, and then
charge pump that serves as a source power the logic circuit, ADC refer- it’s amplified according to the ratio of
for the negative voltage needed by the ence, and the negative supply for the the resistances. A 2.5-A current pro-
high-side current detector. DAC reference. U1 78L05 and U3 duces a 2.5-V potential. This potential

Figure 3—When looking at the analog portion of the power supply, you notice that the rectifier diodes convert alternating current to pulsating DC.

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 27


is compared to the voltage generated only purpose was to verify if the cir-
by the DAC. The comparator U5 cuit works (see Photo 2). For the digi-
LM358 controls the series pass ele- tal part, I used ordinary IC sockets and
ment in order to regulate the current wrapping wire to connect the circuit.
output of the power supply. R11 and You should also use IC sockets so you
R15 are a sampling element of the can remove the IC if it’s defective.
output voltage. The two resistors form Before inserting the ICs, be sure to
a voltage divider and scale the voltage look for the presence of 5 V at the VCC
by 10. Thus, a 23-V potential becomes pins. Also, check if the ground pins
2.3 V. The comparator U5 LM358 are indeed grounded. It’s a good idea
compares this potential to the voltage to use different colored wires so you
generated by the DAC and in addition can trace the signals of different pins.
to controlling the series pass element, If you’re going to make a PCB for the
which regulates the output voltage of analog part, try to be sure the sampling
the power supply. network is close to the output con-
D15 and D16 isolate the two op- nector or pads. Make the traces wide
amps. D8, D9, D10, and D11 protect for nets carrying power from pulsating
the analog switch and ADC when AC to DC. To calibrate the power
there is an error and the sampled volt- supply, burn the calibrate program into
age or current rises above 5 V or drops to the 27C64 EPROM and then power
below zero. C10 and C11 serve as fil- up the circuit. Adjust variable resistors
ter caps to smooth the sampled volt- R2 and R3 until you read 2.55 V on
ages. R14 and R18 limit the current pins 1 and 7 of U9 LM358. Also, adjust
from the sampling points. R28, R29, variable resistor R27 until you get a
D19, and D20 act as a regulator to reading of 2.55 V going to pin 12 of U4
limit the voltage going to U7 MC4741. ADC0820. Key in 5.0 for voltage and
If the circuit is unloaded, the B+ adjust variable resistor R11 of the ana-
potential can reach as high as 31 V. log portion until you get a 5-V reading.
And if this reaches U7, it will suffer
electrical overstress, or EOS. TROUBLESHOOTING
The firmware, which can be down- The only way you’ll know if the
loaded from the Circuit Cellar web circuit is wired correctly is if you can
site, is written in assembly language see messages coming out of the LCD
using a Metalink assembler. One module. The program will work even
thing to note is why the reference is if the ADC or DACs are absent from
2.55 V. The reason is that the ADC the circuit. However, this is not the
and DAC values go from zero to 255. case with the LCD module. The pro-
Therefore, if you use 2.55 V you won’t gram will hang if the LCD module is
need to compute the values needed to not present with dps.bin or dps.hex
obtain a desirable voltage or the read- loaded in the 27C64 EPROM. This is
ing obtained by the ADC. With this because the BUSY pin of the LCD
scheme, you can simply read the ADC module is polled to check if the LCD
and move the decimal point. For is busy or not.
example, a 100 reading from the ADC If the circuit doesn’t work, then
is equivalent to a 10-V potential. And check for the presence of 5 V at the
with an 8-bit value, the resolution of VCC pins. You should also look to see
the voltage is 100 mV and the resolu- if the ground pins are connected to
tion of the current is 10 mA. To pro- ground, and if the reset circuit works.
gram a 1-A current you can send 100 Use a logic probe or an oscilloscope
to the current DAC. To program 1 V, to verify this. Additionally, always
simply send 10 to the voltage DAC. make sure the crystal and pins X1 or
X2 of the microcontroller are in good
CONSTRUCTION AND ASSEMBLY shape. If there’s no output on the
You can construct the digital part of LCD, then reassess your wiring.
the power supply by using point-to- You should also watch for the
point wiring. I built a PCB for the ana- activity of enable E, RS, and R/W
log component, however, the one I pins. Adjust variable resistor R1 for
made was not that great because its good contrast so you can see the char-

28 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


acters. If Enable E is not pulsating, USING THE POWER SUPPLY
inspect the NAND gate (U10). Check To achieve an output of 700 mV,
if the *RD and *WR signals are pul- key in .7. For an output of 5 V, use
sating at the pins of the NAND gate. 5.0. It will detect the number of
Another good idea is to verify keystrokes needed by the position of
whether or not the LCD is being the decimal point. Therefore, to out-
selected. To do this, probe pin 12 of put 10 mA you need to press 0.01 or
the U8 address decoder U8. .01; and to output 500 mA, use 0.50
Key in 5.0 for voltage. If the read- or .50. To output 1 A you’ll have to
ing is zero, look to see if the VRDG key in 1.00, and so on. Remember to
from the analog portion is connected press the Set Voltage button first in
to the digital portion, which can be order to set the voltage, and then
confirmed by inspecting pin 12 of the press the Set Current button to pro-
U7 CD4053. You should read 0.5 on gram the current.
a multimeter.
You should always make sure that ADDITIONAL USES
you wired the U4 ADC0820 correctly. The 80C31-controlled power supply
Look for the *RD signal, *WR signal, has many uses. You can power
and chip select pulse at the pins of U4. numerous circuits on your work-
Key in 0.05 for current and connect a bench or charge a 6-V gel cell for con-
4.7-Ω, 5-W resistor across the output stant voltage charging and to limit
terminals. The reading for current the peak current. In addition, you’ll
should be 0.05 A on the LCD. If it find that you can use the 80C31 to
isn’t, check for a 0.05-V reading on a charge your NiCd batteries by setting
multimeter on pin 13 of the U7 the voltage higher than the battery
CD4053. If that doesn’t work, check if potential and the current to 50 mA. I
the IRDG signal from the analog part
is connected to the digital part.
Noel A. Rios is an electronics and
The U7 MC4741 of the analog part
communications engineer. He has
should be wired correctly and the IC
worked with semiconductor and elec-
itself should be in good shape. If both
tronics companies like Microcircuits,
voltage and current readings are the
IMI, Allegro, and ASTEC. His interests
same, see if the SELECT signal at
include computers, embedded control,
pin 11 of U7 CD4053 of the digital
power conversion, test and measure-
portion is pulsing. If during the cali-
ment, and GPIB control. You may
bration phase there is not 2.55 V at
reach him at [email protected].
the U9 LM358, even if you adjust vari-
able resistors R2 and R3, then inspect
your DAC wiring.
SOFTWARE
Scan for the presence of *WR pulse
at the pins of the U5 and U6 AD7524. To download the firmware, go to
In addition, you should check to see ftp.circuitcellar.com/pub/Circuit_
if the chip select signals are pulsat- Cellar/2002/144/.
ing at pin 12 of U5 and U6 of the
AD7524. If they aren’t, take a peek at RESOURCES
the 74HC138 address decoder U8. Intel Corp., Embedded
And don’t forget to verify the condi- Microcontrollers 1986 DataBook,
tion of the LM358 U9. If you don’t Intel, Mt. Prospect, IL, 1995.
find 2.55 V at pin 12 of ADC0820 U4,
Philips Semiconductor, Philips
then make sure the LM336-2.5 D4 is
80C51 Family Databook, Philips,
wired correctly. Finally, if you don’t
Sunnyvale, CA, 1994.
have –2.5 V at pin 15 of U5 and U6 of
the AD7524, check the wiring of
LM336-2.5 D14. If the programmed SOURCE
voltage and current are not correct, 80C31 Microcontroller
even if the voltage DAC and current Intel Corp.
DAC have correct outputs, take a look (602) 554-8080
at the LM358 U5 of the analog part. www.intel.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 29


channels for expansion of current or

ROBOTICS velocity sensing, for example. Locked


Antiphase and Sign Magnitude PWM

CORNER are supported as well. The user inter-


face is primarily through a 4 × 20 LCD
display and four command buttons.
Are you excited yet?
Sonny Lloyd
THE “BRAINS”
At the core of the controller is the
powerful Atmel AVR ATmega163, a

Extreme OSMC high-performance 8-bit RISC processor


running at 8 MHz. [1] The RISC archi-
tecture of the Mega163 allows it to
achieve nearly 8 MIPS of processing
speed while consuming little power.
Part 2: The Modular OSMC Brain The Mega163 includes 16 KB of flash
memory, 1 KB of RAM, and 512 bytes
of EEPROM. In addition, it’s pro-
grammed in GNU C for the AVR and
uses AvrX, Larry Barello’s RTOS.
One of the most attractive features
of the Mega163 is that it can be pro-
grammed in-circuit using simple, low-

Last month, Sonny


i n Part 1 of this
series, you learned
how the OSMC board
operates and became
cost hardware. In-circuit programming
allows you to upload software updates
such as new features, enhancements,
or bug fixes after the MOB circuit
board has been completed (i.e., popu-
acquainted with its advantages and lated and soldered).
taught you how the value. Now it’s time to discover how To achieve this handy feature, the
the control signals are delivered to the MOB comes with a standard 10-pin 2 ×
OSMC board func- Open Source Motor Controller 5 header connector for programming
(OSMC). The Modular OSMC Brain the Mega163. The header is located
tions. Now he’s going (MOB) controls this process. near the LCD connector on the board.
to show you an inex- The MOB is a full-featured controller
for two OSMC power H-Bridge boards.
The format of this header matches the
STK200/STK300 standard supported
pensive way to Figure 1 shows a block diagram of the by most programmers and software
basic setup, which is designed to that sustain the ATMega family.
assemble and use a achieve electronic speed control. The One of the most popular and best
MOB takes the signals from a standard supported of these programmers is
Modular OSMC Brain, hobby radio control receiver and gener- PonyProg, which was written by
ates the proper control signals to drive Claudio Lanconelli (Circuit Cellar 142).
which is a controller a pair of OSMC boards. The system is The OSMC group recommends this
that uses the signals flexible; it can directly control each
channel for two-stick operation or mix
Mega163 programmer because you can
download the user-friendly software
from a radio control two channels for single-
stick control. In addition,
receiver to drive it has a third auxiliary
PWM
channel that controls a RC
OSMC boards. pair of optoisolators for Serial
MOB
PWM
OSMC 1 Motor

switching relays or other SPI OSMC 2


I2C Motor
devices. It supports 2-, 4-,
16-, and 32-kHz PWM AUX Out
selection, an adjustable
dead band, I2C interface, Switch

and serial interface. The


MOB has spare analog I/O Figure 1—First, check out a conceptual diagram of the OSMC project.

30 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


tion input signal causes a differential
to be added or subtracted from the
throttle speed setting for each motor.
Mix mode is generally the best
choice for high-speed driving. But if
you want to maneuver your project as
if it’s a tank, then Normal mode is for
you. Using two joysticks to independ-
ently control the speed of each
motor’s forward or reverse motion is
Photo 2—The µMOB is an excellent alternative for
Photo 1—The modular OSMC brain provides the sig- tricky, but sometimes it’s preferable.
people who desire a simple-to-operate yet powerful
nal processing for the electronic speed controller. For instance, if the left joystick is motor driver.
pushed forward while the right joy-
for free and the hardware is easy to stick is pulled back, your robot would the auxiliary signal to control a weapon
build. And I’m sure this goes without spin on a dime in a clockwise rota- for my fighting robot. Connecting
saying, but all software revisions to be tion. Normal mode should be selected only AUX 1 provided an ability to
uploaded to the MOB are freely avail- for slower operation or sharp turns; it control a single weapon. To turn on
able from the OSMC project web site. should also be selected if the trans- the weapon, the control stick (or
mitter you’re using contains its own switch) is set to a value above the cen-
CONTROLLING THE MOB channel-mixing scheme. The latter ter point. To turn it off, the stick is
The MOB circuit board in Photo 1 allows the use of any off-the-shelf centered or moved below the center
may look like a simple design, but transmitter/receiver combination as point. And if you want to control a
don’t be fooled. The MOB is a complex an input to the MOB. bidirectional weapon, such as an arm
programmable device, but it’s designed The auxiliary signal is controlled in that extends and retracts, then one
to be flexible and useful for a large the same manner in either Mix mode AUX output is used for extension and
number of applications. It receives or Normal mode. The auxiliary output the other for retraction. Because the
information through three radio servo is split into two signals, AUX 1 and AUX outputs are never both on at the
inputs. The Mega163’s software con- AUX 2. The AUX 1 and AUX 2 out- same time, the weapon will respond
verts the 2-ms servo pulses, using the puts are optically isolated from the as expected to all command inputs.
pulse position modulation (PPM) tech- rest of the MOB circuit, and are
nique, into three separate pulse width designed to safely activate relays or MANY, MANY FEATURES
modulated signals. The first controls other high-power devices without the If you wish to customize the exact
the throttle; the second controls the risk of electrical feedback affecting the operation of the MOB, you’re in luck!
direction; and the last signal—the aux- MOB. They work in a complementary The MOB software provides several
iliary—essentially serves as an on/off fashion such that when AUX 1 is on, user-configurable parameters to opti-
switch for some external device. In AUX 2 is off (and vice versa). mize its operation for a particular robot
order to make the MOB more adaptable The operation of the two outputs is and usage scenario. The MOB’s soft-
to different styles of user interface (e.g., as follows: If the RC signal connected ware user interface consists of seven
joysticks), there are two different selec- to the auxiliary input is above the screens on a 4 × 20 LCD and four push
table control methods: Normal mode center value output, then AUX 1 will buttons, which allow you to change
and Mix mode (see Table 1). be turned on and AUX 2 will be the screens and make selections.
If you prefer to rely on your intuition turned off; conversely, when the signal One option is to set the PWM fre-
and a single joystick to control your RC is below the center value, AUX 2 will quency to 2 (default), 4, 16, or 32 kHz.
project’s speed and direction, then Mix be on and AUX 1 will be off. There is In some applications, it may be neces-
mode is for you. As you might suspect, a large enough deadband so that both sary to have fast signal refresh rates,
when the stick is pushed forward the AUX 1 and AUX 2 remain off while however, the 2-kHz default will suffice
MOB propagates a signal such that the stick is in the center position. for combat robot operation. Two of the
both motors move forward proportion- This creates a number of options for most common PWM techniques are
ally. The same is true when pulling controlling on/off devices with the also selectable: Sign Magnitude and
back on the joystick, except that the auxiliary channel. In my case, I used Locked Antiphase modes. These two
motors now move in reverse. modes determine how the legs
Therefore, the throttle input Name Mix mode function Normal mode function of the H-Bridge are pulsed.
controls the speed of both The sign magnitude PWM
motors equally. To turn right Throttle Speed forward or reverse Motor A speed control scheme requires the
Direction Steering right or left Motor B speed
or left, one motor’s speed use of two I/O lines. One data
Auxiliary Switch AUX 1 and 2 outputs on or off
must be decreased while the line carries the sign bit—
other’s is increased. And so, Table 1—You can control the MOB in Mix or Normal mode. The former works which is sometimes referred
while in Mix mode, the direc- best for one-stick operation and the latter works best for two-stick operation. to as the direction bit—and

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 31


high-side leg of the brakes, it’s essentially acting as a gener-
Battery
OSMC and the oppo- ator, which, in fact, recharges your bat-
5V 5V site low-side leg teries (if only slightly). One noticeable
together so they can problem, however, is that it’s difficult
8V 8V
be driven on or off to tune all the settings of the MOB for
simultaneously. The optimized locked antiphase operation.
Motor
5V
same is true for the If you’re still not satisfied with the
5V
other two legs of the joystick interface, the MOB has yet
8V 8V H-Bridge. The locked another feature that will help to
antiphase method is improve this: a selectable dead band
demonstrated in value of zero to eight, where an eight
Figure 3, where the represents approximately a 10% stick
Figure 2—With the sign magnitude PWM control scheme, one leg is held on red and blue lines rep- throw dead band. A deadband of two
while the opposite leg has the PWM applied to it. resent current flow is the default setting.
corresponding to their Do you want more features? The
will hold one side of the H-Bridge respective color-coded control signal. MOB can monitor the battery supply
(OSMC) in an on state. The second When the joystick is in the center to each OSMC board with auto shut-
I/O line carries the magnitude signal. position, the PWM duty cycle is 50%. down for droop protection. And, as if
The duty cycle of the magnitude Both locked pairs of legs receive the all of this were not enough, you’ll find
PWM signal causes an average load same amount of on time in a given it convenient that the on-board EEP-
voltage to appear across the motor ter- period, so the average voltage across ROM can store all of your settings and
minals. This PWM signal is applied to the motor is effectively zero. To change automatically load them into the
the opposite leg of the sign bit, as the direction motor rotation to forward, MEGA163 at start-up or reset.
indicated in Figure 2. simply increase the duty cycle above
Pulsing the H-Bridge by means of the 50%; to reverse direction, decrease the THE µMOB
sign magnitude method has the distinct duty cycle below 50%. The overall The Micro Modular OSMC Brain
advantage of being easy to implement, control of the motor’s speed is accom- (µMOB) was created by Larry Barello
and thus it’s the default setting. There plished by calculating how much the to suit the needs of people who
are, however, some disadvantages. One duty cycle has changed. For instance, require a fully functional, reliable,
negative aspect of the sign magnitude a 90% duty cycle would cause a for- high-quality motor controller without
PWM control scheme is recognized ward motion of the motor at a fast all of the bells and whistles of the
when the motor is freewheeling or pace (though not quite at full speed). A MOB (see Table 2). You can assemble
coasting. During this action, the stored 45% duty cycle, however, would cause this package on your own by following
current in the motor travels through a slow-moving reverse motion because the detailed assembly instructions
the top two high-side MOSFETs and it deviates from 50% by a mere 5% found on the OSMC project’s web site
back, effectively wasting energy in the and because the cycle is less than 50%. (see Photo 2). The µMOB can be used
form of heat. Another disadvantage is Another highlight of the locked anti- to drive any motor controller (e.g.,
that this mode uses up two I/O lines phase scheme is the ability to receive OSMC) that accepts PWM, DIREC-
of the microprocessor in an environ- regenerative braking for free because TION, and ENABLE signals.
ment that is already low on spares. there is always one pair of locked legs
The other method of control, locked to provide a conductive path back to FUTURE CONSIDERATIONS
antiphase PWM, was implemented the batteries. Recall that when a motor There are many options, add-ons,
solely for experimentation. and features that I would
The results proved that love to see included in
operation in this scheme the MOB in the future.
Battery
requires a high frequency, There are four general-
which is not suitable for 5V 5V purpose unused analog
the OSMC. However, inputs that could be easi-
8V 8V
because of the expanding ly adapted to help facili-
nature of the OSMC proj- tate this. Currently, one
ect, it may one day become Motor add-on package that is
5V 5V
a practical option. One rea- being explored is some
son to look into this 8V sort of system feedback,
8V
scheme is its ability to con- which would be highly
trol the H-Bridge using only valuable because it would
one signal line. The locked allow for straighter steer-
antiphase PWM method ing and improved control
achieves this by locking one Figure 3—The PWM signal is applied to all four quadrants in Locked Antiphase mode. at high speeds.

32 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


PonyProg
Technical Specifications Claudio Lanconelli
www.lancos.com/prog.html
R/C input range 100 10-µs steps between 1 and 2 ms
Sign magnitude PWM output ±32 steps at 10 µs per step (~3 kHz)
Dead-band Selectable 40 or 80 µs SOURCES
Input mixing Selectable mixed (single stick) or normal (tank style)
Atmel AVR Atmega163
Brake mode Selectable brake/coast
Atmel Corp.
Outputs 10-pin headers compatible with the OSMC H-Bridge board
(408) 441-0311
Auxiliary outputs Two open-collector terminals suitable for driving relays
www.atmel.com
Supply voltage range 6.5 to 15 V (LM2940)
BEC output 5-V, 0.7-A maximum (limited by the 12-V supply) OSMC, MOB, µMOB board
Chris Baron and Dennis Millard
Table 2—As you’d suspect, the technical specifications of the µMOB are closely related to the MOB. www.robot-power.com

BUILD IT YOURSELF
What else can I say? Everyone on the
OSMC design team is pleased with the
outcome of the project. The approxi-
mate cost of the entire electronic
speed controller was kept within rea-
son. The OSMC board’s components
cost about $100, and the MOB can be
assembled for approximately $35.
That’s a great deal given the OSMC
project’s capabilities and reliability.
I hope you enjoy building this elec-
tronic speed controller as much as I
did, and that you’ll join us in dis-
cussing related topics (or not) on the
official web site’s message board. I

Sonny Lloyd graduated with a BS in


Electrical Engineering from Ryerson
University in Canada. While attend-
ing university, he worked a 16-month
internship at Siemens Westinghouse
Power. He hopes to win top rankings
next year with his OSMC project in
local and international robotics com-
petitions.

SOFTWARE
To download the code, go to
ftp.circuitcellar.com/pub/Circuit_
Cellar/2002/144/.

REFERENCES
[1] Atmel Corp., “8-bit AVR
Microcontroller with 16K Bytes
In-System Programmable Flash—
Atmega163, Atmega163L,” rev.
1142c, September 2001.

RESOURCES
µMOB Circuit board, starter kits
Larry Barello
e-mail: [email protected]

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 33


First, most low-pass filters can han-

FEATURE dle only limited voltage (usually 50 V),


which means they’re likely to get

ARTICLE destroyed by larger transients. Second,


every transient protection device oper-
ates at a finite speed. Consequently,
the clamp always leaves a residual
George Novacek pulse that must be filtered out before
it enters sensitive circuits and causes
damage. This is especially true of
electrostatic discharge.
The need to place transient limiters

Taming the Transients before the low-pass filters also


explains the difficulty with making a
sealed box, as well as the need to use
the dual cavity design for e-fields in
excess of 100 V per meter when
immunity to large transients is also
the design goal. [1]
Obviously, designers in the automo-
tive, aerospace, and communications

b
industries have to worry about the
possibility of lighting strikes. But
ack in May, I even the humblest consumer appli-
described the chal- ances can be exposed to unexpected
lenges high intensity transients. Therefore, many consumer
Transients, such as radiated fields (HIRF) products can benefit from some level
present to your designs (“Working With of transient protection.
electrostatic dis- EMC,” Circuit Cellar 142). You learned All modern designs that use thin
that radiated fields were composed of film components and microelectronics
charge and lightning, electric (E) and magnetic (H) compo- must address ESD, which is an espe-
nents, and that their ratio, or wave cially sneaky threat because it can
can create major impedance, for predominantly electric weaken a microelectronic device or
problems for many of fields becomes a constant 377 Ω. You cause latent damage. In cases in which
should remember this number because ESD damage occurs, failures often arise
your electronic many RF engineering concepts rely on at the worst possible moment. Some
it. For example, the commonly used ICs are advertised as containing inter-
designs. However, 200-Vpm e-field immunity requirement nal ESD or transient protection, which
originated from the assumption that RF is better than nothing. But you should-
there are several power at 100 W per square meter is n’t rely on them exclusively except for
dangerous to humans: the most rudimentary designs.
ways to limit the com-
V = P × R = 100 × 377= 194.16 DAMAGE TOLERANCE
ponent damage and Two major problems can arise when
functional upset that Hence, the magical 200-Vpm e-field a system is exposed to transients.
immunity requirement for electronic First, the equipment can be badly
results from transient equipment in vehicles. damaged or destroyed completely. You
Transients such as a lightning strike can prevent this by clamping or oth-
exposure. and electrostatic discharge (ESD) pres- erwise limiting the transients. The
ent a different set of problems. You second problem the system can expe-
must remember that transient protec- rience is a functional upset, which
tion will not work without good EMI can occur even when the transient is
immunity. Therefore, transient limiters well clipped and no damage to the
are usually physically located before equipment is apparent. Because dam-
EMI filters. There are two reasons for age prevention is prerequisite, we’ll
this, and if you consider the circuit first consider ways to ensure damage
topology and cabinet construction in tolerance before tackling the problem
Figure 1, you’ll see why this is the case. of functional upset.

34 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


mathematically defined by the fol-
lowing equation:

t
V (t ) =1.033 V0 × sin 2π × f × t × e – π × f × 24

This equation is also known as


Thevenin generator. Here, V0 is the
peak voltage and f the frequency.
What kind of clamps can you use
for transient protection? Here are the
characteristics of an ideal clamp: a
low, precisely defined clamping volt-
Figure 1—The I/O circuit has dual-stage transient protection and EMI filters. Dual spark gaps are ideal for sym- age; immediate response; unlimited
metrical circuits because both clamps fire at once. energy absorption; no follow-on cur-
rent; no leakage; and it would be
As with EMI protection, good you’ll need to clamp. Refer to Figure 2 small, light, and inexpensive. In real
grounding and bonding are essential. to see what it’s like when lightning life, however, we must compromise.
Grounding and bonding practices strikes an aircraft. This beauty reaches Metal oxide varistors (MOVs) or zinc
deserve a separate article for a full 220,000 A! Fortunately, electronic oxide varistors are used in commercial
explanation, but for now I’ll just clarify equipment is rarely subjected to a and industrial applications. Their V/I
the terms. Grounding is the process of direct hit, so the actual exposure is characteristics are nonlinear and look
connecting a conductive medium to a significantly lower. But notice that it’s similar to two back-to-back Zener
reference point (e.g., a PCB ground all done and over with in about 0.1 ms. diodes with symmetrical bipolar clamp-
plane or equipment enclosure). Unlike HIRF, transients are better ing. Because their standby resistance
Remember, be careful and make sure described in time, as opposed to fre- is in megaohms, they have a fairly low
you don’t create ground loops. Electrical quency domain. You can see that the leakage, no follow-on current, and a fast
bonding is the joining of two or more fast rise time will result in a broad fre- response time. But despite the fact that
conductive surfaces to obtain an elec- quency spectrum and that there’s not they’re small, light, and inexpensive,
trically conductive, low-resistance 1- a clamp fast enough not to allow a sig- these clamps are used reluctantly. It’s
to 3-mΩ path. Because this path serves nificant spike to go through into the been said that they tend to deteriorate
to divert high energy (often with high following circuits. with age and use, but I haven’t seen
frequency content), it’s important that The depiction in Figure 2 is a com- data proving appreciable deterioration.
its inductive component is extremely mon double exponential transient Unfortunately, the effectiveness of
low as well. Poor bonding can easily pulse waveform. It’s defined as: transient suppressors can’t be moni-
turn into a good antenna, defeating tored on an ongoing basis, so you have
the entire EMC scheme. I (t) = I0 ( e at – e bt ) to rely on previous experience. And
it’s usually too late by the time you
PIN INJECTION Here, a variety of differing peak cur- discover that the device has failed. In
The effectiveness of the transient rent values I0 and time constants a this respect, a varistor’s Failure mode
protection scheme is tested by pin and b are used to simulate induced is short circuit, which is the preferred
injection. Figure 1 shows a two-stage transients. Figure 3 is the burst of a failure in terms of damage tolerance.
protection circuit that will work for 1-MHz decaying sine wave that’s A similar clamping effect could be
the most demanding applications. achieved with Zener diodes, but
Depending on the actual require- 2 × 105
their energy handling capability is
ments, this circuit can be modi- 1.8 × 105 poor with respect to their size and
fied. To pass the test, a transient 1.6 × 105 cost. Instead, transzorbs have
generator is, in turn, linked to 1.4 × 105 become the popular clamp for crit-
1.2 × 105
every connector pin and then I(t)
5
ical applications. Transzorbs,
1 × 10
10 transients of each polarity are 8 × 104 which are avalanche-type semicon-
applied. To make it more difficult, 6 × 104 ductor devices, are a trademark of
the equipment is usually not pow- 4 × 104 General Semiconductors.
ered during the test. After every 2 × 104 Transzorbs that are similar in
0
connector pin has been exposed, 0 1 × 10–4 2 × 10–4 3 × 10–4 4 × 10–4 5 × 10–4 6 × 10–4 size to 0.5-W Zener diodes are fast,
t
the unit is then powered up and have low capacitance, and can han-
its functionality is assessed. Figure 2—A double exponential transient waveform like this one dle large peak pulse currents. They
can be seen after a lightning strike. This one reaches its 220-kA
In order to select the compo- peak value in 6.4 µs, decaying down to 110 kA in about 70 µs. come as unipolar and bipolar in sin-
nents shown in Figure 1, you must For level 4 pin injection, the same timing is used with 750-V open gle and multiple packages that don’t
understand the type of transients voltage and 150-A or 750-A short circuit current. appear to deteriorate with use.

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 35


2000 current in the clamps, wound or carbon film (I don’t know if
can be at least 20 Ω, you anyone still manufactures the carbon
1000
can usually select small film). Regardless of the current, most
V(t) 0 size transzorbs. They are modern resistors will not survive
–1000 reliable enough to handle 750 V or more across their terminals.
Level 4 lightning (the If you can, you should follow the
–2000
–6 1.5 × 10–5 2.5 × 10–5 3.5 × 10–5 highest level is 5) as it is transzorb with an RC low-pass filter
0 5 × 10
1 ×10–5 2 × 10–5 3 × 10–5 4 × 10–5 defined for avionic equip- to absorb the remnant spike. For dis-
Time
ment. This consists of the crete inputs, this could also function
Figure 3—A decaying sine wave is another pin injection waveform. For 750 V/150 A or 750 V/ as a debouncing filter. Anything from
level 4, it’s a 1500-V per 60-A burst of 1 to 10 MHz, depending on the 750 A test pulses (see 10 to 60 ms should be fine. Your soft-
system resonance.
Figure 2). The 1500 V/60 A ware can handle the main portion of
burst is depicted in debouncing, but the 10-ms delay will
When a large amount of energy Figure 3. Level 4 protection is well clean up the signal and help with EMI.
requires clamping, a Zener diode/SCR beyond the requirements of any com- Power lines, communication lines,
combination is often used. When the mercial product yet is easy and inex- and output drivers can’t afford to have
breakdown voltage of the Zener diode pensive to achieve. it, so keep an eye on the remnant
is exceeded, the SCR fires and crow- If you can’t insert an inline 20-Ω transients.
bars the protected line. This is essen- resistor, which may be the case with Whether or not you’ll need the low-
tially a short circuit, and it’s often power or output driver lines, the fast pass pi filters F1 and F2 in addition to
used to blow a much slower protec- rise time of the transient should allow the dual cavity packaging will depend
tion fuse. One disadvantage of the cir- you to replace it with a choke to limit on your HIRF immunity require-
cuit is the follow-on current, which the current pulse. If that’s not possible ments. If you don’t need them, it
must be interrupted for the SCR to because of bandwidth limitations, would be a good idea to use ferrite
open up. you’ll have to use a higher energy beads or another form of low-pass fil-
Spark gaps, or gas discharge tubes, rated device (e.g., a transzorb or varis- ter with a critical frequency above
are capable of conducting high cur- tor) or a spark gap. 1 MHz. The remnant transients, espe-
rents (see Photo 1). Their response I prefer to go to the second stage by cially those from electrostatic dis-
time is fairly slow and minimum igni- using the spark gap to cut the initial charge, are extremely narrow and RC
tion voltage is above 100 V. After pulse down around 100 to 200 V, and filters may not be efficient in sup-
they’re fired, there’s follow-on current then follow it with a small transzorb. pressing them because of their para-
flowing with a voltage drop of about For the majority of signal lines, R1/R2 sitic impedances.
20 V across the gap until the current can be hundreds of ohms. This allows Finally, let’s talk about the reverse
has been interrupted externally. the transzorbs to operate well below biased diodes D3, through D6. These
Because of these characteristics, spark their rated power. Read the diodes ensure that the IC pins don’t
gaps are primarily found in two-stage “Calculating Transient Protector move more than one diode drop out-
protection circuits (see Figure 1) or Rating” sidebar to learn how to calcu- side the power supply range. Although
schemes protecting high-voltage lines. late the transient protector rating. many ICs have internally protected
A dual spark gap has a center elec- Make sure the R1/R2 resistor is wire pins with the same diode arrange-
trode shaped like a ring. When ment, you still need to be care-
one line fires as a result of over 10,000 ful. The internal diodes may be
voltage, the other line ignites as 1000
capable of absorbing the rem-
well. This is useful for protec- Aluminum/Mylar foil
nant spike, but there are other
tion of symmetrical circuits. issues to address as well.
Surface transfer impedance IZTI mΩ/m

100
Surge protectors have finite
PRACTICAL DESIGN Single braid Optimized
single
internal impedance. A 5-V
APPROACH 10
braid logic circuit needs a clamp that
Referring back to Figure 1, Double presents negligible leakage at
braid
you can see that the threat level 1 5 V, so it would have the
Triax
and maximum value of resistors braid
breakdown voltage at around
R1 and R2 will determine 5.2 V. But during the transient,
0.1
whether or not the spark gap is the voltage across the clamp
needed in the first stage. The could easily rise above 6 V.
0.01
test waveforms are defined in That wouldn’t be healthy for
Solid
terms of the generator’s open copper
the IC. The situation becomes
voltage and short circuit cur- 0.001
screen more serious when the tran-
rent. As long as R1 and R2, 102 103 104 105 106 107 108 sient arrives and the unit is
F (H )
which limit the maximum pulse Figure 4—This plot of transfer impedance shows several common cables. not powered. In the absence of

36 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


the internal power, the junctions have Figures 2 and 3 through a current the coupling of a magnetic field into a
no reverse bias and the 5- to 6-V pulse transformer into the wire harness. [2] shielded wire. It is expressed as:
would feed directly through the IC Will the cable shielding help? Ω
ZT = V × m
into a short circuit presented by the At frequencies below 100 kHz, non- IS
power supply and its bypass capaci- magnetic (standard braid) copper or
tors. If the IC internal protection aluminum wire shielding has little where V is the voltage induced in the
diodes can handle the full brunt of it, effect in a magnetic (H) field, because inner wire and IS the current induced
then your design should be fine. But the skin depth of these materials is in the shield. Figure 4 shows the plot
make sure! high. [1] Above 100 kHz, the skin of transfer impedance for several
depth is sufficient enough to begin to types of cable. For example, let’s
FUNCTIONAL UPSET absorb some of the H-field. This cre- assume you use a 10′ (3 m) long dou-
Knowing that your design survived ates voltage and current in the shield ble-braided cable to interface your
a lightning strike is only one part of ground loop. As the shield-to-ground electronic controller. Here, ZT would
the story. What will the system do bond impedance increases, the voltage be around 5 mΩ per meter in the fre-
when the strike is over? A scrambled coupled in the inner wire decreases. quency spectrum of 1 to 10 MHz,
television picture or a crackling This occurs because the coupled volt- where the lightning transients are
sound in the telephone would be age is a function of the shield current. often found. When the 750-V/750-A
understandable, but the in-flight Ultimately, the least amount of cou- transient shown in Figure 2 is inject-
flame out of a turbofan engine could pling is achieved by disconnecting one ed into the cable through a current
be catastrophic. end of the shield from ground, which transformer the result is:
Transients, especially those caused is contrary to the best e-field shielding
by lightning strikes, can couple requirements. It may be a good com- V = Z T × I S × l = 5 × 10 –3 × 750 × 3 = 11.25 V
through the magnetic field into the promise if the equipment is intended
system wiring and cause common to work primarily in low-frequency This pulse would be safely clamped
mode interference. To examine your interference environments. (as shown by the previous pin injec-
system’s behavior, inject test wave- The concept of shield transfer tion test). Because it would last
forms that are similar to those in impedance was developed to address around 100 µs, the resulting distur-

RS232/RS422/RS485 Converters
RS232 TO RS485
2 wire
• Makes your RS232 port an
RS485 port
• Supports up to 40 RS485
CMC’s low cost converters adapt any devices
RS232 port for RS422 or RS485 • Automatically determines
operation. These converters provide yourdata direction.
• Signal powered version
RS232 device with all the advantages of available
RS422 or RS485 including reliable high
speed operation (up to 200 kbaud) andADA485 (requires 9VDC) $79.00
ADA485-1 for 110VAC
data transmission distances up to 5000 89.00
ADA485L signal powered 84.00
feet. Two AD422s can be used to extend
any RS232 link up to 5000 feet.
Completely transparent to the system; RS232 TO RS485
no software changes of any type are 4 wire
necessary. • Converts an RS232 port for
use with RS422 or RS485
RS232 TO RS422 devices
• Converts bi-directionally • Supports up to 40 RS485 or
between RS232 and RS422 RS422 multidrop devices
• Use as a short haul modem • Adds multidrop capability to
• Plug in and go. No software RS232 devices
changes required • Automatically determines
data direction.
AD422 (Requires 9VDC) $79.00
AD422-1 for 110VAC 89.00 ADA425 (requires 9VDC) $89.00
AD422L signal powered 84.00 ADA425-1 for 110VAC 99.00

Mention this ad when you order and deduct 5%


Use Visa, Mastercard or company purchase order code
CC83
Connecticut microComputer, Inc.
PO BOX 186, Brookfield,CT 06804 (203)740-9890

WWW.2CMC.COM Fax:(203)775-4595
www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 37
bance could be filtered out so that the problem. The simplest solution arises If you are not allowed to reset, then
system couldn’t even hiccup. when the system is allowed to shut the common approach is to hold the
Unfortunately, this is not always down and reset as soon as it detects last valid input for a predetermined
the case. When the surge protectors an invalid input. period of time. Two seconds is general-
begin to clamp, the signal that’s super- How can you detect an invalid ly considered the right amount of time
imposed on the transient also starts to input? It’s the voltage resulting from for the effects of a lightning strike to
clamp. On the differential lines, the the clamping action of the surge pro- settle down. If by then the input has
transient may look like a bona fide tector, which the normal signal is not not gone back to the valid range,
signal (i.e., a trigger pulse), but on allowed to reach. For example, a dis- there’s probably a failure. In this case,
common mode lines both lines may crete input could be 0 to 3 V as another action, such as switching to a
swing to the point where signals are logic 0 (you always want a nice noise backup channel, must be taken.
obliterated. A DC offset could also margin to avoid ground noise prob- If reset or hold isn’t permitted, then
appear on differential and/or common lems), or 3 to 5 V as logic 1. A clamp- you’ll need to use symmetrical inter-
mode lines because of the rectifying ing action would result in a voltage at faces to ensure only common mode
action of the surge protector followed least one diode drop above 5 V or swings of the signal lines. After that,
by low-pass filters. Either way it’s a below zero. increase the common mode range of

CALCULATING TRANSIENT PROTECTOR RATING


In order to select an appropriate surge protector, you close enough for you to select the surge protector. The
need to know how much energy it will have to dissipate. waveform can be divided into simple segments, and their
Some manufacturers specify their device’s maximum cur- respective energies can be calculated and then added for the
rent and the timing of the pulse, but you can use Ohm’s total energy requirement. K = 0.637 for a half sine wave,
law to determine this on your own. otherwise defined as:
Let’s say the pulses of the shape but different timing
I pk × sin π τ× t
than shown in Figure 2 (6.4-µs rise time and 70-µs length)
are to be applied through a 750-V/150-A generator. Right K = 0.5 for the approximation of the rising part of the wave-
away this tells you that its source resistance is: form in Figure 2,
750 = 5
150 I pk × tτ

The current limiting resistance (R1 in Figure 1) is 20 Ω and K = 1.4 for the approximation of the falling part of the wave-
the transzorb clamps is at 5.2 V, assuming the voltage is form in Figure 2:
constant and the internal resistance is negligible.
t
Therefore, the peak current the transzorb will be exposed I pk × e 1.44× τ
to is:
Here, τ is the duration for Ipk to drop to 50%. K = 0.86 for
I P = 750 – 5.2 = 29.79 A the approximation of the damped sinusoid in Figure 3:
5 + 20
t
Now we need to find a device rated for 30 A and at least I pk × sin π × t × e – τ
7 A per 70-µs pulse.
Sometimes surge protectors are specified by the energy where τ is the duration for Ipk to drop to 50%.
they dissipate in joules (J). Looking at the waveform in As an example, let’s take the pulse waveform in Figure 2
Figure 2, the energy is equivalent to the area surrounded and split it into two parts (see Figure S1). The first section is
by the curve and can be calculated as from zero until Ipk reaches its maximum of 29.79 A, which
t
is the peak current calculated above. The time τ = 6.4 µs
E = VC (t) × I (t ) dt = K × VC × I × τ and K = 0.5. For the decaying section, τ = 70 – 6.4 µs. The
0
clamping voltage is 5.2 V.
Here, Vc is the clamp voltage, I is the peak current, τ is This amount of energy (14.25 mJ) is not high and there
the pulse duration, and K is a constant. Solving the inte- are many devices in catalogs that will satisfy this require-
gral based on the accurate waveform is laborious, so in ment. Consult the manufacturers listed at the end of this
order to make your life easier, the constant K has been article in the Resources section. Their data sheets and
published for differ- application notes
ent shapes. It may Section 1: E = 0.5 × Vc × I × τ = 0.5 × 5.2 × 29.7 × 6.4 × 10–6 = 494 × 10–6 J available at their
vary slightly with Section 2: E = 1.4 × Vc × I × τ = 1.4 × 5.2 × 29.7 × (70 – 6.4) × 10–6 = 13.75 × 10–3 web sites contain
respect to time con- Total = 14.25 × 10–3 J a wealth of infor-
stants, but it’s mation.
Figure S1—If you split the pulse waveforms shown in Figure 2, you get these two equations.

38 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


transformers while eliminating REFERENCES
ground loops as well. DC inter-
faces would take a little more [1] Oren Hartal, Electromagnetic
effort, but the linear optocouplers Compatibility By Design, R&B
and isolation operational ampli- Enterprises, West
fiers plentiful on the market can Conshohocken, PA, 1996.
solve most of your problems. [2] Texas Instruments, Inc., “ESD
Application Report,”
PARTING WORDS www.ti.com.
The science of protecting your RESOURCES
equipment from transients isn’t
AVX Corp.
black magic. It just takes some
(843) 448-9411
common sense and experience. www.avxcorp.com
And the only way you’ll gain the
Photo 1—This is a dirty cavity with dual spark gaps and experience needed is by doing the CP Clare
transzorbs. This will guarantee survival in the worst lightning work; so don’t hesitate to plunge (800) 272-5273
strike environment. www.cpclare.com
right into it. Your designs will
your design so that the surge protec- benefit and you’ll learn a great deal. I General Semiconductors, Inc.
tors don’t fire as a result of the (631) 847-3000
planned environment. If you know George Novacek has 30 years of experi- www.gensemi.com
that the maximum planned transient ence in circuit design and embedded RTCA, Inc. “DO-160D
will cause an 11.25-V swing of the controllers. He is currently the vice presi- Environmental Conditions and Test
lines, use 20-V surge protectors and dent and general manager of Hispano- Procedures for Airborn Equipment,”
make sure the input has a 20-V com- Suiza Canada, a division of Snecma, a www.rtca.org.
mon mode input range. world leader in aerospace engine and Semtech Corp.
You can increase the common mode landing gear systems. You may reach (805) 498-2111
input range with optocouplers and him at [email protected]. www.semtech.com

Get your motor running Vis


webit our
for s
s ite
pricpecia
ing l
!

Shown Here: BS2 Carrier Board, Motor Mind C, 2 Easy Roller Wheel Kits

Solution s3 Up to 4.0A Current • 10-24VDC Motors


Motor Mind C Controls 1 or 2 Motors • 40 Pin DIP Package
Serial, Analog or R/C Pulse Control
Solutions Cubed
Solutions Cubed
Simple & Sturdy
(530) 891-8045 Easy Roller Wheel Kit Robot Wheel Kit
www.solutions-cubed.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 39


variety of native CPU buses without

FEATURE glue logic. The one I’ll describe here is


the Indirect Mode 68 interface, which

ARTICLE is a 6800-bus interface with only one


address (A0) in use. The Indirect Mode
interface uses commands and data bus
cycles to access the internal compo-
Peter Chia nents of the S1D13708, so there is a
speed penalty for accesses. The
Indirect Mode interface supports
either an 8- or 16-bit wide data bus.
To reduce the number of signals need-

LCD Controller for a PIC ed to implement Indirect Mode 68,


eight bits should be chosen.
Additionally, the interface requires
four more lines to act as control sig-
nals, which means a total of 12 lines
would be needed on the PIC. Using up
12 I/O lines may seem a bit overboard,
but the gain from adding the
S1D13708 definitely outweighs the
loss of the I/O lines.
In addition to the extra RAM, the
S1D13708 has seven I/O lines, eight

Peter uses PIC parts


i like Microchip’s
PIC controllers
because they can be
used for many different
output lines, and a pulse width modu-
lated line. Because the interface bus
relies on *CS, the 11 PIC I/O lines are
free to be used for other purposes when
the S1D13708 is not being accessed.
kinds of projects. There are, however,
in many of his proj- instances when I would like to display HARDWARE CONNECTIONS
information from the PIC on panels Connecting between the S1D13708
ects, but there are other than LEDs or seven-segment and a PIC microcontroller doesn’t
displays. For that reason, I started require external logic if there are
times when he would thinking about LCD panels. enough I/O lines and the voltage lev-
prefer to be able to LCD panels come in many different
varieties. You can choose from STN
els of the two chips are the same.

display PIC info on an and TFT, color and monochrome, 4- to


18-bit color depths, and various panel
LCD panel rather than sizes. However, it’s difficult to use an
LCD panel with the PIC because it
on segment displays involves so many control signals. So,
this is where the Epson S1D13708
or LEDs. In this proj- LCD controller comes into the picture.
ect, he shows us a The S1D13708 simplifies the inter-
face to the LCD panel to a single-chip
simple way to build an solution. The S1D13708 drives the
panel and adds various display fea-
LCD controller for a tures like picture-in-picture and over-
lays. In addition, it boasts 80 KB of
PIC using few parts. static RAM that can be used for dis-
play purposes and to store data from
the PIC. For example, an Epson ND-
TFD 160 × 160 panel in 8-bit Color
mode uses 25 KB of RAM and leaves
55 KB for the PIC to store data.
Another advantage is that the Photo 1—Here’s the PIC controller interfaced to the
S1D13708 can interface directly to a S1D13708’s evaluation board.

42 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


Microchip’s P18C452 microcontroller Microchip P18C452
S1D13708. The pixel clock for the LCD
has 34 I/O lines that can be used as panel can be set as a derivative of the
CS (RD0) CS*
general I/O lines, 1536 bytes of RAM, A0 (RD1) M/R* main clock source using the S1D13708’s
and runs 20 MHz at 3.3 V. Despite R/W* (RD2) RD/WR* internal divider. Any remaining
EBL (RD3) WE0*
being one of the company’s bigger D[7:0] (RB[7:0]) DB[7:0] unused input lines should be tied to
System CLK CLKI
chips, you’ll find it easy to use. System RESET RESET* ground, as illustrated in Figure 1.
The interface between the S1D13708 Note that there is a set of configura-
DB[15:8]
and P18C452 involves Indirect Mode WE1* tion pins that’s latched on the *RESET
RD*
68 and requires only four output lines BS*
pin of the S1D13708. These pins are
that act as control signals. Eight bidi- AB[16:0] CNF [7:0] and are hard wired. For
rectional lines act as the data bus. A Indirect Mode 68, the CNF [7:0] pins
fully functional S1D13708 LCD con- Figure 1—The P18C452 interfaces with Epson’s
should be wired to be: 00000111. This
troller can be attached to the PIC S1D13708 Indirect Mode 68 interface. Note that when configuration puts the S1D13708 into
microcontroller with only 12 I/O connecting the S1D13708 *RESET pin, you should be Indirect Mode 68: little endian, wait
lines. If a 16-bit data bus is desired, aware of all conditions that may reset the S1D13708 active low, block divide by one, and
(e.g., CPU reset can be asserted during Wake-Up
eight more bidirectional lines from the from Power Down modes or during debug states). GPIO are outputs. Mode 68 is selected
P18C452 can be connected to DB[15:8] by tying *BS to ground. Tying *BS to
and one more output line, acting as As you can see, the hardware con- VDD selects Mode 80.
EBH, connected to the *WE1 pin of nection is simple. The clock and reset The LCD panel connection truly
the S1D13708 (see Figure 1). input are the same for the PIC and depends on the type of panel you’re

Figure 2—Using this schematic, you can interface the Epson S1D13708 to the Microchip PIC17C452. Here is the Epson L2D25001 ND-TFD panel. It’s a pure 3.3-V device.

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 43


going to connect. My office uses has bus control that’s similar to a block of memory. Reading a single
boards that have generic headers that 6800, and Mode 80 resembles an 8080. byte of memory requires setting three
we can connect to various collections Furthermore, both modes have been address registers and a fourth access to
of panels. But not all panels will use changed so that they use only a single the Memory Access Start register.
every LCD pin in the S1D13708 pack- address line (A0) to distinguish In order to implement the bus
age. For example, a 4-bit monochrome between a command access and a data cycles in software you’ll have to refer
panel requires only four of the access. For more information on the again to the Epson web site for the bus
S1D13708’s control signals and four of indirect interface mode interface, timings. A minimum of three steps
its data lines. In contrast, an 18-bit please refer to Epson’s web site. The must be implemented in the software
Sharp HR-TFT will use eight control hardware manual gives clear examples to use the indirect interface. The steps
signals and 18 data lines. of the bus cycles and how data is for an 8-bit data transfer are:
I recommend that you use the transferred between a host (i.e., PIC)
generic connectors to test the differ- and the S1D13708. void command_write (char com-
ent panels. After this is done, you can mand_value)
go ahead and hard wire the final selec- BUS SOFTWARE EMULATION void data_write (char data_value)
tion. The panel connector in Figure 2 When the S1D13708 is in Indirect char data_read (void)
is for an Epson L2D25001 ND-TFD mode it’s not a pure memory-mapped
panel. I used this panel because it’s a device. In fact, the protocol of the bus You can download a C compiler for
pure 3.3-V device and it requires no becomes two addresses (controlled by the routines from Microchip’s web
bias voltage circuitry for panel back- an A0 line) that access either the site. I found the compiler to be per-
light. Essentially, this turns the dis- command register or the data regis- fect for this type of application
play circuitry into a simple connector ter. This makes communication as because I didn’t require tight opera-
issue. The schematic for this circuit simple as issuing a command and tions and the P18C452 had more pro-
was designed to serve as a RS-232 ter- then reading/writing the data register. gram space and speed than I needed.
minal display. The PIC micro listens To access the S1D13708, this protocol The best thing about the compiler is
to the RS-232 port and passes the data must be followed. that it’s free. Take a look at Figure 3
to the S1D13708’s display memory. The S1D13708’s memory is also to see a sequence for reading and writ-
The P18C452 had plenty of horsepow- accessed through the registers. The ing the S1D13708. You can also use
er to handle this task, so a smaller memory address (3 bytes, because the sequence to read memory by
PIC would have been a better choice. 80 KB needs 17 bits to access) has to be implementing a data_read(). Note that
stored in registers 0xC2, 0xC1, and the memory address is autoincre-
THE INDIRECT INTERFACE 0xC0. This creates the pointer for mented after a memory data access
As I mentioned earlier, the future memory accesses. Then a com- and that the start register REG [C3h]
S1D13708 supports various CPU mand (a write access to the register) is doesn’t require a data value. You can
interfaces. In this project, you are issued to register 0xC4 to start the also see a C implementation of the
going to use the indirect interface bus transfer. The address registers are auto- bus cycles in Listing 1.
to connect the PIC and S1D13708. By incremented after each access. The Photo 1 shows the PIC controller
using the indirect interface, microcon- overhead for reading a large block of interfaced to the evaluation board for
trollers that don’t have a true bus memory is the same as reading a small the S1D13708. A voltage translator
interface can be connected to was used on the PIC because
the S1D13708 by implement- my team had an EPROM
ing software emulation to Example 1—The sequence for writing the S1D13708 register REG[7Ch] PIP+ version of the PIC that
Display Start with a value of 28 h is:
toggle the bus cycles. required 5 V for operation.
command_write(0x7C);
The indirect interface data_write(0x28);
The OTP PIC17C452 can
comes in two different fla- operate as a 3.3-V device;
Example 2—The sequence for reading the S1D13708 register REG[26h] and
vors, the Indirect Mode 68 FPFRAME Pulse Start register 0 is: therefore, it will not require
and Mode 80, both of which command_write(0x26);
the voltage shifting on the
support 8- and 16-bit data value_returned= data_read(); I/O lines. In addition, all of
transfers. Additionally, the Example 3—The sequence for writing to S1D13708 memory location 200 h with the evaluation boards were
2 bytes of data is:
two buses are purely asyn- designed to be modular. This
chronous, which means they command_write(0xC0); gave us a bit of flexibility
data_write(0x00);
use only chip select as the command_write(0xC1); when interfacing to various
data_write(0x02);
control signal to catch the command_write(0xC2);
buses. You can download the
bus states. data_write(0x00); schematic for the evaluation
command_write(0xC3); //no data value is needed for the Start register
The indirect interface is data_write(0xAA); //first byte of data written to 0x200 boards from Epson’s web site.
data_write(0x55); //second byte of data written to 0x201
based on two existing and The Epson L2D25001 ND-
well-known buses. The Figure 3—For your own applications, you can use this sequence for reading and TFD panel was chosen for
Indirect Mode 68 interface writing to the S1D13708’s registers. the LCD panel. The timing

44 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


Listing 1—Here you can see a C implementation of the bus cycles. requirements of the panel are the
same as a TFT panel, but it has serial
//these are the simplified Indirect Mode 68 interface bus cycles commands that you can send to the
to mimic on the PIC general I/O pins
LCD panel itself. These commands
#define CommandWriteStep1 0b10010100 //A0 = low, RW = low are used to control features such as
#define CommandWriteStep2 0b10011000 //CS = low, EBL = high partial display. The panel is also a
#define CommandWriteStep3 0b10010100 //EBL = low,CS = high pure 3.3-V device that doesn’t require
#define CommandWriteStep4 0b10110110 //a0 = high, rw = high
#define DataWriteStep1 0b10010110 //rw = low
backlight bias voltages. The back-
#define DataWriteStep2 0b10011010 //cs = low,ebl = high light is a white LED and the intensity
#define DataWriteStep3 0b10010110 //cs = high,ebl = low can be adjusted with the PWM output
#define DataWriteStep4 0b10110110 //rw = high of the S1D13708.
#define DataReadStep1 0b10111010
//c78NORMAL & ~c78CS | c78EBL; CS = low, EBL = high
SO SIMPLE
//routine to mimic a mode 68 command write cycle This project was simple to execute
void command_write (char command_value) because integrating the S1D13708
{
//command write cycle
LCD controller to the PIC didn’t
PORTB = command_value; //place the register onto the data bus require the use of too many support-
TRISB = 0; //make port as output ing parts. In addition, using a 160 ×
LATD = CommandWriteStep1; 160, 8-bit color TFT panel leaves
LATD = CommandWriteStep2;
Nop();
about 55 KB of static RAM that the
Nop(); PIC can access for data storage. There
Nop(); are speed penalties for using the RAM
Nop(); because the Indirect Mode interface
Nop();
LATD = CommandWriteStep3;
bus is emulated with the PIC’s GPIO
LATD = CommandWriteStep4; lines, but you do get extra storage and
LATD = c78NORMAL; a display controller from a single
TRISB = 0xff; //set bus as inputs S1D13708. Furthermore, the PIC
}
//routine to mimic an Indirect Mode 68 interface data write cycle
GPIOs can be regained by multiplex-
void data_write (char data_value) ing the signals, and the S1D13708 has
{ GPIOs and GPOs that the PIC can
PORTB = data_value; //place the register onto the data bus use through its registers. I
TRISB = 0; //make port as output
LATD = DataWriteStep1;
LATD = DataWriteStep2; Peter Chia is an application engineer
Nop(); with the research and development
Nop(); group at Epson in the Vancouver
Nop();
Nop();
Design Center. He earned a degree in
Nop(); Electrical Engineering from the
LATD = DataWriteStep3; University of Victoria and a technol-
LATD = DataWriteStep4; ogist diploma in robotics from
LATD = c78NORMAL; //back to original state
TRISB = 0xff; //set bus as inputs
British Columbia Institute of
} Technology. You may reach him at
//routine to mimic an Indirect Mode 68 interface data read cycle [email protected].
char return_data_read;
char data_read (void) SOURCES
{
TRISB = 0xff; //make port as output S1D13708 LCD controller,
LATD = DataReadStep1; L2D25001 ND-TFD panel
Nop();
Epson Corp.
Nop();
Nop(); +81 226 52 3131
Nop(); www.epson.com
Nop();
Nop(); P18C452 Microcontroller
Nop(); Microchip Technology, Inc.
Nop(); (480) 792-7200
return_data_read = PORTB; www.microchip.com
//place the register onto the data bus
LATD = c78NORMAL; //we can terminate cycle early for speed
return return_data_read; HR-JFT Display panel
} Sharp Electronics Corp.
(800) 237-4277
sharp-world.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 45


part I’ll use to make the original
APPLIED PIC18Fxxx programmer.
Checking on the Internet for the

PCs availability of PIC18Fxxx parts, I see


that the date has been pushed back
again. So, let’s go ahead with this proj-
ect and be ready to roll when the new
Fred Eady PICs finally hit the street.

A MODULAR APPROACH
My original idea was to construct a

Building a Modular basis, with both firmware and hard-


ware, for a universal programming
platform. After some more thought, I

Programming Platform came to the conclusion that being


global in this project would be a nebu-
lous undertaking. Complex problems
always can be broken down into sim-
Part 1: The Program Module pler parts. So, I opted to modularize
the programmer.
Let’s say you’re reading this article
but you never intend to use a
PIC18Fxxx part. What you need right
now is a programmer for a PIC16F628.
The PIC16F628 programming power

a
requirements are identical to the
PIC18Fxxx devices and the physical
t this moment, I programming pins are also the same.
feel like Mick The differences are with the program-
Jagger. I can’t get no ming algorithm and the size and
Fred is dreaming of satisfaction. I’m looking pinout of the programming socket.
forward to using the new PIC18Fxxx The easy thing to do would be to
producing an inexpen- parts because they can run faster and build up this modular PIC18Fxxx pro-
have quite a bit more RAM and grammer and throw in some code and
sive PIC18Fxxx pro- ROM than the currently available sockets to use a PIC16F628 instead.
PIC16Fxxx devices. The problem is For those of you who like to experi-
grammer that will ulti- that I can’t get my hands on any of ment, the modular programmer plat-
mately allow him to the new parts. I can’t even get sam-
ples from the Microchip FAE.
form can be broken down into small-
er subassemblies that you can
use the new PIC parts However, I’m not going to let the remove and replace with a better or
absence of a part keep me from press- experimental circuit by simply pin-
in future PIC Internet/ ing on with this project. Even though ning out the separate submodules to
the main piece of programmable larger subassemblies.
Ethernet projects. hardware is missing, I still have the I won’t get too modular in this
PIC18Fxxx datasheet and program- series, considering that being too
With the datasheet ming specifications to work from. modular adds complexity and cost.
and programming My goal is to produce an inexpen-
sive PIC18Fxxx programmer that
Instead, I’ll stick to a two-module pro-
grammer platform. One module, the
specs in hand, he will ultimately allow me to use the power module, will house all of the
PIC18Fxxx parts in future PIC power components. The other mod-
takes us through the Internet/Ethernet projects. And, ule, the program module, will contain
because the new PIC18F4xx series is the microcontroller, program memory
first part of his project. pin-compatible with the PIC16F87x storage, communications interface,
devices, I can also expand the and any other programming algo-
PIC18Fxxx programmer’s capabili- rithm/target microcontroller-related
ties by simply sticking in a hardware. A standard board-to-board
PIC18Fxxx part with more code and or module-to-module pinout will be
RAM space to replace the PIC16F8xx enforced so that power and program

46 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


the PLCC package much of the human interface smarts
Group
A
because I can reduce the into the PIC16F877 and use a
I/O
Power 5V port PA7 –PA0 footprint and cram more HyperTerminal session for uploads,
supplies GND Group A
A (8) parts onto a smaller downloads, and status information.
control
Group
board. As of this writing, If the need arises for a more
A the PIC16F877 is the detailed programming interface, the
port C I/O
upper PC7 –PC4 most potent flash mem- standard serial interface leaves the
Bidirectional (4)
data bus Data
ory-based microcon- door open to many possibilities,
Group
D7 –D0 bus
B
troller available from including hanging a modem on the
buffer 8-bit
Internal port C
I/O
Microchip. Available in MPP serial port.
data bus lower
(4)
PC3 –PC0 this case means I can The MPP PIC firmware is crafted
physically acquire it. using the CCS PIC C compiler. The
*RD Group
Read/ Group
B The MPP will be capable CCS C compiler contains a number of
*WR write B
A1 control control
port
I/O of substituting the canned routines that handle things
B
A0 logic PB7 –PB0
(8) newer pin-compatible like the PIC16F877 serial port inter-
RESET
PIC18Fxx2/xx8 micro- face and the PIC16F877 pulse width
*CS controllers for the modulation (PWM) module. It’s possi-
PIC16F877 for possible ble that some PIC assembly routines
Figure 1—Although slow by today’s standards, the 8255 is easy to use
and widely available for less than $4 in single quantities. That’s probably
future enhancements. will have to be mixed with the MPP C
why it’s still around. Using the RS-232 serial source, but that won’t be a problem
port is the easiest and with the CCS C compiler.
modules can be exchanged with bet- least expensive method to interface There are plenty of good reasons to
ter, experimental, or specialized user- the MPP to the source of the code that use C here instead of a raw PIC
designed modules. can be downloaded. The PIC16F877 assembler. The key advantage to
Ultimately, I plan to put the has an on-chip universal synchronous using the CCS C compiler is that it is
PIC18Fxxx programmer on profession- asynchronous receiver transmitter inexpensive and, thus, allows just
al printed circuit boards. But, I’ll (USART), so all you need to employ about anyone to modify the MPP
also produce it in point-to-point for- it in this application is the presence firmware. Also, CCS’s C compiler
mat so you can either build it as you of an RS-232 interface IC. The supports the PIC18Fxxx family of
go or soak up the theory and wait for MAX232 is a less-expensive RS-232 devices. That means that all variants
the pretty PC boards. Another advan- interface solution, but I’d rather of the MPP firmware can be written
tage to modularity is that you can spend a little more money and install with the same C compiler.
try various methods and components the Sipex SP233ACP. The stan-
and simply plug in that particular dard MAX232 requires some
module without having to tear the additional charge pump capaci- Control word
whole thing apart each time you tors that are already built into
D7 D6 D5 D4 D3 D2 D1 D0
want to make a change or try some- the SP233ACP.
thing extraordinary. So, I’ll present The MPP requires more Group B
Port C (lower)
all of my hardware gyrations in this than just a simple transmit 1 = Input
series. That way, you can pick and and receive line interface. 0 = Output
Port B
choose from any of my ideas or form There are enough RS-232 1 = Input
your own conclusions and circuits buffers within the SP233ACP 0 = Output
Mode selection
from my experiences. architecture to provide RS- 00 = Mode 0
01 = Mode 1
Because the PIC18Fxxx program- 232-to-TTL translation for 1x = Mode 2
mer I will describe and build here transmit, receive, and clear-
Group A
can be adapted, I won’t box it in with to-send (CTS) flow control
Port C (upper)
the name of a specific microcon- lines with one buffer in 1 = Input
troller. So, from now on I will be reserve. Normally, that last 0 = Output
Port A
designing and building the modular buffer would be put to work 1 = Input
programming platform (MPP). After on the request to send (RTS) 0 = Output
Mode selection
the hardware is in place, I’ll provide line, but in my experience, I 00 = Mode 0
01= Mode 1
various code sets for differing shades always end up ignoring the 1x = Mode 2
of PIC microcontrollers. RTS signal and everything Mode set flag
works just fine without it. 1 = Active

PROGRAM MODULE—SPIN 1 The jury is still out on


Figure 2—Running the PIU in mode 0 makes building the control
Spin (iteration) 1 of the program whether or not I’ll write a word second nature. Even though port C is an 8-bit port on its
module will be based on a PIC16F877 GUI interface for the MPP. own in mode 0, it’s still divided between the groups in the control
microcontroller. I am leaning toward The initial plan is to stuff as word definition.

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 47


requires a great deal of output pins
and has plenty of time to service
them, the 74HCT595 serial-in-to-
parallel-out shift register approach
is the best way to go. If you ignore
the master clear pins on each
74HCT595, you can clock out
8 bits of data per 74HCT595 using
only two I/O pins of any PIC I/O
Photo 1—The blank socket at the far right is a placehold- port. But, you have to consider the
er. A 40-pin ZIF will eventually take its place. I’m consider- negative as well. The downside to
ing putting the nine-pin D shell socket that will become the using the 74HCT595 in the MPP
serial interface on the power module.
configuration is that, if the
74HCT595 is used to provide the
PICING IT APART SRAM address lines, you would have
The PIC16F877 is equipped with to either daisy chain three of them or
three 8-bit I/O ports (B, C, and D), a clock each 74HCT595 individually.
separate 3-bit E port, and port A—a Also, just in case you ever want to
6-bit I/O port. Spin 1 of the MPP will randomly retrieve data from the
include a 128-KB SRAM that will be SRAM, using the 74HCT595s would
partitioned to house the entire pro- force you to keep up with what’s in
grammable code content of the device each 74HCT595 so you could clock in
being targeted. For a PIC18F452, the the desired bits. In a daisy chain of
required SRAM size comes to 32K of 74HCT595s, you would have to clock
16-bit wide memory (64 KB of in the entire 17 bits of address infor-
SRAM) plus additional space for user mation, and that would occur only
ID words and the device configura- after you made sure you knew where
tion word. you were starting and stopping in the
At first glance, it would seem that 17-bit sequence.
the PIC16F877 has enough native I/O There is no doubt I could make this
to accommodate the 128-KB SRAM’s happen with the 74HCT595 parts, but
17 address lines and eight data I/O I don’t want to write extra code just to
lines considering that I previously keep up with where I am in the shift
called out 33 I/O lines spread out pattern. I’m not going to totally dis-
over five I/O ports. The problem is count the 74HCT595 as a solution,
that, in this MPP configuration, at but it looks like too much firmware
least two of the port B lines are used work coupled with too many parts
as the programming clock and data shrouded with too much doubt.
lines. The serial port interface takes Because I’ve temporarily nixed the
three of port C’s pins. Various other 74HCT595, that also puts the
PIC16F877 I/O lines will be called on 74HCT165 parallel-in-to-serial-out
for various control and status duties. converter on the back burner for a
Even more lines will disappear if any while. I need a bidirectional data path
type of external device that
needs to be controlled by the
Control word
PIC16F877 is added to the
D7 D6 D5 D4 D3 D2 D1 D0
MPP hardware configuration.
Obviously, there aren’t
Bit set/reset
enough PIC16F877 I/O lines 1 = Set
X X X
0 = Reset
to handle the 128-KB SRAM
Don't Bit select
without the help of an exter- care 0 1 2 3 4 5 6 7
nal device to add additional 0 1 0 1 0 1 0 1 B0
0 0 1 1 0 0 1 1 B1
I/O port pins.
0 0 0 0 1 1 1 1 B2
There are a couple of
Bit set/reset flag
schools of thought when it 0 = Active
comes to expanding the
Figure 3—This is my favorite 8255 feature. The idea is to offload
effective number of PIC I/O some of the control responsibility regarding the I/O from the host
pins. If the application microcontroller.

48 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


to the SRAM data bus. To accomplish would be a single off-the-shelf IC that The 8-bit bidirectional PIU data
that with the 74HCT165 as a parallel- could share the SRAM data bus and bus resides on the PIC16F877 I/O
in-to-serial-out input device would provide the 17 lines of SRAM address port I designated as the SRAM data
also require another 74HCT595 on the I/O. All of that in a PLCC package bus. Most likely, the PIU and SRAM
output side. After doing some would be great, too. For the part to be data buses will tie up with port D on
research, I believe I’ll have enough able to share a bus implies tristate the PIC16F877.
pins to fully use the PIC16F877 I/O capability, and hanging lots of compo- Data bus arbitration is controlled by
complement without having to resort nents off a kindred set of data lines is the PIC16F877 using the active-low
to the 74HCT595 or 74HCT165 what Intel is known for. chip select (CS) line on the PIU and
devices. So, I won’t bit bang the out- the active-low output enable (OE) line
put of the SRAM or its address pins in LOVE AT FIRST BROWSE on the SRAM. The SRAM’s active-low
this MPP spin. I found the optimal part while chip enable (CE) line is tied perma-
Eliminating the serial-to-parallel browsing through my old Intel nently to ground.
and vice versa ideas means I’ll have to Microcontroller Peripheral data books. Reads and writes for the PIU are
dedicate a full PIC16F877 data port to The 8255 programmable peripheral controlled by its active-low control
the SRAM data bus. It also means I interface (PPI) is the answer. I was signals RD and WR. The PIU RD line
have to find a part that can supply a able to come up with an 8255 look- is also connected to the SRAM OE
minimum of 17 I/O lines to the alike in a PLCC package manufac- pin, and the PIU WR line is physically
SRAM using a minimum number of tured by NEC. NEC calls it a parallel connected to the SRAM’s write enable
PIC16F877 I/O lines. interface unit (PIU) (part number (WE). A high-going RESET signal for
One method that came to mind uPD71055L-10). If you believe the the PIU is assigned to one of the
immediately was to program another datasheets, the NEC part is slightly PIC16F877 I/O pins.
PIC16F877 to be the address line gen- faster (50 ns) than the Intel 82C55A-2
erator under the control of the master during reads and writes. But, both A CLOSER LOOK
PIC16F877 via a virtual serial port parts are functionally identical in Taking a look at Figure 1, you can
that I could establish between the pinout and operation. Because I’ll be see that the internals of the PIU
PIC16F877s. Again, too much work using the NEC part, I’ll refer to the consist of two groups of registers (A
for little gain. The optimal solution uPD71055L-10 as the PIU. and B), presenting 12 bits of I/O

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 49


each. Because I won’t be using the PIU defaults to mode 0 with all I/O wide slices. With A16 low, I can store
special function modes of the PIU, pins configured as inputs. up to 64 KB of the least significant
it’s much easier to think of the PIU as The PIU control word is also used to bytes of the PIC18Fxxx or PIC16Fxxx
three 8-bit I/O ports (port A, port B, access the bit-addressable feature of device instructions. Conversely, if I
and port C). port C of the PIU. As you can see in take A16 high, I have another area of
Port C is logically divided into two Figure 3, the least significant bit of the 64 KB that I can put the most signifi-
groups of four bits. One set of bits control word determines if the selected cant PIC 14- or 16-bit instruction
resides in Group A and the other set port C bit is set or cleared. The upper bytes into. The beauty of this scheme
of bits belong to Group B. Ports A and bits of the lower nibble of the PIU is that I don’t have to increment the
B will be used as SRAM address lines control word points to the bit to be SRAM address to get 16 bits of PIC
A0–A15, with A16 being controlled by toggled. A zero in the most significant data out of the 8-bit wide SRAM.
a bit from port C. The PIU I/O port bit of the PIU control word delineates For instance, let’s say I need to
selection is determined by PIU address the bit set command from the mode store instruction 0x3C83 at SRAM
lines A0 and A1. An internal PIU set command. I’ll press the bits of port location 0x00000. First, I store 0x83
command register is also mapped into C into action as power control pins. at SRAM address 0x00000 with A16
the A0–A1 PIU address space. You can low. Then, I raise A16 and store 0x3C
download a rundown of the PIU pin IN FULL VIEW at SRAM address 0x10000. The PIC
assignments and read/write control Photo 1 is a preliminary shot of the will not use any SRAM area above
logic from the Circuit Cellar web site. MPP. I used the Dallas DS1245 non- 0x08000 or 0x18000, because its
The PIU will operate in mode 0, or volatile SRAM because I simply didn’t ROM area extends to a maximum of
the basic input/output mode. This is have any standard 128-KB SRAMs in only 32 KB. So, A16 is not in the pic-
the simplest PIU mode to set up. the Florida room. ture as far as addressing the PIC
Knowing in advance that all of the What really matters concerning the instructions is concerned.
PIU’s I/Os will be outputs, the control SRAM is how the data will be stored In PIC land, 0x3C83 is the instruc-
word in Figure 2 is easy to fill in. The and retrieved. I need 32K 16-bit words tion at ROM location 0x00000. By
sole 1 bit is the mode set flag resulting of storage. Using the SRAM’s A16 simulating 16-bit SRAM using A16, I
in a control word value of 0x80. At address line, I can logically split the can keep the PIC’s logical instruction-
power-up or following a PIU reset, the 128-KB SRAM into two 64-KB, 8-bit to-address association. That is, the

50 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


Figure 4—Rest assured that there will
be some minor changes made to the cir-
cuit as I begin to write the code.

instruction that will be stored in the to reduce parts count. I’ll also show
PIC’s ROM at address 0x00000 will you how to use the PWM module of
SOFTWARE
reside in the SRAM at address the PIC16F877 to generate the high- For the pin assignments and con-
0x00000 (low byte) and 0x10000 voltage programming power supply. trol logic, go to ftp.circuitcellar.
(high byte), which, when ignoring I’m a little nervous about the com/pub/Circuit_Cellar/2002/144/.
A16, logically equates to SRAM PIC18Fxxx datasheet, because I haven’t
address 0x00000. had the opportunity to handle the SOURCES
Normally, I would store 0x83 at device and work out the potential
PIC C compiler
SRAM location 0x00000 and then gotchas. So, assuming the PIC18Fxxx
CCS, Inc.
store 0x3C at SRAM location parts will be available before I talk to
(262) 797-0455
0x00001. Then, I would have to keep you again, I hope to have some real
E-mail: [email protected]
my mindset focused on converting experience with the PIC18Fxxx parts
the SRAM addressing model to the to pass on to you. Whether or not the PIC18Fxxx, PIC16Fxxx
PIC addressing model. Partitioning parts appear, I’ll still perform experi- Microchip Technology Inc.
the SRAM eliminates the brainteaser ments based on the data in the PIC- (480) 786-7200
and saves cycles as well. 18Fxxx datasheet and knock out some Fax: (480) 899-9210
C code to bring the MPP to life. I www.microchip.com
MPP PREVIEW uPD71055L-10 PIU
That pretty much completes the
NEC Corp.
description of the program module Fred Eady has more than 20 years of
(800) 338-9549
hardware. I’ve included a schematic experience as a systems engineer. He
011-813-3454-1111
for those of you that want to build has worked with computers and com-
www.nec.com
your program module and get ready munication systems large and small,
for Part 2 of this series (see Figure 4). simple and complex. His forte is SP233ACP
Next time, I’ll describe the power embedded-systems design and com- Sipex Corp.
module. The plan is to use switching munications. Fred may be reached at (978) 677-8700
power supply technology in an effort [email protected]. www.sipex.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 51


are battery-powered and require DC

FEATURE motors. There are three common types


of DC motors: permanent magnet

ARTICLE (PM), stepper, and brushless. Toy


manufactures tend to use PMDC
motors because they’re cheap and easy
to control.
Joseph Jones & Ben Wirz Figure 1 depicts a simple PMDC
motor. The voltage (E) at the motor’s
terminals can be described by the fol-
lowing differential equation [1]:

RoCK Specifications where E is the sum of the three volt-


ages across the internal components
Part 4: Tying Up Loose Ends of the electrical model. See Table 1
for definitions of the rest of the vari-
ables. As the motor spins, the interac-
tion between the permanent magnet
field and the windings generates a
voltage (V) that opposes the supply
voltage. In this instance, V is known

t
as the back electromotive force (EMF).
Back EMF voltage is directly propor-
his is the final tional to the motor’s speed and is
installment in our given by the formula:
series on the Robot
In Parts 1, 2, and 3, Conversion Kit (RoCK).
In the past three issues, you’ve learned
Joseph and Ben dis- how we arrived at the RoCK’s specifi- As the motor turns faster, V increases.
cations, how and why we designed the The motor reaches equilibrium and its
cussed the RoCK’s circuitry, and the scheme we used to speed becomes constant when the
program it. This month, we’ll tie up applied voltage is equal to the back
specifications, circuit- the loose ends by describing the EMF voltage minus resistive losses.
ry, and programming. RoCK’s discrete motor driver, explain-
ing the low-level RoCK/host interface,
The motor current (I) is proportion-
al to the total torque produced by
In this final part, and walking you through the creation the motor:
of a new user-programmed task.
they’ll describe its dis-
WHAT IS A MOTOR?
crete motor driver, Before designing a motor driver, When the motor reaches equilibrium
you have to develop an electrical the current is constant, so the follow-
explain the RoCK/ model of the motor you wish to con- ing term goes to zero:
host interface, and trol. So, what’s a motor? A motor is a
device that converts electrical energy
show you how to cre- into mechanical energy. There are
dozens of different types of motors, If you consider only the equilibrium
ate a new user-pro- but the broadest classification divides condition, you can set this term to
them into direct current (DC) and zero. Then, by substituting for V and
grammed task. alternating current (AC). Most robots I, you arrive at the following equation:

E Terminal voltage TL Shaft torque output I Motor current


ω Motor shaft rotation rate L Winding inductance KT Torque constant
RT Terminal resistance KE Back EMF constant V Back EMF voltage
TM Motor torque losses

Table 1—In our analysis of a PMDC motor we refer to these ten symbols.

52 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


mine the constants, but it’s usually
VCC
L unnecessary. The important thing to
E R remember is that at a given load, a SW1 SW3
+
V
– motor’s speed is proportional to the + M –
terminal voltage and its torque is pro- SW2 SW4
Figure 1—A motor can be modeled electrically as an
portional to the motor current.
inductor (L) in series with a resistance (R), and a volt-
age source (V). The voltage (E) at the motor terminals
can be thought of as the sum of the voltages across the MAINTAINING CONTROL
internal components L, R, and V. A voltage (L × dI/dt) Figure 2—Here’s an H-Bridge that’s composed of four
We can control the speed of a electrically controlled switches. It can select the direc-
appears across L when you change the current flowing
PMDC motor by varying the terminal tion of motor rotation.
through the motor. The voltage across R (IR) results
from electrical losses in the motor, and the voltage (V) voltage (E). For reasons of cost and
appears because the motor also acts as a generator. efficiency, we don’t usually vary E reverse the direction of rotation, we
using linear circuit techniques. needed to reverse the polarity of the
Instead, designers typically use a pulse terminal voltage. To do this, we imple-
width modulation (PWM) scheme. mented an electrical configuration
With PWM the instantaneous voltage known as an H-Bridge. An H-Bridge is
applied to the motor is either zero or constructed from four electrically con-
And by solving for ω you get: maximum. The average voltage, how- trolled switches (see Figure 2). With
ever, is proportional to the PWM duty SW1 and SW4 closed, the motor’s ter-
cycle. Many microcontrollers, includ- minal voltage is positive and current
ing the RoCK’s AVR, have a built-in flows from left to right as the motor
In practice, you might not be able to facility for generating PWM. turns forward. Conversely, with SW2
compute this equation because you’ll In comparison to controlling the and SW3 closed, the terminal voltage is
rarely know the torque and back EMF velocity, selecting the motor’s rotation- negative and current flows from right to
constants. You can use a torque gauge, al direction is a bit more involved. In left as the motor turns in the opposite
tachometer, and multimeter to deter- order to change the sign of ω, and thus direction. With at least three switches
open, the motor is disconnected from
the battery and doesn’t turn.
Listing 1—This pseudo-code demonstrates how your computer can communicate with the RoCK by
We can control motor direction by
accessing its own serial port and executing a straightforward program.
using logic components to activate
function Read_RoCK (Addr) //Addr is the address in RAM we wish diagonally opposite pairs of switches.
to read To control velocity, we then use a
Byte_1 = High_Byte(Addr)//the AVR’s RAM requires a 10-bit PWM signal to rapidly open and close
address
the switches.
Byte_2 = Low_Byte(Addr)
Byte_3 = 0 //byte 3 is a dummy byte for the read function
Serial_out(Byte_1) //send a byte to the RoCK SWITCHING INDUCTIVE LOADS
Serial_in() //read and ignore the echoed byte to Motors aren’t as well behaved as
clear input buffer other components (e.g., resistors and
Serial_out(Byte_2)
LEDs). That’s because motors, being
Serial_in()
Serial_out(Byte_3) inductors, can store energy and then
Serial_in() inject it back into your circuit in a
Return Serial_in() //the RoCK reports the value stored destructive fashion.
at Addr The voltage induced across an induc-
end
tor is proportional to the rate of change
function Write_RoCK (Addr, Data) //store data at Addr in RAM of current moving through the induc-
Byte_1 = 0x80 bitwise_OR High_byte(Addr) tor. When the current through an ideal
//High bit set indicates write operation inductor has reached a steady state, the
Byte_2 = Low_Byte(Addr) inductor acts as a short. The equation
Byte_3 = Data //third byte is data in write operation
for the voltage across an inductor is:
Serial_out(Byte_1)
Serial_in()
Serial_out(Byte_2)
Serial_in()
Serial_out(Byte_3) If you want to understand how an
Serial_in()
inductor can create a problem, take a
Return Serial_in() //The RoCK reports the value now stored
at Addr look at Figure 3. When the switch
end closes, the current through the induc-
tor increases until it reaches a steady
state. If the switch is then opened, the

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 53


implemented by using either bipolar used for power switching applications.
VCC
ION
transistors or MOSFETs in the power However, the impressive VCE(SAT) of the
stage driver. Compared to transistors, Zetex parts made these bipolar tran-
VSW
MOSFETs offer better performance sistors suitable for our application.
and lower resistive losses. However, By choosing PNP transistors Q10
they’re more expensive and have more and Q14 for the driver’s high side, we
complex control requirements. simplified our design. If we had used
Figure 3—The action of an inductor is to oppose The bipolar design described here NPN transistors, we would’ve had to
changes in the current flowing through the inductor. delivers a continuous current of drive their bases at a voltage higher
When we attempt to stop the current, ION, flowing
300 mA per motor, and accepts a bat- than the power rail. Although PNP
through the inductor by opening the switch, the induc-
tor reacts by rapidly increasing the voltage VSW. tery motor supply voltage range of 4 to transistors are less efficient then their
15 VDC. (Note that the motor current NPN counterparts, the Zetex units
collapsing magnetic field around the supplied by the H-Bridge driver is lim- met our requirements.
inductor induces a large voltage spike. ited by the specifications of the driver Q6 and Q7 form a logical AND gate
The result is a large current change transistors. The production version of requiring both the PWM and direction
(dI) over the short time (dt), and a the RoCK may use higher current signal to be high for the motor to
large potential at VSW. This voltage transistors.) By avoiding MOSFETs we receive a positive voltage at its termi-
spike, known as inductive kickback, reduced both cost and board space. nals. Q22 performs a logical inversion
can easily exceed the manufacturer’s The 300-mA continuous current rating of the DIR signal. With PWM high
ratings of the power-switching device. is adequate for the many RC cars and DIR low, the motor receives a
However, we can clamp this kickback using alkaline AA or 9-V batteries. negative voltage at its terminals. With
voltage to a safe level by connecting a Zetex produces a series of capable Q6 and Q7 turned on, current flows
reverse-biased diode across any switch SOT-23 bipolar transistors. We used out of the base of Q10, through Q6
that controls an inductor. Because the Zetex FMMT489TA for the low and Q7, and into the base of Q15. The
motors have large inductance, clamp- side NPN transistor (Q11 and Q15), base drive current is limited by R32,
ing diodes play an important role in and the Zetex FMMT589TA for the and given by the following formula:
the design of any motor driver. high side PNP transistors (Q10 and
Q14). Both transistors offer a VCE(SAT) of
A PRACTICAL DESIGN less than 200 mV at:
Now that you understand the basic
concepts, we’ll move ahead and IC = 300 mA The selection of the base resistor
describe the RoCK’s motor driver (see value was a compromise between
Figure 4). We began the design of an The low VCE(Sat) rating reduces the max- providing adequate base drive for the
H-Bridge driver by selecting the physi- imum power dissipation to 60 mW for power transistors and maximizing
cal components needed to create the each of the transistors. Because of their efficiency at higher battery voltages.
abstract switches shown in Figure 2. high thermal resistance, SOT-23 pack- In the previous formula, you see that
Generally, PMDC motor drivers are age bipolar transistors aren’t generally the minimum base current occurs at

Offset Name Description Offset Name Description

0 pg_speed Global max robot speed 20 pv_i


1 pd_dance_index Dance selector 21 pr_time Time between random events
2 pd_dist_fact Time/distance ratio 22 pr_dur Duration of random event
3 pi_a The parameters pi_a 23 pc_dir Robot turn angle
4 pi_b through pi_i are the 24 pe_backup Escape backup time
5 pi_c coefficients of a matrix 25 pe_spin Escape spin time
6 pi_d that transforms left and 26 pe_fwd Escape forward time
Table 2—The RoCK 7 pi_e right IR detector inputs 27 reserved Reserved for future expansion
behaviors use these 8 pi_f into left and right velocity 28 reserved
parameters to compute 9 pi_g and action 29 reserved
outputs. Parameter values 10 pi_h 30 pj_angle Joystick drive angle
are copied from flash 11 pi_i 31 pj_speed Joystick speed
memory or EEPROM and 12 pv_a The parameters pv_a 32 pj_active Joystick active
held in RAM during pro- 13 pv_b through pv_i are the 33 pb_tempo Tempo of buzzer tune
gram execution. The RAM 14 pv_c coefficients of a matrix 34 pb_select Buzzer input source
address of a particular 15 pv_d that transforms left and 35 pee_high_addr High byte of EEPROM Addr
parameter is computed by 16 pv_e right photocell values 36 pee_low_addr Low byte of EEPROM Addr
adding the appropriate off- 17 pv_f inputs into left and right 37 pee_data Data for EEPROM
set to the base address 18 pv_g velocity and action 38 pee_flag Write EEPROM data flag
given by a constant called 19 pv_h 39 px_frob Map user potentiometer value to parame-
parameter.

54 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


the minimum battery voltage. Both RoCK’s internal variables and simplify program execution. The data address
the PNP and NPN transistors have a programming. That software hasn’t space is located in the AVR’s 512 bytes
beta (gain) of at least 50 throughout been written yet, however, we’ll of RAM, which contains the AVR’s
their operational range. A 330-Ω describe the low-level interface that it control registers, stack, and all of the
resistor maintains the required base will be based on. RoCK’s variables. There’s also a third
drive current of at least 6 mA across The AVR uses a Harvard architec- memory space, 512 bytes of EEP-
the voltage range. ture that establishes separate memo- ROM. Special instructions provide
With a 4-V battery, the base current ry spaces for program and data. access to this memory.
would be 7 mA; with a 15-V battery, Program memory consists of the To compute their outputs, the RoCK’s
the current would be 40 mA. A higher RoCK’s software instructions and behaviors incorporate one or more
battery voltage reduces the motor dri- certain constant values. The AVR’s adjustable parameters. The RoCK’s
ver’s efficiency by pushing more cur- flash memory provides program stor- tasks specify values for these behavior-
rent into the base than is necessary. age, and it can’t be changed during effecting parameters (see Table 2). Built-
We expected that most users would
employ low-voltage batteries, so we
optimized the driver for the lower
range. The quiescent current is unaf- Frustration? No, thanks.
fected by the base resistor choice.
Shoot through often creates perplex-
Fun? Yes, please. NeW n
Vers
io

ing problems for discrete H-Bridges. Satisfied customers - the key to our success
Shoot through is a transient condition > that´s why every new EAGLE version is based
that occurs when the high and low on the feedback from our customers
sides of the H-Bridge are unintention- > that´s why all our customers have access to our
ally turned on simultaneously. For highly acclaimed, comprehensive support, free
example, suppose the motor in of charge
Figure 2 is going forward (SW1 and > that´s why EAGLE has no hidden costs for
libraries or modules which prove to be
EAGLE 4.0
SW4 are on) and the direction is sud- indispensable after purchasing Schematic Capture • Board Layout
Autorouter
denly reversed (SW1 and SW4 turn off > that´s why we really want customers to enjoy
for Windows
®
while SW2 and SW3 switch on). If, at working with EAGLE
the time of reversal, SW3 turns on > that´s why EAGLE is one of the top-rated and
faster than SW4 turns off, then there programs for schematic capture and board
layout Windows is a registered trademark of Microsoft Corporation
is a momentary short from the power Linux is a registered trademark of Linus Torvalds

rail to ground. In the best-case sce-


nario, this situation results in wasted Version 4.0 Highlights
power. In the worst case, transistors ! New Library Management with
Component Browser
are destroyed. ! Technology and Package variants for
Supplementary components can be components
! Design your own commands via User
added to the circuit to protect against Language
shoot through. These components ! Unlimited length for component
names/values
would provide hard-wired time delays ! Design Rules define pad/via
that turn the drive transistors on and dimensions and shapes
! Net Classes for Autorouter and DRC
off in a definite order. Integrated motor ! Minimum Autorouter grid: 0.02 mm
driver ICs use this method. But, we ! SMD pads can be rounded or round
! Different pad shapes for Top, Bottom,
chose the lower-cost approach by or Inner layers
adding complexity to the software
rather than the hardware. Whenever EAGLE 4.0 Light is Freeware! FREE
the motor direction is reversed, the You can use EAGLE Light for testing and for Prices Light Standard Professional
non-commercial applications without charge. The Freeware
RoCK’s software outputs a zero on the Version is restricted to boards up to half Eurocard format, Layout 199$ 399$
with a maximum of two signal layers and one schematic
PWM line for 1 to 2 ms and then sheet. All other features correspond to those of the Layout +
Schematic 398$ 798$
restores the commanded PWM value. Professional Version. Download it from our Internet Site
or order our free CD. Layout +
Thus, motor direction changes only The Standard Version is suitable for boards in Eurocard Autorouter 398$ 798$

when the power is off. format with up to 4 signal layers The Professional Version Layout +
has no such limitations. Schematic + 49$ 597$ 1197$
Autorouter
HOST INTERFACE http://www.CadSoftUSA.com
Pay the difference for Upgrades
We turn now to the RoCK/host 800-858-8355
computer interface. Ultimately, you’ll CadSoft Computer, Inc., 801 S. Federal Highway, Delray Beach, FL 33483
benefit from a host computer-based Hotline (561) 274-8355, Fax (561) 274-8218, E-Mail : [email protected]
software module that will monitor the

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 55


in tasks store default parameter strate the latter, we will create a
values in flash memory, and Offset Name Description new user task called BumpEm.
user-programmed tasks keep 0 Photo_left Left photocell
BumpEm is a simple task that
initial values in EEPROM. In 1 Photo_right Right photocell makes the RoCK move in a large
either case, parameter values 2 Motor_bat Voltage of motor battery circle. If the robot bumps into
are copied to RAM at startup. 3 Logic_bat Voltage of logic battery something, the beeper sounds,
4 User_pot Setting of user potentiometer
To program a user task you 5 IR_detect Left and right IR detection bits
and the RoCK backs up and
must store parameter values in 6 Bump 1-bit collision detection chooses another direction. We
EEPROM. To change robot 7 User_button State of user button need only two primitive behav-
behavior on the fly, the host iors, Cruise and Escape, to com-
computer writes parameter val- Table 3—Functions of the RoCK constantly update the value of these
pose this task.
ues to RAM. real and virtual sensors. Values are stored at consecutive fixed locations The Cruise behavior makes
All interactions between the in RAM and are accessible to the host computer. Values are offset from the robot move, ignoring all sen-
RoCK and host computer are the base address constant called sensor. sors. Cruise uses a parameter,
conducted using the 3-byte called pc_dir, that tells it which
serial protocol (3BP) described in we used the Select button and user way to move. When the value of
Part 2 (Circuit Cellar 142). The 3BP potentiometer to select the Remote pc_dir is 128, the Cruise behavior
reads and writes locations in RAM. task. The remote task calls the sends commands to the robot’s
To communicate with the RoCK, Joystick behavior, and Joystick motors that produce a forward
your computer must access its own decides the robot’s speed and direction motion. If the value is 64, Cruise
serial port and execute a simple pro- by watching the parameters pj_angle, makes the robot spin in place to the
gram. You can write the program in pj_speed, and pj_active (see Table 2). left; a value of 148 will make the
Visual Basic, C, Lisp, or another The host computer can directly con- robot spin to the right; and a value of
familiar language. Listing 1 shows trol the motion of the robot by writ- zero or 255 will make the robot back-
the pseudo-code we wrote. ing values to these variables via the up. Thus, pc_dir indicates the turn
The simulated code in Listing 1 Write_RoCK function. To obtain the angles for the robot. And we’ll choose
assumes the availability of functions address in RAM of a parameter, we a value of, say, 130 to make the
called Serial_out and Serial_in. added the base address parameter to RoCK arc a little to the right.
These functions send and receive the offset given in Table 2. The Escape behavior decides when
1 byte of data to the serial line. The the robot should try to escape from a
code also relies on a function to select PROGRAM A TASK collision with another object. The
the highest two bits of a 10-bit Monitoring and controlling the actions of the Escape behavior are
address, High_Byte, and the lowest robot directly from your host comput- specified by three parameters:
eight bits, Low_byte, as well as a func- er is a matter of reading or writing pe_backup, pe_spin, and pe_fwd.
tion to OR together two bytes, called addresses in RAM. Programming a These three parameters determine
bitwise_OR. user task means storing certain values how long the robot should backup,
in nonvolatile EEPROM. To demon- spin in place, and move forward after
MONITOR AND CONTROL
Monitoring key locations is simple
when you use the functions described
previously. Suppose you want the cur-
rent value of the right photocell.
From Table 3 you can see that
photo_right has an offset of one. This
means that the value is located in
RAM at the location sensor plus one.
In the current compilation, sensor has
the value 0x0BC. Therefore, you call
Read_RoCK (0x0BD) to get the value
of the right photocell. Communicat-
ing with the RoCK at 9600 bps and
allowing four byte transfer times to
send three and receive one byte
means that the host can get an updat- Figure 4—The RoCK’s discrete motor driver is implemented using small SOT-23 bipolar transistors. Reverse-
ed value for any sensor reading in a biased diodes between the emitter and collector of each driver transistor (Q10, Q11, Q14, and Q15) protect the
transistor from destructive motor-induced voltage spikes. Transistor pair Q6 and Q7 and also Q18 and Q19 form
minimum of about 4 ms. AND gates. These gates select diagonally opposite pairs of driver transistors and thus motor direction. The selec-
We can also use the host computer to tion is made by the DIR-A signal along with the inverse of DIR-A created by Q22. The PWM-A signal then rapidly
directly control our robot. To do this, switches the selected pair to control motor speed.

56 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


a collision. The definitions we must write the indices
Address range Description
for these values are such of Escape and Cruise, six
that we can make the 0–9 Priority list for user program 1 and five respectively, to
robot backup for 250 ms by 10–49 Parameter list for user program 1 the user priority list of
setting pe_backup to 16, 50–59 Priority list for user program 2 user task one (see Table 4).
spin for 500 ms by setting 60–99 Parameter list for user program 2 To store our choices in
100–109 Priority list for user program 3
pe_spin to 31, and then EEPROM, we access the
110–149 Parameter list for user program 3
give up control immediate- RoCK’s EEPROM writer
150–159 Priority list for user program 4
ly by setting pe_fwd to 160–199 Parameter list for user program 4 function by writing special
zero. 200–349 User-programmed song (150 notes maximum) registers that were created
There are two more 350–500 User-programmed dance (150 steps maximum) in RAM. For example, the
important parameters: 500–509 Reserved first value we want to set is
pb_select, which is the 510 Steering configuration flag, differential drive versus drive/steer the highest priority behav-
511 Index of the most recent user-selected task
beeper control parameter, ior in user task one.
and px_frob, which is the Referring to Table 4, you
Table 4—The AVR’s 512 bytes of EEPROM memory are mapped as shown.
index of the parameter see that user task one is
that receives input from the user behavior. Rather than controlling at location 0 in EEPROM. The value
potentiometer. The beeper behavior speed, the user potentiometer could we want to store here is six, the
is written so that we can make the be used to make the robot drive in index of the Escape behavior. To do
beeper sound whenever a collision various directions. this, we use Write_RoCK to write
occurs if we write a three to We now know the parameter val- the high part of the EEPROM address
pb_select. We will set px_frob to the ues needed for the BumpEm task. (zero) to parameter pee_high_addr.
index of pg_speed (zero) to make the But we also need to specify the We write the low part of the address
user potentiometer control robot behavior priority list. The highest (also zero) to pee_low_addr, the data
speed. If we instead set px_frob to priority behavior must be Escape, (six) to pee_data. Finally, we write a
the index of pc_dir (23), then the which will control the robot during a one to pee_flag. As soon as this final
user potentiometer would control collision. Cruise gets the second high- step is taken, the data is actually
the drive angle used by the Cruise est priority slot. To instantiate this, stored in EEPROM.

Need a better bridge?

ICON H-Bridge
DC Motor Interface Module

Up to 40VDC Motors
12A Continuous/25A Peak
Over Current Fuse
Over Temperature Fuse
Serial or Direct Drive Mode
2.5” X 1.9” Footprint
Solutions 3
SOLUTIONS CUBED • (530) 891-8045 PHONE • WWW.SOLUTIONS-CUBED.COM
www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 57
All of the other values we want to site, www.wirz.com/rock/, for avail-
RESOURCE
store can be saved in the same fash- ability and additional information.
ion. And when they’re finally writ- Pitman, “Pittman Servo Motor
ten, we’ll have created the new Joseph L. Jones grew up in a small Application Notes,”
BumpEm task. We can have the town in the Missouri Ozarks. He stud- www.pittmannet.com.
RoCK run this task by pressing the ied physics at MIT and received a BS
user button and twisting the user in 1975 and an MS in 1978. He took a SOURCE
potentiometer just as we would do for trip around the world, worked at the
FMMT489TA, FMMT589TA
any of the built-in tasks. MIT Artificial Intelligence Lab, and is
Zetex Semiconductors
now senior roboticist at iRobot Corp.
44 161 622 4444
SERIES SUMMARY You may reach him at [email protected].
www.zetex.com
We hope you’ve found our series to
Ben Wirz also grew up in a small
be instructive and that you’re now
town in the Missouri Ozarks. He
eager to build a robot. There are many
studied physics and electrical engi-
resources for learning more about
neering at Washington University in
robots. Searching the ’Net will return
St. Louis, and graduated in 1997. He
hundreds or even thousands of hits.
is currently employed as a senior
You may find a robot users group or a WINNING PROJECTS
electrical engineer by iRobot in addi- MPSLIC: A single-chip FPSLIC MP3
robot club in your area. Joseph’s book,
tion to running his company, Wirz decoder and player
Mobile Robots: Inspiration to
Electronics. You may reach him at Blueport: A card-sized module intended
Implementation, is designed to help to be used as a smart SPI peripheral to
[email protected].
you get started in robotics. And final- provide seamless communication over
ly, please check for new develop- Bluetooth
ments and more information about
REFERENCE Versatile Communications Card for
the RoCK on our web site. I [1] J. Jones, A. Flynn, and B. Seiger, Linux
Mobile Robots: Inspiration to For project descriptions and abstracts, visit
Authors’ Note: We plan to offer the Implementation, 2nd ed., A.K. www.circuitcellar.com/dl2001/index.htm
RoCK for sale. Please check our web Peters, Ltd., Natick, MA, 1999.

58 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


analog-to-digital converter used to

FEATURE interface to signals such as sensor


inputs and other analog waveforms.

ARTICLE There are two serial communications


systems: the Serial Peripheral
Interface (SPI), which is synchronous,
and the Serial Communications
Ross Bannatyne & Interface (SCI), which is asynchro-
Dave Wilson nous. The LVI is a low-voltage inhibit
module with software-selectable trip
points, and there are two timer mod-
ules that each offer a variety of hard-

Dealing With Motor ware timer functions. The specific


functions that have been implemented
to facilitate the low-distortion motor

Control Dead-Time control are included in the pulse


width modulator module.

DEAD-TIME DISTORTION
Distortion To drive a three-phase electric
motor, a six-transistor inverter circuit
is commonly used. Most voltage-
sourced inverters require a dead time

t
to be inserted between the turning off
of one transistor in a half-bridge, and
he precise con- the turning on of its complementary
trol of electric device. Otherwise, both transistors in
motors is becoming a half-bridge may be on at the same
Dead-time distortion more popular and afford- time, which would destroy the circuit
able because of specific enhance- by shorting together VDD and ground.
can be problematic ments in general-purpose 8-bit By inserting this dead time, a dis-
microcontrollers. In this article, tortion is introduced in the output
when you’re trying to we’ll discuss the type of hardware voltage and current waveforms when
feature that has been added to a low- the inverter is driving an inductive
design a motor con- cost microcontroller to improve its load (such as a motor). This distor-
troller. But that does- motor control capability.
A major problem facing designers
tion, however, can be satisfactorily
corrected in most situations. By
n’t mean you have to of motor controllers is the source of using a Hall Effect current sensor or
distortion that’s common to power other current sensing device, correc-
settle for noisy, rough- stages using totem-pole transistor tion waveforms can be generated that
configurations driving inductive are synchronous to the motor phase
running motors. Ross loads. On AC induction motors run- currents and applied to the PWM sig-
ning open loop, the problem typical- nals. There is also a sensorless tech-
and David explain ly manifests itself as poor low-speed nique that accomplishes this with-
there are inexpensive performance (e.g., torque ripple and
rough operation).
enhanced microcon- The MC68HC908MR32 microcon-
CPU
32-KB
Flash memory
768-byte
troller solves the problem by sensing EEPROM
RAM

trollers that can cor- the motor phase voltages during the
dead-time intervals and modifying
rect distortion. the modulation waveform to cancel LVI Timer
A
Timer
B
SCI

the effects of the distortion. This


results in quieter and smoother run-
ning motors. PWM
ADC SPI
The main features of the microcon- (Low distortion)

troller are the 32 KB of flash EEPROM


program memory and 768 bytes of Figure 1—A diagram of the MC68HC908MR32 shows
RAM (see Figure 1). There is also an its 32 KB of flash memory and 768 bytes of RAM.

60 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


out the need for current sen- V+ subtracting n from d1, we
V+
sors. This feature has been obtain the distortion voltage
integrated into the Desired load V– that’s actually impressed
voltage
MC68HC908MR32 micro- across the phase 1 leg of the
controller. Thus, the benefits PWM to top load, which is shown as the
transistor
of distortion correction can bottom waveform of Figure 4.
i+
be brought to the arena of This voltage sets up a current
PWM to bottom
low-cost motor control appli- transistor in that phase that is a func-
cations that cannot afford the i– tion of the load impedance.
more expensive current sens- Actual load When the original sine wave
voltage (for i+)
ing techniques. current is added back in by
Figure 2 illustrates a half- Actual load superposition, the result is a
bridge circuit composed of voltage (for i–) current waveform with
IGBTs that generate a clipped peaks (see Figure 3).
desired PWM output wave- In fact, under certain condi-
form with a 50% duty cycle. V– tions when the distortion
Dead time
Note that with no dead waveform is large with
time, this could easily be respect to the modulation
achieved by turning on the waveform, the distortion can
Figure 2—During dead time, load inductance defines voltage to keep inductive
top transistor for half of the current flowing through the diodes. Note how dead time affects the pulse width actually cause the current to
cycle, and turning the bot- of the inductive load voltage. dip at its peaks.
tom transistor on for the
remainder of the cycle. However, we assume that the motor load is bal- PROBLEMS WITH DISTORTION
with dead time inserted, the on anced, we can average the three dis- Several serious problems can arise
times of both the top and bottom tortion voltages to obtain the motor because of dead-time distortion. The
transistors are shortened evenly, so neutral voltage n. Unlike three-phase amplitude of the distortion per unit of
neither the top nor bottom PWM sig- sine waves, the distortion waveforms bus voltage is equal to the ratio of the
nal corresponds to a 50% duty cycle. don’t result in a neutral voltage of dead time to the PWM period. Because
Because of the inductive effects of zero over time. Instead, it’s a square dead time is a system parameter that
the load during the dead-time inter- wave with transitions every 60°. is usually fixed in accordance with the
val, the pulse width of the output For the sake of this analysis, assume switching characteristics of the power
voltage will be effected. It will be that the motor is a three-phase y con- devices, the problem is usually asso-
either larger or smaller than desired nected load (although the results apply ciated with higher PWM frequencies.
(depending on current polarity) by an equally to delta connected loads). By In some cases, you will specify a
amount equal to one dead-time inter-
val. This in turn causes an offset in
the average output voltage. After the Voltage with correction disabled

voltage waveform has been effected, Current is


negative
the current waveform will be distort-
ed as well. You can see a depiction of
this in Figure 3.
To understand the shape of the
current waveform, it’s necessary to
consider the distortions and interac-
Current is
tions of all three phases. If we positive
assume a steady state load, it’s safe to
12 V Peak-to-peak
also assume that the angular separa- Current with correction disabled
tion of each line current is 120°. The
distortion voltage is 180° out of phase
with the current for each phase, so
each of the distortion waveforms are
also separated by 120°, as is illustrat-
ed in Figure 4.
Assuming the motor load is linear,
superposition can be used to analyze
the system response to the distortion 2 V Peak-to-peak
alone (i.e., the modulation signal
equals zero). Under this condition, if Figure 3—As you can see, voltage and current distortion result from dead time.

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 61


higher PWM frequency to mini- these signals. With no distortion
mize the total harmonic distor- i1 correction applied, the register
tion (THD) without realizing that d
1
chosen for each half-bridge driv-
the distortion from dead time i ing a motor phase does not
2
actually gets worse. d
change during the course of opera-
2
Another problem is that voltage tion, and defaults to an odd num-
i
distortion causes current distor- 3 bered PWM value register. When
tion, the result of which is torque d
3 correction is enabled, the PWM
pulsations felt on the motor shaft. n module toggles between two
Under certain conditions, this can PWM registers for each motor
translate into stability problems d -n
1
phase. One when the current
between the motor and drive. polarity for that phase is positive,
Unlike the modulation signal and the other when it’s negative.
Figure 4—These are calculated distortion waveforms.
that is purposely impressed upon The waveforms of Figure 5 are
the motor windings, the ampli- obtained by programming one reg-
tude of the distortion is not affected CORRECTING WITH PWM ister with the desired pulse width
by the modulation index. This means Because the distortion effect from plus the dead time, and the other reg-
that the problem, when viewed from a dead time can be fairly well character- ister with the desired pulse width
signal-to-noise perspective, is most ized, it stands to reason that the cure minus the dead time.
severe when the voltage is small. On should be equally straightforward. In actuality, to obtain an output
an AC induction motor, this occurs This is true, with the exception of a pulse width delta of plus or minus one
when the motor revolutions per few second-order effects. The output dead time on the MC68HC908MR32
waveform has a distortion with char- when using Center Aligned mode,
acteristics that can be closely approxi- the correction value should be plus
i+ condition i– condition mated, so the answer is to counter- or minus one-half of the value in the
Desired
load voltage
V+ modulate the original PWM signal to dead time register. This is because
provide noise cancellation. In other the PWM resolution in Center
Top Gnd words, a correction signal is superim- Aligned mode is one-half that of
PWM
posed on top of the sine wave signal in Edge Aligned mode.
Bottom
PWM the processor to cancel the output dis- An economical way to measure the
tortion. The distortion signal resem- current polarity for each phase is to
Actual
load voltage bles a square wave; therefore, the cor- use the current polarity sense inputs
rection term is also a square wave. on the ’MR32. These three pins are
Figure 5—This example of distortion correction is And because the distortion signal is used to monitor the PWM voltage
accomplished by the redistribution of dead time. synchronized to the current waveform waveforms supplied to each terminal
for that phase, the correction term of a three-phase motor. Each input is
minute are also small, and the also must be synchronized to the sampled during the dead time of the
momentum of the rotor cannot same current waveform. PWM signals associated with that
smooth out the torque pulsations, Another way to view the correction motor phase. If the input is high dur-
making them even more apparent. process is illustrated in Figure 5. ing the dead time, the current polarity
Another common problem is that Recall from Figure 2 that the
the distortion is synchronous with the dead time was balanced
motor current and 180° out of phase between the top and bottom 0.5-hp 3-phase motor

with it. At low frequencies, this PWM signals. For that par- PWM Frequency = 7.3 KHz

effect combines with the stator resis- ticular example, a 50% duty
Output : w = 1.7 Hz
tor losses to further reduce the cycle was desired. With the
motor torque. Over-modulation in insertion of dead time, the
the form of a voltage boost can be top and bottom PWM sig-
used to mitigate this problem. nals had their on times
However, the torque pulsations from reduced by an equal amount
the distortion are still present. to something less than 50%.
The previous analysis is based on The MC68HC908MR32
the supposition that the distortion always uses a single PWM
waveform is perfectly rectangular. register to derive the top and
There can be variances from this bottom signals for each tran-
premise that have an effect on the cor- sistor in a half-bridge, and it
rection technique and make it even automatically inserts a pro-
more complex to correct for. grammable dead time into Figure 6—Here’s a partially corrected current waveform.

62 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


is determined to be neg- detecting when the cur-
ative, and vice versa. V+
rent waveform is
This information can PWM to approaching a zero
top transistor On Off On Off
then be used by hard- crossing, and acting
ware in the PWM mod- before it actually occurs.
i+
ule to automatically tog- On Off On Off On
What you need is a
PWM to
gle between one of two bottom transistor
i–
waveform discriminator
PWM registers, as dis- that can tell the differ-
cussed earlier. Load voltage ence between these
(for high i+)
voltage waveforms.
ZERO-CROSSING Figure 8 illustrates a
Load voltage
DISTORTION (for low i+)
V– distortion correction
When the distortion is system acting on a sin-
corrected in this man- Load voltage
gle phase that incorpo-
ner, the current wave- (for low i–) rates this sort of voltage
form in Figure 6 is sensing technique. By
obtained. The modula- Load voltage using either hysteresis
tion index is scaled, so (for high i–) or a simple low-pass fil-
the current peak ampli- ter, the sensor detects
tude matches that of Dead-time interval before
whether or not the load
Figure 3. Otherwise, the the assertion of the top PWM inductor aggressively
same modulation index snaps the voltage wave-
Dead- time interval before
results in a 50% increase the assertion of the bottom PWM form during the dead-
in the peak amplitude, time intervals. At the
which demonstrates the Figure 7—The load voltage waveforms look as shown under various current conditions. end of each dead time
severity of the distor- region, the comparator
tion. Although most of the distortion phenomenon is not observable. The output is sampled by the D-type flip-
is gone, some still exists at the zero problem occurs when the other tran- flops, and the results are stored for
crossings. This causes torque pulsa- sistor is on and the inductor must both dead-time intervals. If the induc-
tions that can be detected on the drive the output voltage through the tor cleanly snaps the voltage wave-
motor shaft. To eliminate this distor- full power supply range during the form, then both results will agree
tion, you need to go beyond our first- dead-time interval. with each other.
order explanation of the distortion The net effect is that the voltage For example, if both sampled out-
source in order to understand what’s waveform does not transition instanta- puts are low, the current is large and
happening to the system during the neously when the current polarity flowing out of the inverter.
current zero crossings. changes. Instead, a softer transition Conversely, when both sampled out-
Up to now, we’ve assumed that the occurs that takes the edge off of the dis- puts are high, the current is large and
distortion waveform is a perfect rec- tortion waveform. Figure 7 illustrates flowing into the inverter. However,
tangular wave shape, and therefore has the voltage waveforms out of one half- under low-current conditions (regard-
“snappy” rising and falling edges. bridge of the inverter under
Related to this premise, we have also various current conditions. V+

implied that the inverter output volt- We now draw a distinction


Processor
ages are either high or low at any between the dead-time inter-
PWM1
DT1
given time, including the dead-time val before the assertion of the D Q
i+
Memory location $0024

intervals. These assumptions are true top PWM and the dead-time PWM1

when the current amplitude is high. interval before the assertion of i–


However, under low-current condi- the bottom PWM. If you com-
or
tions, which occur near the zero cross- pare the two dead time regions τ
ings, the inductor is less aggressive in in a given PWM period, you’ll Voltage D Q DT2
PWM2 sensor
snapping the voltage high or low. notice that when the current PWM2

Presumably, this is because of para- magnitude is large, the volt-


sitic capacitance in the motor and ages during the dead times are
drive, which can support the induc- the same regardless of polarity.
tor’s low current flow. Prior to the However, when the current DT1 DT2 Load current condition
0 0 High amplitude i+
dead-time interval, if the output volt- magnitude is small, the volt- 1 1 High amplitude i–
0 1 Low amplitude, either polarity
age was already driven in the direc- age waveforms are different
tion that the inductor would drive it in the dead-time intervals. Figure 8—Take a look at this sense scheme for optimized dead-
based on the current polarity, this This suggests a strategy for time distortion correction.

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 63


value can be toggled Edinburgh, Scotland in 1991, and has
Voltage with correction enabled
before the current attended the University of Texas at
0.5-hp 3-phase motor
PWM Frequency = 7.3 KHz begins to flatten out. Austin for an executive MBA pro-
gram. He is currently the Americas
Output: w = 1.7 Hz
RESULTS OF COR- distribution manager for the 8/16-bit
RECTION Division of Motorola SPS. You may
Figure 9 illustrates write to him at r11607@email.
the results of dead-time sps.mot.com.
12 V Peak-to-peak
Current with correction enabled distortion correction
using this technique David Wilson earned a B.S.E.E. from
and the hardware on John Brown University in 1979 and
the MC68HC908MR32. an M.S.E.E. from the University of
By using the voltage Wisconsin in 1986. From 1979 to
information obtained 1990, David held design engineering
during the dead time, positions with several companies and
the software can count- worked in fields ranging from motor
er-modulate the PWM control to nuclear pulse measure-
2 A Peak-to-peak waveforms to cancel ment. David currently performs vari-
the distortion. We ous field applications assignments for
Figure 9—By using the voltage information obtained during the dead
time, the software can counter-modulate the PWM waveforms to cancel
measured these results Motorola. You may reach him at
the distortion. The output waveforms were obtained with the voltage sen- from a 0.5-hp three- [email protected].
sor using hysteresis. phase motor with a
PWM frequency of
less of polarity), the sampled results 7.3 kHz with 3-µs dead time. I SOURCE
will be different, indicating to the MC68HC908MR32 Microcontroller
control algorithm that a current zero Ross Bannatyne graduated from the Motorola, Inc.
crossing is looming in the near future. Electrical and Electronic Engineering (847) 576-5000
Therefore, the distortion correction honors program at the University of www.motorola.com
Tools to Move Data

TCP/IP Solutions
NEW
Products

µFlashTCP-EP * LogicFlex * Dual-E * LogicFlex-EPX *


10Base-T Ethernet 10Base-T Ethernet 2 Ethernet Ports 10Base-T Ethernet
2 Serial Ports 2 Serial Ports 2 Serial Ports 2 Serial Ports
7-34 VDC 46 Digital I /O’s 3 Counter / Timers 16 Opto-Isolated inputs
Optional I/O Interface Programmable Xilinx CPLD 5 Digital I /O’s 16 Relay Outputs @ 500mA ea.
Rugged Enclosure w/ Hardware Clock/Calendar Onboard Connectors Quick-Disconnect Connectors
Industry Standard Expansion Bus for USNET TCP/IP Rack Mount Enclosure
Connectors Peripheral Boards Software in Kits LCD & 6 Pushbuttons
Starts at $229 Starts at $189 Starts at $199 Starts at $499

*All products based on the Intel 386Ex with DOS and NE2000 compliant, 10Base-T Ethernet. Standard
memory includes 512K RAM & 512K Flash plus DIP socket to accept an M-Systems DiskOnChip.
Development systems contain necessary hardware and software tools for fast development.

JK microsystems connects you with embedded control solutions. Our cost-effective DOS based
controllers are ideal for data acquisition, networking or industrial technology applications.

JK microsystems, Inc. 1403 Fifth St., Suite D


Davis, CA 95616 USA
Visit us on the web www.jkmicro.com
Call 530-297-6073 Fax 530-297-6074

64 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


short they are, they all work in

FEATURE essentially the same way. There’s no


magic length at which a pipeline

ARTICLE becomes an ultra-pipeline.


However, long pipelines can be
ultra-headaches for their designers. So,
as you learned in Part 1, long
Jim Turley pipelines are not always beneficial
even though they’re a necessary evil
needed to reach higher clock frequen-
cies. The more pipeline stages there

Starting Down the Pipeline are, the more chainsaws you have to
juggle and the bigger the mess if
something slips up.
Just for fun, we’ll look at Intel’s
Itanium pipeline and the Opteron
from AMD. Both of these are high-
Part 2: The Long and Short of It end, “super-pipelined” processors that
are about as complex as you can get
while still keeping your sanity.
As you can see in Figure 1,
Itanium’s pipeline is 10 stages long.
Even though the Itanium is an insane-
ly complex chip with 25 million tran-

t
sistors, it still has an in-order pipeline.
Athlon and other processors are out-
here’s no deny- of-order machines that rearrange
ing that micro- instructions on the fly.
processor pipelines Itanium is so fast (800 MHz at first,
are getting longer and with faster chips sure to follow) that
Long pipelines are chips are getting faster. But honestly, fetching instructions requires three
needed to reach high- what good is a long pipeline? Does it
necessarily mean better performance,
pipeline stages (the five-stage proces-
sor did it in one). Itanium’s Stage 1
er clock frequencies. cooler engineering, and bragging rights calculates the memory address of the
at the next nerd party? next instruction it needs to fetch.
However, longer The high-end chips from Intel and Stage 2 accesses Itanium’s on-chip
Advanced Micro Devices (not to instruction cache (one of three), and
pipelines aren’t nec- mention SPARC, PowerPC, and Stage 3 puts the new instruction into
Alpha (R.I.P.)) have pipelines that are a buffer. At this point, there’s a break
essarily better in the 10 stages or longer, and most are in the pipeline while Itanium gathers
complicated world of two-way superscalar and aggressive-
ly out of order. Some of these
instructions into its small 24-instruc-
tion buffer.
microprocessors. For aspects are actually purposeful fea- After a brief stop in the buffer,
tures (i.e., they’re beneficial in some instructions move on to Stage 4 where
insight into the issue, way), but others are hacks aimed at they are decoded and the chip decides
overcoming inherent limitations in what type of execution unit (e.g., inte-
read Jim’s explana- the chip’s design. ger, floating point) it will use. Stage 5
performs register renaming, an
tion of the pros and PUT THAT IN YOUR PIPE AND advanced technique that resolves the
cons of processors SMOKE IT
Somewhere along the line, a bright
difference between Itanium’s real reg-
isters and the registers the instruction
with long pipelines. spark in the marketing department thinks it’s using. Note that Itanium
decided to coin the phrase “super- has so many registers, 256 in all, that
pipelining.” Not to be outdone, one it takes two full pipe stages (6 and 7)
of his colleagues came up with just to find and transfer operands from
“hyper-pipelining.” But these terms them. Then, in Stage 8, Itanium actu-
don’t mean a thing. Pipelines are ally executes the instruction, which
pipelines, and no matter how long or takes only one cycle. Stage 9 warms

66 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


up the data cache for a pending store Instruction queue
or handles last-minute branches.
1 2 3 4 5 6 7 8 9 10
Finally, Stage 10 writes the results of

General

instruction

registers

registers

registers
Instruction

instruction

Execute
the instruction into a register or to

Write back
Data cache
Remap

Access

Access
PC

cache

Queue

Issue
memory (data cache, really). Whew!

ORDER OF EXECUTION
Itanium is pretty straightforward Figure 1—Intel’s Itanium pipeline is in order and 10 stages long.
compared to some of the more exotic
pipelines, but it still carries out some tion is about to change the register in instructions to get the best perform-
out-of-order execution. Out-of-order some way. Other instructions are not ance out of 20-year-old code.
execution is just what it sounds like: allowed to read from that register The Opteron’s 12-stage pipeline is
executing instructions in a different until its scoreboard bit is cleared. longer than Itanium’s because x86
order from the way they appear in the This simple expedient prevents instructions are more complicated and
program. Out-of-order execution dis- instructions from stepping on each harder to decode than Itanium’s com-
obeys the programmer’s (or the com- other’s results. paratively organized VLIW instruc-
piler’s) sequence of instructions and tions (see Figure 2). If you’re a pro-
reorganizes them to make better use CISC PIPE COMPLICATIONS grammer who has written x86 assem-
of the chip’s hardware resources. Itanium is conservative by modern bler code, you know it’s not too diffi-
Certain high-end processors will standards when it comes to out-of- cult. But if you’ve ever had to disas-
dispatch (begin processing) instruc- order execution. On the other hand, semble x86 code, you know how
tions out of order, while others will AMD’s upcoming Opteron is much hideously complex that instruction
only retire (finish processing) instruc- more aggressive about executing set can be. Imagine the Opteron doing
tions out of order. Some processors instructions out of order. The two that disassembly in 1 ns (1 GHz).
will do both. Itanium falls into the processors should have roughly equiv- The Opteron fetches three instruc-
middle category, launching instruc- alent performance, but they get there tions at the same time, and almost
tions exactly the way they appear in in different ways. immediately converts them into its
the code but not necessarily finishing The Opteron is an out-of-order own internal RISC notation. So, for
them that way. processor because it has to be. It exe- the first few pipeline stages, the
For example, if the program calls for cutes x86 instructions that are com- Opteron is a CISC processor; after
one long, complicated instruction fol- patible with Athlon, Pentium, and that, it’s purely a RISC machine. The
lowed by two short, easy instructions, more than two decades of older x86 Opteron’s internal RISC instruction
then Itanium can dispatch all three processors. Itanium, in contrast, exe- set is proprietary to AMD and isn’t
simultaneously, assuming that the cutes new IA-64 instructions that documented anywhere.
integer and floating point execution explicitly define program parallelism The Opteron, like the Itanium, has
units aren’t busy. But there’s no point in such a way that the processor does- nine internal execution units for float-
holding up the two simple operations n’t have to figure out anything. The ing-point instructions, integer instruc-
just because the FP instruction is tak- Opteron doesn’t have this advantage, tions, branch instructions, etc. It tries
ing forever. Itanium allows them to so it shuffles and reorganizes x86 to keep as many of these nine units as
complete even though the busy as possible by aggressive-
instruction before them isn’t ly reorganizing and rearrang-
finished. This is in-order dis- ing the instructions in its
patch combined with out-of- L2 L1 Fetch queue. This means that x86
Convert

Instruction Instruction
order retirement. cache cache Decode
instructions can, and often
The exception to this rule is are, launched before other
Decode
if the three instructions are instructions that appeared
Decode
somehow dependent on one earlier in the program.
another. If the shift instruc- Integer Integer Integer FP Oftentimes, just a few parts of
buffer
tion is supposed to shift the buffer buffer buffer an x86 instruction can be dis-
results of the floating point patched for execution because
square root, it cannot finish (or a single instruction might
AGU

AGU

AGU
ALU

ADD
ALU

ALU

Miscellaneous

even start) until the floating decompose into multiple


MUL

point square root is done. internal RISC operations, all


Itanium uses a register score- of which can be executed
board to detect this. Each of independently.
the 256 registers has an invisi- The Opteron takes an
ble scoreboard bit that is auto- Figure 2—Advanced Micro Devices’s Opteron pipeline includes stages to opportunistic approach to
matically set when an instruc- decode instructions and a different mix of execution units. reorganization. If one of its

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 67


nine execution units is free, processor has two execution
the Opteron will do its best Dispatch and register remapping units, it’s not a two-way
to find an instruction that superscalar processor.
can use it and move it to A more common exam-
Branch unit Integer unit FP unit
the head of the queue. ple is a dedicated address
There are several tricks generation unit (AGU). An
involved in this process. AGU is akin to a simpli-
First, the Opteron must fied general-purpose ALU
Predicate bits (64)
make it look as though all Integer registers FP registers
that’s tweaked for generat-
of the instructions ran in (128) (128) ing addresses. Usually, it is
order. It can’t arbitrarily able to add and subtract
rewrite programs for you! but not multiply and
To do this, the Opteron divide. An AGU often
waits to commit the results Figure 3—Intel’s Itanium includes twice as many integer units as the Opteron from treats carry and borrow dif-
AMD. But, it’s at the cost of floating point execution.
of most instructions. The ferently than a normal
chip keeps hidden backup ALU, depending on how
copies of most registers and flags, and have been superscalar for years. the processor likes to wrap addresses
it stores them permanently when the Today, superscalar execution is fairly around memory boundaries.
instructions that should have come common and only low-end or mid- A load/store unit is another exam-
before are finished. The more instruc- range embedded processors tend to be ple of a specialized execution unit,
tions the Opteron reorders, the more uniscalar (i.e., not superscalar). which in this case is a chunk of hard-
shadow registers it has to juggle, Ideally, a two-way superscalar proces- ware dedicated to memory transfers.
which adds a lot of hardware. sor would be as fast as two separate With a separate load/store unit, a
The Opteron also makes multiple processors running at the same speed. processor can load operands from
copies of the main x86 registers (for Realistically, however, this isn’t the memory while it also crunches num-
example, AL, AX and SP). Each inter- case. There are always drawbacks to bers. This vastly improves bandwidth.
nal RISC operation thinks it’s using processing multiple instructions at
the same registers, but in reality each the same time inside the same chip. BROADLY PARALLEL THEMES
one has its own. The Opteron then It doesn’t take long to reach the point Apart from these special cases, truly
has the task of synchronizing all the of diminishing returns, which is why superscalar processors have an assort-
updates to these registers and resolv- the Opteron, Itanium, Alpha, and ment of execution units, usually with
ing conflicts in the order they should other high-end processors all have some duplication. Itanium has nine
have occurred, not necessarily the about six to nine execution units execution units: four integer units,
way they actually happened. instead of 100. three branch units, and two floating-
Resolving two or more branches at point units. Coincidentally, AMD’s
once is even more exciting, but I’ll MASS EXECUTION Opteron processor has nine execution
save that for another day. The first requirement of a super- units, although AMD chose a different
scalar processor is multiple execution division of labor. In addition, the
SUPER-DUPER SCALAR units. Recall that the execute stage is Opteron has three integer units, three
In the midst of all this pipeline talk, one of the stages in a conventional address-generation units, and three
we breezed right over parallel, or processor pipeline, usually located floating-point units like the Athlon
superscalar, execution. In one sense, somewhere in the second half of the processor before it.
all microprocessors are parallel pipe. Unless you have two or more Do multiple execution units mean
because they perform multiple opera- execution units, there’s no point in multiple pipelines? Not really. Even
tions simultaneously. With a five- trying to execute more than one massively superscalar processors gen-
stage pipe, five different instructions instruction at a time. erally have only one pipeline in the
are in various stages of completion. Superscalar processors must have sense that all instructions pass
But what’s usually meant by parallel multiple execution units. But just through the same five, 10, or 12
execution is superscalar execution, because a processor has multiple exe- stages. The pipeline is wider because
which is the running of two or more cution units doesn’t mean it’s super- multiple instructions are traveling
instructions through the same scalar. Surprisingly, many uniscalar down the pipe at once.
pipeline stage at the same time. So, processors have multiple execution In the cases of the Itanium, Athlon,
superscalar execution is like a double- units. They might, for example, use and Opteron, the chips fetch three
barreled shotgun; it gives you twice separate hardware circuits for multi- instructions simultaneously. (This is
the bang for your buck. plication and calculating square coincidental, even though it’s affect-
Big superscalar computer systems roots. Any single instruction might ed by the nature of x86 code.) These
have been around for a long time, and use one or the other, but never both three instructions are cracked at the
there are even some microprocessors at the same time. Although the same time, rearranged to fit internal

68 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


buffers, and hopefully dispatched written today are inherently serial. In a sense, Intel’s VLIW is a big
simultaneously. This last stage, how- They’re designed in accordance with step backward. Early microprocessors
ever, is the real key to maximizing Turing and von Neumann’s principles, simply executed instructions one at
performance. where one instruction follows another a time in program order. But years
Itanium’s designers obviously in a straight line. Adding a million ago, processor designers started reor-
thought integer code was more impor- execution units in parallel won’t help ganizing instructions and executing
tant (or at least more plentiful) than when the program itself is sequential. them out of order to take advantage
floating-point code, so they put in What’s the solution? The obvious of little tweaks in the hardware that
twice as many integer units as FP answer is to rewrite all your code the programmer might not know.
units (see Figure 3). The designers of using parallel programming languages. Today’s processors have taken that
the Athlon and Opteron balanced But that’s a bigger pill than most peo- concept of looking for the advantage
these two fifty-fifty. Both camps dedi- ple are willing to swallow. In the to the extreme. Now, Itanium moves
cated three units to branch resolution meantime, companies like AMD and Intel’s processors back to the begin-
and address generation, which indi- IBM are extracting what little frag- ning, executing exactly what the pro-
cates the importance of branch han- ments of instruction-level parallelism grammer (or compiler) has written.
dling in a fast processor. (ILP) they can from existing software. Itanium retains the multiple execu-
Superscalar processors can dispatch It isn’t easy and it isn’t pretty, but it tion units and the wide and fast
an instruction only if an execution works and preserves existing software, pipelines of other RISCs, but elimi-
unit is free to handle it. In Athlon’s which is often the most important nates the on-the-fly reorganization
case, for example, only three integer consideration of all. that complicates those other chips.
instructions (e.g., add, subtract, shift, In contrast, Intel’s IA-64 family has The basic problem still remains,
rotate, etc.) can be used simultane- started down a different road. Itanium though. How do you squeeze paral-
ously. If a fourth integer instruction uses VLIW concepts borrowed from lelism out of a sequential program?
comes along, it has to wait in mainframes, minicomputers, and even Currently, Itanium relies on its com-
Athlon’s internal instruction queue other microprocessors. Rather than pilers to discover small bits of paral-
until one of the other three finishes making the processor work hard to lelism in normal C code (where there
and moves to the next pipeline stage. reorganize and reshuffle instructions, isn’t much). Intel’s long-term goal
Fortunately, that’s only a one-cycle VLIW spells it out in software. The may be to encourage programmers to
wait for Athlon (or most other RISC chip actually can be pretty stupid shift to other languages where VLIW
chips). A worse case would be a cou- about how it dispatches and executes (oops, EPIC) really pays off. Intel has
ple of long-latency floating-point instructions. Itanium makes no made a leap in hardware (forward or
instructions plodding their way attempt whatsoever to execute backward, depending on your view)
through Athlon’s two FPUs. If a third instructions out of order or to look for and is betting that software can make
floating point instruction comes along, opportunities to rearrange instruc- the big leap with it. I
it would probably wait several cycles tions. In VLIW-land, that’s the compil-
before one of the FPUs is free again. er’s job and Itanium trusts what the Jim Turley is an independent analyst,
Obviously, the more execution compiler tells it. VLIW is a lot like columnist, and speaker specializing in
units a chip contains, the better its RISC; it moves the problem out of the microprocessors and semiconductor
chances of keeping additional instruc- hardware and into the software. intellectual property. He is the former
tions in flight at once. The flip side, VLIW, which Intel calls EPIC, fires a editor of Microprocessor Report and
however, is complexity. The more barrage of instructions at the proces- Embedded Processor Watch and host
execution units a chip contains, the sor. The chip then does what it’s told of the annual Microprocessor Forum
more instructions it has to juggle and without second-guessing the arrange- and Embedded Processor Forum con-
the bigger the chip will grow. Also, ment of instructions or worrying ferences. You may write to him at
additional execution units don’t nec- about dependencies between them. As [email protected] or visit his web
essarily help to move more instruc- you can see, the software is smart, site at www.jimturley.com.
tions down the pipeline. You’re still and the hardware is dumb.
limited by what the programmer Theoretically, this allows Intel to
wrote, and most programming lan- eliminate the complex rat’s nest of SOURCES
guages (and most programmers) sim- dependency checking and out-of-order
Opteron processor
ply do not support parallelism. hardware from the processor, which
Advanced Micro Devices, Inc.
makes the whole process simpler and
(408) 732-2400
SEARCHING FOR PARALLELS faster (Doesn’t this sound like RISC
www.amd.com
You can’t squeeze blood from a all over again?). Thus, as Athlon,
turnip, and you can’t extract paral- Opteron, PowerPC G4, and others go Itanium processor
lelism from a sequential program out of their way to shuffle and Intel Corp.
(well, not much, anyway). Virtually rearrange instructions out of order, (408) 765-8080
all of the software and PC programs Itanium does just the opposite. www.intel.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 69


tables clarifying the information. Now
FROM THE you’ll learn about the SmartMedia
module, and we’ll explore how the

BENCH DOS FAT file format is applied. In


addition, this project consists of cir-
cuitry, which interfaces a SmartMedia
socket with a host’s serial port. A
Jeff Bachiochi PIC18F452 handles the SmartMedia,
serial port, I2C storage, and power
selection. The serial command struc-
ture is kept simple, and it will afford
any computer or embedded system

SmartMedia File Storage “smart” access to a SmartMedia


device via a few simple commands.

C:
Part 2: Directory Entries The DOS prompt is one of the most
recognizable messages known to com-
puter users. Although Windows has
almost succeeded with its plan to do
away with the DOS prompt, it still
can be found in many Start menus.
The letter in the DOS prompt is

h
usually an indication of the type of
physical apparatus connected as a
ave you ever storage device. Even though any
wondered if you’d device can have any drive letter, A
open the mythical and B have become synonymous with
Last Pandora’s box? Because
of my curious nature, I’m prone to
floppy drives, C and D with hard
drives, and E and F with CD drives.
month, act without full knowledge of what In DOS, when a carriage return
I’m getting myself into. Although I (<cr>) is entered, an active device will
Jeff feel like I can relate to some aspects respond with its drive letter. This
of Confucian thought, I try to supple- indicates that the device is installed
explained ment my curiosity with caution. I and ready for use. For this project,
start many projects without any the processor will respond to a <cr>
how to knowledge of what the outcome will with an S: designation after the
exchange embedded be. I’m not sure if I’m subconscious-
ly trying to set myself up for a fall,
application has recognized that a
SmartMedia device has been inserted
data with your PC or if I just need to constantly push into the SmartMedia socket and the
my own envelope. device has been identified. Prior to
applications. In Part 2, This project, however, has given me that time, the application responds
a new appreciation for the DOS FAT with a “No Media” message or some
he’ll cover the Smart- file format. The tiny scraps of infor- other error message.
mation available on how it works are One of the differences in the
Media module and a good indication of the black magic PIC18xxxx series microprocessors is
teach you how to nav- originally used to create it. However,
it’s worth your while to try to make
the multi-level (high/low-level) inter-
rupt structure. The high-level inter-
igate within its DOS sense out of this because it can be use- rupt has fast in and fast out capabili-
ful for other projects. Therefore, most ties, and can automatically save and
FAT file structure. of what I’ll describe here is applicable retrieve the most valuable registers.
to other devices that are based on the In addition, it can interrupt program
same general DOS FAT file system. flow (including a lower-level inter-
In my previous column, I described rupt) without requiring lengthy code,
the parts of the DOS FAT file system decreasing the interrupt latency. Two
and how they are applied to the interrupts are used for the serial
SmartMedia to obtain compatibility. interface. The command interpreter
You can refer to that overview for the routine and Character Received and

70 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


Figure 1—The SmartMedia interface can run on either 5 or 3.3 V. The voltage is selected via ICZ. The RS-232 converter is not necessary when connected directly to the
TTL I/O of the host processor.

Transmitter Empty interrupts handle is determined by the state of the One of the connections on the
all the serial communications with GFORMF (good format) flag bit. So, SmartMedia interface is an output,
an external host. determining the state of this flag is which reflects the device’s working
The PIC18F452 has 1536 bytes (six where I’ll begin this month’s column. voltage. As you can see in Figure 1,
256-byte blocks) of RAM for tempo- pin 17 (Vsense) of the SmartMedia is
rary storage. Two of these blocks are INSERT MEDIA HERE connected to an input pin on the
used as TX and RX ring buffers. One of the most confusing aspects processor via a pull-up. The
Commands from a host always of building or upgrading a PC is how SmartMedia will pull the input to a
require an ending carriage return. the working voltage of processors has logic low if the module requires 5 V.
Characters received by this applica- been reduced from a system’s 5-V To handle both 3.3 and 5-V mod-
tion are placed into the RX buffer, level down to 3.3-V (and lower) core ules, this project was designed to run
while characters placed in the TX voltages. Getting those motherboard entirely on either voltage. Doing so
buffer by this application are sent out jumpers correct for the processor you allows the processor to be connected
to a host. When the command inter- were installing was a pain. directly to the SmartMedia, without
preter recognizes a <cr> in the RX SmartMedia was developed at a time the need for voltage transition buffers.
buffer, the interpreter searches the when 5-V memory was the norm. The When running on 3.3 V, the serial
buffer for a legal command. If the <cr> first SmartMedia devices were 5-V interface will drop to a ±6-V swing but
is found by itself, the <cr> command modules, now SmartMedia is 3.3 V. will still function well with most seri-
routine is evoked. Here’s where the Fortunately (or unfortunately) this al interfaces. The application requires
command prompt S:, or “no media” means that in order to be completely a regulated 5 V. The 5 V along with an
message, is placed in the TX buffer for compatible, you need to handle both on-board 3.3-V regulator is applied to
transmission to the host. The message 5- and 3.3-V devices. a Linear Technology LTC1470. Logic

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 71


inputs to the ’1470 select one media and will let the applica-
Write Write Read
(and only one) of the two input command address data tion know how much data can
CE
voltages and apply it to power be stored, how much data is
the rest of the circuitry. CLE handled at a time, and how
A mechanical switch on the many pages are grouped into a
ALE
SmartMedia socket indicates to block. Note that the block is
the processor that a SmartMedia *WE also the minimum cluster size
module has been inserted into allocated for files.
*RE
the socket. Upon power-up, the
application must initialize its *BSY
MODULE CIS/IDI
I/O ports and peripherals, and Now that you know the
I/O Command
place the SmartMedia socket physical makeup of this partic-
Multiple Multiple
interface into a safe condition address Data ular module, you can access
before checking the SmartMedia bytes bytes the memory looking for the
socket for module insertion. I Figure 2—Look at the general format for reading data from the SmartMedia. Card Information Structure
chose to use input port C.2 on (CIS) and Identify Drive
the microprocessor as the insertion facturer’s code data byte and a device Information (IDI). This information
input because it can produce an inter- data code byte. The general format must be located on the first good sec-
rupt on an edge transition. Although it of communications with the tor of the media. Finding the CIS/IDI
isn’t of any particular importance that SmartMedia module can be found in indicates that the media has been
an insertion be detected and acted on Figures 2, 3, and 4. physically formatted and can be recog-
quickly, it would be prudent to disable SmartMedia communication is sim- nized as a PC-ATA card (when insert-
(and ensure the safety of) the ilar to I/O peripherals on a multi- ed into a PCMCIA ATA adapter). All
SmartMedia socket interface as soon plexed data bus. Commands, address- pages have been checked beforehand
as the module is removed from the ing, and data values are passed using and whole blocks marked as bad if all
socket. Therefore, the media is the write enable strobe (WE) for infor- the pages are not error free.
removed immediately and independ- mation going to the module, and the The CIS assures that you can expect
ently of the main execution loop. read enable strobe (RE) for information to find SmartMedia-specific informa-
When media insertion is detected, coming from the module. The module tion at the appropriate locations (i.e.,
the application checks for the proper recognizes commands when the com- the block good/bad indicator or page
working voltage and, if necessary, it mand latch enable (CLE) is held high checksum). Comparing data on the
instructs the LTC1470 to remove the by the application during communica- CIS page to that stored in the applica-
3.3 V and apply 5 V as the circuitry tions. The module recognizes an tion’s CIS table identifies a good CIS.
source. After the working voltage has address (LSB first) when the address At this point, what you have is simi-
been set, a little investigative work can latch enable (ALE) is held high during lar to a blank diskette. You know
be done to identify the inserted module. communications. Additional commu- what it is and how much it could
nication (without CLE or ALE) indi- hold, but not how it does it.
MODULE ID cates data being passed. Although the
The application’s first access to the SmartMedia module has a status regis- MODULE BOOT SECTOR
SmartMedia is to its ID register. A ter that can be read, a separate The operating system determines
device ID read will produce a manu- ready/*busy output from the module how data will be stored. Like other
can be used to determine when non-compatibility issues, the storage
the module is busy doing inter- format used by the OS is not necessar-
Write Write Write nal processing (i.e., updating ily compatible with other OSs and
command address data
address pointers or erasing/pro- may not be readable on machines
*CE
gramming a block of data). running other OSs. So, you must
CLE The data returned by the ID determine how and where the media
ALE read command is used as an is to be used in order to ensure com-
offset in the DEVICE_CODE patibility. This project assumes that
*WE
table of your application. This the SmartMedia will be used with the
*RE
table provides CAPACITY (in Windows/MSDOS-compatible OS, and
*BSY
megabits), UNITS_PAGE so the SmartMedia will have the DOS
I/O (unit = 256 bytes), SECTORS_ FAT file system format.
Command BLOCK (pages/block), and The physical organization of all
Multiple Multiple
address data
NUM_BLOCKS (total blocks = disks is in the form of cylinders,
bytes bytes NUM_BLOCKS × 0x100). heads, and sectors (CHS). The drive
Figure 3—Similar to the read format, the write format allows data These values are the physical contains multiple magnetic surfaces
to be written into the SmartMedia. parameters of the inserted of floppy/hard platter(s), which are

72 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


read by one magnetic head per sur- Page within the same PBA. This
Write
face. Each surface is divided into means that you can search for a spe- command
Programming
individual rings, or tracks, that pass cific LBA of interest and that the *CE
beneath the head as the surface PBA is independent of the LBA (i.e.,
CLE
rotates. Each head can be positioned an LBA can be moved to a different
ALE
over any track on its surface. Each PBA without affecting the rest of the
track is divided into a number of file structure). You’ll realize the *WE
*RE
segments, or sectors, which hold one importance of this when I discuss
*BSY
unit of data bytes. Hence, each sec- the saving of files.
I/O
tor on the drive can be identified by The boot sector can actually con-
Write
its CHS position. tain executable code; however, I
When you’re talking about the stor- won’t cover that topic here. Instead, Figure 4—After the data is written to the SmartMedia,
age area, it’s much easier to think of you need to verify that the boot sec- a programming command initiates self-programming
of a block of data.
this as one linear chunk rather than tor exists and retrieve some addi-
individual sectors of cylinders of heads. tional information from it. Each sec-
Therefore, Logical Block Addressing tor, or page, of data is separated into LBA-PBA TRANSLATION
(LBA) is used to translate the CH (of three areas: even, odd, and redun- So far, you haven’t run into any
CHS) into linear LBA. Remember the dant. Separate commands can be problems finding the CIS-IDI and
UNITS_PAGE and SECTORS_BLOCK used to retrieve area data from a boot sector (except for potential bad
identified earlier? The block size is page. Each command begins access sectors forcing a move to the next
important here because the physical to a page in a specific area of stor- physical block). The terminology can
format of SmartMedia also uses age. The application may read any or be confusing at times, so I’ll bring
Block Addressing, or Physical Block all of the data area. In fact, continu- you up to speed.
Addressing (PBA) to be more specific. ously reading data will retrieve data Sectors are grouped into physical
You should note that this is extreme- from the following areas and on into blocks of 16 512-byte pages (in the
ly important because the relationship the next page. case of an 8-MB module) and charac-
between PBA and LBA can be a cause Three RAM sections are set aside terize the physical makeup of the
of great confusion. for the even (256 bytes), odd SmartMedia. In this case, each physi-
The first thing found on any (256 bytes), and redundant (16 bytes) cal block is made up of 16 physical
disk/diskette formatted for DOS will areas so that a full page can be stored sectors. Physical block 0 consists of
be the boot sector. The boot sector at one time. With the boot sector read physical sectors with a PBA of 0x0-F.
is found in the first sector of the from the SmartMedia into RAM, the Physical block 1 consists of physical
disk, where PBA/LBA = 0. You application looks for the fixed data sectors with a PBA of 0x10-1F. You
already know that the CIS/ISI signature 0xAA55 in the last data can see how the pattern goes.
should be in the first good sector of bytes of the odd page at sector bytes The logical makeup of the DOS FAT
the first good PBA. However, if this 0x1FFE–0x1FFF. This identifies the file system is that of logical sectors
is a bad block, you may need to go boot sector and acknowledges the grouped into logical sectors, cylin-
the next PBA to find it. So, do we presence of some additional informa- ders, and heads (these were just
have a conflict with the location for tion. The boot sector indicates where defined by the boot sector). You’ll see
the boot selector? Well, yes and no. to look for the next part of the DOS shortly that the size of a sector is also
If we define a relationship between format, the partition sector. 512 bytes, which is the same as a
LBA and PBA as something other The boot sector has space allocated physical page not counting the redun-
than equal, we can make everyone for four partitions. Usually, only dant area. Each logical sector has an
happy (if not confused). hard disks use multiple partitions LBA. Because the logical sectors/track
By placing the boot sector in the and the SmartMedia will be interest- equals the physical sectors/block, a
SmartMedia at the next good sector ed in only the first partition sector logical block is identical to that of a
of the next good PBA, we have information. The boot sector carries physical block, 16 logical sectors.
established a relationship for this two pieces of information for each Logical block 0 holds logical sectors
module between PBA and LBA. On partition, the partition start and end with an LBA of 0–0xF, while logical
SmartMedia with no defective sectors address in CHS format and partition block 1 holds logical sectors with an
the LBA would have an offset of 1 sector and partition size in absolute LBA of 0x10–0x1F.
from the PBA. You would need to sectors. As I’ve indicated, the boot This all works to make the LBA
look at the PBA+1 to find the LBA = 1. sector has been arbitrarily named relate directly to the PBA because
For SmartMedia with some bad ini- LBA = 0. Use the partition sector they’re equal in size. The offset differ-
tial blocks, this offset would be entry in the boot sector to locate the ence between the boot sector LBA = 0
greater than 1. The LBA is written partition sector information. For an and PBA = 0 is the key to finding the
into the Block Address Field (BAF) in 8-MB module this is logical sector rest of the logical blocks and sectors.
the redundant area of each Sector or 0x19 (LB1-PAGE9). As I explained earlier, each logical

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 73


block’s number is written into the far) would require 16 KB of storage MODULE PARTITION SECTOR
physical block where it resides in (8192 blocks × 2 bytes per block). The partition sector is the second
the SmartMedia module, begin- That’s a job for external EEPROM. part of the DOS FAT file system and
ning with the boot sector’s logical I chose to use an I2C serial EEP- defines all of the remaining unknowns.
block 0. That’s important because ROM for this LB/PB conversion table To locate the partition sector, you
when the SmartMedia needs to because it’s available in large densi- must look to the LB/PB conversion
rewrite any sectors/blocks to new ties. The PIC has I2C support making table for the location of logical block
physical locations, these will the interface and software routines an (LB) 1 (LBA = 0x19, sector 9 of LB 1
retain the LBA but get a new PBA. easy addition to the circuit. according to the boot sector informa-
Only the physical location of the Initialization should clear the EEP- tion for an 8-MB SmartMedia module).
block changes; it retains its logi- ROM device each time a SmartMedia The addresses (1 × 2) and (1 × 2) + 1 of
cal relationship. module is inserted and recognized to the EEPROM device are read to deter-
So, if the application needs to ensure that the table is free from mine the physical block (PB) in which
find a particular LBA, it has two extraneous data. Then the redundant the partition sector (sector 9) will be
choices. It can either read physi- area of each physical block can be located, PBA = (PB × 16 sectors per
cal blocks until it finds the logical read from the SmartMedia and legal block) + sector offset 9.
block number it is interested in, (used) logical blocks can have their With the partition sector read from
or it can make a table of used log- physical block number stored in the the SmartMedia into RAM, the appli-
ical blocks in order to find where conversion table’s logical block cation looks for the fixed data signa-
a logical block is physically locat- address in the E2. The physical block ture 0xAA55 in the last data bytes of
ed. Clearly, if the table is kept up number (a 16-bit value) is stored in the odd page at sector bytes
to date, it’s the quickest way to consecutive addresses in EEPROM at 0x1FFE–1FFF. This identifies the parti-
locate a PBA. However, this addresses (logical block number × 2) tion sector and acknowledges the pres-
requires building a table and keep- and (logical block number × 2) + 1. To ence of some additional information.
ing it somewhere. Although the keep this table up to date, the physi- In the partition sector, the applica-
PIC18F452 has over 1500 bytes of cal block numbers must be updated tion can retrieve logical format infor-
RAM, a table of all LBAs for the whenever a write changes mation like the number of bytes per
largest SmartMedia available (so SmartMedia data. sector (equals the physical bytes per

74 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


will begin in LBA 0x1D (FAT1 + three
Listing 1—The DIR command reports to the host via the serial port. sectors). The directory begins in the
S: LBA following the last sector used by
DIR the last FAT table. This would put
the beginning of the directory in LBA
Volume in drive S is 0x20 (FAT2 + three sectors).
Volume Serial Number is 0000-0000
Directory of S:
MODULE DIRECTORY TABLE
IM01OLYM The directory is the third part of
the DOS FAT file system. From the
0000 files(s) 0000000000 bytes
0001 dir(s) 00008E0000 bytes free partition sector you learned that the
directory table could have up to
S: 256 entries. Each directory entry (file
or subdirectory) requires 32 bytes of
table space, and one sector will hold
sector of the SmartMedia) and the how much room they require. The 16 entries. Thus, a maximum of
number of sectors per cluster, which partition sector also indicates the 256 entries will require a directory
equals the physical sectors per block maximum number of entries the table of 16 sectors (256/16).
of the SmartMedia. Although these directory will contain. Initially, the directory table doesn’t
values are not required to match, hav- The FAT is located in the LBA sec- have an entry and will contain all
ing them correspond makes conver- tor following the partition sector. In zeros. If you’re searching the directo-
sion much more simple. The media’s the example of an 8-MB SmartMedia ry for an entry and the first value is
ID and label are found in the partition module, the FAT1 table will begin in zero, then you can rest assured that
sector. Information about the final LBA 0x1A because the LBA of the this is an empty entry. Directory
two parts of DOS FAT file system can partition sector is 0x19. According to table entries that are in use contain a
be found in the FAT and directory. the data in the partition sector, there printable ASCII character (actually a
The FAT type is identified, as well as are two FATs that are each three sec- slightly abbreviated set). When an
how many FAT tables are used and tors in length. This means that FAT2 entry is deleted, only the first charac-

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 75


ter is changed (to an 0xE5). Therefore, into trouble (huge cluster sizes) with mum possible cluster number is
some files can be undeleted because larger storage media. That’s why you’ll slightly less. A few values in the FAT
they’re still present if the clusters find FAT16 and FAT32 file systems. table are reserved. An entry of zero
holding the file haven’t been reused. It’s a pain working with a byte and a means the cluster isn’t used, one is
When a real entry is found, the half, especially when the 12-bit values illegal, and 0xFF7 indicates a bad clus-
application can determine whether are packed together. Originally, this ter. Any entry that’s higher means last
it’s a file or subdirectory entry by was done to save one sector per FAT. cluster (EOF). DOS uses the FAT to
looking at the file size (the last four Although it’s clever, it creates more determine where it can store new data
bytes in the entry). The attribute bit 4 work to pull apart the packed 12-bit in an unused cluster.
is set for subdirectory entries by look- values. Two 12-bit values are packed A cluster defined in the directory
ing at the entry’s attribute byte. You into three bytes using an unusual entry, pointing to the beginning clus-
can refer to last month’s tables to see arrangement, even byte b7-b0, odd ter for a directory entry, also refers to
what else is in the directory entry. byte b3-b0, even byte b11-b8, and odd a cluster entry in the FAT. Let’s say
The word value stored at offset byte b11-b4. Sixteen- and 32-bit FAT the directory entry for a file points to
0x1A–1B is a cluster number and indi- are nice whole bytes and don’t require cluster two. You can find the begin-
cates where you will find either the fancy packing and unpacking. ning of that file in cluster two and an
beginning of the file or the subdirecto- In terms of code, if you read a indicator in the FAT for cluster two of
ry. Remember that the partition sector word starting with the first byte of a the status of that cluster. If the 12-bit
told you the cluster size, which is 12-bit packed 3-byte entry in LSB-to- value stored in the cluster two entry
equivalent to the block size. This MSB format and OR it with 0x0FFF, of the FAT is 0xFF8 or higher, then the
means that any file or subdirectory you have the cluster number for the file ends within cluster two. However,
requires a minimum of one cluster of even-numbered FAT entry. And if if the FAT entry for cluster two has
storage space (even if it’s only 1 byte you read in a word starting with the another value (e.g., 2–0xFF6), then this
long). In addition, if a file is larger than second byte of a 12-bit packed 3-byte value is the next cluster number in
one cluster, it must allocate additional entry in LSB-to-MSB format and the file’s chain.
space, whole clusters at a time. rotate it right four times (with zeros Read this cluster for more file data
So, from the directory entry you coming into the most significant bit), and then refer to the FAT entry for
can tell where a file starts. But what you have the cluster number for the that cluster number to see whether
about large files that require more odd-numbered entry. the file continues in additional clus-
than one cluster, where are the addi- The first two clusters, zero and one, ters or ends there. You can, of course,
tional clusters? The FAT indicates are reserved. The FAT entry for these use the size value in the directory
how the clusters are chained together. clusters must be initialized to 0xFF8 table to determine how many clusters
As far as subdirectories go, a subdi- and 0xFFF (that’s 0xF8, 0xFF, and 0xFF there should be and how many bytes
rectory entry points out to the cluster as packed data). This is why the maxi- of the last cluster are actually used.
where a new set of directory entries
can be found. When a new subdirecto-
ry is created, two entries are placed Listing 2—The CD dirname command reports to the host via the serial port.
into it, the “.” and “..” entries. These
S:
are pointers to the sub- and parent CD IM01OLYM
directory and they help navigate the
directory structure. I’m going to skip
S:/IM01OLYM
over the topic of long file names
DIR
here, but be aware that long file
names bend the rules of the directory Volume in drive S is
entry in order to fit into the 32-byte Volume Serial Number is 0000-0000
Directory of S:/IM01OLYM
directory entry format.
.
MODULE FAT TABLE ..
Back in the partition sector you P1010001.JPG 0003034D bytes
P1010002.JPG 00030330 bytes
found an indication of the FAT type.
FAT12 is the most common for small 0002 files(s) 000007077D bytes
storage devices. The “12” indicates 0002 dir(s) 0000861A83 bytes free
the number of bits used to hold a
S:/IM01OLYM
cluster number. A maximum of 4096
CD ..
clusters (actually, this number is lim-
ited to the range of two and 4086) S:
would be possible. You can see from
this number that you quickly run

76 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


You know how a file or subdirecto- there are no additional entries. In this addition, the dirname is added to the
ry entry points to a cluster. But, how case, the partition table defined a drive designation and the new com-
is a cluster number related to the log- maximum of 256 entries (that’s a full mand prompt is reported. When a
ical blocks (LB) of the DOS FAT file block of 512-byte sectors). match is not found an error message
system? Clusters zero and one are If a legal entry is found, the appli- is reported. The directory pointer
reserved, and the first usable FAT cation extracts the FILE_NAME1-8, LSA_DIR remains unchanged.
entry is two, cluster two. Therefore, FILE_EXT1-3, cluster number, and If a dirname of “..” is used while in
cluster two will refer to the first stor- FILE_SIZE from the directory entry. a subdirectory, the search will find a
age cluster, which is the one that fol- Given that bit 4 of the attribute byte match. This can be seen in the direc-
lows the root directory. indicates whether the entry is a file tory list of a subdirectory. The “.”
You know the root directory begins or subdirectory, the application can subdirectory entry points to itself,
in LB = 2, specifically LBA = 0x20, perform separate tasks. If this is a while the “..” subdirectory entry
and has 256 16-byte entries for a table file, then the FILES counter is incre- points back to the parent directory.
length of 10 sectors. That puts the mented and the file size is added to To simplify this application, only one
first available storage at LBA = 0x30. a USEDBYTES accumulator. The subdirectory level is saved with the
LBA = 0x30 is the first sector of LB = application then reports the drive designation. Take a look at
3, whereas cluster two must refer to FILE_NAME, FILE_EXT, and Listing 2 for a display of the CD
LB = 3. In this case, + 1 is the cluster FILE_SIZE. If this is a subdirectory, dirname command report to the host
offset and one is added to the cluster then the DIR’s counter is increment- via the serial port.
number to get the LB = 3. This means ed and the application reports the
that the 16 sectors in that LB will be FILE_NAME (directory name). NAVIGATION COMPLETE
LBA = 0x30–0x3F. The final two routines are file_bytes Now that you can maneuver within
and free_bytes. File_bytes reports the the SmartMedia’s DOS FAT file struc-
ACCESSING THE DIRECTORY total number of files found (in this ture, you can begin working with
The DIR command is necessary to directory) and the total number of file files. Whew! No wonder you don’t see
make use of the DOS FAT file sys- bytes used. Free_bytes reports the much published on this. From now
tem. The DIR command will access total number of subdirectories found on when I think DOS FAT, I’ll think
the present (initially the root) directo- (in this directory) and the number of COW (can of worms). Next month
ry and produce information about the bytes free for use. This routine finish- bring your tackle box. I
storage media and files, or subdirec- es with a report of the command
tory entries, located within the prompt. Take a look at Listing 1 for a
directory table. When this applica- display of the DIR command report to Jeff Bachiochi (pronounced BAH-key-
tion’s command interpreter recog- the host via the serial port. AH-key) is an electrical engineer on
nizes the DIR command, it jumps Circuit Cellar’s engineering staff. His
into a routine that emulates the SUBDIRECTORY ENTRY background includes product design
standard DIR command. This is done Even though I’ve used this and manufacturing. He may be
through six routines that report its SmartMedia in my Olympus Digital reached at jeff.bachiochi@circuitcel-
findings, volume, serial, directory, Camera, there are no files shown on lar.com.
file_bytes, and free_bytes. this SmartMedia because the camera
The first two reports are the volume puts its picture files into a subdirec-
name and serial number. The 11-char- tory. Therefore, I’ve got to be able to SOURCES
acter volume name and double word change directories to see them. A LTC1470 Switch
serial number were originally read CD dirname command must be rec- Linear Technology Corp.
from the partition sector and stored in ognized. This differs slightly from a (408) 432-1900
RAM when the module was inserted. DIR command in that I don’t have www.linear.com
These items may or may not have been to report anything other than suc-
initialized with any useful information. cess or failure, and so the directory’s PIC18F452 Microcontroller
Many normally skip this option when entries must be searched again. But Microchip Technology Inc.
storage media is formatted. this time when an entry is found it’s (480) 792-7200
The third routine takes the present, compared to the dirname given in www.microchip.com
or working, directory LBA and con- the CD request.
Olympus digital camera
verts it into a PBA. This sector is read If a match is found, the cluster num-
Olympus America, Inc.
from the SmartMedia and the applica- ber in the entry is saved as the new
(800) 645-8160
tion scans directory entries looking LSA_DIR. This is the variable used as
www.olympusamerica.com
for legal ones. Only the first character the pointer to the present directory.
of each 32-byte entry needs to be The next time a DIR is requested, SmartMedia
checked. Erased entries are skipped, this LSA will be converted to a PBA SSFDC Forum
and an empty entry indicates that and read from the SmartMedia. In www.ssfdc.or.jp/english/index.htm

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 77


If there’s any surprise with the

SILICON results, it’s the significant showing


(42%) for 16-bit chips. The result is

UPDATE interesting, because 16-bit parts have


always been dark horses, seemingly
relegated to combine the worst of both
the 8- (limited performance and mem-
Tom Cantrell ory) and 32-bit (cost, power, size)
worlds. But, far be it from me to impose
my opinion over the collective wis-
dom of survey respondents. Designers
are saying 16-bit parts have a place in
their quiver of silicon solutions. And

Eight Isn’t Enough judging by the raft of releases crowd-


ing my in-basket, suppliers are saying,
“You want it, you got it.”

SWEET (AND SMALL) SIXTEEN


Much as when working with 8-bit,
where seminal architectures such as
the ’51, ’68, and PIC still prevail,
designers can go back in time to find

t
answers to their 16-bit questions. A
case in point is the Texas Instruments
he latest Circuit MSP430 family of 16-bit MCUs. In one
Cellar reader sur- of my earlier articles (“Sweet Sixteen,”
Noting the vey is complete and,
as usual, has some
Circuit Cellar 126), I traced the roots of
the MSP430 all the way back to chips
fact that interesting nuggets of information. that served as the basis for TI’s venture
Unlike supply-side driven market into personal computers in the ’70s.
67% of research (e.g., quarterly shipments), Again, as with 8-bit parts, the popu-
the Circuit Cellar survey provides larity of yesteryear’s parts is explained
respon- useful insight into what designers in by the realities of the embedded mar-
the trenches are thinking. ketplace. Designers want the lowest
dents in a In some cases the survey results price, lowest power, simplest chip that
Circuit Cellar reader’s reinforce conventional wisdom. For
instance, when was the last time you,
can meet their goals and hold all of
the newfangled trimmings. With it’s
poll had a proclivity or for that matter, anyone you know, multiple addressing modes and memo-
designed in a 4-bit chip? It’s lonely at ry-to-memory architecture, the
for 8-bit chips, Tom’s the bottom of the processor pecking MPP430 may not be a theologically
order with only 6% of survey respon- pure RISC. But, putting the emphasis
asking you to forget dents signing on the 4-bit dotted line on the “R,” it’s a fact that in the old
(see Figure 1). A likely explanation days, all chips were reduced as a mat-
about bits for a for the weak support for 4-bit chips ter of necessity.
moment and examine is found in the overwhelming popu-
larity for 8-bit parts. A full two-
alternatives from TI, thirds (67%) of respondents signed-
100
90
80
up. Why bother messing with some 70
Cyan, and Adelante. obscure mini-me 4-bit chip when
60
50
40
67

42 35
55 58

entry-level mainstream 8-bit parts 30 26 28


20
can do more for less? 10
6

The 32-bit chips needed to carry the 0


ry
RAM
MC it-plus

,
GA
PU

16 PU

PU

Flas ROM
emo

ever-bulkier software baggage fared


32-b MPU

DSP
MC -bit
MC bit

MC bit

/FP
U/M

U/M

U/M

M,D

hm
4-

8-

pretty well, too. One-quarter (26%) of


U/

EEP
PLD
SRA

survey respondents showed interest,


proving that the long-awaited (and
Figure 1—Interestingly, I was surprised to see that 16-
long-hyped) migration to 32-bit chips bit chips garnered a better than respectable showing in
is slowly but surely underway. the latest Circuit Cellar reader survey.

78 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


Two new members of the ’430 fami- just talking about pin count. Thanks Test 1 20 P1.7/TA2/TDO/TDI
ly, the ’11x2 and ’12x2, remind that to the low power and small die size, VCC 2 19 P1.6/TA1/TDI
P2.5/ROSC 3 18 P1.5/TA0/TMS
more bits do not necessarily make a these plastic small-outline packages VSS 4 17 P1.4/SMCLK/TCK
XOUT 5 16 P1.3/TA2
bloated chip. In fact, except for the get a chance to live up to their name XIN 6 15 P1.2/TA1
16-bit instruction set and ALU, a with the tiniest versions barely more *RST/NMI 7 14 P1.1/TA0
P2.0/ACLK/A0 8 13 P1.0/TACLK/ADC10CLK
close look reveals these parts are oth- than a 0.25″ (6.6 mm) on each side. P2.1/INCLK/A1 9 12 P2.4/TA2/A4/VREF+
P2.2/TA0/A2 10 11 P2.3/TA1/A3/VREF–
erwise similar to their lean and mean Regarding price, these 16-bit parts
MSP430x11x2
8-bit counterparts (see Figure 2). The may not match the loss-leader 8-bit
chips are certainly like 8-bit parts in chips, but at less than $3 in volume Test 1 28 P1.7/TA2/TDO/TDI
VCC 2 27 P1.6/TA1/TDI
their memory and I/O pretensions. (10K) they come mighty darn close. P2.5/ROSC 3 26 P1.5/TA0/TMS
Four to 8 KB of flash memory for Considering the extra performance V SS 4 25 P1.4/SMCLK/TCK
XOUT 5 24 P1.3/TA2
code, an extra 256 bytes for data, and and features, the 16-bit price differ- XIN 6 23 P1.2/TA1
*RST/NMI 7 22 P1.1/TA0
256 bytes of RAM is a more likely ence is arguably a NOP for many P2.0/ACLK/A0 8 21 P1.0/TACLK/ADC10CLK
home for ASM rather than C or Java. embedded applications. Even the tools P2.1/INCLK/A1 9 20 P2.4/TA2/A4/VREF+
P2.2/TA0/A2 10 19 P2.3/TA1/A3/VREF–
As an aside, I should note that the are a bargain more befitting an 8-bit P3.0/STE0/A5 11 18 P3.7/A7
P3.1/SIMO0 12 17 P3.6/A6
flash memory retention time guaran- chip. There’s certainly no 16-bit stick- P3.2/SOMI0 13 16 P3.5/URXD0
tee is 100 years. It’s clear that TI has a er shock for the MSP-FET430P120, P3.3/UCLK0 14 15 P3.4/UTXD0

handle on the concern over flash which costs just $99 (see Photo 1). MSP430x12x2

memory chip senility posed by other


Figure 2—The MSP430F11x2 and ’12x2 from TI may
vendors’ meager 10-year guarantees. NEW CHIP ON THE BLOCK be 16 bits under the hood, but their size, power con-
What could be more blue collar There’s further evidence that 16-bit sumption, and price are more like an 8-bit chip.
than the collection of I/O: a 16-bit devices are more than a fill-in-the-gap
timer, 10-bit A/D converter, USART, fad. The introduction of new architec- at the maximum 25-MHz clock rate,
and so on? The MSP430 does have tures from new suppliers is always a depending on the instruction mix and
some modern tweaks, for example, a sign of market interest. The eCOG1 more so the cache-hit ratio. That’s a
fast autoscan mode and data transfer from Cyan Technology is a good exam- lot faster than the 1- to 2-MIPs 8-bit
controller for the 200-ksps A/D con- ple (see Figure 3). Keeping in mind I chips of the good-old days, but the lat-
verter. Nevertheless, it’s pretty clear have only a few pages of preliminary est 8-bit chips are pushing double-
that when it comes to peripherals, data from Cyan, there’s little obvious digit MIPs ratings as well. Although I
having more bits in the CPU doesn’t difference between the eCOG1 and don’t have the spec sheet, the nominal
mean less mainstream I/O. other high-end 8-bit MCUs. A decent clock rate, watch crystal clock genera-
What about power consumption? I amount of memory (64 KB of flash tor, multiple clock domains, and
suppose it’s no surprise that, all else memory and 4 KB of RAM), a full hand-held (i.e., battery-powered) target
(except the ALU) being equal, the bank of I/O (including a 12-bit ADC), markets all imply the prospect of low-
MSP430 family would be competitive, copious timers and serial ports, and power consumption.
but in fact the TI parts even put many even a temperature sensor are neat, Despite the apparent (and welcome)
8-bit parts to shame. Operating across but nothing you won’t find on the lat- lack of press release pretension, even
a 1.8- to 3.6-V range, the 16-bit chips est high-integration 8-bit parts. the sparse eCOG1 data at hand piques
consume a mere 200 µA per mega- Meanwhile, the programmer’s model my interest. For instance, the chip
hertz. With a CPI approaching one, looks like a 6502 on steroids (see includes a 512-line instruction cache
we’re talking a fraction of a milliwatt Figure 4). It has an accumulator and a that works in conjunction with direct
per MIPS. Better yet, cut power con- couple of index registers, all stretched connect external SDRAM. Reflecting
sumption to nanoamps with Standby to get beyond 64 KB in a pinch. Of the real time requirements of embed-
mode, which is easy to use because course, there are popular 8-bit chips ded apps, the cache has what’s called
TI, paying attention to the details, like the Z180 and 68HC12 that have Deterministic mode (a fancy name for
designed the chip to wake-up and get taken a similar beyond 64-KB tack. turning it into RAM), and individual
going again in just 6 µs. The performance of the eCOG1 is cache lines can be locked. Both the
Historically, the mainstream good, but not outlandish. I’d say cache and SDRAM interface are some-
embedded prospects for 16-bit chips you’re looking at roughly 5 to 10 MIPs thing you’d more likely find on a 32-
like the 68K and ’186 were bit processor than on an 8- or
limited to applications with 16-bit controller.
relatively high pin counts. By There’s also an External
contrast, the MSP430 parts Host Interface (EHI), which
match their 8-bit I/O and provides a 16- or 32-bit DMA
power consumption aspira- interface to an external host.
tions with small 20- (’11x2) The DMA controller sup-
and 28- (’12x2) pin packages. Photo 1—Low-cost tools are a hallmark of 8-bit chips that Texas Instruments ports circular and linked-list
And when I say small, I’m not carries forward with the 16-bit MSP430 family. schemes to minimize the

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 79


software overhead typically associated
with buffer management.
Even more unique is what’s called
the IntAct communications interface,
licensed from an outfit called Amino
Communications. After visiting Cyan’s
and Amino’s web sites, I was able to
glean that IntAct is a kind of propri-
etary econo-version of high-perform-
ance serial I/O schemes like Rapid I/O Photo 2—The price of the eCOG1 eval hardware is
reasonable, especially considering that the device
or Infiniband. In essence, the IntAct includes a full-function (there are no time or code size
port is like a router with backbone limits) C compiler.
and local upstream and downstream
links. Nodes connected to local links nearly 10 years in a variety of applica-
can establish a virtual circuit connec- tions, such as pagers, gas meters, and
tion across the backbone similarly to automated toll collection systems.
the way TCP/IP allows computers to Notably, that means there’s no wait-
connect via the Internet. With a ing around for tools and such. The
clock and two data lines in each company offers a $249 eval board (see
(upstream and downstream) direction, Photo 2) that uses the chip’s built-in
the spec mentions a typical data rate eICE debug interface and includes
of 180 Mbps. It’s not the gigabit-plus such extras as 8 MB of SDRAM and
of the fancier standards, but signifi- 10/100 Ethernet. There’s also a C tool-
cantly faster than the typical SPI- or chain noteworthy for being fully vali-
UART-based make-do solution. dated against ANSI/ISO conformance
Pragmatic business factors also weigh tests, all the more impressive consid-
in U.K.-based Cyan’s favor. Cyan is a ering it’s free.
spin-off from well-respected Cambridge
Consultants, spawning ground for other THE LONG AND SHORT OF IT
credible players such as Bluetooth Another interesting import comes
powerhouse Cambridge Silicon Radio. from Belgium-based Adelante
Thus, the eCOG1 isn’t some hand- Technologies. As the result of a merg-
waving, back-of-the-napkin newbie er between the Philips DSP division
architecture. In fact, the core technol- and Frontier Design (the latter itself a
ogy of the eCOG1 has been in use for spin-off from the Mentor Graphics
Channel A

Channel B

Stream

Down
Up

USART/SPI/IR 4-KB Data


Dual EHI
/IrDA/I2C/SCI iRAM IntAct
UART Control

24-bit
PWM Switching multiplexer Addr/data
EMI
8-bit data

VDD
12-bit sensor 64-KB
ADC MMU Flash
EPROM 16/32-bit
PIF
Temperature Interface
sensor
MUX
29-bit I/O
GPIO
Register or control
4 Code System
VIN block
cache clock
External
Power Interrupt Timers
triggers
on request IRC
reset Clock inputs
eCOG1
Low-power eICE Host computer
Reset_In CPU core

Figure 3—An MMU, instruction cache, and the intriguing 180-Mbps IntAct interface are some of the unique fea-
tures that differentiate the eCOG1 from Cyan Technology.

80 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


16 bits 16 bits 8 bits

AH/AL or A AH AL Flags T B I U C S N Z
7 6 5 4 3 2 1 0
24 bits
Debug Interrupt Arithmetic/
Index x UXH UX flags flags logic flags
User
Index y UY mode
Index x IXH IX
Interrupt
Index y IY mode
Program
counter PC 16 bits
16 bits Program space
FFFFFF
Data space
Scratchpad FFFF Large address
RAM FFE0 range: 00FFFF: End of small
User mode: 16,320 x 16 address range
Indexed 64-K x 16
IY Small address 000004: Interrupt routine
0000 range: start address
64K x 16 000000: Reset address

Figure 4—More bits doesn’t mean more complexity, as the 16-bit eCOG1 retro programmer model demonstrates.

European operation) Adelante is also, Adelante’s chief claim to fame is


like Cyan, a startup that brings that the underlying VLIW is cleverly
impressive credentials to the table. fronted with a 16-bit ISA. Combining
This time we’re looking at a 16-bit the speed and circuit simplicity of a
foundry-independent core designed to VLIW with the code efficiency of a 16-
serve efficiency-minded DSP applica- bit chip sounds great, but it sounded
tions such as cell phones. Or is that a to good to be true initially. However,
96-bit core? after talking to one of the designers, I
As you can see in Figure 5, the Saturn have a better understanding and appre-
core is indeed a VLIW under the hood. ciation for the scheme. Conventional
It’s kind of a streamlined version of the 16-bit instructions, typically used for
TI ’C6x I suppose. With two 16-bit mul- housekeeping, indeed use only one or
tipliers, four 16-bit ALUs, two address a few of the functional units at a time.
calculation units, a barrel shifter, loop Yes, that seemingly goes against the
control, saturation, and bit manipula- goal of fully utilizing every transistor
tion, there’s plenty of raw horsepower all the time, but who says you need
on tap. Clock rates up to 210 MHz trans- 12-function units cranking away to
late to 420 million MACs per second. read a keypad or blink an LED?

Application-Specific
instructions
Program memory
16-bit instructions

16 bits 8 bits 4(16-bit)/2(40-bit) ALUs


Dual Standard ASI
VLIW
Havard instruction table

96 bits Application-Specific
Execution Units

MPY MPY ALU ALU ALU ALU SST ACU ACU


PCU LCU BMU AXU
0 1 0 1 2 3 BRS X Y

Input registers

Register files
Product registers Overflow registers
DCU
Address registers

Figure 5—VLIW for the masses might be an apt description for Adelante’s Saturn DSP core.

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 81


When it does come time to put the
Listing 1—Is it code or is it hardware? Adelante Technologies has its feet in both camps, so only the sili-
pedal to the metal, as in DSP inner
con knows for sure.
loops, the eCOG1 uses Application-
Specific Instructions (ASIs) to shift filter loop:
into full VLIW hyper-drive. One of the *px0 = ADCin;
x0 = *px0++, y0 = *py0++;
16-bit opcodes is detected as invoking
a0 = 0, p0 = x0 * y0, x0 = *px0++, y0 = *py0++;
an ASI, with the last eight bits index-
ing into a table of 256 96-bit VLIW repeat NTAPS-2
instructions. { a0 += p0, p0 = x0 * y0, x0 = *px0++, y0 = *py0++;}
As a core, the 256 × 96 table typi-
a0 += p0, p0 = x0 * y0, px0--;
cally would be implemented in ROM a0 += p0;
and filled with a predefined, fixed set r1 = round (a0);
of VLIW instructions deemed most ADCout = r1;
useful in a particular design. However,
there is the possibility of implement-
ing some or all of the table as RAM.
This implies an intriguing ability sim- So far, the Philips side of the with fancy OSs and performance-at-
ilar to reconfigurable computing to Adelante equation is plain to see. What any-price applications.
dynamically redefine and modify the does Frontier Design bring to the We’ve got 4- and 8-bit chips. We’ve
ASI instruction set at run time. party? Perhaps a look at the Saturn C- got 32- and 64-bit chips. The fact is,
Saturn offers three levels of upgrade like assembly language is a clue (see the 16-bit gap between them is just
flexibility not found on a fixed function Listing 1). Note that Frontier’s prior too big to ignore and it’s never going
chip. In addition to the aforementioned claim to fame was using C-like lan- away. Ultimately, nobody really cares
ASIs, for even more performance guages for hardware description. how many bits a chip has. What mat-
Application-Specific Execution Units Maybe we’re moving beyond the era ters is whether or not the chip can do
(AXU) can be added internally to the of mere programming and hardware the right job at the right price. Forget
core, piggybacking on the existing description languages toward some- the bits. Looking at the parts from TI,
data path and functional units. Beyond thing that might be described as a Cyan, and Adelante, I see chips that
AXUs, stand-alone Application- “system definition language.” make sense, and that’s what counts. I
Specific Coprocessors (ASCP) can The idea would be that an advanced
boost performance even further. SDL tool would look at the big picture, Tom Cantrell has been working on
Adelante uses a Viterbi butterfly and then automatically (optimally) chip, board, and systems design and
inner-loop example to illustrate the partition the work between pure soft- marketing for several years. You may
hierarchy of customization options. ware, pure hardware, and everything reach him by e-mail at tom.cantrell@
The algorithm calls for two adds, two in-between (including ASIs, AXUs, circuitcellar.com.
subtracts, two compares, two status and ASCPs). It seems like Adelante is
updates, and four memory accesses well equipped to lead the way in REFERENCE
(i.e., 12 instructions on a conventional breaking down some of the barriers
[1] T. Cantrell, “Sweet Sixteen,”
chip). This can be swept into just two between hardware and software. Circuit Cellar 126, January 2001.
ASIs at the cost of zero additional sili-
con. Adding an optimized AXU delivers POWER OF TWO SOURCES
a further 4× boost over the ASI option. There was a time when I might
Saturn DSP Core
That’s more than a 20× speed-up over have believed 16-bit chips were
Adelante Technologies
a non-accelerated design at the cost of doomed to be little more than a tran- 32 16 391 411
a mere 1000 or so additional gates. sition between their 8- and 32-bit www.adelantetech.com
Still not speedy enough? Drop in an counterparts. But for now, considering
IntAct
optimized ASCP and you can get up to the Circuit Cellar survey numbers
Amino Communications Ltd.
60 butterflies per clock cycle, if you’re and flurry of activity, I’d say it’s safe 44 0 1954 784500
willing to throw 15K gates at the prob- to take 16-bit chips off the endan- www.aminocom.com
lem. That’s a whopping 600× speed-up gered species list.
eCOG1
over the conventional baseline. Indeed, if anything, the 8- to 32-bit Cyan Technology Ltd.
Customizing things is all well and gap may be widening. Regarding vol- 44 0 1954 207070
good, but getting an ASIC to work is ume, the center of gravity in the 8-bit www.cyantechnology.com
never easy to begin with. To simplify market is moving ever lower, thanks
MSP430x11x2, MSP430x12x2
matters, Adelante offers the Lunar to the less-than-$1 MCUs that are Microcontrollers
subsystem that combines the raw sprinkled everywhere. Meanwhile, Texas Instruments
Saturn core with the glue logic to 32-bit chips can’t seem to escape the (800) 336-5236
make integration easier. tendency toward bloat that comes www.ti.com

82 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


IDEA BOX
THE DIRECTORY OF PRODUCTS AND SERVICES
AD FORMAT: Advertisers must furnish digital submission sheet and digital files that meet the specifications on the digital submission sheet.
ALL TEXT AND OTHER ELEMENTS MUST FIT WITHIN A 2″″ × 3″″ FORMAT. Call for current rate and deadline information. Send your disk and digital submis-
sion sheet to: IDEA BOX, Circuit Cellar, 4 Park Street, Vernon, CT 06066 or e-mail [email protected]. For more information call Sean Donnelly at (860) 872-3064.

Suppliers Directory now available online. Check out our web site
www.circuitcellar.com to see who has what and how to get it!

phyCORE Modules:
NEW GENERA TION
GENERATION
SINGLE BOARD COMPUTERS
■ Insert-ready sub-mini SBCs (small as 47x55 mm.) supporting the
Philips 8xC591
8xC591, 89C51Rx2
89C51Rx2, XACx
XACx, XAGx
XAGx, Infineon C167Cx
C167Cx,
Motorola MPC555 & ST Microelectronic ST10F168
■ Low EMI design achieved via GND circuitry, 6 to 8 layer PCB, by-
pass capacitor grid and short signal traces achieved via small
footprint and use of 0402 SMD passive components
■ 32 KB to 8 MB external SRAM & Flash (controller-dependent)
■ FlashTools enable on-board in-system (ISP) programming
■ RS-232, RS-485, I2C & CAN interfaces; ADC; Chip-Select signals
■ Controller signals extend to standard (2.54 mm.) or high-density
Molex (0.625 mm.) header pins on two sides of the board,
allowing the SBC to be plugged like a "big chip" into targets
■ Available in Rapid Development Kits including Development Board,
AC adapter, serial cable and SPECTRUM CD with eval software tools
(Keil, TASKING), FlashTools, electronic documentation and demos
PHYTEC America LLC ■ 255 Ericksen Avenue ■ Bainbridge Island, WA ■ USA 98110
www.phytec.com (800) 278-9913

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 83


PC KEYBOARD EMULATION
Interface Keypads, Switches, or RS-232 to your PC Keyboard Input
MODEL KE24 ONLY $
9995
• Up to 12 x 12 matrix • Programmable • RS-232 Port • Macro Capability

The KE24 is the ultimate in flexibility. Inputs or serial data can


emulate any of the 101 keys from a standard keyboard.

MODEL KE18 ONLY $


4495
• Up to 9 x 9 matrix • 2.5" x 3.0" Size • PC Keyboard Port • PCXT, AT Compatible

The KE18 combines a multitude of features with small size at an


economical price. Custom units available.

HAGSTROM Toll Free: 888-690-9080


Phone: 607-533-4441 Fax: 607-533-4443
ELECTRONICS www.hagstromelectronics.com
11 Fiddlers Green
Lansing, NY 14882

84 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 85
86 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com
www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 87
www.DreamTech.com

ting
Staart
Pentium 4
DESIGN YOUR DREAM P4!
WITH INTEL MAIN BOARD, $399
PROCESSOR & SOUND.
System includes:
• 1.8GHz Intel Pentium 4 Processor
• Intel 845WN Main Board
• 1 Parallel, 1 Serial, 4 USB & PS/2 Port
• Integrated Audio
• P4 Mid Tower Chassis & ATX PS

Dream P4 P4 with Intel 845GB MB


32MB VGA & sound.
845D OS ready!

1.6GHz $579
ITEM #3426
VISIT

POWERFUL PENTIUM 4 ~ WITH INTEL 845GB


MAIN BOARD & FAST PC/2100 MEMORY!
VALUE PRICED WITH 256MB RAM, 20GB HD,
MOUSE, SOUND & MODEM!

• 1.6GHz Intel Pentium 4 Processor


• 256MB PC/2100 DDR Memory
• 20GB 7200RPM Hard Drive
1•510•353•1800

• 3.5" 1.44MB Floppy Drive


• 56X CD-ROM
• 1 Parallel, 1 Serial, 4 USB & PS/2 Port
• ATI Xpert 2000 32MB AGP Video Card
• Sound Card & 120 WATT Speakers
• Logitech PS/2 Mouse
• 107 Enhanced Internet Keyboard
• 56K v.90 Lucent PCI Modem w/Fax
• P4 Mid Tower Chassis & ATX PS

with DVD &


Dream P4 WinXP Home
Entertainer
1.8GHz $799
ITEM #3403

BEST BUY! INTEL 845BG MAIN BOARD WITH


INTEGRATED SOUND, 60GB HD & 256MB RAM.
INTERNATIONAL

AVAILABLE UP TO 2.2GHz!
LOCAL &

• 1.8GHz Intel Pentium 4 Processor


• Intel 845BG Main Board
• 256MB PC2100 DDR Memory
• 60GB 7200RPM ATA 100 Hard Drive
• 3.5" 1.44MB Floppy Drive
• 16X DVD CD-ROM
• 1 Parallel, 1 Serial, 4 USB ports
• 64MB AGP GeForce Video Adapter
• P4 Mid Tower Chassis & ATX PS
• Integrated Sound & 120W Speakers
• 107 Enhanced Keyboard
1•800•A•Dreamer

• Lucent 56k v.90 PCI Modem


• Windows XP Home & Optical Mouse

Dream with 850MV &


WinXP Professional
XP-Pro
1.9GHz
ITEM #3408
$949
FAST & RELIABLE WITH RAMBUS MEMORY,
WINDOWS XP PROFESSIONAL & MORE!
• 1.9GHz Intel Pentium 4 Processor
• Intel 850MV Main Board
• 256MB PC/800 RAMBUS Memory
• 60GB 7200RPM ATA 100 Hard Drive
• 3.5" 1.44MB Floppy Drive
• 56X CD-ROM
• P4 Mid Tower Chassis & ATX PS
• 1 Parallel, 1 Serial, 4 USB ports
• 64MB AGP GeForce Video Adapter
• Integrated Sound & 107 Keyboard
CALL

• Netgear 10/100 PCI Ethernet Card


• Windows XP Pro & Microsoft Mouse

DreamTech
© July 2002

QUALITY COMPUTERS SINCE 1983


Email: [email protected]
Tel: 510.353.1800 Fax: 510.353.0990
40950 Encyclopedia Cr. ~ Fremont, CA 94538

88 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


EMBEDDED INTERNET
Prototyping Board with the CCS C compiler and libraries
PICmicro® MCU
C COMPILER
A high order language with extraordinary optimization
Complete hardware kit with 56K modem and specifically designed for the PICmicro® MCU.
examples using CCS C source code on a
PICmicro® MCU. Examples include an Access to all PICmicro hardware
embedded e-mail program and a web server. features form C

Internet Prototyping Board includes: Built-in libraries that work with all chips for RS232
PIC16F877 Flash Chip Schematics . Serial I/O, I2C, discrete I/O and precision delays
ICD Interface PC Cable
Full V.90 Modem Power Supply Source code drivers and ready to run programs
RS232 Port Phone Cable
Push Buttons Example Programs included for LCD modules, keypads, 24xx and
Analog Inputs 93xx serial E2 PROMS, X10, DS1302 & NJU6355
Real Time Clocks, Dallas Touch Memory Devices,
Our limited time offer also includes: DS2223 & PCF 8570 serial SRAM, LTC1298 &
Debugger Unit (ICD)
CCS PCW Windows IDE Compiler PCF8591 A/D converters and more
TCP/IP Lean book, by Jeremy Bentham Use
discount code Integrates with simulators/emulators, such as
IPB0702-CC
MPLAB®.
ALL FOR ONLY $ 499! to order...
ACT NOW! PRICES STARTING AT:
(OVER 20% IN SAVINGS) COMMAND-LINE COMPILERS FOR$125
WINDOWS IDE COMPILERS FOR $350

http://www.ccsinfo.com/picc
262.797.0455 x35

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 89


RAD
PROTO
Bring your dream to life
PSoC PIC AVR RABBIT MSP430
Rapid Prototyping Service
Prototyping Support Products
Embedded Engineering Services
Wireless Systems Specialists
Embedded Networking Specialists
Programming in C - ASM - FORTH
Data Collection Specialists
Data Logging Products
Quality.Timely.Affordable
Certified PSoC Consultant

WWW.RADProto.COM
Denver, Colorado, 720-940-5002
[email protected]

Send PC Video & Audio to


Remote Screens On Cat-5 Cable

Up to 500 feet
Cat-5 Cable

 Crisp Image at 1280 x 1024


 Sends Audio on Same Cable
 1 Local and up to 8 Remotes

Solutions for all Your Video Needs


 Video Matrix Switches
 High-Resolution VGA Cables
 KVM Switches and Extenders
 Scan Converters & Video Scalers
Hall
HallResearch
ResearchTechnologies,
Technologies,Inc.
Inc.
www.hallresearch.com

800-959-6439

90 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


Email: [email protected]

www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 91


RS232
to Windows
WinWedge inputs real-time
serial data from any device
direct into Excel, Access, VB
or any Windows program.

www.taltech.com

New CE
version!

92 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


www.circuitcellar.com CIRCUIT CELLAR® Issue 144 July 2002 93
ADVERTISER’S INDEX
The Advertiser’s Index with links to their web sites is located at www.circuitcellar.com under the current issue.
Page Page Page Page
85 Abacom Technologies 1 Earth Computer Technologies 23 Micromint Inc. 3 Scott Edwards Electronics Inc.
74 Accutech 48 ECD (Electronic Controls Design) 84 MicroSystems Development, Inc. 88 Sealevel Systems Inc.
85 ActiveWire, Inc. 86 EE Tools (Electronic Engineering Tools) 87 MJS Consulting 90 Senix Corp.
22 All Electronics Corp. 75 EMAC, Inc. 49 Mouser Electronics Inc. 83 Sensory, Inc.
88 Allied Components 48 ExpressPCB 26 MVS 83 Signum Systems
85 Amazon Electronics 84 FDI-Future Designs, Inc. 86 Mylydia Inc. 87 SmartHome.com
9 Amulet Technologies 84 Hagstrom Electronics 65 NetBurner 91 Softools
92 AP Circuits 90 Hall Research Technologies, Inc. 95 Netmedia, Inc. 39,57 Solutions Cubed
90 Appspec Computer Tech. Corp. 74 HI-TECH Software,LLC 33 New Micros, Inc. 92 Spectrum Engineering
84 Atlantic Quality Design, Inc. 91 HVW Technologies Inc. 87 OKW Electronics Inc. 83 Square 1 Electronics
86 Avocet Systems, Inc. 90 IDSmicronet.com 93 Ontrak Control Systems 50 SUMBOX Pty Ltd.
85 Bagotronix, inc. 87 IMAGEcraft C2 Parallax, Inc. 16 Systronix
17,84 Basic Micro 86,92 Intec Automation, Inc. 83 Phytec America LLC 92 TAL Technologies
55 CadSoft Computer, Inc. 86 Intronics, Inc. 83 Phyton, Inc. C3 Tech Tools
89 CCS-Custom Computer Services 28 Intuitive Circuits, LLC 91 Picofab Inc. 89 Techniprise Inc.
85 Cermetek Microelectronics Inc. 81 JED Microprocessors Pty Ltd. 91 Pioneer Hill Software 40,41 Technologic Systems
92 Conitec 64 JK microsystems 85 Prairie Digital Inc. 93 Technological Arts
37 Connecticut mircoComputer Inc. 29 JR Kerr Automation & Engineering 89 Pulsar Inc. 88 Tern Inc.
91 Copeland Electronics Inc. 28 LabJack Corp. 91 R2 Controls 90 Triangle Research Int’l Inc.
91 Cyberpak Co. 28 Lakeview Research 15 R4 Systems Inc. 37 Trilogy Design
10 Cypress MicroSystems 93 Lemos International 7 Rabbit Semiconductor 93 Weeder Technologies
C4 Dataman Programmers, Inc. 2 Link Instruments 90 Rad Proto 91 Xilor Inc.
86 DataRescue 93 Lynxmotion, Inc. 85 R.E. Smith 87 Z-World
83 Decade Engineering 58 MaxStream 58 Remote Processing 29 Zagros Robotics
90 Delcom Engineering 89 MCC (Micro Computer Control) 89 RLC Enterprises, Inc. 85 Zanthic Technologies Inc.
87 DesignTech Engineering 90 Microcross 88 RPA Electronics Design, LLC
90 Digital Products Co 89 Micro Digital Inc 86 Rutex
88 Dreamtech Computers 92 microEngineering Labs, Inc. 4 Saelig Company

Are You Grounded?


Attention Advertisers:
Driving the NKK Smartswitch—Part 2: Graphics and Text September Issue Deadlines
Embedded Smarts Fix Analog Flaws Space Close: July 11
Material Due Date: July 18
An Open-Source HCS Project
Theme: Internet & Connectivity
Digital Distributor-Less Ignition System
Robotics Corner: The CarolBot
RISCy Business: RISC Projects by Cornell Students
I Above The Ground Plane—PC Audio Bits
I From the Bench: SmartMedia—Part 3: Reading a File
I Silicon Update: FPGA News Flash W
I Applied PCs: Building a Modular Programming Platform—Part 2: Building the PCB IE
EV
Analog Techniques PR 145
94 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com
PRIORITY INTERRUPT
Like Avoiding a Bus

e ver hear the one about the mid-level manager who arrives at the office every morning, flips on his com-
puter, and scans everything with anti-virus software? He scans the hard drive, system files, RAM, even the
CD-ROM. He runs three different anti-virus programs just to make sure. He does this every morning. He does
this every day even though his computer has been turned off overnight. Who knows, perhaps something sneaked
in between the time he ran the anti-virus scans yesterday and turned on his computer again today. After all, you can’t be too careful
when it affects your job.
Besides, according to all of the daily news reports, it’s a cyber war out there. There are so many deadly computer viruses just
waiting for the opportunity to find an unprotected computer that your only defense is obsessive alertness. Constant media
reminders about the overwhelming cost and destruction from ILoveYou, Michelangelo, SirCam, and other Internet-born germs
make his palms sweat as he quickly yet conscientiously performs his daily search and destroy mission. Our mid-level manager is
determined that no two-bit cyber-thug or third-world terrorist is going to infiltrate his computer. After all, you can’t be too cautious
when it affects your job.
After the scanning is concluded, the leery manager downloads his e-mail from the company Intranet and proceeds to work. He
clicks on an e-mail that he sent to himself from his computer at home. Suddenly a strange and horrified look comes over his face.
He jumps up, rips the Ethernet connection out of the back of the computer and yanks the power cord out of the wall. Frantically, he
dials the network administrator and yells, “We’ve got a virus! My file is gone! It could only be a virus!”
Almost instantly, the network administrator appears at his desk, still panting from the long run down the hall. Viruses are no
minor event. Heading it off early might save hours of system rebuilds later. A quizzical look from the tech and our manager frantical-
ly exclaims, “It deleted my budget folder! I worked on it last night and I e-mailed it to myself this morning. I do this all the time. I work
on something at home and I e-mail it back to the office. This time, something ate it! It’s a deadly virus for sure!”
The network administrator reconnects the computer and sits down at the keyboard. After feverishly typing for 10 minutes, he
looks up and says, “You didn’t attach the file, sir. I looked at e-mail logs on the server. I can see your e-mail from home but there’s
no file. You forgot to attach it.” With that, he gathers up all the test disks he had expected to need, turns toward the office door, and
adds, “I’ll be down in the server room if you have any real problems.”
The manager frantically paces back and forth. “I never forget to send a file! It must be a virus. It must be a new one that’s really
insidious.” Quickly, he jumps in his chair and logs onto the Internet. “Now, if I can just find one of the anti-virus sites that details a
new one that deletes e-mail files. After all, you can’t be too careful when it affects your job,” he mutters.
As comical as this scenario sounds, I’m sure you’ve all met an individual like this or have heard of a similar situation. The con-
stant over-hyping about virus alerts and virus destruction in the media has created a paranoid culture within the ranks of some com-
puter users. Is it much ado about nothing? Certainly not.
Anti-virus software is an important application for all computer users. I’m not denying the gravity of the issue, but it shouldn’t
be cause for paranoia or fear at every newly announced bug in Outlook or Explorer. In the total population of computer users,
most have never seen or received a virus. In truth, the easiest virus path into a computer is a dumb user. Despite all of the warn-
ings about e-mail attachments as a source of viruses, a survey last year found that more than 40% of people would open an e-
mail appearing to be from someone they know if the following appeared in the subject line: “Great Joke,” “Look at this Message,”
or “Special Offer.”
Beware of the media propaganda and don’t suspect that every computer anomaly is generated by a virus. For intelligent users,
virus management is like avoiding being hit by a bus. Looking both ways before crossing the street is the same as deleting suspect
messages and filtering downloads. The best anti-virus technique is the expression of knowledge, not fortification.

[email protected]

96 Issue 144 July 2002 CIRCUIT CELLAR® www.circuitcellar.com


STILL THE WORLD’S MOST
POWERFUL PORTABLE
$795 PROGRAMMERS?
inc 4mb ram

NEW MODEL $1295

Surely not.
Surely someone somewhere
has developed a portable programmer that
has even more features, even greater
flexibility and is even better value for
money.
Actually, no. But don’t take our word for
DATAMAN-48LV it. Use the feature summary below to see
• Plugs straight into parallel port of PC or how other manufacturers’ products compare.
laptop
S4 GAL MODULE MONEY-BACK
• Programs and verifies at 2, 2.7, 3.3 & 5V
• True no-adaptor programming up to 48 • Programs wide range of 20 and 24 pin
30 DAY TRIAL
logic devices from the major GAL vendors If you do not agree that these truly are the
pin DIL devices
most powerful portable programmers you can
• Free universal 44 pin PLCC adaptor • Supports JEDEC files from all popular buy, simply return your Dataman product
• Built-in world standard PSU - for go- compilers within 30 days for a full refund
anywhere programming
• Package adaptors available for TSOP,
SUPPORT
PSOP, QFP, SOIC and PLCC • 3 year parts and labor warranty
• Optional EPROM emulator • Windows/DOS software included
• Free technical support for life
DATAMAN S4 • Next day delivery - always in stock
Orders received by 4pm will normally be despatched same day.
• Programs 8 and 16 bit EPROMs, Order today, get it tomorrow!
EEPROMs, PEROMs, 5 and 12V FLASH, Still as unbeatable as ever. Beware of
Boot-Block FLASH, PICs, 8751 cheap imitations. Beware of false
microcontrollers and more promises. Beware of hidden extras.
• EPROM emulation as standard If you want the best, there’s still only one
• Rechargeable battery power for total choice - Dataman.
Dataman Programmers Ltd
portability Order via credit card hotline - phone 215 East Michigan Avenue
• All-in-one price includes emulation today, use tomorrow. Orange City, FL 32763
leads, AC charger, PC software, spare Telephone (904) 774-7785
Alternatively, request more detailed Fax (904) 774-7796
library ROM, user-friendly manual information on these and other market- Home page: http://www.dataman.com
• Supplied fully charged and ready to use leading programming solutions. Email: [email protected]

You might also like