Prévia do material em texto
circuitcellar.com
EE: NBTI and FPGA Design
LOCATION: Singapore
PAGE: 30
TIPS: Testability Design
LOCATION: Canada
PAGE: 52
DIO: LED Curve Tracer
LOCATION: United States
PAGE: 56
CODING: Serial Displays
LOCATION: United States
PAGE: 70
PLUS
Engineer’s Grand Ideas
// Award-Winning Product Designer
// Former Host of Protoype This!
// And More
INTERNET & CONNECTIVITY
Design a DSP-SQL Interface
to Access Large Databases
Build a Single-Board
N8VEM Computer
Kinect-Based Prosthetics Control
Assistive Robotics
The world’s source for embedded elecTronics engineering informaTion
JULY 2013
ISSUE 276
http://www.netburner.com/kits
mailto:sales@netburner.com
http://www.netburner.com
The widest selection of the newest products.
Over 3 million products from over 500 manufacturers.
Authorized distributor of semiconductors
and electronic components for design engineers.
Mouser and Mouser Electronics are registered trademarks of Mouser Electronics, Inc. Other products, logos, and company names mentioned herein, may be trademarks of their respective owners.
The Newest Products for Your Newest Designs®
www.mouser.com
10:56 AM
http://www.mouser.com
http://mouser.com
The neTwork
The Team
Founder: Steve Ciarcia
edITor-In-CHIeF: C. J. Abate
mAnAgIng edITor: mary Wilson
ASSoCIATe edITor: nan Price
ConTrIBuTIng edITorS: Jeff Bachiochi, Bob Japenga,
robert Lacoste, ed nisley,
george novacek
ProJeCT edITorS: Ken davidson, david Tweed
PuBLISHer: Hugo Van haecke
ASSoCIATe PuBLISHer: Shannon Barraclough
ArT dIreCTor: KC Prescott
ConTroLLer: emily Struzik
CuSTomer SerVICe: debbie Lavoie
AdVerTISIng CoordInATor: Kim Hopkins
our inTernaTional Teams
United Kingdom
Wisse Hettinga
+31 (0)46 4389428
w.hettinga@elektor.com
USA
Hugo Van haecke
+1 860 289 0800
h.vanhaecke@elektor.com
Germany
Ferdinand te Walvaart
+49 (0)241 88 909-0
f.tewalvaart@elektor.de
France
Denis Meyer
+31 (0)46 4389435
d.meyer@elektor.fr
Netherlands
Harry Baggen
+31 (0)46 4389429
h.baggen@elektor.nl
Spain
Eduardo Corral
+34 91 101 93 85
e.corral@elektor.es
Italy
Maurizio del Corso
+39 2.66504755
m.delcorso@inware.it
Sweden
Wisse Hettinga
+31 (0)46 4389428
w.hettinga@elektor.com
Brazil
João Martins
+351214131600
joao.martins@editorialbolina.com
Portugal
João Martins
+351214131600
joao.martins@editorialbolina.com
India
Sunil D. Malekar
+91 9833168815
ts@elektor.in
Russia
Nataliya Melnikova
8 10 7 (965) 395 33 36
nataliya-m-larionova@yandex.ru
Turkey
Zeynep Köksal
+90 532 277 48 26
zkoksal@beti.com.tr
South Africa
Johan Dijk
+27 78 2330 694 / +31 6 109 31 926
J.Dijk@elektor.com
China
Cees Baay
+86 (0)21 6445 2811
CeesBaay@gmail.com
Issue 276 July 2013 ISSN 1528-0608
CIRCUIT CELLAR® (ISSN 1528-0608) is published monthly by Circuit Cellar
Incorporated, 111 Founders Plaza, Suite 300, East Hartford, CT 06108.
Periodical rates paid at East Hartford, CT and additional offices. One-year
(12 issues) subscription rate USA and possessions $50, Canada $65,
Foreign/ROW $75. All subscription orders payable in U.S. funds only via Visa,
MasterCard, international postal money order, or check drawn on U.S. bank.
Cover photography by Chris Rakoczy—www.rakoczyphoto.com
Subscriptions
Circuit Cellar, P.O. Box 462256, Escondido, CA 92046
E-mail: circuitcellar@pcspublink.com
Phone: 800.269.6301, Internet: circuitcellar.com
Address Changes/Problems: circuitcellar@pcspublink.com
Postmaster: Send address changes to Circuit Cellar, P.O. Box 462256,
Escondido, CA 92046.
US Advertising
Strategic Media Marketing, Inc.
2 Main Street, Gloucester, MA 01930 USA
Phone: 978.281.7708, Fax: 978.281.7706, E-mail: peter@smmarketing.us
Internet: circuitcellar.com
Advertising rates and terms available on request.
New Products: New Products, Circuit Cellar, 111 Founders Plaza, Suite 300,
East Hartford, CT 06108, E-mail: newproducts@circuitcellar.com
THE WORLD’S SOURCE FOR EMBEDDED ELECTRONICS ENGINEERING INFORMATION
Tech the Future explores the solutions for a
sustainable future provided by technology,
creativity and science.
mailto:w.hettinga@elektor.com
mailto:h.vanhaecke@elektor.com
mailto:f.tewalvaart@elektor.de
mailto:d.meyer@elektor.fr
mailto:h.baggen@elektor.nl
mailto:e.corral@elektor.es
mailto:m.delcorso@inware.it
mailto:w.hettinga@elektor.com
mailto:joao.martins@editorialbolina.com
mailto:joao.martins@editorialbolina.com
mailto:ts@elektor.in
mailto:nataliya-m-larionova@yandex.ru
mailto:zkoksal@beti.com.tr
mailto:J.Dijk@elektor.com
mailto:CeesBaay@gmail.com
http://www.rakoczyphoto.com
mailto:circuitcellar@pcspublink.com
mailto:circuitcellar@pcspublink.com
mailto:peter@smmarketing.us
mailto:newproducts@circuitcellar.com
MeMbership counter
supporting coMpanies
All Electronics Corp. . . . . . . . . . . . . . . . . . 78
AP Circuits . . . . . . . . . . . . . . . . . . . . . . . 32
ARM. . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Beta Layout. . . . . . . . . . . . . . . . . . . . . . . 53
BusBoard Prototype Systems. . . . . . . . . . . 79
CadSoft Computer . . . . . . . . . . . . . . . . . . . 7
CAN Technologies. . . . . . . . . . . . . . . . . . . 77
CC Gold Archive USB . . . . . . . . . . . . . . . . 65
Cleverscope. . . . . . . . . . . . . . . . . . . . . . . 15
Colorado Micro Devices, Inc. . . . . . . . . . . 51
Crystalfontz America, Inc. . . . . . . . . . . .53, 77
Custom Computer Services . . . . . . . . . . . . 79
Elektor . . . . . . . . . . . . . . . . . . . . . . . 38, 39
EMAC, Inc. . . . . . . . . . . . . . . . . . . . . . . . 51
ExpressPCB . . . . . . . . . . . . . . . . . . . . . . . 31
EzPCB. . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Fabstream. . . . . . . . . . . . . . . . . . . . . . . . 73
Flash Memory Summit 2013 . . . . . . . . . . . 55
Flexipanel, Ltd. . . . . . . . . . . . . . . . . . . . . 78
Front Panel Express, LLC. . . . . . . . . . . . . . 19
Grid Connect, Inc. . . . . . . . . . . . . . . . . . . 15
Holtek Semiconductor, Inc. . . . . . . . . . . . . 21
Hot Chips Symposium. . . . . . . . . . . . . . . . 33
Imagineering, Inc. . . . . . . . . . . . . . . . . . . C4
Ironwood Electronics . . . . . . . . . . . . . . . . 78
Jeffrey Kerr, LLC. . . . . . . . . . . . . . . . . . . . 77
JYE Tech, Ltd. . . . . . . . . . . . . . . . . . . . . . 77
Labcenter Electronics . . . . . . . . . . . . . . . . . 5
Linksprite . . . . . . . . . . . . . . . . . . . . . . . . 79
MaxBotix, Inc. . . . . . . . . . . . . . . . . . . . . . 79
Micro Digital, Inc.. . . . . . . . . . . . . . . . . . . 47
Microchip Technology, Inc.. . . . . . . . . . . . . C3
Microengineering Labs, Inc.. . . . . . . . . . . . 78
Mosaic Industries, Inc. . . . . . . . . . . . . . . . 79
Mouser Electronics, Inc. . . . . . . . . . . . . . . . 1
MyRO Electronic Control Devices, Inc. . . . . 79
NetBurner . . . . . . . . . . . . . . . . . . . . . . . . C2
Newark element14 . . . . . . . . . . . . . . . . . . 11
Pololu Corp.. . . . . . . . . . . . . . . . . . . . . . . 59
RS Components . . . . . . . . . . . . . . . . . . 26–29
Saelig Co., Inc. . . . . . . . . . . . . . . . . . . . . 45
Technologic Systems . . . . . . . . . . . . . . . 8, 9
Triangle Research International, Inc. . . . . . 78
285587 83
Not a supporting company yet?
Contact Peter Wostrel (peter@smmarketing.us, Phone 978.281.7708, Fax 978.281.7706)
to reserve your own space for the next issue of our member's magazine.
Not a member yet?
Sign up at circuitcellar.com
Head Office
Circuit Cellar, Inc. 111 Founders Plaza, Suite 300, East Hartford, CT 06108
Phone: 860.289.0800
Copyright Notice
Entire contents copyright © 2013 by Circuit Cellar, Inc. All rights reserved.
Circuit Cellar is a registered trademark of Circuit Cellar, Inc. Reproduction
of this publication in whole or in part without written consent from Circuit
Cellar, Inc. is prohibited.
Disclaimer
Circuit Cellar® makes no warranties and assumes no responsibility or
liability of any kind for errors in these programs or schematics orfor the
consequences of any such errors. Furthermore, because of possible
variation in the quality and condition of materials and workmanship of
reader-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.
© Circuit Cellar 2013 Printed in the United States
We
now have
members
in countries.
mailto:peter@smmarketing.us
http://circuitcellar.com
4 CIRCUIT CELLAR® • circuitcellar.com
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
06 EDITOR’S LETTER
Not a Hockey Fan?
By Mary Wilson
10 NEW PRODUCTS
13 MEMBER PROFILE
13 CLIENT PROFILE
15 TEST YOUR EQ
16 MCU-Based Prosthetic Arm
with a Kinect
By Jung Soo Kim, Nika Zolfaghari,
and James Andrew Smith
30 NBTI and FPGA Design
By Sharad Sinha
34 Systematic Digital
Processing (Part 1)
Combining Embedded DSP with SQL
By Emily Marasco, Mike Smith,
and Maddie Lowe
44 DIY Single-Board
Computers (Part 1)
Design and Expansion Options
By Oscar Vermeulen and Andrew Lynch
48 QUESTIONS & ANSWERS
Engineer to the Core
An Interview with Joe Grand
By Nan Price
CONTENTS
ISSUE 276Internet & Connectivity
July 2013
52 THE CONSUMMATE
ENGINEER
Testing and Testability (Part 3)
Testability Design Issues
By George Novacek
56 ABOVE THE GROUND PLANE
LED Characterization
Arduino-Based Curve Tracer
By Ed Nisley
62 FROM THE ARCHIVES
Wireless Data Exchange
Build a 2,700-lb Bluetooth Headset
By Tom Struzik (Circuit Cellar 240,
July 2010)
70 FROM THE BENCH
Serial Displays Save
Resources (Part 1)
Routines, Registers, and Commands
By Jeff Bachiochi
76 CROSSWORD
80 TECH THE FUTURE
Using Socially Assistive
Robots to Address
the Caregiver Gap
By David Feil-Seifer
PAGE 16
PAGE 56
PAGE 44
http://www.labcenter.com
mailto:info@labcenter-electronics.com
6
EDITORIAL CALENDAREDITORIAL CALENDAR
IISSUESSUE TTHEMEHEME
270 January Embedded Applications
271 February Wireless Communications
272 March Robotics
273 April Embedded Programming
274 May Measurement & Sensors
275 June Communications
276 July Internet & Connectivity
277 August Embedded Development
278 September Data Acquisition
279 October Signal Processing
280 November Analog Techniques
281 December Programmable Logic
Analog Techniques: Projects and components dealing with analog signal
acquisition and generation (e.g., EMI/RF reduction, high-speed signal integrity,
signal conditioning, A/D and D/A converters, and analog programmable logic)
Communications: Projects that deal with computer networking, human-to-
human interaction, human-to-computer interaction, and electronic information
sharing (e.g., speech recognition, data transmission, Ethernet, USB, I2C, and SPI)
Data Acquisition: Projects, technologies, and algorithms for real-world data
gathering and monitoring (e.g., peripheral interfaces, sensors, sensor net-
works, signal conditioning, ADCs/DACs, data analysis, and post-processing)
Embedded Applications: Projects that feature embedded controllers and
MCU-based system design (e.g., automotive applications, test equipment,
simulators, consumer electronics, real-time control, and low-power techniques)
Embedded Development: Tools and techniques used to develop new hard-
ware or software (e.g., prototyping and simulation, emulators, development
tools, programming languages, HDL, RTOSes, debugging tools, and useful tips)
Embedded Programming: The software used in embedded applications
(e.g., programming languages, RTOSes, file systems, protocols, embedded
Linux, and algorithms)
Internet & Connectivity: Applications that deal with connectivity and
Internet-enabled systems (e.g., networking chips, protocol stacks, device
servers, and physical layer interfaces)
Measurement & Sensors: Projects and technologies that deal with sensors,
interfaces, and actuators (e.g., one-wire sensors, MEMS sensors, and sensor
interface techniques)
Programmable Logic: Projects that utilize FPGAs, PLDs, and other program-
mable logic chips (e.g., dynamic reconfiguration, memory, and HDLs)
Robotics: Projects about robot systems, devices capable of repeating motion
sequences, and MCU-based motor control designs (e.g., mobile robots, motor
drives, proximity sensing, power control, navigation, and accelerometers)
Signal Processing: Projects and technology related to the real-time processing
of signals (e.g., DSP chips, signal conditioning, ADCs/DACs, filters, and compar-
isons of RISC, DSP, VLIW, etc.)
Wireless Communications: Technology and methods for going wireless (e.g.,
radio modems, Wi-Fi/IEEE 802.11x, Bluetooth, ZigBee/IEEE 802.15.4, cellular,
infrared/IrDA, and MCU-based wireless security applications)
Mary Wilson
editor@circuitcellar.comJu
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
THE WORLD’S SOURCE FOR EMBEDDED ELECTRONICS ENGINEERING INFORMATION
UPCOMING IN CIRCUIT CELLARUPCOMING IN CIRCUIT CELLAR
FEATURESFEATURES
Raspberry Pi I/O Board (Part 1): Introduction to the Raspberry Pi,
by Brian Millier
Systematic Digital Processing (Part 2): DSP-SQL Analysis
Functions, by Emily Marasco, Mike Smith, and Maddie Lowe
DIY Single-Board Computers (Part 2): Logic Design, by Oscar
Vermeulen and Andrew Lynch
COLUMNSCOLUMNS
Serial Displays Save Resources (Part 2): Button Commands,
by Jeff Bachiochi
Introduction to Switched-Capacitor Filters, by Robert Lacoste
Testing and Testability (Part 4): Self Diagnostics, by George Novacek
Concurrency in Embedded Systems (Part 8): Using Files in
Concurrent Linux Designs, by Bob Japenga
Hockey can be fun, unless you’re building a surface-mount
device (SMD) prototype and the “puck” is one of the tiny com-
ponents getting away from your soldering iron.
In an article appearing last month in Circuit Cellar, “DIY
Surface-Mount Circuit Boards: Tips and Tricks for Building SMD
Prototypes,” engineer James Lyman inadvertently sparked a bit
of debate on the magazine’s website. Readers posted various
alternatives to Lyman’s approach to the “SMD hockey” chal-
lenge. Here’s how Lyman’s article describes the problem and his
solution:
“When I built my first few surface-mount boards, I did what
so many amateurs and technicians do. I carefully placed each
minute component on the circuit board in its correct position,
and then spent several minutes playing ‘SMD hockey.’ With
nothing holding the component in place, I’d take my soldering
iron and heat the pad component while touching the solder to
the junction. Just as the solder was about to melt, that little
component would turn into a ‘puck’ and scoot away. Using the
soldering iron’s tip as a ‘hockey stick,’ I’d chase the little puck
back to its pads and try again, which was maddening...
“It slowly occurred to me that I needed something to hold
each part in place while soldering—something that would glue
them in place. Commercial houses glue the components down
on the boards and then use a wave soldering machine, which
does all the soldering at once. That’s exactly what I started
doing. I use J-B Weld, a common off-the-shelf epoxy.”
Here is a sampling of alternative solutions readers posted to
circuitcellar.com.
• From Bill: “If you must use epoxy, then the cheapest fast-
setting epoxy from Poundland will do the trick.
“Personally, I’ve always used a tiny spot of cheapo CA
superglue, which gives you 20−60 s to position the component.
If there are a lot of SMDs on the board, you might want to use
anaccelerant spray to reduce the CA cure to 5 or 10 s. If you
can’t afford proper CA accelerant, then isoprop or a gentle waft
above the board with a cloth soaked in a little household
ammonia will do the trick.”
• From Trevor: ”I did a lot of hand soldering of SM parts
years ago and agree that it is best to fix the parts before
soldering.
“I used an adhesive made for SM parts from RS
Components, which comes in a syringe and is really easy to
use. ” (Trevor’s post provides a link to his preferred Electrolube
brand.)
• From Kevin: ”Crikey, epoxying all the components first is a
bit brutal. What if you want to change one? Melt the solder and
twist, all at the same time?
“Much easier to tin one pad, then place the part on it with
tweezers and touch it with the iron, one end soldered fine, now
solder the other end.”
Feel free to visit circuitcellar.com to weigh in or take some of
the advice offered there.
Not a Hockey Fan?
CIRCUIT CELLAR® • circuitcellar.com
EDITOR’S LETTER
mailto:editor@circuitcellar.com
www.cadsoftusa.com
GET THE LATEST
VERSION!
New features of version 6.4:
http://www.cadsoftusa.com
http://www.embeddedarm.com/ad.php?ad=43
10
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
NEW PRODUCTS
HIGH-PERFORMANCE VECTOR SIGNAL GENERATOR
The R&S SMW200A high-performance vector signal generator combines flexibility, performance, and intuitive operation
to quickly and easily generate complex, high-quality signals for Rohde & Schwarz’s LTE-Advanced and next-generation
mobile standards. The generator is designed to simplify complex 4G device testing.
With its versatile configuration options, the R&S SMW200A’s range of applications extends from single-path vector signal
generation to multichannel multiple-input
and multiple-output (MIMO) receiver test-
ing. The R&S SMW200A provides a base-
band generator, an RF generator, and a
real-time MIMO fading simulator in a single
instrument.
The R&S SMW200A covers the 100 kHz-
to-3-GHz, or 6 GHz, frequency range, and
features a 160-MHz I/Q modulation band-
width with internal baseband. The generator
is well suited for verification of 3G and 4G
base stations and aerospace and defense
applications.
The R&S SMW200A can be equipped with
an optional second RF path for frequencies
up to 6 GHz. It can have a maximum of two
basebands and four fading simulator mod-
ules, providing users with two full-featured
vector signal generators in a single unit.
Fading scenarios (e.g., 2 × 2 MIMO, 8 × 2 MIMO for TD-LTE, and 2 × 2 MIMO for LTE-Advanced carrier aggregation) can be
easily simulated. Higher-order MIMO applications (e.g., 3 × 3 MIMO for WLAN or 4 × 4 MIMO for LTE-FDD) are easily sup-
ported by connecting a third and fourth source to the R&S SMW200A.
The R&S SMW200A ensures high accuracy in spectral and modulation measurements. The SSB phase noise is –139 dBc
(typical) at 1 GHz (20-kHz offset). Help functions are provided for additional ease-of-use, and presets are provided for all
important digital standards and fading scenarios. LTE and UMTS test case wizards simplify complex base station conformance
testing in line with the 3GPP specification.
Contact Rohde & Schwarz for pricing.
Rohde & Schwarz
www.corporate.rohde-schwarz.com
MIXED-SIGNAL OSCILLOSCOPE WITH PROTOCOL ANALYZER
The USBee QX is a PC-based mixed-signal oscilloscope (MSO) integrated with a protocol analyzer utilizing USB 3.0 and
Wi-Fi technology. The highly integrated, 600-MHz MSO features 24 digital channels and four analog channels.
With its large 896-Msample buffer memory and data compression capability,
the USBeeQX can capture up to 32 days of traces. It displays serial or parallel
protocols in a human-readable format, enabling developers to find and resolve
obscure and difficult defects.
The MOS includes popular serial protocols (e.g., RS-232/UARTs, SPI, I2C, CAN,
SDIO, Async, 1-Wire, and I2S), which are typically costly add-ons for benchtop
oscilloscopes. The MOS utilizes APIs and tool builders that are integrated into the
USBee QX software to support any custom protocol.
The USBee QX’s Wi-Fi capability enables you to set up testing in the lab from
your desk. The Wi-Fi capability also creates electrical isolation of the device
under test to the host computer.
The USBee QX costs $2,495.
CWAV, Inc.
www.usbee.com
1 5
http://www.corporate.rohde-schwarz.com
http://www.usbee.com
Sense-ability.
Newark element14 makes it easy to fi nd all of your sensors and transducers – fast. newark.com
3:10 PM
http://newark.com
12
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
NEW PRODUCTS
FREE PCB DESIGN SOFTWARE SUITE
FabStream is an integrated PCB design and manufacturing solution
designed for the DIY electronics market, including small businesses,
start-ups, engineers, inventors, hobbyists, and other electronics enthu-
siasts. FabStream consists of free SoloPCB design software customized
to each manufacturing partner in the FabStream network.
The FabStream service works in three easy steps. First, you log onto
FabStream’s website (www.fabstream.com), select a FabStream manu-
facturing partner, and download the free design software. Next, you can
create PCB libraries, schematics, and board layouts. Finally, the soft-
ware leads you through the process of ordering PCBs online with the
manufacturer.
You only pay for the PCBs you purchase. Because the service is mostly
Internet-based, FabStream can be accessed globally and is available
24 hours a day, seven days a week, 365 days a year.
FabStream’s free SoloPCB Design software includes a commercial-quality schematic capture, PCB layout, and autorout-
ing in one easy-to-use environment. The software is customized to each manufacturing partner. All of the manufacturer’s
production capabilities are built into SoloPCB, enabling you to work within the manufacturers’ constraints. Design changes
can be made and then verified through an integrated analyzer that uses a quick pass/fail check to compare the modifica-
tion to the manufacturer’s rules.
SoloPCB does not contain any CAM outputs. Instead, a secure, industry-standard IPC-2581 manufacturing file is automat-
ically extracted, encrypted, and electronically routed to the manufacturer during the ordering process. The IPC-2581 file con-
tains all the design information needed for manufacturing, which eliminates the need to create Gerber and NC drill files.
FabStream is available as a free download. More information can be found at www.fabstream.com
DownStream Technologies, LLC
www.downstreamtech.com
ZigBee SINGLE-CHIP SOLUTION WITH AN ARM Cortex-M3 MCU
The CC2538 system-on-chip (SoC) is designed to simplify the development of ZigBee wireless connectivity-enabled smart
energy infrastructure, home and building automation, and intelligent lighting gateways. The cost-efficient SoC features an
ARM Cortex-M3 microcontroller, memory, and hardware accelerators on one piece of silicon. The CC2538 supports ZigBee PRO,
ZigBee Smart Energy, and ZigBee Home Automation to deliver interoperability with existing and future ZigBee products. The
SoC also uses IEEE 802.15.4 and IVv6 over low-power wireless personal area networks (6LoWPAN) to support IP standards-
based development.
The CC2538 is capable of supporting fast digital management and features
scalable memory options from 128-to-512-KB flash to support smart energy
infrastructure applications. The SoC sustains a mesh network with hundreds of end
nodes using integrated 8-to-32-KB RAM options that are pin-for-pin compatible for
maximum flexibility.
The CC2538’s additional benefits include temperature operation up to 125°C and
optimization for battery-powered applications using only 1.3 µA in Sleep mode.
The CC2538DK development kit provides a complete development platform for
the CC2538, enabling users to see all functionality without an additional layout. It
comes with high-performance CC2538EMK evaluation modules and motherboards
withan integrated ARM Cortex-M3 debug probe for software development and
peripherals including an LCD, buttons, LEDs, and a light sensor and accelerometer
for creating demo software. The boards are also compatible with the Texas Instru-
ments (TI) SmartRF Studio to run RF performance tests. The CC2538 supports current and future Z-Stack releases from TI
and over-the-air software downloads for easier upgrades in the field.
The CC2538 is available in an 8-mm × 8-mm QFN56 package and costs $3 in high volumes. The CC2538 is also available
through TI’s free sample program. The CC2538DK costs $299.
Texas Instruments, Inc.
www.ti.com
http://www.fabstream.com
http://www.fabstream.com
http://www.downstreamtech.com
http://www.ti.com
M
EM
B
ER
P
R
O
FI
LE
13
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
Member Name and Location: Joe Pfeiffer,
Las Cruces, NM
Education: BS with a double major in
Computer Science and Physics, 1979, and a
PhD in Computer Science, 1986, both from
the University of Washington in Seattle
Occupation: Joe was a professor in the
Department of Computer Science at New
Mexico State University in Las Cruces until
he retired in 2010. Joe’s research interests
focused on visual programming languages
and geometric reasoning for mobile robots.
Most of his teaching involved computer architecture, Assembly language
programming, and OSes.
Member Status: Joe says he’s been a Circuit Cellar subscriber for at
least 10 years.
Technical Interests: He enjoys programming Microchip Technology
PIC processors. More recently, he has become interested in Android pro-
gramming and development under Linux.
Most Recent Embedded Tech-Related Acquisition: Joe bought a
model rocket altimeter (and a bunch of
related connectors and things) for a
rocket he’s building for his National Asso-
ciation of Rocketry Level 2 high-power
certification.
Current Projects: Joe is currently
developing a shop oven. “I want it to be
useful for solder reflow work—so I’ll want
it to be able to follow the reflow temper-
ature profile—and also accurately main-
tain a temperature for applications like
powder coating. I’m planning a USB
interface so I can log its activity for later
analysis,” he explained.
Thoughts on the Future of Embedded Technology: Joe
feels that computing is becoming more pervasive and connect-
ed. “From a digital caliper that cost me under $10, to a Blue-
tooth-connected OBD-II scanner for a car—it’s just amazing,” he
said. “One thing I worry about is that, along with so much in
computing and technology, the bar is getting too high for entry.
As through-hole, hand-solderable components slowly disappear,
it seems like it’ll be harder and harder for someone to create a
first simple project and get started,” he added.
Joe Pfeiffer
CL
IE
N
T
PR
O
FI
LE
Client: Custom Computer Services (CCS), Inc.
Location: 1020 Spring City Drive, Waukesha, WI
53186
Contact: Sales, sales@ccsinfo.com
Embedded Products/Services: CCS specializes
in embedded software and hardware development
tools. Available to the development community is
a range of solutions for Microchip Technology
microcontrollers, and digital signal controllers
(DSCs), that include: C compilers, prototyping
boards, development kits, and programmers/debuggers. CCS also offers
custom engineering services and a line of embedded Ethernet devices (e.g.,
EZ Web Lynx). For more information visit www.ccsinfo.com.
Product Information: The CCSC Version 5 compiler with all of its new fea-
tures and enhancements has just been released! Version 5 is the first release
to include an aggressive code optimizer, plus a dynamic C Profiler tool. Other
enhancements include:
• New libraries—generate relevant and tight code for a specific application.
Included are: RS-232, RS-485, PWM, timers, a capacitive touchpad, and
more.
• C++ stream operator support—C++
streams provide a unified interface for I/O and
data formatting.
• Serial port monitor—a graphing capability
enables real-time graphing at a PC from a Microchip
Technology PIC microcontroller program. For more
information on Version 5, visit www.ccsinfo.com
/version5.
Exclusive Offer: For Circuit Cellar readers, CCS
is offering $60 off the purchase price of any
development kit. Development kits include: the
IDE C Compiler, prototyping board, an ICD-U64
debugger/programmer, a breadboard with auxiliary parts, a power
supply, and cables. Call the sales department at 262-522-6500 ext.
35 and mention the promo code CC60, or visit ccsinfo.com/cc60
and use the promo code CC60 in your cart. This offer is valid until
August 31, 2013.
CCS, Inc.
Circuit Cellar prides itself on presenting readers with information
about innovative companies, organizations, products, and services
relating to embedded technologies. This space is where Circuit Cellar
enables clients to present readers useful information, special deals,
and more.
mailto:sales@ccsinfo.com
http://www.ccsinfo.com
http://www.ccsinfo.com/version5
mailt:sales@ccsinfo.com
http://ccsinfo.com/cc60
No problem!
Use coupon code CCPDF713
PLUS!
www.cc-webshop.com
MISSED an issue?
LOST an issue?
www
.cc-wewww
http://www.cc-webshop.com
http://www.cc-webshop.com
What’s your EQ? The answers are posted at
www.circuitcellar.com/eq/. You can contact
the quizmasters at eq@circuitcellar.com.
Problem 1
Suppose you have an ordinary switch mode
buck regulator. The input voltage is 100 V, the
switch’s duty cycle is exactly 50%, and you
measure the output voltage as 70 V. Is this
converter operating in continuous conduction
mode or discontinuous conduction mode? How
can you tell?
Problem 2
Since a diode can be placed in a High-Impedance
state (reverse-biased) or a Low-Impedance
state (forward-biased), they are sometimes
used to switch AC signals, including audio and
RF. What determines the magnitude of a signal
that a diode can switch?
15
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
Problem 3
What common function does the following truth
table represent?
A B C X Y Z
0 0 0 → 0 0 0
0 0 1 → 0 0 1
0 1 0 → 0 1 0
0 1 1 → 0 0 1
1 0 0 → 1 0 0
1 0 1 → 0 0 1
1 1 0 → 0 1 0
1 1 1 → 0 0 1
Problem 4
Write the equations for the logic that would
implement the table.
800.975.4743 USA • 1 630.245.1445
gridconnect.com/gridarm.html
TH E N ETWO RK I NG E XPE RTS
Leaders in the
embedded and
networking
marketplace
providing network
hardware, high
quality software
and services
The gridARM™ System on a Chip (SOC) is a high performance, low cost,
low power, highly integrated single chip with 10 / 100 / 1000 Mbps Ethernet,
USB, CAN, Serial, SRAM Memory, SPI, I2C, RTC and internal peripherals
designed to provide a complete solution for embedded applications.
$10.00
(Qty 100)
each
EN
G
IN
EE
R
IN
G
Q
U
O
TI
EN
TTEST YOUR EQ
CONTRIBUTED BY
DAVID TWEED
July 2013
�
�
�
�
�
�
�
�
�
�
�
�
�
�
�
�
�
�
������������
��� �������������
��� �������������
��� �������������
��� ���������
�������������������������������
����
����
����
�
���
�������������� ���
�������������� ���
�������������� ���
�������������� ����
���������
����
����������
����
����������
����
����������
����
���������
�������������
�����
������������������������
����� ����� ����� ����� !!!!"�"�"�"���������
���������
����
�������� ���
�����������
��
�
��
���� �������
�������
�����������������
����������
����
������������� �
�����
����
������
������������ �
��
��� ������ �������� �
��!""� #$�������
��
��%����!&�����'%��
����������� �(���%�������)
�����
��!*+� ��,� ��#%���� ���
�����
�#� �$
�#� �$
�#� �$
�#� �$��������
http://www.circuitcellar.com/eq/
mailto:eq@circuitcellar.com
http://www.cleverscope.comhttp://gridconnect.com/gridarm.html
16
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
e designed an inexpensive, adaptable platform for
prototype prosthetics and their testing systems.
These systems use Microsoft’s Kinect for Xbox, a motion-sensing
device, to track a healthy human arm’s instantaneous movement,
replicate the exact movement, and test a prosthetic prototype’s
response. The complete design is shown in Photo 1.
Kelvin James was one of the first inventors to embed a micro-
processor in a prosthetic limb in the mid-1980s. His Motorola
HC11-based design was licensed to Ottobock HealthCare to
form the basis of the C-Leg lower limb prosthetic.[1] With the
maker movement and advances in embedded electronics,
mechanical T-slot systems, and consumer-grade sensor sys-
tems, these applications now have more intuitive designs. Inte-
grating Xbox provides a platform to test prosthetic devices’ con-
trol algorithms. Xbox technology also enables prosthetic arm
end users to naturally train their arms.
PARTS SELECTION
There are four main hardware component categories in our
design: actuators, electronics, sen-
sors, and mechanical support.
Robotis Dynamixel motors combine
power-dense neodymium motors
from Maxon Motors with local angle
sensing and a high gear ratio trans-
mission in a compact case. Atmel’s
on-board 8-bit ATmega8 microcon-
troller, which is similar to the stan-
dard Arduino microcontroller, has
high (17-to-50-ms) latency.
Instead, we used a 16-bit Freescale
Semiconductor MC9S12C32 micro-
controller on an Arduino form-fac-
tor board. It was bulkier, but it was
ideal for prototyping. The Xbox sys-
tem provided high-level sensing.
Finally, we used Twintec’s MicroRAX 10-mm profile T-slot alu-
minum to accelerate the mechanical prototyping (see Figure 1).
PHYSICAL ARM SPECIFICATIONS
While prosthetics help improve many disabled individuals’
quality of life, they are not without their setbacks. Our goal was
to design a prosthetic arm that was different from those cur-
rently available. We combined a prosthetic structure with the
popular Kinect technology. To start, we built a working proto-
type of a smooth-moving prosthetic arm.
We developed four quadrant-capable H-bridge-driven motors
and proportional-derivative (PD) controllers at the prosthetic’s
joints to run on a MC9S12C32. Monitoring the prosthetic’s
angular position provided us with an analytic comparison of the
programmed and outputted results.
For the hardware, we designed a two-joint prosthetic arm
(shoulder and elbow joints with one degree of freedom each, ver-
tical movement) similar to an actual human arm regarding
motion and length. We used an off-the-shelf motor driver during
initial prototyping. In later develop-
ment stages, we replaced the driver
with a customized motor driver for
greater flexibility and customization.
Once we built a working prosthet-
ic prototype, the PC-based Kinect
was integrated into the system. We
sent the data collected from the
Kinect to the prosthetic arm so it
replicated the user’s motion, which
was also captured by the Kinect.
Because prosthetics need to be
individually adjusted, we used
MicroRAX T-slot aluminum parts.
As with MakerBeam, MicroRAX
parts have a 1-cm × 1-cm cross
section. They are lighter and less
The technology behind Microsoft’s Kinect for Xbox motion-sensing device
can extend beyond gaming and into engineering applications. This project
integrates a Kinect and a prototype prosthetic arm and demonstrates a
platform to test control algorithms for prosthetics.
MCU-Based Prosthetic Arm
with a Kinect
by Jung Soo Kim, Nika Zolfaghari, and
James Andrew Smith (Canada)
W
FEATURE ARTICLE
Photo 1—A Microsoft Kinect motion-sensing device is at the
heart of the prosthetic arm design.
17
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
making it relatively unresponsive. Therefore, we decided to
implement a separate controller enabling more flexible and pre-
cise motor movement control. This controller is composed of an
H-bridge (Arduino “motor shield” board) and a more powerful
MC9S12C32 microcontroller board.
JOINT POSITION CONTROL
The RX-28 is an off-the-shelf servomotor that combines a
Maxon Motors brushed DC motor with an 8-bit microcontroller,
an angle sensor, a metal gearbox, and a pair of ports for RS-485
serial communication and power. One of these was located at the
shoulder joint and one was located at the elbow joint. After mod-
ifications were made, we continued to use the DC motor, posi-
tion sensor, and gearbox.
We used a 300° potentiometer coupled to the gear’s output
shaft for angle feedback. We had to disconnect the poten-
tiometer from the on-board control circuitry and connect it to
an external MC9S12C32. To obtain readings from the poten-
tiometer, we connected it to three different lines: ground, 5-V
power, and output. We took the potentiometer 5-V input direct-
ly from the microcontroller to make the potentiometer refer-
ence consistent with the controller and to reduce the possible
signal fluctuation. The ground was common grounded with the
circuitry and the controller to reduce possible noise and other
interferences.
We also wanted the potentiometer to have consistent data with
the controller. As the motor shaft spun, the gears spun along with
the shaft, which provided the potentiometer with the motor’s cor-
responding output speed. Moreover, the 5 V corresponded to the
motor’s 300º rotation. Therefore, every 1 V was equal to a 60º
arm motion. This enabled the information to be collected from the
microcontroller with any voltage variation. It also enabled the
microcontroller to analyze the data collected and determine the
exact position at which the motor had rotated.
MICROCONTROLLER
The processing unit was based on Technological Arts’s 16-bit
Esduino microcontroller board with a two-axis Arduino Motor
Shield, which enabled control of two RX-28s (see Photo 2). The
PWM and direction signals from the microcontroller were passed
to the motor shield to output the bidirectional voltage supplied
to the motor.
To use the microcontroller, we set up a timer, a real-time
interrupt (RTI), a serial communication interface (SCI), PWM,
and analog/digital conversion (ADC). Toward the final stages of
the microcontroller setup, we intro-
duced a phase-locked loop (PLL) to
match the microcontroller’s Run
Mode clock to the fastest clock rate
supported at 24 MHz. We set the RTI
to trigger every 1,024 µs, which
yielded a 976-Hz control frequency.
This was fast enough to provide
responsive motor control. Also, we
added a global counter within the
RTI, which was used as a global clock
with 1,000 counts equivalent to
1.024 s (i.e., 1,024 µs × 1,000). Our
expensive than industrial equivalents from 80/20 or Bosch, but
are just as versatile and adaptable. To approximate human
anatomy, we used MicroRAX parts to represent the upper and
lower arms. We used one Dynamixel motor at each of the two
joints: one at the shoulder and one at the elbow. The upper
arm’s humerus, which was made of MicroRAX, was 24.1-cm
long and weighed 39 g (without the motor). The lower arm’s
radius and ulna were 27.8-cm long and weighed 32 g each. The
entire arm’s mass, including actuators but without amplifiers
and the microcontroller, was approximately 194 g.
We equipped the end of the prosthetic arm with a standard
robot gripper hand. While we used a Cybot cyberhand
model, several low-end (e.g., Lynxmotion) and high-end
(e.g., Robotiq) off-the-shelf robot gripper and prosthetic
solutions (e.g., Ottobock’s Michelangelo Hand) are available.
MOTOR SPECIFICATIONS
While many servomotors are available on the market, only a
few combine a high power-to-weight ratio motor with gearing and
a convenient chassis at a relatively low cost. The Dynamixel
range is exceptional in this regard. Among Robotis’s range of
actuators,the RX-28 robot actuator offers midrange affordable
performance. Its torque profile indicated that it would be capable
of holding the arm in place and lifting light loads. More powerful
motors are also available. The RX-28 has an 12-to-16-V operat-
ing voltage range. Since the motor would carry a low load, we
used 12 V to supply the motor. The RX-28 is equipped with a DC
motor, a potentiometer, a gear box with a 192:1 gear ratio, and
a RS-485-serial-capable 8-bit microcontroller that provides
feedback and control to the motor. We
found the ATmega8 chip had high
(17-to-50-ms) latency.
The recently released Robotis
Dynamixel MX-28 actuator contains an
ARM Cortex-M3 72-MHz, 32-bit
processor with full PID control. Howev-
er, the electronics are not available
across Robotis’s product line. Our
modifications can be applied across the
board or to non-Robotis actuators.
Furthermore, control is only propor-
tional, not proportional-derivative,
Photo 2—A Technological Arts Esduino microcontroller
board is at the heart of the prosthetic arm design.
Figure 1—The prosthetic arm’s mechanical components include a Microsoft
Kinect sensor, a Technological Arts Esduino microcontroller, a Robotis
Dynamixel RX-28 robot actuator, and Twintec’s MicroRAX aluminum framing.
Kinect sensor
Prosthetic
arm
Patient-adaptable
extruded
aluminum
Dynamixel
actuators
Esduino
microcontroller
Off-the-shelf
mechanical
parts
Power-dense
packaged
motors and
transmissions
Off-the-shelf
electronics
Intuitive and
robust
sensor
18
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
MC9S12C32 code is based, in large part, on sample code pro-
vided by Jonathan Valvano at the University of Texas.
The global clock based on this convenient conversion was
essential in many aspects of the project (e.g., setting the mod-
ule’s user-requested running time). We set the PWM to use an
8-bit channel, which provided a 255 period. This enabled us to
modulate the 12-V motor’s power duty cycle to output from
0/255 to 255/255. Along with the direction bit, this was fed to
the motor shield’s H-bridge to control the motor’s speed and
direction. We set up six of the microcontroller’s analog ports in
10-bit ADC mode to convert a 0-to-5-V input as a 0-to-3 form
feed (i.e., 0 to 1,023) digital output. We established an SCI,
which enabled communication to the computer via an on-board
USB interface. A USB-to-microcontroller retrofit module and its
drivers for a Future Technology Devices International (FTDI)
FT232R USB UART IC were provided with the microcontroller.
Our pin setup layout was based on the reference manual
for Freescale’s MC9S12C32 family of 16-bit microcontrollers,
the Esduino pin map datasheet, and a Freescale block dia-
gram (see the Resources section of this article for more
information). Figure 2 shows the connections between the
microcontroller and the Kinect. We used Freescale’s free
CodeWarrior integrated development environment (IDE) for
all the C programming.
ADC MEASUREMENT CONVERSION
The potentiometer on the actuator’s output shaft yielded a
voltage proportional to its angle. We measured this voltage with
Included files
Microcontroller start
Initialization
PWM Init
RTI Init
Kinect start
COM Port setup
Send start token
Capture skeleton/rendering
Calculate angles
(shoulder, elbow)
Send angles
(shoulder, elbow)
SCI Init
Variable Init
StartBit = 0
If start token
acquired
Serial
communication
If end token
received
Compare
measured vs. desired
PWM Duty cycle
direction bit
Input acquire
(desired angle,
ADC measurements)
StartBit = 3
No
Yes
No
RTI Service
Angle (potentiometer)Motor
Motor unit
ADC
PD ControllerMotor shield
Voltage
Yes
Yes
No
If End button pressed
Send end token
Close virtual COM port
Microcontroller
Kinect
PLL Init (SCI.c)
SCI Init (SCI.c)
ADC Init (ADC.C)
Figure 2—The software connection
between the microcontroller and the
Kinect is shown.
PID equations:[3]
[1]
For this application, the K
P
and K
D
values were
10 Quanta
PWM
/Quanta
ADC
and 1 Quanta
PWM
× s/Quanta
ADC
,
respectively, for the shoulder, and 1 Quanta
PWM
/Quanta
ADC
and
zero/Quanta
PWM
× s for the elbow, respectively. The K
P
gain
for the shoulder was much larger than that of the elbow
because of the larger load it needed to control. Furthermore,
the elbow’s K
D
value was zero, as it had a much lighter load to
control. These values may be adjusted based on the arm mass
and desired applications of the arm.
Upon PD controller implementation, we decided an inte-
gral gain was also needed to enable a smoother and more
controlled motion. The following section explains how the
controller gain values were converted to the appropriate
Quanta
PWM
units.
CONTROLLER GAIN CONVERSIONS
The proportional controller used its measurement as raw
data in Quanta
ADC
units with the gain values adjusted corre-
sponding to its Quanta
PWM
units. The angle difference between
τ θ θ θ θ = K + K
K and K r
P D
P P
DESIRED DESIRED
−( ) −
eepresent the proportional
and derivative gains, respectiveely
represents position
represents velocity
θ
θ
the MC9S12C32’s 10-bit ADC in “hard” real time, once per
1.024 µs, courtesy of the RTI interrupt service routine (ISR).
Hard real time was required because our controller used time-
derivative angle values. Furthermore, any timing variation
resulted in poor PD motor control algorithm performance.
After the measured values were digitalized in quanta units,
calculation was required to convert the angle back to its own
units of degrees. Usually a unit is not associated with an ADC;
however, we used “quanta” to balance overall units. A 10-bit
ADC will output values from 0 to 1,023 quanta.
Since the microcontroller was responsible for acquiring the
measurement and controlling the arm, the timing of such
processes was critical. As a result, the angle measurement
needed to be processed in real time on the microcontroller to
be used in the PD controller. However, processing the angle
measurement for the PD controller required a conversion to
Quanta
PWM
units in a 0-to-255 scale from Quanta
ADC
units in a
corresponding 0-to-1,023 scale. As previously mentioned, the
5-V range corresponded to the motor’s 300º rotation. There-
fore, once again, every 1 V was equal to a 60º arm motion.
THE CONTROLLER’S PURPOSE
We implemented a PD controller at each joint to aid with the
arm’s stability and control and improve steady-state error,
which is the difference between a system’s input and output
after the natural response has decayed to zero.[2] The PD con-
troller can be described by the following equation, which is sim-
ilar to the common PD control algorithms used in Allen Bradley
19
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
http://www.ezpcb.com
http://frontpanelexpress.com
http://www.ezpcb.com
20
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
the previous angle position and the current angle position was
calculated in Quanta
ADC
units multiplied by its proportional gain
in units of Quanta
PWM
/Quanta
ADC
. The following equations show
the calculation of the proportional control as a part of the PD
controller calculation:
[2]
where the variables in Equation 2 can be viewed in terms of
their units, so the units for the PWM output is Quanta
PWM
:
[3]
Calculation of velocity:
PWM output = KCURRENT PREVIOUS Pθ θ−( ) ( )
Quanta = Quanta
Quanta
Quanta
PWM ADC
PWM
ADC
( )
[4]
where the variables in Equation 4 can be viewed in terms of
their units, so the units for the PWM output is Quanta
PWM
:
[5]
This PD output provides the motor output, which powers the
arm’s motions. Hence, the basic prosthetic arm system was
complete. The following sections describe optional steps you
may take to integrate the prosthetic arm system with
Kinect.
PWM output=
Time
K
CURRENT PREVIOUS
D
θ θ−( ) ( )
∆
Quanta =
Quanta
second
Quanta second
Quanta
PWM
ADC PWM
×
AADC
Listing 1—We based the code on Microsoft’s “Skeleton Basics-WPF C# Sample.” We used this code and a virtual COM port to mimic a traditional RS-232
serial connection on the PC’s USB port. This provides a communication bridge between the Kinect and the prosthetic arm.
public MainWindow()
{
InitializeComponent();
_serialPort = new SerialPort(“COM6”, 115200, Parity.None, 8, StopBits.Two);
_serialPort.Open();
if (_serialPort.IsOpen == true)
{
this.statusBarText.Text = “Port Connected.”;
}
else
this.statusBarText.Text = “Port Not Connected.”;
}
Listing 2—We commented out DrawBone code for hips and legs. These sections are not needed, as our focus was only on an arm.
private void DrawBonesAndJoints(Skeleton skeleton, DrawingContext drawingContext)
{
// Render Torso
this.DrawBone(skeleton, drawingContext, JointType.Head, JointType.ShoulderCenter);
this.DrawBone(skeleton, drawingContext, JointType.ShoulderCenter, JointType.ShoulderLeft);
this.DrawBone(skeleton, drawingContext, JointType.ShoulderCenter, JointType.ShoulderRight);
this.DrawBone(skeleton, drawingContext, JointType.ShoulderCenter, JointType.Spine);
this.DrawBone(skeleton, drawingContext, JointType.Spine, JointType.HipCenter);
// this.DrawBone(skeleton, drawingContext, JointType.HipCenter, JointType.HipLeft);
// this.DrawBone(skeleton, drawingContext, JointType.HipCenter, JointType.HipRight);
// Left Arm
this.DrawBone(skeleton, drawingContext, JointType.ShoulderLeft, JointType.ElbowLeft);
this.DrawBone(skeleton, drawingContext, JointType.ElbowLeft, JointType.WristLeft);
this.DrawBone(skeleton, drawingContext, JointType.WristLeft, JointType.HandLeft);
// Right Arm
this.DrawBone(skeleton, drawingContext, JointType.ShoulderRight, JointType.ElbowRight);
this.DrawBone(skeleton, drawingContext, JointType.ElbowRight, JointType.WristRight);
this.DrawBone(skeleton, drawingContext, JointType.WristRight, JointType.HandRight);
// Left Leg
// this.DrawBone(skeleton, drawingContext, JointType.HipLeft, JointType.KneeLeft);
// this.DrawBone(skeleton, drawingContext, JointType.KneeLeft, JointType.AnkleLeft);
// this.DrawBone(skeleton, drawingContext, JointType.AnkleLeft, JointType.FootLeft);
// Right Leg
// this.DrawBone(skeleton, drawingContext, JointType.HipRight, JointType.KneeRight);
// this.DrawBone(skeleton, drawingContext, JointType.KneeRight, JointType.AnkleRight);
// this.DrawBone(skeleton, drawingContext, JointType.AnkleRight, JointType.FootRight);
USB Flash MCU
USB Flash MCU
Part No.
HT68FB540
HT68FB550
HT68FB560
HT66FB540
HT66FB550
HT66FB560
Internal Clock
12MHz
12MHz
12MHz
12MHz
12MHz
12MHz
VDD
2.2V~5.5V
2.2V~5.5V
2.2V~5.5V
2.2V~5.5V
2.2V~5.5V
2.2V~5.5V
I/O
17
25
37
25
37
45
A/D
---
---
---
12-bit x 8
12-bit x 16
12-bit x 16
System Clock
32kHz~16MHz
32kHz~16MHz
32kHz~16MHz
32kHz~16MHz
32kHz~16MHz
32kHz~16MHz
Program Memory
4K x 16
8K x 16
16K x 16
4K x 16
8K x 16
16K x 16
Data Memory
256 x 8
512 x 8
768 x 8
512 x 8
768 x 8
1024 x 8
Timer
10-bit CTM x 2
10-bit STM x 1
16-bit STM x 1
10-bit CTM x 2
10-bit STM x 1
16-bit STM x 1
End-points
4
6
8
4
6
8
Package
20QFN
20/24SSOP
40QFN
48/64LQFP
24/28SSOP
48LQFP
10-bit CTM x 2
10-bit STM x 1
16-bit STM x 1
24/28SSOP
48LQFP
10-bit CTM x 2
10-bit STM x 1
16-bit STM x 1
28SSOP
48LQFP
10-bit CTM x 2
10-bit STM x 1
16-bit STM x 1
28SSOP
40QFN
48LQFP
10-bit CTM x 2
10-bit STM x 1
16-bit STM x 1
www.holtek.com
Up to 1,000,000 times re-programming cycles
Supports both ISP and IAP firmware updates
Integrated OCDS development interface
USB 2.0 Full-speed compatible
Up to 8 Endpoints with user-defined FIFO capacity
Internal 12MHz oscillator with 0.25% accuracy
Up to 45 bidirectional I/O lines
12-bit resolution A/D converter
Dual SPI and I2C Serial Interfaces
4 Timer Modules supporting PWM output generation
Enhanced USB Interface Flash MCU SolutionsEnhanced USB Interface Flash MCU Solutions
USB Flash MCUUSB Flash MCU
Holtek’s new 8-bit USB Flash MCUs, the HT68FB5x0 series and HT66FB5x0
series, fully meet with the USB2.0 Full-Speed standard. The devices, with their
integrated HIRC 12MHz oscillator, having a 0.25% accuracy for all USB modes,
have no need for an external crystal oscillator as well as possessing the advantages
of high performance and low cost. These new devices have a Program Memory
capacity of 4K/8K/16K Words and with their integrated In-System Programming and
In-Application Programming technology, users have a quick and convenient means
of upgrading their application programs. The devices, including the I/O type
HT68FB5x0 series and A/D type HT66FB5x0 series, are suitable for computer
peripheral applications, such as Gaming Mouse, Keyboard, Joystick, USB Key, USB
Bridge, Wireless USB Dongle, TV Game peripherals etc.
High Precision Oscillator High level of Functional Integration Easy Firmware Updates
Comparison Table
.holtek.comwww
rnal ClockIntePart No.
Program ClockSystem VDDrnal Clock
orya MemDatryMemoProgram I/O
sntEnd-poirTime A/D
PackageA/D
rnal Clock
12MHz
12MHz
12MHz
12MHz
12MHzHT66FB550
HT66FB540
HT68FB560
HT68FB550
HT68FB540
IntePart No.
Program
4K x 16
8K x 16
16K
4K x 16
8K x 1632kHz~16MHz
32kHz~16MHz
32kHz~16MHz
32kHz~16MHz
32kHz~16MHz
Clock
2.2V~5.5V
2.2V~5.5V
2.2V~5.5V
2.2V~5.5V
2.2V~5.5V
System VDDrnal Clock
ory
256 x 8
512 x 8
768 x 8
512 x 8
768 x 88K x 16
4K x 16
x 16
8K x 16
4K x 16
a MemDatry
37
25
16K 37
25
17
MemoProgram I/O
s
4
6
16-bit STM x 1
16-bit STM x 1
16-bit STM x 1
10-bit STM x 1
TM x 2C10-bit
6
10-bit STM x 1
TM x 2C10-bit
4
10-bit STM x 1
TM x 2C10-bit
8
12-bit x 16
12-bit x 8
---
16-bit STM x 1
16-bit STM x 1
ntEnd-poir
10-bit STM x 1
TM x 2C10-bit
---
10-bit STM x 1
TM x 2C10-bit
---
Time A/D
Package
20/24SSOP
48LQFP
48LQFP
48LQFP
48LQFP
40QFN
28SSOP
12-bit x 16
28SSOP
12-bit x 8
24/28SSOP
24/28SSOP
20QFN
A/D
12MHzHT66FB560
16K32kHz~16MHz2.2V~5.5V
x 81024 x 1616K 45
16-bit STM x 1
10-bit STM x 1
TM x 2C10-bit
8 12-bit x 16
48/64LQFP
40QFN
12-bit x 16
http://www.Enhanced
http://www.holtek.com
http://www.holtek.com
mailto:sales@holtek.com
http://www.holtek.com
22
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
USING THE KINECT
We used the Kinect to track a healthy arm’s move-
ment and to mimic that movement on the prosthetic.
The Kinect improves on the Nintendo Wii by providing a
low-cost motion-tracking system of a caliber previously
available only to expensive high-end motion-capture
systems from Qualisys and Northern Digital’s Optotrak.
Beyond Xbox 360 games, the sensor itself is used in var-
ious engineering projects with an open C++, C#, or VB
software development kit (SDK).
For the prosthetic arm to replicate a healthy arm’s
motion, the prosthetic arm’s microcontroller requires the
position information of the user’s arm. The Kinect’s SDK
provides multiple PC-based software libraries and meth-
ods, which we used to generate commands that were
relayed to the MC9S12C32 over USB.
We believe that offering an alternative method of tuning and
training the prosthetic is important to the end user. Rather
than being forced to use scripts or control code, the end user
should be able to physically interact with the prosthetic in a
dynamic way, showing it the motions required for everyday
tasks. For example, a user may prefera slow and deliberate
movement action when reaching for a favorite coffee mug. A
fast and powerful swing may be preferred when playing bad-
minton. By using the Kinect to show the arm the kind of
desired movement, the switch between different movement
types can be simple and straightforward.
KINECT SDK AND DEVELOPER TOOLKIT
SPECIFICATIONS
Developer toolkit version 1.5 contains code samples for “skele-
ton tracking.” This reduces a person’s image to a stick-figure
“skeleton” (see Photo 3). We used the C# version of “Skeleton
Basics-WPF,” which provided a GUI output rendering on the PC of
10 to 20 links, depending on whether the person was sitting or
standing. In Photo 3 you can see the 10-link version of the head,
shoulder, and arms.
USB SERIAL COMMUNICATION INTERFACE
With the Kinect “SkeletonBasics-WPF” software installed
and tested, we needed to establish serial communication
between the MC9S12C32 and the Kinect. We mimicked an
RS-232 serial connection over the PC’s USB hardware.
Instructions for establishing a “Virtual COM port” on the PC
that supports the FT232R USB-to-serial UART interface are
available at FTDI’s website and from Technological Arts (see
the Resources section at the end of this article).
The code in Listing 1 shows how to configure this COM port
on the PC (115,200 bps, no parity bits, 8 data bits, and 2 stop
bits), which should be identical to
how the MC9S12C32’s SCI is also
set up in CodeWarrior. Note that
COM Port 6 is used, but depend-
ing on your PC, it may be a dif-
ferent number. Check your PC’s
settings.
To achieve natural motions in
the prosthetic arm, we needed
the PC to communicate quickly
with the microcontroller. We used
a 115,200-bps data rate. We
maximized communication effi-
ciency by transmitting only rele-
vant body part data. We did not
render the hip and legs. We
achieved this by commenting out
the DrawBone command for hip
and legs in the DrawBonesAnd
Joints function, as shown in
Listing 2.
SMOOTHING THE
KINECT SENSOR
The SkeletonBasics-WPF
code enables the designer to
Photo 3—These are the vectors of the right and left shoulder, elbow, and wrists as
illustrated using a Microsoft Kinect.
Listing 3—Setting Kinect smoothing parameters reduced motion tracking jitter.
if (null != this.sensor)
{
// Turn on the skeleton stream to receive skeleton frames
TransformSmoothParameters smoothingParam = new TransformSmoothParameters();
{
smoothingParam.Smoothing = 0.7f;
smoothingParam.Correction = 0.3f;
smoothingParam.Prediction = 1.0f;
smoothingParam.JitterRadius = 1.0f;
smoothingParam.MaxDeviationRadius = 1.0f;
// Some smoothing with little latency (defaults).
// Only filters out small jitters.
// Good for gesture recognition in games.
//{0.5f, 0.5f, 0.5f, 0.05f, 0.04f};
// Smoothed with some latency.
// Filters out medium jitters.
// Good for a menu system that needs to be smooth but
// doesn’t need the reduced latency as much as gesture recognition does.
//{0.5f, 0.1f, 0.5f, 0.1f, 0.1f};
// Very smooth, but with a lot of latency.
// Filters out large jitters.
// Good for situations where smooth data is absolutely required
// and latency is not an issue.
//{0.7f, 0.3f, 1.0f, 1.0f, 1.0f};
};
this.sensor.SkeletonStream.Enable(smoothingParam);
23
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
trade off between jitter and potentially high accuracy and low
latency, or smooth and lower accuracy and higher latency. We
chose some smoothing as it appeared more natural. The
smoothing parameter can be set in the WindowsLoaded()
function (see Listing 3).
EXTRACTING JOINT POSITION AND ANGLE
CALCULATION
The Cartesian (x, y, and z) position data from the Kinect
SDK told us the location of skeleton “bones” in 3-D space. We
needed to convert this into motor joint commands for the
prosthetic arm’s shoulder and elbow joints. Mathematically,
this meant creating 3-D vectors and taking dot products of
normalized coordinates between vector pairs and then apply-
ing an arccosine. We accomplished this through a new func-
tion called AngleBetweenTwoVectors() on the PC. It took the
Listing 4—This is the code for calculating the angle at the shoulder and elbow, based on the “bone” structure vectors created by the Kinect.
public double AngleBetweenTwoVectors(Skeleton skeleton, JointType jointType0,JointType jointType1)
{
double dotProduct = 0.0f;
double x0=0, y0=0, z0=0, x1=0, y1=0, z1=0;
if (jointType0 == JointType.ShoulderRight)
{
y0 = skeleton.Joints[JointType.ShoulderLeft].Position.X - skeleton.Joints[jointType0].Position.X;
x0 = skeleton.Joints[JointType.ShoulderLeft].Position.Y - skeleton.Joints[jointType0].Position.Y;
z0 = skeleton.Joints[JointType.ShoulderLeft].Position.Z - skeleton.Joints[jointType0].Position.Z;
}
else if (jointType0 == JointType.ElbowRight)
{
x0 = skeleton.Joints[jointType0].Position.X - skeleton.Joints[JointType.ShoulderRight].Position.X;
y0 = skeleton.Joints[jointType0].Position.Y - skeleton.Joints[JointType.ShoulderRight].Position.Y;
z0 = skeleton.Joints[jointType0].Position.Z - skeleton.Joints[JointType.ShoulderRight].Position.Z;
}
double d0 = Math.Sqrt((x0 * x0) + (y0 * y0) + (z0 * z0));
if (jointType1 == JointType.ElbowRight)
{
x1 = skeleton.Joints[jointType1].Position.X - skeleton.Joints[JointType.ShoulderRight].Position.X;
y1 = skeleton.Joints[jointType1].Position.Y - skeleton.Joints[JointType.ShoulderRight].Position.Y;
z1 = skeleton.Joints[jointType1].Position.Z - skeleton.Joints[JointType.ShoulderRight].Position.Z;
}
else if (jointType1 == JointType.WristRight)
{
x1 = skeleton.Joints[jointType1].Position.X - skeleton.Joints[JointType.ElbowRight].Position.X;
y1 = skeleton.Joints[jointType1].Position.Y - skeleton.Joints[JointType.ElbowRight].Position.Y;
z1 = skeleton.Joints[jointType1].Position.Z - skeleton.Joints[JointType.ElbowRight].Position.Z;
}
double d1 = Math.Sqrt((x1 * x1) + (y1 * y1) + (z1 * z1));
if (d0 != 0)
{
x0 /= d0;
y0 /= d0;
z0 /= d0;
}
if (d1 != 0)
{
x1 /= d1;
y1 /= d1;
z1 /= d1;
}
dotProduct = x0 * x1 + y0 * y1 + z0 * z1;//
return (double)Math.Round((360 / (2 * Math.PI)) * Math.Acos(dotProduct));
}
skeleton and two types of joints as its parameter and output
the calculated angle as a double-precision floating-point
number. In this code, we assumed the right arm is the
healthy arm.
To calculate the shoulder joint angle, we needed two vec-
tors: one from the left shoulder to the right shoulder and
another from the right shoulder to the right elbow. The dot
product was taken between these two vectors and passed
through an arccosine to provide the shoulder angle. Next, to
calculate the elbow joint’s angle, we needed another two
vectors: one from the right shoulder to the right elbow and
another from the right elbow to the right wrist. The dot prod-
uct between these two vectors, which was passed through
an arccosine function, yielded the elbow angle. Photo 3
shows these vectors in color. Listing 4 shows the code we
used to determine the two joint angles.
worked reasonably well for our purposes.
PROSTHETICS POTENTIAL
Developments in the maker and consumer worlds have the
potential to make adaptive prosthetics more affordable than
what is currently available. Here, we’ve shown how to com-
bine off-the-shelf Arduino-compatible parts, servomotors,
aluminum T-slots, and a Kinect into an adaptable, scalable
prosthetic arm.
This approach for a prosthesis testbed provides engineers
and designers with an array of possibilities to improve the
everyday lives of individuals with manipulation or mobility
needs. To that extent, our project illustrates a unique way of
combining core engineering principles with a Kinect, which is a
sensor conventionally used for gaming purposes.
Using the key elements shown here, we think new, more nat-
ural ways of training and tuning prostheses could be achieved.
The Kinect enables potential end users to manipulate their pros-
theses without requiring complicated scriptingor programming
methods. I
Author acknowledgements: We would like to thank our lab and
project colleagues Fakhreddine Taleb, Jamil Jivraj, Ronnie Wong,
and Anna Leshchenko. We would also like to thank the Chair of
the School of Fashion at Ryerson University, Robert Ott, and
Claudia Song, the fashion student who designed and created the
garments for our mannequin.
Editor's note: Visit circuitcellar.com/tag/kinect to see a video of
the prosthetic arm and its movement.
24
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
Listing 5—This code shows the appropriate placement of the AngleBetweenTwoVectors() function.
using�(DrawingContext�dc�=�this.drawingGroup.Open())
{
//�Draw�a�transparent�background�to�set�the�render�size
dc.DrawRectangle(Brushes.Black,�null,�new�Rect(0.0,�0.0,�RenderWidth,�RenderHeight));
if�(skeletons.Length�!=�0)
{
for�each�(Skeleton�skel�in�skeletons)
{
if�(skel.TrackingState�==�SkeletonTrackingState.Tracked)
{
angA�=�AngleBetweenTwoVectors(skel,�JointType.ShoulderRight,�JointType.ElbowRight).ToString();
angB�=�AngleBetweenTwoVectors(skel,�JointType.ElbowRight,�JointType.WristRight).ToString();
angBL�=�AngleLeft(skel).ToString();
if�(Time_i�==�0)
Time_i�=�DateTime.Now.Ticks;
Time_now�=�DateTime.Now.Ticks;
if�((Time_i�+�205�<�Time_now)�&&�(trackStart�=�true))
{
Time_i�=�Time_now;
_serialPort.Write(“B”�+�angB�+�“\r”);
_serialPort.Write(“A”�+�angA�+�“\r”);
_serialPort.Write(“H”�+�angBL�+�“\r”);
statusBarText.Text�=�angA�+�“����“����+angB;
}������������
this.DrawBonesAndJoints(skel,�dc);
}
}
}
USING USB TO SEND ANGLES
We used the AngleBetweenTwoVectors() function to send
the angle information to the microcontroller. In the Skeleton
Basics-WPF sample code the function SensorSkeletonFrame
Ready() is where it renders the skeleton if any skeleton is
detected. This function constantly refreshes itself to update the
skeleton’s movement. Therefore, this should be the appropriate
placement of the AngleBetweenTwoVectors() function. Listing 5
shows the insertion of these codes.
Because of the nondeterministic way Windows operates,
we cannot guarantee the exact time the SkeletonBasics-
WPF’s AngleBetweenTwoVectors() function will output the
two angles, angA and angB. The Kinect code’s time base was
100 ns. After every 205 increments (or 2.05 ms) in the code,
we sent motion data to the MC9S12C32 to the FTDI virtual
COM port. The PC’s FTDI driver code handled sending the
data over USB to the FTDI chip on the Esduino board, where
it was converted to TTL voltage levels and read by the
MC9S12C32’s SCI module.
We also found that Kinect-to-MC9S12C data packets can be
lost or corrupted from time to time. This can lead to the incor-
rect desired angles for the microcontroller and result in poten-
tially dangerous movements.
We implemented a simple packet-checking scheme to ver-
ify whether the angle data had been corrupted while travel-
ing through the USB cable and associated hardware. We sent
the letters “A” and “B” before the numeric angles. When the
MC9S12C received the Kinect data, it checked for these let-
ters and disregarded the data if the letters did not match.
While it wasn’t as robust as a formal checksum scheme, it
http://circuitcellar.com/tag/kinect
25
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
PROJECT FILES
To download the code, go to ftp://ftp.circuitcellar.com/
pub/Circuit_Cellar/2013/276.
REFERENCES
[1] I. Austen, “Computerized Control Is Next for Artificial
Limbs,” New York Times, 2002.
[2] N. S. Nise, Control Systems Engineering 5th Edition,
Wiley, 2009.
[3] BESTune, “Three Types of PID Equations,” http://best
une.50megs.com/typeABC.htm.
RESOURCES
Freescale Semiconductor, Inc., “MC9S12C/MC9S12GC
Family Reference Manual: HCS12 Microcontrollers,” 2010,
www.freescale.com/files/microcontrollers/doc/data_sheet/
MC9S12C128V1.pdf.
Lynxmotion, www.lynxmotion.com.
MicroRAX, www.microrax.com.
Microsoft, Inc., “Kinect for Windows,” www.microsoft.
com/en-us/kinectforwindows.
———, “Skeleton Basics-WPF C# Sample,” http://msdn.
microsoft.com/en-us/library/hh855381.
Northern Digital, Inc., Optotrak Certus Motion-Capture
System, www.ndigital.com.
Qualisys, www.qualisys.com.
Robotiq, http://robotiq.com.
Technological Arts, “Esduino: MC9S12C-Based Arduino-
Compatible,” 2010, http://support.technologicalarts.ca/
docs/Esduino/TAdocs/Rev2/EsduinoDAT2.PDF.
———, “Esduino Pin Map,” http://support.technological
arts.ca/docs/Esduino/TAdocs/Rev2/EsduinoPinMap.
pdf.
———, “Configuring Windows USB Virtual COM Ports,”
http://support.technologicalarts.ca/docs/BDMPods/
ConfiguringVirtualCOMports.pdf.
J. Valvano, “Programming the Tech Arts 9S12C32 and
9S12DP512 Boards,” 2012, http://users.ece.utexas.edu/
~valvano/metrowerks.
E. Weisstein, “Dot Product,” Wolfram Research,
http://mathworld.wolfram.com/DotProduct.html.
SOURCES
Arduino Motor Shield
Arduino | http://arduino.cc
Cortex-M3 Processor
ARM, Ltd. | www.arm.com
ATmega8 Microcontroller
Atmel Corp. | www.atmel.com
MC9S12C Microcontroller family and CodeWarrior
IDE
Freescale Semiconductor | www.freescale.com
FT232R USB UART IC
Future Technology Devices International, Ltd. |
www.ftdichip.com
Kinect for Xbox
Microsoft Corp. | www.microsoft.com
Dynamixel motors and RX-28 and MX-28 robot
actuators
Robotis, Inc. | www.robotis.com
Esduino microcontroller board
Technological Arts | www.technologicalarts.ca
MicroRAX aluminum T-slot framing
Twintec, Inc. | www.microrax.com
Jung Soo (James) Kim (jung.kim@ryerson.ca) is an under-
graduate student in Biomedical Engineering at Ryerson Uni-
versity in Toronto, Canada. He achieved his first degree in
Computer Engineering at the University of Waterloo in Water-
loo, Canada. While obtaining his first degree, he gained work
experience with industry partners including Fortress Invest-
ment Group, Bell Canada, and Qualcomm through the univer-
sity’s internship program. He is currently completing the final
year of his second degree and wishes to pursue graduate
studies.
Nika Zolfaghari (nika.zolfaghari@ryerson.ca) is a master’s
degree student at Ryerson University in Toronto, Canada. She
completed her undergraduate degree in Biomedical Engineer-
ing at Ryerson University. She is currently researching reha-
bilitation engineering, specifically spinal cord injury and
upper-body balance. Nika is the Women in Engineering liaison
at Ryerson University, the founding president of the Biomed-
ical Engineering Society (BMES) Ryerson Student Chapter,
and a member of the Institute of Electrical and Electronics
Engineers (IEEE).
Dr. James Andrew Smith (jasmith@ee.ryerson.ca) specializes
in Biomedical Engineering at Ryerson University in Toronto,
Canada. He was Biomedical Engineering Program Director
from 2010 to 2011 at Ryerson University and is currently the
Biomedical Engineering Stream Coordinator. His research
combines aspects of biomechanics and robotics with active
research projects in legged systems, obstetrics, and surgical
systems. James teaches courses in biomedical engineering,
microprocessors, sensing, and measurement. In addition to
teaching awards he has received at the University of Alberta,
he was a recipient or co-recipient of four IEEE Real World
Engineering Projects awards from 2007 to 2010. He was also
the second-place co-recipient in the IDEO-organized design
competition at the 2012 Healthcare Innovation Conference in
Houston, Texas.
ftp://ftp.circuitcellar.com/pub/Circuit_Cellar/2013/276
http://bestune.50megs.com/typeABC.htm
http://www.freescale.com/files/microcontrollers/doc/data_sheet/MC9S12C128V1.pdf
http://www.lynxmotion.com
http://www.microrax.com
http://www.microsoft.com/en-us/kinectforwindows
http://msdn.microsoft.com/en-us/library/hh855381
http://www.ndigital.com
http://www.qualisys.com
http://robotiq.com
http://support.technologicalarts.ca/docs/Esduino/TAdocs/Rev2/EsduinoDAT2.PDF
http://support.technologicalarts.ca/docs/Esduino/TAdocs/Rev2/EsduinoPinMap.pdfhttp://support.technologicalarts.ca/docs/BDMPods/ConfiguringVirtualCOMports.pdf
http://users.ece.utexas.edu/~valvano/metrowerks
http://mathworld.wolfram.com/DotProduct.html
http://arduino.cc
http://www.arm.com
http://www.atmel.com
http://www.freescale.com
http://www.ftdichip.com
http://www.microsoft.com
http://www.robotis.com
http://www.technologicalarts.ca
http://www.microrax.com
mailto:jung.kim@ryerson.ca
mailto:nika.zolfaghari@ryerson.ca
mailto:jasmith@ee.ryerson.ca
ADVERTISEMENT
Last month, I talked about how DesignSpark uses
technology files to store configurations settings.
In this article we’ll begin a new project and start
a schematic design. We’ll start by configuring
the DesignSpark libraries and then we’ll set up
a schematic title block so we can create a nice-
looking schematic.
Configuring the libraries
DesignSpark uses library files to organize all of
your design information. Schematic symbols are
one library type and PCB footprints are another.
They are then combined to make a component
library that you can use to place parts and doc-
umentation symbols into your design. The only
difference between a documentation symbol and
a regular component is that a documentation
symbol contains either a schematic symbol or a
PCB symbol, but not both. If you would like more
information about DesignSpark’s library system
and how it works, there is a good tutorial at [1].
In this article we will make a schematic documen-
tation symbol to use a title block in a schematic.
But before we do that, we need to double-check
DesignSpark’s library search paths. You do that
by going into the “Files -> Libraries...” menu and
selecting the “Folders” tab. Here you will see a
screen that looks something like Figure 1.
You want to make sure that the directory where
you are storing your library files is listed as the
first item in the “Folders and Search Order” box,
which in my case is “C:\Users\Neil Gruending\
Documents\dspcb2lib\library.” You can reorder
the directory list by selecting the directory that
you want to move and using the Up/Down but-
tons. I would recommend that you don’t save any
changes or new files into the DesignSpark system
default library folders, just in case the libraries
get overwritten in a future upgrade.
Now that the library paths are set up, you can
create a new schematic symbol library to store
our schematic title block by selecting the “New
Lib…” button on the “Schematic Symbols” tab.
Then select the “New Item…” button to open up a
blank schematic symbol page. For more informa-
tion, you can review the symbol creation tutorial
on the DesignSpark website [1].
Creating a schematic title block
Personally, I always use title blocks on a sche-
matic to make them look much more professional
and to help document a design. DesignSpark is
different from other packages because schematic
title blocks are stored in a schematic component
library instead of a template file or technology
file, which means that DesignSpark will ignore
any drawing elements in a schematic technology
file. DesignSpark comes with several title block
templates in its Schema library in several differ-
ent sizes such as A4 and Letter, but I prefer to
use Tabloid (11 in. × 17 in.) for my designs. I
also prefer to use a more traditional documenta-
tion area that takes up less of the drawing area.
In my last article, I showed you how to use true-
type fonts in a schematic technology file, but
there is a downside to using them in a schematic
title block. That’s because DesignSpark shifts
truetype fonts slightly downward when printing
By Neil Gruending
(Australia)
Starting a
Schematic Design
Figure 1.
Inspecting DesignSpark’s
library paths.
ADVERTISEMENT
Tips & Tricks
a schematic to a PDF file. That normally doesn’t
matter for things such as reference designators.
But in title blocks where text alignment is more
important, you’ll definitely notice. Therefore, I
chose to use stroke fonts for my title block, which
is shown in Figure 2.
I recommend that you name the various text styles
so that they’re easy to modify later. In my case,
I ended up with the styles shown in Figure 3.
The numbers and letters around the drawing area
frame use the text style “Frame” and the field
descriptions use the text style “Title-small.” Field
items use the style “Title.” Since DesignSpark
doesn’t support project variables, you have to
add the text strings to the title block manually,
which is why all of the title block fields are blank
in the schematic component. Also, you don’t have
to add these text styles to the schematic tech-
nology file because they will be copied into the
schematic when you add the title block.
Once you’ve finished editing the title block, save
it to the schematic symbol library you created
earlier so that we can create a schematic docu-
ment symbol. The first step is to open the Library
Manager (“File->Libraries…”) and go to the Com-
ponents tab. You can create a new component
library by selecting the “New Lib…” button and
then create the document symbol by clicking
on the “New Item…” button, which will open the
“New Component” window. Here you can give
the component a name and select your title block
symbol. Unchecking the “PCB Symbol” check box
will make the component a schematic document
symbol like we need. Save your changes and let’s
start a new DesignSpark project.
Creating a new project
DesignSpark uses projects to collect all of the
relevant information about a design, such as
schematics and PCB documents, in one place.
The main reason for using a project is to allow
a set of schematic sheets to be linked to a PCB
design. The linked schematic sheets can then
act as one large project where global net infor-
mation is shared and all component designators
are unique.
Creating a new DesignSpark project is simple.
Go into the “File -> New’”menu to open the “New
Design” window, select
“Project” and then press
“OK.” You will then be
prompted where to save
the new project and then
a blank project will be
created for you. Now you
can add existing files to
the project by using the
“Project -> Add Files to
Project…” menu. Add-
ing new items to a proj-
ect is done by opening
the “New Design” win-
dow. But before clicking
on OK, make sure you
check the “Add to Open
Project” box.
Conclusion
Now that we can cre-
a t e p r o j e c t s a n d
nice-looking schematic
templates, the next
step is to start draw-
ing your design using
components from the
DesignSpark libraries.
You can also create and
use your own libraries
with some extra com-
ponent attributes that
will make it easier to
generate bill of material
(BOM) listings later. The
title block I’ve drawn
here (Figure 4) is
available from my dsp-
pcb2lib project on Bit-
bucket at [3].
Internet References
[1] www.designspark.
com/tutorial/components-library-structure-
library-manager
[2] www.designspark.com/tutorial/components-
creation-with-symbol-footprint-wizards
[3] https://bitbucket.org/neilg/dspcb2lib
Figure 2.
Structure and layout of the schematic title block.
Figure 3. Text formatting in the title block.
Figure 4. A completed schematic title block.
http://www.designsparkcom/tutorial/components-library-structure-library-manager
http://www.designspark.com/tutorial/components-creation-with-symbol-footprint-wizards
https://bitbucket.org/neilg/dspcb2lib
ADVERTISEMENT
In line with a strong trend
in the industry, Renesas
underscores that its latest
GR Sakura board is Arduino
compatible. This overview
allows you to check for
yourself just how far that
compatibility goes.
Difference #1
Okay, the GR Sakura board
is pink! But then, look at
the specs—Pink is Power!
Difference #2
It’s the 8 bit, 16 MHz, and
limited memory of the AVR
controller against the full 32
bit, 96 MHz, and massive
memory capacity of the
Renesas processor. The
real question is: Which
applications will actually
unleash GR Sakura’sfull
potential?
Difference #3
The USB Host functionality
on the Sakura board shows
potential. It is implemented
with a Mini-B connector,
while a Type-A connector
can be fitted on the back
side of the board.
By Wisse Hettinga
SPOT THE DIFFERENCE
Arduino Uno GR Sakura
Supply Voltage(s) 5-V processor operating voltage
3.3-V processor operating voltage
5-V board supply voltage
USB
Type B connector
Board runs off USB voltage by default.
Mini-B connector
Type A connector provides Host support
Board runs off USB voltage by default
Network None Ethernet RJ45
ADVERTISEMENT
Spot the Difference
Difference #4
You can’t deny that the true
power of the Arduino concept
is due to the huge and easily
accessible program library (at
www.arduino.cc), rather
than the hardware. However,
don’t underestimate the
programming options available
for the Sakura board either. It
has lots of features that come
to life once you start using
the Cloud Base Compiler. Just
hook up the board to your PC,
push the right buttons—all well
documented—and watch the
board appear as a new drive
connected to your PC. With the
new drive, a link is provided
that takes you straight to
the website. If you have an
Android phone, have a look
at Gadget Director—an easy,
“icon” based programming
language.
Find all the references at
www.designspark.com and
go to the Design Centers.
ARDUINO UNO vs. GR SAKURA FULL
Arduino Uno GR Sakura
Processor
ATmega328
8 bit
16-MHz operating frequency
RX63N
32 bit
96-MHz operating frequency
Memory
32-KB Flash, of which 0.5 KB used by bootloader
SRAM: 2 KB
EEPROM: 1 KB
1-MB Flash
RAM: 128 KB
Data Flash: 32 KB
MicroSD socket
http://www.arduino.cc
http://www.designspark.com
o many FPGA designers, FPGAs
are like black boxes, a higher
abstraction of custom-designed ICs. To
designers, FPGAs appear as a sea of
gates, memories, and other on-chip
modules to access and program accord-
ing to a design’s requirements. To gain a
better understanding of FPGA-based
product design, a good FPGA designer
should be aware of certain device physics
issues.
Some aspects of FPGA-based product
designs affect their performance over
their life cycles. A well-designed product
should not only meet certain require-
ments and provide a given set of func-
tionalities, it should continue to do so.
Many FPGA designers are unaware of
CMOS device physics. Designers don’t
need an in-depth understanding. However,
since FPGAs are CMOS devices, a little
awareness of IC failure modes and their
impact can go a long way in producing
robust FPGA designs and suitably planning
for the product’s entire life cycle.
One issue is negative-bias tempera-
ture instability (NBTI), which is a factor
in designs based on the popular Xilinx
Virtex-4 devices. Even with the advent
of newer FPGA families (including the
Virtex-7 devices released in 2012),
many designers still use Virtex-4
devices for product applications includ-
ing telecommunications, signal process-
ing, and digital-image processing. Not
all product designs require a big FPGA
such as the Virtex-6 or Virtex-7.
Many designers choose Virtex-4
devices based on cost and other design
considerations—such as the need for
processor blocks, Peripheral Component
Interconnect Express (PCIe), and inter-
face blocks. Table 1 shows the number
of logic cells, DSP slices, and other
resources in different generations of
Virtex FPGAs.
Xilinx has been careful to mitigate NBTI
in all device families after the Virtex-4,
either through diligent designing (as in
the Virtex-7) or by making speed file
changes. The speed files contain data
about timing through different circuit
blocks on FPGAs. Xilinx has properly
sized its speed bins when NBTI could not
be avoided. This ensures Xilinx’s ISE
WebPACK design software implements
the design within the timing margins (as
dictated by the speed bins) to avoid
future design failure.
UNDERSTANDING NBTI
NBTI is basically a shift in a transistor’s
threshold voltage over a time period due
to the application of negative voltage on
its gate. This effect is prominent in P-
type MOSFETs (i.e., P-MOSFETs or
PMOS). Due to an increase in the thresh-
old voltage, there is a degradation of
mobility, drain current, and transconduc-
tance of P-channel MOSFETs. These
effects lead to transistor slowdown,
adversely affecting switching speed and
causing a digital circuit slowdown. The
stressing voltage’s duty cycle and the
transistor’s operating temperature also
Table 1—These are the resources available in different generations of Virtex FPGAs.
30 CIRCUIT CELLAR
® • circuitcellar.com
Negative-bias temperature instability (NBTI) can affect the performance of
FPGA-based designs. Changing a product’s design or altering files containing
circuit block information can reduce NBTI. This article provides an introduction
to NBTI and describes its impact on FPGAs and digital clock managers.
NBTI and FPGA Design
by Sharad Sinha (Singapore)
T
FEATURE ARTICLE
Device
Family
Minimum
(Slices)
Maximum
(Slices)
Minimum
(DSP slices)
Maximum
(DSP slices)
Minimum
(PowerPC
Processor
Blocks)
Maximum
(PowerPC
Processor
Blocks)
Minimum
(Embedded
Ethernet MACs)
Maximum
(Embedded
Ethernet MACs)
Minimum
(Endpoint
Blocks for
PCIe)
Maximum
(Endpoint
Blocks for
PCIe)
Virtex-4 6,144 89,088 32 512 1 2 2 4 0 0
Virtex-5 3,120 51,840 24 1,056 1 2 2 8 1 4
Virtex-6 11,640 118,560 288 2,016 0 0 0 4 0 4
Virtex-7 44,375 305,400 840 3,600 0 0 0 0 1 4
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CMOS inverter will affect the overall
device performance. As a designer, you
need to ensure that the device will work
31
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
for at least 10 years under worst-case
operating conditions.
Xilinx has qualified FPGA fabric (i.e.,
slices) as well as subcircuits such as
digital clock managers (DCMs) and
block random access memory (BRAM).
The accelerated stress-qualification
testing showed Virtex-4 DCM’s maxi-
mum operating frequency decreases if
the FPGA is consistently held in a static
condition for a long period.[1] This basi-
cally means if the device is powered up
but isn’t configured, it can lead to loss
of DCM performance over a period of
contribute to NBTI.
NBTI’s effects have been known since
1966. However, it has only become a
reliability issue in the last few years as
the semiconductor industry has shrunk
transistor dimensions. Gate electric fields
have increased due to this scaling. The
increase in chip operating temperatures
and the replacement of buried-channel
PMOS with surface-channel PMOS in
smaller dimensions have also led to
NBTI’s emergence as a reliability issue.
In buried-channel PMOS, the current
flow is at a distance from the gate oxide
layer. In surface-channel PMOS, the cur-
rent is very close, making it easier for the
P-channel holes to be pulled into the
oxide layer (see Figure 1). Also, lowering
the operating voltage at smaller transis-
tor geometries has made circuit behavior
susceptible to even small changes in
threshold voltage.
When negative voltages are applied
to a PMOS transistor’s gate, holes
(which are positively charged) can be
“pulled” into and become stuck in the
oxide layer. This increases the threshold
voltage, leading to degradation in cir-
cuit performance.
NBTI is less of a concern in N-type
MOSFETs (i.e., N-MOSFETs or NMOS)
because the shift in threshold voltage can
be recovered once the voltage stress is
removed. That is not the case in PMOS. A
good reference on NBTI, its modeling, and
associated semiconductor physics phe-
nomena is available from D. Schroder’s
white paper “Negative-Bias Temperature
Instability: What Do We Understand?”
(Microelectronics Reliability, 2007).
NBTI AND VIRTEX-4
The Xilinx Virtex-4 FPGA has 250-nm
I/O transistors, 100-nm memory and
pass-gate transistors, and 90-nm logic
transistors. NBTI affects all ofthem. A
PMOS transistor’s performance in a
Figure 1a—In buried-channel PMOS, the current flow is at a distance from the gate oxide layer. b—In
surface-channel PMOS, it is very close, making it more likely that the P-channel’s holes will be pulled
into the oxide layer.
Source
Current
Buried-channel PMOS
Gate
Drain Source Current
Surface-channel PMOS
Gate
Drain
a) b)
http://www.expresspcb.com
CIRCUIT CELLAR® • circuitcellar.com
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
32
REFERENCES
[1] A. Lesea and A. Percy, “Negative-Bias Temperature
Instability (NBTI) Effects in 90-nm PMOS,” Xilinx WP 224,
2005, www.xilinx.com/support/documentation/white_
papers/wp224.pdf.
[2] Xilinx, Inc., “AR# 21127 Virtex-4 FPGA DCM: What Are
the DCM Parameters that Must Be Met to Protect Virtex-4
FPGA DCMs Against NBTI Effects?,” www.xilinx.com/
support/answers/21127.htm.
RESOURCES
D. Schroder, “Negative-Bias Temperature Instability:
What Do We Understand?,” Microelectronics Reliability,
2007, http://schroder.personal.asu.edu/Published%
20Papers/118.%20Microel.%20Rel%20June%2007%
20NBTI.pdf.
Xilinx Inc., “Virtex-4 DCM NBTI,” www.xilinx.com/
support/troubleshoot/clocking_debug.htm#c_7.
SOURCE
Virtex FGPA family and ISE WebPACK design
software
Xilinx, Inc. | www.xilinx.com
Sharad Sinha (sharad_sinha@pmail.ntu.edu.sg) is a fourth-year
PhD candidate at Nanyang Technological University, Singapore.
He works in embedded systems with a focus on FPGA design
methodologies and reconfigurable computing. Prior to beginning
his PhD, Sharad was an FPGA design engineer at Processor
Systems in India for two years. You can read his blog about elec-
tronics and computer engineering, technology development, and
so forth at www.sharadsinha.wordpress.com.
time and it may not lock up
to its specified maximum
frequency.
There are three reasons
why this information is
important to you as an FPGA
design engineer. First, it
affects any Virtex-4-based
FPGA design that uses
DCMs, and lockup to the DCM’s maximum operating frequency
is expected.
Second, many designs use multiple intellectual-property
(IP) blocks on an FPGA, leading to a system-on-a-chip
(SoC). If it’s driven by DCM-generated clocks, your design
may not meet these individual IP cores’ clocking require-
ments, particularly if the DCM is not properly configured and
used. This can lead to a potential SoC failure. That is why
Xilinx instructed designers to load a null bitstream for a cer-
tain class of Virtex-4 devices.[2] This ensures the DCMs stay
active when the device is powered up but isn’t configured for
more than the maximum time it takes to configure the
Virtex-4 from power up, which is 10 min.
The third important reason is, because of NBTI, there are
specific reset criteria for Virtex-4 DCMs. The latest Xilinx ISE
versions insert auto calibration blocks in certain Virtex-4
devices. Specific macros are needed for other Virtex-4 devices
to ensure that unused DCMs in a design are put in continu-
ous-calibration mode. These blocks require a reset of at least
200 ms. The DCM may not
come out of reset if the
duration is any shorter. Xil-
inx offers more advice on
workarounds to handle
NBTI issues (see the
Resources section at the
end of this article).
Returning to the SoC
paradigm, even reset design needs a careful analysis in light
of NBTI effects when the SoC is built on a Virtex-4 platform.
Besides, you must factor a reset of at least 200 ms into the
entire design process any time your SoC or a Virtex-4-based
design interfaces with other modules on a board.
THE MORE YOU KNOW
In the end, it is important to understand NBTI and other
device physics issues from a system perspective, where clock
and reset design are also important—especially now, with the
SoC design paradigm gaining tremendous traction in the
design community. Often, designers tend to focus too much on
low-level details and forget how a particular design fits into a
large system. With NBTI, clearly there is a relationship
between low-level details and system issues for this particular
type of IC failure mode. I
“NBTI is basically a shift in a transistor’s
threshold voltage over a time period due to
the application of negative voltage on its
gate. These effects lead to transistor slow-
down, adversely affecting switching speed
and causing a digital circuit slowdown.”
mailto:sharad_sinha@pmail.ntu.edu.sg
http://www.sharadsinha.wordpress.com
http://www.xilinx.com/support/documentation/white_papers/wp224.pdf
http://www.xilinx.com/support/answers/21127.htm
http://schroder.personal.asu.edu/Published%20Papers/118.%20Microel.%20Rel%20June%2007%20NTBI.pdf
http://www.xilinx.com/support/troubleshoot/clocking_debug.htm#c_7
http://www.xilinx.com
http://www.apcircuits.com
HOT CHIPS brings together designers and architects of high-performance chips,
software, and systems. The tutorial and presentation sessions focus on up-to-the-
minute developments in leading-edge industrial designs and research projects. The
expanded poster session features industry as well as student posters.
Morning Tutorial
Heterogeneous System Architecture (HSA): Overview and Implementation
AMD, ARM, Qualcomm
Afternoon Tutorial
Fast Storage for Big Data Bay Storage, Fusion IO
SoC1
• AMD’s Kabini SoC AMD
• Intel’s Bay Trail SoC for Tablets, Netbooks, and Entry Desktops Intel
• Clover Trail+ – Intel’s Next Atom SoC Smartphone Platform Intel
Keynote 1 The Chip Design Game at the End of Moore’s Law
Dr. Robert Colwell, Director of
Microsystems Technology Office DARPA
Processors
• Next Generation POWER Microprocessor IBM
• IBM zEC12 Mainframe Symmetric Multiprocessor System IBM
Keynote 2 Google Glass
Babak Parviz Google
SoC2
• AMD’s Richland Client APU SoC AMD
• A 50% Lower Power ARM Cortex CPU using DDC Transistors with Body Bias Suvolta
Interconnects
• Silicon Photonics Platform for Integration of Optical IOs with ASICs Luxtera
• NetSpeed eNoC – a Quantum Leap in On-Chip Interconnect Design Netspeed
• Integrating Rack Level Connectivity into a PCI Express Switch Pixtech
FPGA Based Dataflow
• Dataflow Architectures for 10Gbps Line-Rate Key-Value-Stores Xilinx
• Trading and Risk in a Chip with Multi-Scale Dataflow Computing Maxeler
• An FPGA-Based In-line Accelerator for Memcached U. Texas
M
on
da
y
A
ug
us
t
26
Tu
es
da
y
A
ug
us
t
27
August 25-27, 2013
A Symposium on High-Performance Chips
Memorial Auditorium, Stanford University, CA
http://www.hotchips.org
ADVANCE PROGRAM25
S
un
.
A
ug
. 2
5
Networking
• Serial Networking Memory Bandwidth Engine Breaks 4.5 B Accesses/sec Mosys
• HARRIER– A 22nm 200Gb/s High-Performance Network Flow Processor Netronome
Keynote 3 Intellectual Property Issues in the Computer
and Electronics Industries
Michael Brody, Vice-Chair, Intellectual Property Winston
and Strawn
Mobility
• Qualcomm Hexagon DSP: An Architecture for Mobile Multimedia Qualcomm
• Power Management Challenges in Wireless WAN SoCs Intel
• 5th Generation Touchscreen Controller for Mobile Phones and Tablets Cypress
Processors 2
• Hardware-level Thread Migration in a 110-core Shared-Memory Processor MIT
• Haswell Client Product Family Intel
• Microprocessors for Roots of Trust Bluerisc
Processors 3
• SPARC64 X+ : Fujitsu’s Next-Generation Processor for UNIX Servers Fujitsu
• SPARC M6: Oracle’s Next-Generation Processor for Enterprise Systems Oracle
• Bixby: the Scalability and Coherency ASIC in Oracle’s Enterprise Systems Oracle
• XBOX One Silicon Microsoft
A Symposium of the Technical Committee on Microprocessors and Microcomputers
of the IEEE Computer Society and the Solid-State Circuits Society
Warthman
Associates
Technical Writers
www.warthman.com
Organizing Committee
Chair
Jan Willem Van De Waerdt
Cypress
Vice Chair
Krste Asanovic UC Berkeley
Member at Large
Ralph Wittig Xilinx
Finance
Lily Jow HP
Advertising
Don Draper Oracle
SponsorshipAmr Zaky Broadcom
Publications
Randall Neff
Press
Ralph Wittig Xilinx
Registration
Charlie Neuhauser Neuhauser
Associates
Larry Lewis
Location Services
John Sell Microsoft
Allen Baum
Volunteer Coordinator
Gary Brown Tensilica
Webmasters, IT
Kevin Broch
Alice Erickson Alice Erickson
Consulting
Production
Lance Hammond
Mike Albaugh
Keith Diefendorff
Steering Committee
Chair
Alan Jay Smith
Committee Members
Allen Baum
Don Draper Oracle
Pradeep Dubey Intel
Lily Jow HP
John Mashey Techviser
John Sell Microsoft
Keith Diefendorff
Program Committee
Program Co-Chairs
Don Newell Qualcomm
Mike Flynn Maxeler Tech.
Committee Members
Forest Baskett NEA
Pradeep Dubey Intel
Fred Weber
Alan Jay Smith UC Berkeley
Samuel Naffziger AMD
Subhasish Mitra Stanford
Israel Koren U. Massachusetts
Thomas McWilliams BayStorage
Rumi Zahir Intel
Ralph Wittig Xilinx
Oliver Pell Maxeler Tech.
Patrick Hung CPO Tech.
Behnam Robatmili Qualcomm
Bill Dally NVIDIA
Founder Bob Stewart SRE
http://www.hotchips.org
http://www.warthman.com
from two sets of Patching’s data sets
(see Figure 1). The major vertical line in
Figure 1a (dashed arrow) is the acoustic
pickup from the 60-Hz electrical buzz
generated by household appliances. This
34
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
s a skilled electrical engineer
or researcher, you can probably
design an effective data collection sys-
tem in fairly short order. But when
you’re dealing with large amounts of
data (e.g., gigabits), it can be tough to
systematically process it all. In this arti-
cle series, we describe a solution to this
common embedded system design
problem. You’ll see how we used this
solution in three different projects.
THE HUM
The “Hum” is a persistent, low-
frequency sound that is not audible to
everyone. Worldwide, people use the
Internet to discuss England’s Bristol
Hum, New Mexico’s Taos Hum, and Aus-
tralia’s Bondi Hum, to name a few. In
2008, residents in the Ranchlands com-
munity of Calgary, Canada, started
hearing a sporadic, low-frequency noise.
The noise was reported at around 40 Hz,
which is more than two octaves below
middle C on the piano.
Because the Hum is not experienced by
everyone in a community, people ques-
tion whether it is real, imagined, or
health related (e.g., tinnitus). When
Patching Associates Acoustical Engineer-
ing, a Calgary-based acoustic diagnostic
firm, researched the Calgary Hum as a
voluntary community project, it loaned
its industrial noise recording equipment
to some affected residents.
We used MathWorks’s MATLAB
scientific programming tool to create a
high-resolution, 10-min spectrograph of
You can use a DSP-SQL interface to access large amounts of data on a server.
This article describes a digital-signal processing design that combines MATLAB
and a server query language into a database on a server, enabling easy access
to externally collected data.
Systematic Digital Processing (Part 1)
by Emily Marasco, Mike Smith, and
Maddie Lowe (Canada)
A
FEATURE ARTICLE
Combining Embedded DSP with SQL
Figure 1—MathWorks’s MATLAB provided acoustical spectographs and high-resolution line spectra. a—A
46-Hz Hum, with many harmonics, begins in House 1. b—Here is the Hum at low intensity before growing
louder. c—Different Ranchlands Hum sources appear in House 2, including a 44-Hz Hum with no harmonics
and a periodic signal with many harmonics, sweeping. d—This Hum is 19 to 23 Hz. Considerable acoustic
pickup from appliances (60 Hz and harmonics) exists in House 1 but not in House 2.
a) b)
c) d)
35
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
Even limiting the cell phone application
to handle the recording is not a problem-
free solution. Cell phone microphones are
not really intended to pick up 40-Hz sig-
nals, as this frequency is nearly outside
the minimum range of human hearing,
which is 20 Hz.
We attempted to solve this problem
by using inexpensive wideband micro-
phones and mixers available from a
local music store. After consulting with
the in-store musicians, we chose a
Behringer ECM8000 measurement con-
denser microphone capable of record-
ing low-frequency tones (e.g., 40 Hz).
We also selected a Behringer mixing
console for amplification and limited
prefiltering.
The second step was to set up an
Internet-based method for residents to
send us sound recordings of noises in
their homes. We would then compare
those recordings to sound signatures
from various potential industrial sound
signals captured by other resident
“sleuths.”
The third step is the focus of this arti-
cle. We needed a way to systematically
handle the digital data.
THE MIND2SAIL PROJECT
The Mind2Sail project’s purpose was
to determine how electroencephalo-
graphic (EEG) signals from NeuroSky’s
MindWave and MindBand single- and
dual-electrode sensors could be used to
control a Martin 16 sailboat. This was an
alternative to the Martin 16 voice con-
troller discussed in “Voice Recognition
Controlled Sailboat: Speech-Recognition
Control Aids Disabled Sailors,” Circuit
Cellar Ink 113, 1999.
Maddie worked on the Mind2Sail proj-
ect during her summer internship (which
was supervised by Mike). Her research
involved trying to determine whether a
standard commercial brain-computer
interface could be modified to become a
useful controller for the disabled.
The Mind2Sail project required a lot of
collection and storage of data from vari-
ous volunteers thinking sailing commands
(e.g., “Sail in,” “Rudder starboard,” and so
forth). The next step was to identify the
“best” algorithms to reliably compare the
EEG signals with various prerecorded
“gold-standard” training signals. This
would provide the basic functionality of an
signal’s 120- and 180-Hz harmonics are
shown. Figure 1b shows there is little
60-Hz pickup.
We were particularly interested in the
acoustic signature of “a” Ranchlands
46-Hz Hum (black arrows). Further evi-
dence that “this” Hum is real included
the changes in its detailed sound ecol-
ogy from noise-like (180 s), a weak
broad signal (360 s), and then into a
strong sharp signal with harmonics
(570 s). The quotes around “a” and
“this” indicate another problem we
were trying to solve. Is there one Hum
source that generally affects the whole
community or are there several more
localized Hum sources?
Figure 1c shows the recording at a
different house on a later date. The
Hum was 44 Hz with no overtones. It
was accompanied by a 25-s periodic
signal that swept from 19 to 23 Hz (see
Figure 1d).
Normal industrial sound analysis tools
use a one-third harmonic analysis
approach. They examine power levels in
“harmonically related” standard fre-
quency bands. These types of programs
are better designed to answer specific
questions about previously identified
industrial noise sources. We wanted to
find out if we could identify whether
there are one or more similar noise
sources present.
SOUND RECORDING
AND ANALYSIS
Working with Patching, we wanted to
use existing and analytical tools to iden-
tify the Hum’s presence within a given
acoustic recording. Then we planned to
switch to a higher-resolution signal
analysis approach to identify the “sound
ecology” of the sound signatures
recorded on different days in different
parts of the community.
The first step was to obtain more
sound recordings and analysis per-
formed in the community. We consid-
ered modifying the analysis program of
the “SnoreRecognizer” mobile phone
application demonstrated in the two-
part article series “Mobile Application
Development” (Circuit Cellar 245, 2010,
and 246, 2011). However, we thought it
would be easier to have residents
record the sound and submit it to us for
further analysis.
Photo 1—These screenshots show the key
Microsoft SQL Server Express installation
stages.
a)
b)
c)
d)
e)
36
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® •circuitcellar.com
alternative controller to assist the
disabled.
Working on these projects made
us recognize one key thing: The
Mind2Sail, the Hum, and the
SnoreRecognizer are all investiga-
tive research projects that involve
the systematic application of digi-
tal-signal processing (DSP) algo-
rithms to data collected from
many sources.
A BENEFICIAL
INTERFACE
Many Circuit Cellar readers
may be familiar with using C,
C++, or MATLAB code to develop
algorithms to analyze DSP data.
MATLAB and other programming
languages typically provide an
interface that enables you to use
a server query language (SQL)
for database server interrogation.
Indeed, after a couple of
months, a “technologically savvy”
reader will begin to recognize
some similarity between the
behavior of SQL commands and
the vectorization present in
MATLAB and other languages to
handle simultaneous operations
on all elements of a matrix. How-
ever, if you don’t have several
months to learn the basics, our
DSP-SQL interface may help you
develop a DSP project that
accesses a server database.
FINDING AND
INSTALLING A SERVER
Once the research development
is completed, we will need to
move the results from the
Mind2Sail and Hum projects out
into the volunteer community. To
reduce costs, we based the DSP-
SQL interface on Microsoft’s SQL
Server Express, which is available
for a free download from Microsoft’s website (see the Resources
section at the end of this article).
You need to download ENU\x86\SQLEXPRWT_x86_ENU.exe
to install the server on an XP machine or a Windows 7 32-bit
laptop. You need to download ENU\x64\SQLEXPRWT_x64_
ENU.exe for a Windows 7 64-bit machine.
The following instructions and screenshots will enable you to
set up a basic server configuration: Running the SQLExpress
installer, you will see the Installation Screen shown in Photo 1a.
Launch the new SQL Server wizard. The SQL Server Setup
files will be installed and updated if you read and accept the
license terms. This brings you to the Feature Selection screen
(see Photo 1b). Clicking Next automatically downloads the
default configuration. This brings you to the Configuration
screen. Set “Named Instance” to “HOME_SQLEXPRESS,” then
press Next, which causes the “Instance_ID” to default to the
same name. This brings you to the Connect-to-Server screen
(see Photo 1c). Since we were running a password-protected
stand-alone machine, we simply needed to click Connect.
Click through the Server Configuration and Database Engine
Listing 1—Calls to the DSP-SQL interface from the MATLAB script DSPSQL_main.m enable the user to
connect to the database server (line 4), gathering or retrieving DSP data information from a variety of
input sources (lines 7–10), and using various analysis methods to characterize the DSP data (lines
12–15). Lines 17–19 generate a comparison report that shows the relative success of specific database
algorithms. The MainDataTable.m script uses various DSPQSL_Dataclass methods to check if a data
table already exists on the server (lines 32–35). If not, it fills the data table with a default number of
recordings from a recording device.
1 function DSPSQL_main( ) % DSPSQL_main.m
2 debugDSPSQL = 1; % ACTIVATE DSPSQL DEBUG MODE
3 % CONNECT TO DATABASE SERVER USING DSP_SQL_DATABASE CLASS
4 dbObject = DSPSQL_Database(‘localhost\SQLEXPRESS’, ‘CCArticle’, ...
’Trusted_Connection=Yes’, debugDSPSQL); % NO SPACES AROUND = SIGN
5
6 % STORE OR RETRIEVE THE DSP SIGNALS FROM THE MAIN ‘DSP DATA TABLE’
7 MainDataTable(dbObject, ‘SimulatedSnores’, ‘CHIRP’);
8 % MainDataTable(dbObject, ‘Mind2Sail’, ‘EEG’);
9 % MainDataTable(dbObject, ‘RecordedPhrases’, ‘VOICE’’);
10 % ETC.
11 % PERFORM COMPARATIVE ANALYSIS VIA FUNCTION POINTERS
12 PerformAnalysis(dbObject, ‘SimulatedSnores’, ‘Correlation’, @Correlation);
13 % PerformAnalysis(dbObject, ‘SimulatedSnores’, ‘PowerFreqBands’, ...
% @PowerFreqBands);
14 % PerformAnalysis(dbObject, ‘Mind2Sail’, ‘Correlation’, @Correlation);
15 % ETC.
16 % GENERATE COMPARATIVE REPORTS
17 ComparisonReport(dbObject, ‘SimulatedSnores’, ...’Correlation’,
@Correlation); %, ‘PowerFreqBands’, @PowerFreqBands);
18 % ComparisonReport(dbObject, ‘Mind2Sail’, ...% ‘Correlation’, @Correlation,
‘PowerFreqBands’, @PowerFreqBands);
19 % ETC.
20 end
30 function MainDataTable(obj, dataTable, recordingDevice)% MainDataTable.m
31 % RETURN IF THE DATA TABLE ALREADY EXISTS
32 if DSPSQL_TableExists(obj, dataTable)
33 fprintf(‘Data table <%s> exists\n’, dataTable);
34 return;
35 end
36 % OTHERWISE ADD A NEW DATA TABLE TO THE SERVER DATA BASE
37 % DEFAULT FIELDS ‘Record_ID’ , ‘Capture_Date ‘ TO BE ADDED AUTOMATICALLY
38 DSPSQL_AddNewTable(obj, dataTable , ‘CommandNumber’,...’ExampleNumber’,
‘SampleRateHz’, ‘RecordedData’, ‘BLOB’);
39 % FILL THE TABLE WITH NEW DSP INFORMATION FROM THE RECORDING DEVICE
40 for numCommand = 1 : 4 % DEFAULT TO AN INITIAL SET OF 4 COMMANDS
41 for numExample = 1 : 6 % WITH 6 EXAMPLES OF EACH COMMAND
42 recording = GetDeviceRecording(recordingDevice, ... numCommand,
numExample);
43 DSPSQL_NewRecord(obj, dataTable , numCommand, numExample,
...recording.sampleRateHz, recording.data);
44 end
45 end
46 end
37
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
Configuration screens. This will enable you to tell Microsoft
about Windows and SQL Server Error system crashes. We
declined and were presented with the Complete screen. The
final step is to add a specific database to the server. Activate
the SQL Server Management
Studio from the start menu (see
Photo 1d). Right click on the
Databases Menu Item and
select New Database. On the
New Database screen, enter
CCArticle then click OK, not
Add. You are good to go if your
screen looks something like
what is shown in Photo 1e. Click
on the + icon near CCArticle to
see the database’s default con-
figuration. As we will explain
later, knowing the way to the
CCArticle | Tables icon will
prove useful following SQL
errors.
USING THE DSP-SQL
INTERFACE
One way to make research
ideas a reality is to visualize and
then use the ideal product. This
is a variation of test-driven
development (TDD), where you
imagine the code for a product
already exists and start testing it
(see the two-part article series
“Practical Application for TDD,”
Circuit Cellar 176 and 177,
2005). You only need to under-
stand about a half-dozen SQL-
related commands and concepts
to get reliable access information
from a database. However, the
devil is in the details. Therefore,
we decided to develop a
DSP-SQL interface that would
hide details from the inexperi-
enced user.
The interface needed to be
flexible to enable more powerful
SQL commands to be issued for
more experienced users. Listing 1
shows the visualized main func-
tion, DSPSQL_main( ), for the
project code. This code demon-
strates connecting to a database
to enable storage of simulated
and actual DSP signals from our
external embedded system
recording devices. The data is
then retrieved from the SQL serv-
er and some basic statistical
analysis is performed on the signals before performance results
are reported.
The first command issued from MATLAB (Listing 1, line 4)
calls the DSPSQL_Database( ). This establishes a connection to
Listing 2—Lines 110–118 show the basic principles of generating simulated snores (i.e., chirps). Lines
120–127 show how audio phrases are captured from a microphone. The process of communicating via
semaphores and messages to an external Mindwave AP () to capture real-time EEG data is shown in lines
130–158.
100 function recording = GetDeviceRecording(recordingDevice, ... numCommand,
numExample)
101 fprintf(‘Inputting <command %d> example %d from device %s\n’, ... numCommand,
numExample,recordingDevice);
110 if strcmp(recordingDevice, ‘CHIRP’) % SIMULATED SNORES WITH CHIRPS
111 recording.sampleRateHz = 44000;
112 deltaT = 1 / recording.sampleRateHz; % SAMPLE INTERVAL
113 % SETCHIRP CHARACTERISTICS AND GENERATE RECORDING
114 startFrequency = 1000 * (1 + numCommand + (rand(1) ‐ 0.5);
115 centreFrequency = startFrequency + 1500;
116 time = 0 : deltaT : (4096 ‐ 1) * deltaT;
117 approxHalfTime = 2048 * deltaT;
118 recording.data = chirp(time, startFrequency, approxHalfTime, centreFrequency);
120 elseif strcmp(recordingDevice, ‘VOICE’) % GRAB AUDIO FROM A MIKE
121 recording.sampleRateHz = 44000 / 8; % SET AUDIO INFORMATION
122 sampleBitSize = 24;
123 numChannels = 2;
124 recordingLength = 2; % RECORD 2 SECONDS
124 % USE MATLAB INBUILT FUNCTIONALITY
125 recordingObject = audiorecorder(recording.sampleRateHz, ... sampleBitSize,
numChannels);
126 recordingObject.recordblocking(recordingLength);
127 recording.data = recordingObject.getaudiodata( );
130 % IN PRACTICE, WE USED A NEUROSKY API TO CAPTURE MINDWAVE EEG DATA
131 % AND DIRECTLY STORE INTO THE DATABASE USING A C_SQL INTERFACE
132 % WITH A SIMILAR APPROACH USED FOR THE HUM DATA
133 % THE FOLLOWING DEMONSTRATES AN APPROACH TO DYNAMICALLY
134 % CAPTURE NEW EEG DATA
135 elseif strcmp(recordingDevice, ‘EEG’)
136 % USE MESSAGES TO COMMUNICATE WITH EXTERNAL CAPTURE PROGRAM
137 pause(5); % WAIT FOR SEMAPHORE THAT EEG DEVICE IS READY
138 while IsReady(‘EEGCapture\Message’) ~= 1;
139 pause(5); % HARD CODE PAUSES IN PROTOTYPE TO AVOID DATA RACES
140 end
141 fileID = fopen(‘EEGCapture\Message’, ‘rt’); % REQUEST NEW SAMPLE
142 fprintf(fileID, ‘0, %d, %’, numCommand, numExample);
143 fclose(fileID);
144 pause(20); % WAIT FOR SEMAPHORE THAT NEW EEG DATA IS READY
145 while IsReady(‘EEG\EEGCapture\Message’) ~= 1;
146 pause(20);
147 end
148 fileID = fopen(‘EEGCapture\Message’, ‘rt’);
149 fgets(FID); % IGNORE THE SEMAPHORE ON THE FIRST LINE
150 recording.sampleRateHz = fscanf(‘%f’, fgets(fileID));
151 numPtsRecorded = fscanf(‘%d’, fgets(fileID));
152 recording.data = zeros(1, numPtsRecorded);
153 for count = 1 : numPtsRecorded
154 recording.data(count) = fscanf(‘%f’, fgets(fileID));
155 end
156 fclose(fileID);
157 end
158 end
B
o
o
ks
The world of electronics
at your fi ngertips!
Elektor.STORE
BOARDS, BOOKS, DVDs AND MORE AT WWW.ELEKTOR.COM/STORE
OS Hard- and Software for Electronics Applications
Open Source Electronics on Linux
If you have ever wanted to take advantage of the expanding fi eld of open source software for
electronics and everyday applications, this book is for you. Using the Linux OS, Warwick A. Smith
guides you through the world of open source hardware and software, teaching readers to use EDA
tools and software that is readily available online, free to download. The hardware projects inside
can be built using easily obtainable parts, in the comfort of your own home, on single sided PCBs,
or professionally manufactured with output fi les generated by you. Open Source Electronics on
Linux is about changing today’s electronics enthusiast into empowered, savvy, discerning engi-
neers capable of building and modifying their creations, be it solely on Linux or in tandem with
your current operating system.
272 pages • ISBN 978-1-907920-19-6 • $47.60
NEW
!
This book and mo
re
are available at
www.elektor.com
/store
Learning to fl y with Eagle
Eagle V6 Getting Started
Guide
The book is intended for anyone who wants an
introduction to the capabilities of the CadSoft’s
Eagle PCB design software package. The reader
may be a novice at PCB design or a professional
wanting to learn about Eagle , with the inten-
tion of migrating from another CAD package.
After reading this book while practicing some
of the examples, and completing the projects,
you should feel confi dent about taking on more
challenging endeavors. This book is supplied
with a free copy of Eagle on CD-ROM for
MS Windows, Linux and Mac.
208 pages • ISBN 978-1-907920-20-2 • $47.60
th Eagleh l
Bestseller!
10 captivating lessons
PIC Microcontroller
Programming
Using the lessons in this book you learn how to
program a microcontroller. You’ll be using JAL, a
free but extremely powerful programming lan-
guage for PIC microcontrollers. Starting out from
scratch virtually, you slowly build up the knowl-
edge. Assuming you have absorbed all lessons
— meaning you have actually completed all the
exercises — you should be confi dent to write PIC
microcontroller programs, as well as read and
understand programs written by other people.
284 pages • ISBN 978-1-907920-17-2 • $47.60
0 i i l
http://www.elektor.com/store
http://www.elektor.com/store
C
D
/D
V
D
-R
O
M
s
K
its &
M
o
d
u
les
Elektor US
111 Founders Plaza, Suite 300
East Hartford, CT 06108
USA
Phone: 860.289.0800
Fax: 860.461.0450
E-mail: order@elektor.com
Elektor is more
than just your favorite
electronics magazine.
It’s your one-stop shop
for Elektor Books,
CDs, DVDs,
Kits & Modules
and much more!
www.elektor.com/store
TAPIR
Sniffs it Out
Attention boy scouts, professionals and
grandfathers! This ultrasensitive wide-
band E-smog detector offers you two extra
senses to track down noise that’s normally
inaudible. TAPIR - short for Totally Archaic
but Practical Interceptor of Radiation - also
makes a nice project to build: the kit
comprises everything you need - even the
enclosure, ingeniously consisting of the
PCB proper. Using the TAPIR is dead easy.
Connect the headphones and an antenna
and switch it on. Move it around any elec-
trical device and you’ll hear different noises
with each device, depending on the type
and frequency of the emitted fi eld.
Kit of parts
Art.# 120354-71 • $21.50
140 Min. Video Presentation
DVD Masterclass Feedback
in Audio Amplifi ers
In this Masterclass we address several aspects
of feedback in audio amplifi ers. The focus, al-
though not entirely math-free, is on providing
insight and understanding of the issues in-
volved. Presenter Jan Didden provides a clear
overview of the benefi ts that can be obtained
by feedback and its sibling, error correction;
but also of its limitations and disadvantages.
Recommended to all audio designers and
serious audio hobbyists!
ISBN 978-1-907920-16-5 • $40.20
40 Mi Vid P t ti
DVD Elektor 2012
The year volume DVD/CD-ROMs are among the
most popular items in Elektor’s poduct range.
This DVD-ROM contains all editorial articles
published in Volume 2012 of the English,
Ame rican, Spanish, Dutch, French and German
editions of Elektor. Using the supplied Adobe
Reader program, articles are presented in the
same layout as originally found in the magazine.
An extensive search machine is available to
locate keywords in any article. With this DVD
you can also produce hard copy of PCB layouts
at printer reso lution, adapt PCB layouts using
your favourite graphics program, zoom in / out
on selected PCB areas and export circuit dia-
grams and illustrations to other programs.
ISBN 978-90-5381-273-0 • $37.90
More than 75,000 components
CD Elektor’s Components
Database 7
This CD-ROM gives you easy access to design
data for over 11,100 ICs, 37,000 transistors,
FETs, thyristors and triacs, 25,100 diodes and
2,000 optocouplers. The program package con-
sists of eight databanks covering ICs, transistors,
diodes and optocouplers. A further eleven ap-
plications cover the calculation of, for example,
zener diode series resistors, voltage regu lators,
voltage dividers and AMV’s. A colour band de-
coder is included for determining resistor and
inductor values. All databank applications are
fully interactive, allowing the user to add, edit
and complete component data. This CD-ROM is
a must-have for all electronics enthusiasts!
ISBN 978-90-5381-298-3 • $40.20
M th 75 000 t
Elektor Linux Board
Extension
This extension board was developed to further
propel our Embedded Linux series of articles
and the matching GNUblin board. It has a dis-
play, buttons, a real time clock and 16 GPIOs.
Linux devotees, switch on your solder irons.
The Linux extension board includeseverything
needed to provide the user interface for a wide
variety of projects!
Module, SMD-populated and tested board,
incl. LCD1, X1, K1-K4, BZ1, BT1 for home assembly
Art.# 120596-91 • $50.20
A whole year of Elektor magazine onto a single diskkt i t i l di
Bestseller!
Elekttor Linux Board
TAPIR
A t # 120596 91 $50 20
TAPIR
Art.# 120596-91 • $50.20
t
Back in Stock!
http://www.elektor.com/store
mailto:order@elektor.com
40
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
the SQLExpress database and
returns an instance of the database
object dBObject, from our MATLAB
DSPSQL_Database class. Next, calls
are needed to MainDataTable()
(lines 7–9) for various recording
devices. This enables the user to
build a new, or retrieve an existing,
MainDataTable from the database.
Then calls to DSPSQL_main (lines
12–14) use a variety of different
DSP algorithms to generate a
series of AnalysisTables. The
AnalysisTables can then gener-
ate ComparisonReports on the
algorithm (lines 17–19).
Tables are a key element for any
SQL database development. A table
is made of fields (columns) and
data the user has placed, record by
record, into the table rows associat-
ed with those fields.
With the Mind2Sail application,
we chose the following fields for the
main table in the database that
stored all the captured data:
Record_ID, a unique identifier or
key associated with each record, data row, present in the table;
ExampleNumber and CommandNumber to identify the examples
(recordings) of the various EEG commands we had captured;
CaptureDate and SamplingRateHz to store basic information
about the data captured by NeuroSky’s MindBand BCE inter-
face; and RecordedData, which is the EEG data.
We used equivalent fields when testing the system by using
audio-chirp signals to mock (mimic) the SimulatedSnores
analysis and using audio phrases to test ideas for analyzing
EEG signals. The Hum project required us to replace the
CommandNumber with a CodeNumber for each particular Ranch-
land resident. This ensured the anonymity needed to meet
the University of Calgary’s ethics approval requirements.
Listing 1 shows the MainDataTable.m script, which uses
DSPSQL_Database class method DSPSQL_TableExists( ) (line
32) to check if the server already holds the data table. If it is
not there, we create a new data table with the information fields
we want to use, DSPSQL_AddNewTable( ), which is shown in
line 38. The DSPSQL interface automatically adds the default and
critical Record_ID and Create_Date fields.
Listing 1 shows the final lines (40–45), which call Get
DeviceRecording( ) to capture a default number of example
recordings of each of the commands we want to investigate.
Finally, line 46 shows the newly captured experimental data,
which is placed onto the server as a new record,
DSPSQL_NewRecord( ).
GetDeviceRecording( ) uses built-in MATLAB commands
to generate the simulated snores (CHIRP, lines 110–118,
etc.) and capture audio phrases (VOICE, lines 120–128) to
mimic the more complex EEG signals. Actual, rather than
simulated, Mind2Sail and Hum signals were gathered by
external programs that used other interfaces to place data
directly onto the server. Listing 2, lines 130–158, shows how
semaphores and messages were used to dynamically capture
these signals to enable immediate analysis.
WORKING WITH A RECORD
SQL seems much like other programming languages (e.g.,
C/C++). The first similarity is that the database record acts as
an array of SQLField where each element is a struct:
struct SQLField{
char SQLFieldName[ ];
char SQLTypeInfo[ ];
SQLType experimentalData[row][ ];
}
There are many SQL data types. In an embedded system, the
flexibility of using integer-type nibbles, bytes, half words, words,
long words, and so forth is all about minimizing the amount of
system memory used, which leads to increased profits. The
availability of many SQL data types, TINYINT, SMALLINT, INT,
and BIGINT, again is related to minimizing memory usage. How-
ever, their purpose is to increase access speed.
Be careful: SQL Float types are not the same as Decimal
types. In an embedded system, you would think about using
31:1 or 16:16 fixed-point arithmetic, depending on where
you wanted to put the (implied) binary point into the integer
stored in memory. The idea is extended to numeric values
with the DECIMAL[p;s] SQL data types. Here p (the preci-
sion) specifies the total number of digits that can be stored
and s (the scale) specifies the number of digits that can
Listing 3—The SerializeData method WriteToBytes( ) (lines 230–237) converts numerical values into
a byte array, BLOB, the byte equivalent of the MATLAB function sprintf( ). In the byte equivalent of
MATLAB function sscanf( ), the method GetObjectFromBytes (lines 240–245) converts the byte array
back into numerical values.
200 import java.io.*;
210 public class SerializeData implements Serializable {
211 private Object o;
220 public SerializeData(Object obj) { o = obj; }
230 public static byte[] WriteToBytes(Object obj) {
231 SerializeData sd = new SerializeData(obj);
232 ByteArrayOutputStream baos = null;
233 baos =new ByteArrayOutputStream( );
234 ObjectOutputStream out = new ObjectOutputStream(baos);
235 out.writeObject(sd);
236 return baos.toByteArray( );
237 }
240 public static Object GetObjectFromBytes(byte[ ] buf) {
241 SerializeData data = null;
242 ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(buf));
243 data = (SerializeData) in.readObject( );
244 return data.getObject( );
245 }
250 private Object getObject( ){ return o; }
260}
41
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
occur after the decimal point. Decimal precision can range from
5 to 17 bytes. SQL FLOAT[p] values also have an associated pre-
cision and are stored as 32-bit values (4-byte, single-precision p
is less than 25) or 64-bit values (8-byte, double-precision p is
greater than 25).
USING A BINARY LARGE OBJECT
It’s fairly straightforward to add a single integer or float val-
ues into a SQL server database table. However, it’s not easy to
add a DSP signal array cap-
tured by your embedded sys-
tem. Direct SQL access to
each element in an N-point
array requires adding new N
fields to our data table. Gen-
erating such a large file is
unlikely to enable fast access
to a Hum record that is many
minutes, perhaps hours, in
length!
The solution was to use a
binary large object (BLOB), or
serialized field. Using BLOBs
and normal fields requires the
SQL equivalent knowledge to a
C/C++ programmer perform-
ing binary file I/O, fread( )
and fwrite( ), or text file
I/O, fputs( ) and fgets( ).
However, all the requests for
help on the MATLAB user
group pages hint that BLOBs
require some fancy bit mani-
pulating inside the MATLAB
environment because of their
special SQL varbinary[ ]
syntax.
The solution to something
this difficult proved trivial
since we had our own “indus-
trial-experienced SQL expert.”
Maddie took advantage of the
MATLAB Java interface to
develop SerializeData.jar
(see Listing 3). This script
essentially takes something
that should be standard in
MATLAB and externalizes it
into an environment (e.g.,
Java), where it is actually
standard.
In the Java method,
WriteToBytes( ), a new
ByteOutputStream is set up
(lines 230–237) and used to
convert the input object to a
byte array. This is analogous
to setting out a new string
output stream in MATLAB and using:
outputString =
sprintf(‘%d’, inputValue);
to convert a numerical object into a string. The Java method
GetObjectFromBytes( ) works on byte arrays by using the Java
Byte ArrayInputStream (lines 240–245) in an equivalent
manner to a MATLAB programmer converting a string back to
Listing 4—These are the DSPSQL_Database class’ key elements. In lines 311–321, the constructor
DSPSQL_Database( ) sets up communicationwith a specified SQL Express server. Lines 330–357 show the key
method DSPSQL_SendSQLQuery( ), which can be used to send specific SQL queries to the database server.
300 classdef DSPSQL_Database < handle
301 properties (GetAccess=private)
302 connection
303 debugDSPSQL
304 end % PROPERTIES
310 methods
311 function obj = DSPSQL_Database(serverName, ...
schemaName, authentication, debugDSPSQL_arg);
312 obj.connection = actxserver(‘ADODB.Connection’);
313 obj.debugDSPSQL = debugDSPSQL_arg;
314 javaaddpath(pwd); % SET UP PATH TO SERIALIZEDATA.CLASS
315 connectSQLReq=sprintf(‘Provider=SQLOLEDB;Data Source=%s;Initial
Catalog=%s;%s’,... serverName, schemaName, authentication);
316 try % TRY TO CONNECT TO SERVER
317 obj.connection.Open(connectSQLReq);
318 catch ME
319 error(getReport(ME));
320 end
321 end
330 function result = DSPSQL_SendSQLQuery(obj, query)
331 errorOccurred = 0;
332 cmd = actxserver(‘ADODB.Command’); % GET A CONNECTION
333 try
334 cmd.ActiveConnection = obj.connection;
335 catch % KNOWN MATLAB BUG – WILL ALWAYS FAIL ‐‐
336 end% IGNORE IT
337 cmd.CommandText = query;
338 try
339 recordSet = cmd.Execute();
340 catch EH
341 if obj.debugDSPSQL == 1 % GOT TOO FANCY AND TRIED INVALID SQL QUERY
342 fprintf(‘Unrecognized SQL Query: %s\n\n%s\n’, query, getReport(EH));
343 recordSet = 0;
344 errorOccurred = 1;
345 else
346 rethrow(EH); % IGNORE ERROR ‐‐ RETURN 0
347 end
348 end
349 if errorOccurred
350 result = 0;
351 else
352 if recordSet.state ~= 1
353 result = 1; % NO RECORD EXISTS
354 else
355 result = recordSet;% RETURNED A VALID RECORD SET FROM DATA BASE
356 end
357 end
590 end
In Listing 2, line 42, DSPSQLNewRecord( ) was used in
GetDeviceRecording( ) to add newly captured recordings
to the server MainDataTable. This function first determines
the largest value of Record_ID, which is used to uniquely
identify (i.e., act as a key) each record set stored in the
table (Listing 5, lines 386–393). This requires the use of the
SQL server-side procedure MAX( Record_ID)) used inside
the SQL command SELECT ... FROM tableName (Listing 5,
line 387).
The INSERT INTO tableName SQL command uses a string
of the form VALUES ( fieldValue1, fieldValue2, ...,
..., ?) to store the new values into the table (Listing 5,
42
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
a value:
outputValue = sscanf(‘%d’,
inputString);
SOME SERIOUS SQL
CONCEPTS
Note: Readers who prefer to
just use our DSP-SQL interface
to retrieve, analyze, and report
on the experimental data might
consider skimming over the SQL
details in this section.
Listing 4 shows the details of the
DSPSQL_Database class construc-
tor, which uses a MATLAB
ACTIVE_X server object (line 312)
when attempting to connect to the
SQL_Express server. Line 315
shows the construction of a
connectSQLRequest string to
identify the server, the database
on that server, and the password
information.
In Listing 1, line 4, these
parameters were set as local
host\SQLEXPRESS, CCArticle,
and Trusted_Connection=Yes. If
there are spaces around the
equals sign in the Trusted
Connection string, the request
will fail.
In Listing 4, DSPSQL_SendSQL
Query( ) is the key method for
communicating between MATLAB
and the server. First, a
ActxServerObject( ) is gener-
ated (line 332) and pointed
toward the established server
connection (line 334). This imme-
diately triggers a known MATLAB
bug, which is ignored via a
try-catch-end structure (lines
333–336).
The required SQLQuery is then
sent to the server (line 339),
which returns a recordSet, or the error response EH, which is
shorthand for NO_IDEA_WHAT_YOU_WANT? If the debugDSPSQL
flag is set, then details of the problem are printed out (lines
341–348).
Listing 5 shows how our DSP-SQL interface hides a lot of the
details around client-server communications. DSPSQL_Table
Exists( ) uses the OpenSchema( ) method of the ActiveX
class to get a recordSet listing of all tables on the server (line
361). As shown in Listing 1, line 36, a new table can be added
by calling the method DSPSQL_AddNewTable( ). This creates a
properly formatted CREATE TABLE query (Listing 5, lines
371–376) to send to the server (line 377).
Listing 5—Other key methods of the DSPSQL_Database class hide the specifics of the SQL comments needed
to communicate with the server-side SQL Express: lines 360–368, DSPSQL_TableExists( ); lines 370–371,
DSPSQL_AddNewTable( ); and lines 380–406, DSPSQL_NewRecord( ).
360 function tableExists = DSPSQL_TableExists(obj, tableName)
361 recordSet = obj.connection.OpenSchema(‘adSchemaTables’).GetRows;
362 tableNames = recordSet (3,ismember(recordSet (4,:),’TABLE’));
363 if ~ismember(tableName, tableNames)
364 tableExists = 0;
365 else
366 tableExists = 1;
367 end
368 end
370 function DSPSQL_AddNewTable(obj, tableName, varargin)
371 SQLQuery = sprintf(‘CREATE TABLE dbo.%s (Record_ID float’, tableName);
372 % LAST FIELD OF DSP_SQLRECORD IS ALWAYS A DATA ARRAY STORED AS A BLOB
373 for temp = 1 : (nargin‐4)
374 SQLQuery = sprintf(‘%s,%s float’, SQLQuery, varargin{temp});
375 end
376 SQLQuery = sprintf(‘%s,%s varbinary(max) )’, SQLQuery, varargin{nargin ‐ 3});
377 obj.DSPSQL_SendSQLQuery(SQLQuery); % PASS SQLQuery TO SERVER
378 end
380 function newRecordNumber = DSPSQL_NewRecord(obj, tableName, varargin)
381 cmd = actxserver(‘ADODB.Command’); % Make this part of the constructor
382 try
383 cmd.ActiveConnection = obj.connection;
384 catch % IGNORE KNOWN MATLAB BUG
385 end
386 % FIND Record_ID OF LAST RECORD IN TABLE
387 SQL_Query = sprintf(‘SELECT MAX(Record_ID) FROM dbo.%s’, tableName);
388 cmd.CommandText = SQL_Query;
389 lastID = cmd.Execute().GetRows{1};
390 if isnan(lastID) %
391 lastID = 0;
392 end
393 newRecordNumber = lastID + 1;
394 SQL_Query = sprintf(‘INSERT INTO dbo.%s VALUES(%d’, ... tableName,
newRecordNumber); % IMPROVE BY INSERTING DATE
395 % STORE ALL FIELDS BUT THE LAST FIELD, A DSP DATA ARRAY BLOB, AS FLOATS.
396 for temp = 1:(nargin‐3)
397 SQL_Query = sprintf(‘%s,%f’, SQL_Query, varargin{temp});
398 end
399 % MAGIC BACKDOOR WHEN TELLING SERVER ABOUT BLOBS
400 SQL_Query = sprintf(‘%s,?’, SQL_Query);
401 BLOBdata = SerializeData.WriteToBytes(varargin{nargin‐2});
402 cmd.Parameters.Append(cmd.CreateParameter(‘’, 205, 1, ‐1, BLOBdata’));
403 % SEND SQL_Query OF TO THE SERVER
404 cmd.CommandText = sprintf(‘%s)’, SQL_Query);
405 cmd.Execute();
406 end
43
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
lines 394–402). The special marker ? (line 400), is a signal
to the server that a BLOB, rather than a numeric value,
needs to be stored at this server table location. This is han-
dled by first serializing the data array, (line 401) then plac-
ing the array on the server via a special back door
cmd.Parameters.Append ( ) byte stream (line 402). Other
useful DSPSQL interface methods, together with this article’s
demonstration code, are available on Circuit Cellar’s FTP site.
WHAT HAVE WE LEARNED?
In the first part of this article series, we discussed three
projects requiring a similar type of analysis. What these
research investigations have in common is a need to store a
large amount of externally collected digital data for future
analysis and comparison. We outlined how to set up a DSP
project that combines MATLAB and SQL into a database on a
server, enabling data to be accessed simply and efficiently.
We provided a brief overview on how to use the DSP-SQL
interface and discussed how to place external data into an
SQL database as a record entry.
We also discussed BLOB fields and how they can be used
to enable fast access of stored large DSP data arrays with a
little bit of file I/O knowledge. We developed an easier
method to manipulate BLOBs by using the MATLAB Java
interface to develop the SerializeData class. For those
interested in the nuts and bolts behind the server-side oper-
ations, we added a little extra information about how
advanced SQLconcepts interact with the MATLAB ACTIVE_X
server.
In Part 2 of this series, we will discuss how to develop DSP-SQL
analysis functions that access the stored database information.
We will also describe additional DSP-SQL methods needed to
support the DSP-SQL interface. Using these additional func-
tions, we will show how we used a receiver operating charac-
teristic (ROC) approach to determine the effectiveness of our
proposed analysis methods to distinguish between similar and
dissimilar DSP signals. I
Author acknowledgements: Financial support was provided
through a Markin Undergraduate Health Scholarship (Maddie),
a Natural Sciences and Engineering Research Council (NSERC)
of Canada industrial postgraduate scholarship (Emily), and an
industrial collaborative research and development grant from
Analog Devices, CDL Systems, and NSERC (Mike). Additional
support was provided by NeuroSky and the University of
Calgary, Canada.
PROJECT FILES
To download the code, go to ftp://ftp.circuitcellar.com/
pub/Circuit_Cellar/2013/276.
RESOURCES
R. Kotchorek, M. Smith, and V. Garousi, “Mobile Applica-
tion Development (Part 1): Program a Sound-Monitoring
Prototype,” Circuit Cellar 245, 2010.
———, “Mobile Application Development (Part 2): A
Sound-Detection Algorithm,” Circuit Cellar 246, 2011.
Microsoft Corp., “Microsoft SQL Server 2012 Performance
Dashboard Reports,” www.microsoft.com/en-us/download/
details.aspx?id=29063.
NeuroSky, www.neurosky.com.
Patching Associates Acoustical Engineering, Ltd.,
www.patchingassociates.com.
M. Smith, et al, “Practical Application for TDD (Part 1): Write
Software in a Test-Driven Development Environment,”
Circuit Cellar 176, 2005.
———, “Practical Application for TDD (Part 2): Automated
Test-Driven Environment,” Circuit Cellar 177, 2005.
M. Smith, T. Turner, and S. Alvey, “Voice Recognition
Controlled Sailboat: Speech-Recognition Control Aids
Disabled Sailors,” Circuit Cellar Ink 113, 1999.
SOURCES
ECM8000 Measurement condenser microphone
Behringer | www.behringer.com
MATLAB Programming language
MathWorks, Inc. | www.mathworks.com
Emily Marasco (eamarasc@ucalgary.ca) is a graduate student in
Electrical Engineering at the Schulich School of Engineering, Calgary,
Canada. She obtained her undergraduate degree in Computer
Engineering with a minor in Music from the University of Calgary in
2011. Her research interests include engineering education and
cross-disciplinary curriculum development.
Mike Smith (Mike.Smith@ucalgary.ca) is a professor in Electrical
and Computer Engineering at the Schulich School of Engineering,
Calgary, Canada. He published his first Circuit Cellar article in
1992, and has continued to publish many more articles over the last
20 years. His interests include embedded systems, software, and
biomedical and rehabilitation engineering.
Maddie Lowe (Maddie.Lowe@ucalgary.ca) will return from her
internship’s third year to complete her Software Engineering
degree (specializing in biomedical) at the Schulich School of
Engineering, Calgary, Canada. She intends to pursue a career
developing bionics when she graduates in June 2014.
“You only need to understand about a
half-dozen SQL-related commands and
concepts to get reliable access
information from a database. However,
the devil is in the details. Therefore,
we decided to develop a DSP-SQL
interface that would hide details from
the inexperienced user.”
mailto:eamarasc@ucalgary.ca
mailto:Mike.Smith@ucalgary.ca
mailto:Maddie.Lowe@ucalgary.ca
ftp://ftp.circuitcellar.com/pub/Circuit_Cellar/2013/276
http://www.microsoft.com/en-us/download/details.aspx?id=29063
http://www.neurosky.com
http://www.patchingassociates.com
http://www.behringer.com
http://www.mathworks.com
44
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
echnology develops at breakneck speed. Today there
is no sensible use for an 8-bit, 64-KB computer with
less processing power than a mobile phone. Yet, a lively
“retrocomputing” subculture has existed ever since the
8080, the Z80, the 6809, and the 6502 processors faded
from view.
In the early 1990s, nostalgic users wrote software emulators
to relive the “vintage” experience of their old Commodore 64
or Apple II. Others preferred the actual hardware and began
collecting classic computers. As their old machines occasionally
broke down, people began cultivating the art of computer
diagnosis and repair into a new form of retrocomputing.
RETROCOMPUTING
Next to software emulation and hardware maintenance, a
third strain of retrocomputing has emerged: designing and
building your own system from a “bag of chips” and a circuit
board. It is easy to create a functional computer on a little cir-
cuit board—considering all the information now available on the
Internet. These retro machines may not have much practical
use, but the learning experience can be tremendously valuable
(see Photo 1).
Hobbyists with no background in electronics somehow pick up
the required skills, and they often share their homebrewing
experiences online. Although some of their creations are stun-
ningly exotic, most people build simple machines. They use a
CPU and add RAM, ROM, a serial port, and maybe an IDE inter-
face for mass storage. And most hobbyists run either BASIC
(e.g., the 1980s home computers) or use a “vintage” OS such
as CP/M.
Running CP/M, in fact, is a nice target to work toward. A lot of
good software ensures your homebrew computer can do some-
thing interesting once it is built. As the predecessor of MS-DOS,
CP/M also provides a familiar command-line interface. And it is
simple. A few days of study are enough to port it to your circuit
board.
Still, one challenge remains: If you want homebrewing to be
an enduring hobby instead of a one-off project, you should
have some perspective beyond putting together a minimal
computer and switching it on. Working on your own, it can
become progressively more difficult to take the next steps (i.e.,
building graphics subsystems or using exotic processors) or to
add state-of-the-art microcontrollers to create “Frankenstein”
You can build your own computer on a small circuit board. This article describes
a simple single-board CP/M design that uses just one high-capacity RAM chip
and is compatible with a serial or PC terminal.
DIY Single-Board Computers (Part 1)
by Oscar Vermeulen (Switzerland)
and Andrew Lynch (USA)
T
FEATURE ARTICLE
Design and Expansion Options
Photo 1—Here is a homebrew N8VEM system with a single-board computer
(SBC) and disk/IDE card plugged into the ECB backplane. The ECB card on the
far right is a bus monitor, which adds classic “blinkenlights” to the system. In
front is a vintage-style hex keyboard/monitor. (Photo courtesy of Nik Brisevac,
The N8VEM Home Brew Computer Project)
45
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
There is nothing preventing you from
plugging in your own CPU board design.
But if you do, you’re not forced to
develop all the other expansion boards
on your own.
As the novelty of designing a simple
single-board computer (SBC) wears off,
you may prefer to focus your energy on
exploring graphics systems or ways to
hook up 8-bit machines on the Internet.
Or, you may want to jump into systems
software development and share your
experiences with a few hundred others.
Retrocomputing is not always backward-
facing. Making “Frankenstein” systems
by adding modern Parallax Propeller
chips or FPGAs to old hardware is a nice
way to gain experience in modern digital
electronics, too.
THE N8VEM SBC
At 10-cm × 16-cm (roughly 4” × 6”),
the N8VEM computer does not look par-
ticularly impressive (see Photo 2). How-
ever, it provides all the capabilities of an
early 1980s commercial microcomputer.
In fact, thanks to CP/M, it is software-
compatible with those microcomputers,
offering a range of good programming
languages (e.g., BASIC, C, Pascal, and
Assembler).Excellent editors (e.g., ZDE)
and word processors (e.g., WordStar) are
also available. You could also run simple
spreadsheets, databases and interactive
games (e.g., Zork).
The small-sized N8VEM makes one
concession to modern-day electronics: It
uses a single, high-capacity RAM chip. All
the other electronics are components
that would have been used “back in the
day” (e.g., simple 74LS logic chips, a Z80
microprocessor, and classic interface
chips). A battery backs up the N8VEM’s
memory; therefore, the RAM disk is a
systems (i.e., blends of old and new tech-
nology that can do something useful,
such as automate your home).
THE HISTORY OF N8VEM
This is where the N8VEM Google
group comes in. In 2006, Andrew Lynch
published his own single-board CP/M
design to engage and involve others. He
intended the N8VEM (named after his
ham radio license) to be expandable
with add-on cards. Soon after, an infor-
mal collaborative effort emerged around
a Google mail group. A website was set
up to share the hardware and software
produced.
Builders with a range of skills became
involved, from well-known systems
builders to beginners. They bought
Lynch’s $20 circuit board and ordered
the required electronic components and
a soldering iron from an online electron-
ics distributor. After two days of wielding
the soldering iron, they could create a
CP/M computer that uses ROM and RAM
disks for storage and has plenty of built-
in vintage software.
The design can be expanded into a
“powerful” (we use the term lightly here)
multiprocessor system with “blinken-
lights,” hard disks, graphics subsystems,
and various OSes. People also started to
build miniaturized variants, PC/XT clones,
and 32-bit machines.
However, N8VEM is not about soldering
kits. It is about joining in, trying new
things, and picking up skills along the
way. These skills range from reading
schematics to debugging a computer
card that does not operate as intended.
The learning curve may be steep at
times, but, because the N8VEM mail
group is very active, expert help is avail-
able if or when you get stuck.
Photo 2—This is the
N8VEM in its $20 stand-
alone incarnation. Even
without any other boards,
this SBC provides sufficient
I/O and storage options to
be a full-fledged CP/M
computer.
http://www.saeling.com
http://www.saelig.com
46
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
practical storage mechanism, especially because a ROM disk
comes with most essential software installed. Use the N8VEM
with a serial terminal, or (more likely) with a PC terminal pro-
gram. The XMODEM protocol enables files to be transferred to
and from the N8VEM.
The ECB bus is at the core of the N8VEM’s expansion options.
The N8VEM can plug into a “backplane” and access about two
dozen or so peripheral cards that have been created so far.
However, the first expansion option is actually not an ECB card
but the $5 parallel port IDE (PPIDE) mini board, which enables
the use of an IDE hard disk or a CompactFlash card. The costs
are minimal. Even an old 256-MB drive offers more storage
than CP/M software can reasonably fill.
The N8VEM is supported by an effective toolchain. Wayne
Warthen’s RomWBW project bundles many builders’ source
codes into a smooth-running CP/M system, supporting most
ECB peripherals out of the box. The EPROM also contains a ROM
disk that can be filled with your choice of applications. A suite
of utility programs, written by Douglas Goodall, enables easy
maintenance of hard drives and terminal settings. The well-
known SIMH emulator has an emulation mode for the N8VEM
system. Therefore, software can be developed from a modern
PC, tested on the emulator, and copied onto CompactFlash
images to run on the real machine.
GETTING STARTED: BOOKS AND TOOLS
Homebrewing is straightforward once you figure out how to
do things. That is why homebrewing as a group is so practical.
Still, two pieces of background information will prove indispen-
sable for any builder: an understanding of basic computer
hardware and Assembly language. Reading up on these topics
will not only make things easier, but will also help you under-
stand what you are putting together. (See the Resources sec-
tion at the end of this article for helpful information.)
Only a few tools are necessary. Although, for many, building
an electronics lab is part of the fun. A good soldering iron, an
inexpensive “solder sucker” to correct mistakes, and a multi-
meter are absolute requirements. A secondhand oscilloscope is
a useful additional tool. A logic analyzer can also be a big help
by enabling you to simultaneously inspect multiple signals and
determine what is wrong. Old logic probes are expen-
sive and cumbersome. New designs (e.g., Saleae’s
Logic 8-channel USB logic analyzer) are inexpensive
and better.
At some point you will need an EPROM program-
mer, unless you want to depend on others to burn
EPROMs for you. Ensure you have a programmer that
can deal with a range of (E)EPROMs, as N8VEM
boards use many types. Finally, a laboratory power
supply is a wise investment, mostly because it has a
current limiter that cuts power when a short circuit
could otherwise blow up your board!
GOING FURTHER
The first step is to add the $20 backplane and put
the N8VEM and backplane into a case. Options
range from DIY woodwork to buying a standard 19”
card cage. After that, the choice is personal.
For example, you can add video display unit (VDU) cards,
which free you from using a PC and bring that warm glow of
old cathode ray tubes (CRTs) into the room. Using vintage
CRT chips is also interesting from a hardware and software
perspective. You could also incorporate hard and floppy disk
drives to increase the N8VEM’s “vintage” qualities (although,
in practice, you probably won’t use the floppy disks too
often).
You can also create “Frankenstein” systems, since it can
be interesting to blend old and new technology. For instance,
the PropIO, an add-on expansion card for the N8VEM, adds
mass storage in the form of a modern SD card. At the same
time, its on-board Propeller chip supports a video graphics
array (VGA) monitor and a PS/2 keyboard. You could also
add blinkenlights. A front panel with dozens of switches and
flashing lights is fun. The ECB bus monitor card looks like a
classic front panel, but it is actually a more sophisticated
debugging tool.
MULTIPROCESSOR SYSTEMS
Another option is the 6x0x board, which deserves special
attention. This board adds a second processor and OS to the
N8VEM. You can plug in a 6502, a 6802, or a 6809 micro-
processor and let it run DOS/65, Flex, or Cubix. The 6502 will
appeal to those with an Apple II or a Commodore back-
ground, but the 6809 is the most interesting option. It was
considered the most powerful 8-bit microprocessor, and the
Cubix OS gives it a comfortable operating environment with
a full toolchain.
In a typical N8VEM approach, the 6x0x board was developed,
then expanded with an extra I/O board. Then, it was provided
with a custom backplane to use ECB cards without the Z80
present as a server.
The N8VEM is appealing to retrocomputing enthusiasts
because it has a card rack full of peripherals operating the “big
three” 8-bit microprocessors, running everything from CP/M
to Flex. It can take years to master that universe of hardware
and software, with plenty of manageable yet satisfying proj-
ects still waiting to be completed. For instance, OS/9 is just a
project away.
Photo 3—The 20-MHz Zeta board is a more compact SBC designed to fit under a 3.5” disk
drive. A stackable daughterboard adds a modern Parallax Propeller microcontroller, providing
video graphics array (VGA), SD card storage, and an experimentation breadboard area.
(Photo courtesy of Sergey Kiselev)
47
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
RESOURCES
S. Ciarcia, Build Your Own Z80 Computer,Computing Mcgraw-Hill, 1981,
http://retro.hansotten.nl/uploads/z80/BuildYourOwnZ80.pdf.
The N8VEM Home Brew Computer Project, http://n8vem-sbc.pbworks.com,
and Google group, https://groups.google.com/group/n8vem.
S-100 Computers, www.s100computers.com.
R. Zaks, Programming the Z80, Sybex Inc., 3rd edition, 1981.
SOURCES
Propeller chips
Parallax, Inc. | www.parallax.com
Logic 8-channel USB logic analyzer
Saleae, LLC | www.saleae.com.
Oscar Vermeulen (o.vermeulen@altis.ch) lives in Switzerland with his wife and
5-year-old son. His passion for computing developed in his early years. It later
evolved into a lively interest in computer history.
Andrew Lynch (lynchaj@yahoo.com) is an engineer who enjoys making homebrew
computers. His lifelong interest in computers started early and has grown into a
enjoyable career. Andrew lives in Ohio with his family.
THE CUTTING EDGE
The N8VEM has spun off new projects
in various directions. If you like keeping
things simple, the Zeta board is a small-
er project. It offers a fast (20-MHz) CP/M
computer with SD cards as mass storage,
a VGA connector, and an on-board Pro-
peller experimentation area all on a cir-
cuit board the size of a 3.5” floppy drive
(see Photo 3).
The N8 is a more complex board in the
spirit of the 1980s home computers. The
Xi 8088 is an IBM PC/XT-compatible.
Motorola 68000 and Intel 80286 proces-
sor boards are in advanced stages of
development.
THE TRAILING EDGE
In the last few years, development
efforts have also broadened to produce
the well-known S-100 bus, which was
made famous by the original 1975 Altair
computer. New S-100 cards provide
everything from mass storage devices
and video cards to 80286 and 68000
processor cards. With that range of
options, builders can either provide a new
lease on life for old S-100 systems, or
simply create a brand-new one.
KEEPING THINGS TOGETHER
The N8VEM Google mail group
includes an array of projects and involve-
ment from people with a range of skill
sets. It is remarkable how the group
binds all these builders together. The
youngest builder is 14 years old. It would
be impolite to mention the age of the
oldest.
If you have ever used 8-bit computers,
you’re likely to encounter some of the
vintage machine designers in the N8VEM
Google mail group. This builder organiza-
tion makes it easy to join, whether
homebrewing is your full-time hobby or
you just want to own a $20 self-built
computer for fun.
WHAT’S NEXT?
In Part 2, we will provide a detailed,
technical look at the N8VEM’s logic
design. If you have never looked at a
computer’s inner workings, it may sur-
prise you to see how easy it is to fully
comprehend an 8-bit computer. The arti-
cle will provide a starting point for anyone
interested in exploring the N8VEM’s sys-
tem software and expansion hardware. It
will also describe how a handful of logic ICs form the N8VEM’s memory and I/O man-
agement and its reset and bus interfacing circuitry. I
ARM • Cortex • ColdFire • PowerPC • CodeWarrior • CrossWorks • GCC • IAR EWARM
www.smxrtos.com
Processors Supported: www.smxrtos.com/processors
Free Evaluation Kits: www.smxrtos.com/eval
Free Demos: www.smxrtos.com/demo
Save time – and money – with embedded
software solutions built to run right out of the
box. Get development started quickly, with no
integration required and full support for popular
tools. With Micro Digital you have low-cost,
no-royalty licensing, full source code, and direct
programmer support. So get your project off to a
great start. Visit us at www.smxrtos.com today.
Free SMX Evaluation Kits are available for
many processors at www.smxrtos.com/eval.
Your solution
is here.
Y O U R R T O S P A R T N E R
800.366.2491 sales@smxrtos.com
mailto:o.vermeulen@altis.ch
mailto:lynchaj@yahoo.com
http://retro.hansotten.nl/uploads/z80/BuildYourOwnZ80.pdf
http://n8vem-sbc.pbworks.com
https://groups.google.com/group/n8vem
http://www.s100computers.com
http://www.parallax.com
http://www.saleae.com
http://www.smxrtos.com
http://www.smxrtos.com/eval
mailto:sales@smxrtos.com
http://www.smxrtos.com
http://www.smxrtos.com/processors
http://www.smxrtos.com/eval
http://www.smxrtos.com/demo
group. All were at least six years older
than me and they became my mentors
(whether they knew it or not) for nearly
the next decade. They helped me to
focus my energy on projects that would
have positive impacts for other people.
They also helped reinforce the hacker
mindset—that is, not being afraid to try
unconventional solutions to problems,
pushing the limits of technology, being
dedicated to learning through constant
experimentation, and sharing my pas-
sion with others. Being involved in the
L0pht was a very special time for me and
shaped much of how I view the world.
NAN: You grew up and went to
school in Boston. How did you end up
in California?
JOE: Being in Boston for nearly 28 years
left me with a lot of history (both good and
bad). Everywhere I looked, I had a story,
a feeling, or a connection to a time or
event. I needed a clean slate. I had just
left @stake, a computer security consult-
ing firm that we started out of the L0pht,
and my wife (girlfriend at the time) had
just finished graduate school. She was also
looking for new adventures, so we packed
up our stuff and drove across the country
not really knowing what we were going to
do when we got to California. We lived in
San Diego for a few years and ultimately
settled in San Francisco when I started
work on Discovery Channel’s Prototype
This! television show.
San Francisco was a natural fit for us,
and when the show ended, we decided
to stay. Being close to Silicon Valley and
48
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
Engineer to the Core
An Interview with Joe Grand
NAN: Give us some background
information. When and how did you
discover electronics. What was your
first project?
JOE: I got involved with computers and
electronics in 1982, when I was 7 years
old. My first system was an Atari 400
computer, an Atari 810 floppy disk drive,
and an Atari 830 acoustic coupler modem.
I spent every waking hour playing com-
puter games, trying to write my own pro-
grams, and connecting to local bulletin
board systems. I was continually experi-
menting and questioning. I remember
learning hexadecimal by poking around
with a binary editor and figuring out how
to replace names on game title screens
with my own.
My brother, who is six years older than
me, was also interested in computers and
electronics. He would repair audio equip-
ment, build telephone and computer
gadgets, and disassemble broken elec-
tronics to scavenge them for parts. He
had a cabinet that served as a junk bin
for components and broken boards.
When I did chores for him, like doing his
laundry or cleaning his room, he’d let me
pick something from the cabinet.
I was 13 years old when I hand-etched
my first circuit board to make a “ring-
busy device.” The device was simply a
resistor across the tip and ring of the
telephone line that had an RJ-11 plug for
easy insertion/removal. It would make
the telephone switch at the central office
believe your phone was off the hook
(thus, providing a busy signal to any
incoming caller), but would still enable
you to make outgoing calls. It was a fun,
mischievous device, but also very prac-
tical to prevent annoying phone calls
during dinner.
Right from the start, I had a strong
emotional connection to all things elec-
tronic. I could just understand how
technology was working even if I was
unable to explain why. I knew early on
that I wanted to be an electrical engi-
neer. I wore this proudly on my sleeve,
which didn’t help my ranking in the
social hierarchy of elementary school!
NAN: What have been some of your
influences?
JOE: In the early 1990s, when I was still
a teenager, I joined a group called L0pht
Heavy Industries (pronounced “loft” and
spelled ell-zero-ph-t, http://en.wikipedia.org/wiki/L0pht). The L0pht was a club-
house for Boston-area hackers who had
met on local bulletin board systems and
it was one of the first publicly known
“hackerspaces.” The L0pht simply started
as a place to store computer equipment,
tinker with technology, and hang out, but
it ended up as seven close-knit friends
changing the face of computer security
vulnerability research and disclosure.
We would examine networks, software
applications, and hardware products for
security flaws. If we discovered a vulner-
ability, we would challenge the vendor to
not only acknowledge the problem, but to
fix it. This is now common practice, but
back then, it was a feat practically
unheard of.
I looked up to the other guys in the
From his grade-school Atari obsession and his teenage involvement in the L0pht
Heavy Industries hacker group, to co-hosting Discovery Channel’s Prototype This!
and starting his own company, Grand Idea Studio, Joe Grand has always maintained
his passion for engineering. Joe and I recently discussed his journey and his lifelong
love of all things engineering.—Nan Price, Associate Editor
CIRCUIT CELLAR® • circuitcellar.com
QUESTIONS & ANSWERS
http://en.wikipedia.org/wiki/L0pht
49circuitcellar.com • CIRCUIT CELLAR
®
JOE: My most relevant and
memorable engineering expe-
rience was when I worked for
Continuum (formerly Design
Continuum, www.continuum
innovation.com), a design and
innovation consultancy based
in West Newton, MA. I had
worked on and off at the com-
pany during college and took
a full-time engineering posi-
tion in 1998. I was one of only
two electrical engineers. We
worked very closely with
industrial designers, mechani-
cal engineers, manufacturers,
and clients to create innova-
tive new products. Some key
projects I contributed to were
the A.T. Cross iPen (an early
digital writing tablet) and the
FluidSense FS-01 portable
infusion pump (voted one of
the best inventions of 2000 by
Time magazine). It was during my time at Continuum that I
learned about the product development and production manu-
facturing processes and sharpened my skills as an engineer.
NAN: Tell us about your experience working on Discovery
Channel’s Prototype This! television show. Do you have a
favorite project?
JOE: Prototype This! (http://en.wikipedia.org/wiki/Prototype_
This!) was a short-lived engineering entertainment show that
followed the real-life design process of a unique prototype
each episode. Although we only filmed for one season (com-
prising 13 episodes), the show gained a “cult” status of sorts
among engineers and makers. It aired on Discovery Channel
in the US in late 2008, but is now airing elsewhere throughout
the world. The show is also available on Netflix, making it
accessible to viewers who may have missed the show the first
time around.
To be clear, I’m an engineer to the core, and I never had any
intention of being in front of a camera as part of my job. But, the
opportunity to show off engineering to the world in a way that
was fun, entertaining, and somewhat educational seemed too
good to pass up. Producing the show turned out to be a difficult
and frustrating process, as we not only had to be on-screen tel-
evision hosts trying to convey complex, technical builds in a way
most viewers would understand, but we also had to actually
engineer, design, build, and test the prototypes.
We ended up building ridiculously crazy contraptions includ-
ing “Mind Controlled Car” (Episode 1), giant 10’ “Boxing Robots”
(Episode 2), and a “Traffic Busting Truck” that could elevate
itself over other traffic and move in any direction (Episode 3).
Each build had its own special flavor and design challenges and
I actually enjoyed working on all of them. From an engineering
point of view, I was most proud of the AirTrax control system
its electronics stores (e.g., Jameco Electronics, WeirdStuff
Warehouse, and HSC Electronic Supply) is quite useful, and I
always get a thrill driving by the offices of chip vendors I use
on a daily basis.
NAN: You started your own product design firm, Grand
Idea Studio, in 2002. Tell us about the company.
JOE: Grand Idea Studio (www.grandideastudio.com) is a prod-
uct design and licensing firm specializing in consumer/house-
hold devices and modules for electronics hobbyists. I started the
company to create an environment that suited me best and
would enable me to focus on what I loved to do. The majority
of my work stems from ideas developed in-house or with my
industrial design/mechanical engineering partners. I prefer to
design simple, effective devices that serve a specific purpose.
I’m all for using technology—but only where it’s needed—to
make a product better.
Much of my time is spent building prototypes or proof-of-con-
cepts of ideas (though many of those don’t ever see the light of
day) that are sold and/or licensed to suitable partners. Some
projects I’ll release as open source (usually through a Creative
Commons Attribution license), so others can learn from my
experiences and build upon my work to make something better.
I also teach a hardware hacking course at public and private
events (www.grandideastudio.com/portfolio/hardware-hacking-
training). The course focuses on teaching board-level hardware
hacking and reverse-engineering techniques and skills. It’s a
combination of a lecture and hands-on exercises covering the
hardware hacking process, proper use of tools and test meas-
urement equipment, circuit board analysis and modification,
embedded security, and common hardware attack vectors. The
course concludes with a final hardware hacking challenge in
which students must apply what they’ve learned to defeat the
security mechanism of a custom circuit board. Design engineers
and computer security researchers don’t often join forces. Being
both, I feel like it’s part of my responsibility to help make that
connection.
NAN: Tell us about your engineering experience prior to
Grand Idea Studio.
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
“Boxing Robots” was one of Joe’s most memorable episodes from his stint
on Discovery Channel’s engineering entertainment show, Prototype This!.
(Photo courtesy of Boj Florido)
Here’s Joe in action in Prototype
This!, Episode 6: “Robotic Firefighter
Assistant,” (Photo courtesy of Boj
Florido)
http://www.continuuminnovation.com
http://en.wikipedia.org/wiki/Prototype_This
http://www.grandideastudio.com
http://www.grandideastudio.com/portfolio/hardware-hacking-training
functional electronic devices. I believe
we were the first large-scale event to
provide electronic badges to attendees.
It changed what people have come to
expect from a conference badge. The
challenge was to create something that
scrutinizing hackers would enjoy, appre-
ciate, play with, and modify, while stay-
ing within the budget (around $10 per
badge in 10,000-unit quantities).
The various badge designs have dis-
played custom scrolling text messages,
turned off your television, transferred
files over infrared, pulsed to music using
fast Fourier transforms (FFTs), and pro-
vided USB functionality for computer
control. They have incorporated tech-
nologies such as capacitive touch, RGB
LEDs, microelectromechanical systems
(MEMS) based microphones, “zero
power” cholesteric LCDs, and microcon-
trollers ranging in size from tiny six-pin
devices to powerful 64-pin behemoths.
The physical PCBs used extremely com-
plicated mechanical outlines, multiple
layers of custom solder mask colors, and
laser etching onto single-sided aluminum
substrate PCBs.
Full details about the badges, along
with schematics, source code, pictures,
attendee hacks, and related articles, are
available at www.grandideastudio.com/
portfolio/defcon-x-badge (where x = 14,
15, 16, 17, 18).
NAN: Are you currently working on
or planning any projects? Can you
tell us about them?
JOE: There will (hopefully) never be a
shortage of cool projectsto work on. I
like to keep multiple plates spinning at
one time, though I can only talk about
50
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
as soon as the prototype hardware is
ready. This lets me validate that each
hardware subsystem behaves as required
and, if necessary, I can easily make
changes to the design.
Once the hardware design has been suf-
ficiently proven, I’ll move to a production
design and form factor. Then, I’ll finish up
the firmware, refine my documentation
(which I work on throughout the process),
and either release the design or move to
production. If things go wrong, which they
can sometimes do, then I may make mul-
tiple iterations of a design before it’s ready
for production.
When I’m in the throes of the design
process, I’m obsessed with the work. I
think about it constantly—on my daily
runs, in the shower, at bedtime, and
sometimes while sleeping. I try to antici-
pate worst-case scenarios, component
tolerances, failure modes, and how the
end user will interact with the device
(both correctly and incorrectly).
Every project I work on is currently my
favorite and each project comes with its
own challenges, successes, and failures.
As soon as I’m done with one project, I’m
looking for the next thing to do.
I’m particularly fond of my work on the
DEF CON badges. Held every summer,
DEF CON (www.defcon.org) is the largest
and oldest continuously running hacker
event of its kind. It’s a mix of good guys,
bad guys, government officials, and
everyone in between, all having fun,
sharing information, seeing old friends,
and learning new things.
For five years (2006–2010) I had the
honor of designing the official confer-
ence badges, which were artistic, fully
(Episode 3), the PyroPack (Episode 6:
“Robotic Firefighter Assistant”), and the
underwater ROV controller (Episode 10:
“Virtual Sea Adventure”). All of the docu-
mentation for my contributions to the
builds, including schematics, source
code, and development notes, is available
at www.grandideastudio.com/prototype-
this.
Ultimately, the show proved to be
unsustainable (from financial and time
perspectives), but it was an unforgettable
experience. The best thing is how the
show continues to inspire future engi-
neers. Nearly every day I receive e-mails
from viewers asking for details about a
particular build or what it takes to
become an engineer, and I do my best to
point them in the right direction.
NAN: You’ve designed dozens of
things—from computer memory-
imaging tools to children’s products
to medical devices. Tell us about your
design process. Do you have a
favorite project?
JOE: I think my design process is very
typical. I start by identifying and sourc-
ing key components for the project. I’ll
put together a preliminary block diagram
and then build a proof-of-concept or pro-
totype using a breadboard or PCB
(depending on complexity and/or other
constraints).
If the design is an embedded system
that requires firmware, I’ll start writing it
For DEF CON 17, Joe created seven badge shapes,
one for each type of DEF CON participant—human,
goon (staff), press, speaker, vendor, contest
organizer, and uber (contest winner). Each shape
served as a puzzle piece. Attendees completed the
puzzle by placing the seven badges in the correct
positions, as shown in this photo.
This close-up of the DEF CON 18 badge shows the
LCD and laser engraving. The badge is built
around a Freescale Semiconductor MC56F8006
digital signal controller. It features a Kent Displays
cholesteric liquid crystal display (ChLCD).
The backside of the DEF CON 18 badge Joe
designed shows simplicity, artistry, and hackability
through USB and (unpopulated) JTAG interfaces.
http://www.grandideastudio.com/
http://www.defcon.org
http://www.grandideastudio.com/prototype-this
51
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
some of those plates.
At the recent 2013 DESIGN West conference, I released the
JTAGulator (http://jtagulator.com), which is an open-source,
Parallax Propeller-based hardware tool that assists in identi-
fying on-chip debug (OCD) and/or programming connections
from test points, vias, or component pads on a target device.
Discovering available interfaces is a common step in hard-
ware hacking or reverse engineering, as they are usually left
unprotected and can be used to extract memory or affect the
state of a system on the fly.
A few similar tools exist, but they are either incomplete,
closed source, or proof of concept. I wanted to create some-
thing that could be used in actual, real-world situations and
that would help new people get involved in hardware hacking.
The tool will also help to highlight the insecurity of leaving
OCD interfaces enabled in production devices and hopefully
serve as a catalyst for change in the engineering community
(where convenience often trumps security). The JTAGulator
currently supports JTAG and I will be making continued
refinements to the firmware to add support for additional
OCD protocols.
Last year, I finished up the Emic 2 Text-to-Speech module
(www.grandideastudio.com/portfolio/emic-2-text-to-speech-
module), which has just started to appear in lots of interesting
projects. The module is a self-contained, multi-language voice
synthesizer that converts a stream of digital text into natural-
sounding speech. It’s based on the Epson S1V30120 text-to-
speech (TTS) IC, which uses the familiar DECtalk engine and is
easy to interface to any microcontroller through a standard
serial interface. Though embedded speech synthesis has been
around for a while, there was no small form factor, low-cost
solution readily available. So, I made one. A search for “Emic
2” on YouTube will result in various projects that use the mod-
ule, including a tweet reader, a color-to-voice converter, a talk-
ing thermometer, an interaction with Apple’s Siri, and some
singing demonstrations.
Some other projects I have planned include experimenting
with PCB reverse-engineering techniques, hacking with a
BeagleBone Black and OpenCV, and designing a new RFID
system.
NAN: What do you consider to be the “next big thing”
in the embedded design industry?
JOE: I’ve been increasingly concerned with the improper and
(sometimes) socially unacceptable use of technology. From
cameras at every street corner to mobile devices tracking
your every move to Facebook and Google (among others)
controlling your personal data, privacy has become some-
thing we’re slowly (and willingly?) losing. It’s a slippery slope
that I don’t think many people will notice until it’s too late.
The problem is largely driven by our society’s mass adoption
of technology and taking that technology for granted. As an
engineer and hacker, I strive to educate others about the
unintended consequences of blindly using technology and
hope it will make them more aware. I
ïïï KÉã~ÅáåÅKÅçãLé~åÉä|éÅLééÅ|ÉQHKÜíã
bbnn rr ffmmjj bbkk qq=jj ll kk ffqqll oo=^̂kk aa =`` ll kk qqooll ii= = == = == = == = == = == = == = == = == = == = == = == = =
Colorado
Micro
Devices
Drop in, Turn on and Tune in!
sales@coloradomicrodevices.com
www.coloradomicrodevices.com
< RadioBlocks
1-inch square, FCC + CE
certified 802.15.4 wireless
modems that are
simply useful.™
With open source software.
BORA >
The binary explorer
board. Complete
CPLD-based digital
logic trainer with
complete courseware.
(719) 434-7201
http://jtagulator.com
http://www.grandideastudio.com/portfolio/emic-2-text-to-speech-module
mailto:sales@coloradomicrodevices.com
http://www.coloradomicrodevices.com
http://www.emacinc.com
http://www.emacinc.com/panel_pc/ppc_e4+.htm
uppose you need to design a small
embedded controller. The functional
requirements state that the electronics are to
control a robotic arm. An electric actuator moves
the arm while a linear variable differential trans-
former (LVDT) attached to it providesposition
feedback. The position command is generated by
using a handle to move another LVDT’s core. The
system is powered from a 12-VDC distribution
and must satisfy stated environmental conditions.
Figure 1 shows the system black box diagram.
At this point, some engineers like to start
drawing schematic diagrams, but this practice is
just as bad as writing source code without hav-
ing the program flow expressed by pseudocode
or a flow chart. Figure 1 suggests the minimum
extent of the acceptance test procedure (ATP) as
discussed in Part 2 of this series. Most likely,
you’ll only be required to
verify that the load position
tracks the command within
the specified speed and
accuracy.
During the circuit and soft-
ware design, you should
consider the operational
requirements with respect to
the environment—such as
the temperature, vibration,
humidity, and electromag-
netic compatibility (EMC). At
the end of the design, the
qualification testing, which is performed only once,
will prove the specification compliance.
DESIGN REQUIREMENTS
As the first design step, you should decompose
the black box diagram into the white box dia-
grams, thus defining the functions to be per-
formed (i.e., derived requirements). Most of these
functions require verification only during the
development process. At this point, you also
decide what will be accomplished in the hardware
and the software.
The decomposition can be in a table or graphical
format. Each functional block should contain techni-
cal requirements (e.g., voltages, timing, etc.). You
should handle the software design the same way.
The white boxes decompose into schematic dia-
grams or, in the case of software, into pseudocode
52
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
An important aspect of product testing involves ensuring the product
can be automatically tested easily, repeatedly, and often. The first two
parts of this article series walked you through building a dedicated
tester and discussed common testing techniques. Part 3 focuses on
guaranteeing products can be efficiently tested.
Testing and Testability (Part 3)
by George Novacek (Canada)
Testability Design Issues
S
TH
E
CO
N
SU
M
M
A
TE
E
N
G
IN
EE
R
Figure 1—Before drawing schematics, it is helpful to create a black box system diagram.
DC Power input
Control
Actuator
LVDT
Position
feedback
Processor
LVDT Position
command
THE RATIOMETRIC METHOD
There are different ways to decode the
LVDT signal. I chose the ratiometric
53
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
or flow charts. Figure 2 and Listing 1
show how the “LVDT Position command”
black box from Figure 1 is broken out.
Figure 2—Breaking
the black box system
diagram down into a
white box diagram
helps define the
functions.
Conditioning
Conditioning
LVDT
1:1:1
V1
V2
Excitation
7 V
3,200 Hz
700 Ω�
ADC
ADC
µC
Common
method for this example. The magni-
tude of P reflects the LVDT’s position
using this formula:
This calculation is performed in soft-
ware (see Figure 2).
When using the ratiometric
method, the excitation voltage and its
frequency are not critical. This simpli-
fies your circuit and test design. The
conditioning circuits don’t need
absolute accuracy, but their matching
is paramount because a mismatch
affects the positioning accuracy.
Thus, a sweep through the entire
command range compared with the
output position during the ATP pro-
vides a good indication of the con-
troller’s health. For development and
PCB tests, you’ll want to access these
circuits and software functions as
autonomous modules.
With software design, waiting until
the hardware is available is impracti-
cal. When the software is modularized
(e.g., what is shown in Listing 1), you
P
V
V
=
V2
+ V2
1
1
−
Listing 1—This pseudocode derives the position command. If V1 + V2 is less than the minimum
Excitation value, a fault is indicated and a fault handler is called.
int acquireCommand()
{
analogRead (V1);
analogRead (V2);
if (( V1 + V2) < minimumExcitation) // check excitation magnitude
{
faultLVDT(); // LVDT fault handler
{
P = (V1-V2)/(V1+V2); // LVDT position
return(P);
}
PC
B-
PO
O
L®
is
a
r
eg
is
te
re
d
tr
ad
em
ar
k
of
B
et
a
LA
YO
UT
G
m
bH
&
present
www.pcb-pool.com
www.magic-pcb.com
www.pcb-pool.com
www.magic-pcb.comwww.magic-pcb.com
Embedded RFID
• Authenticating
• Tracking
• Protecting
• Tracking
• Protecting
NOW a
vailable
- with a
ntenna
conne
ction
- for al
l quant
ities
Get your UHF RFID Kit
at www.beta-eSTORE.com
http://www.pcb-pool.com
http://www.magic-pcb.com
http://www.beta-eSTORE.com
http://www.crystalfontz.com
54
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
RESOURCES
CONAS-ZG, “LVDT Sensor Tutorial,” http://e.conas-zg.com.
E. Mulo, “Design for Testability in Software Systems: A
Software Engineering Research Group Literature Study,”
2007, http://swerl.tudelft.nl/twiki/pub/Main/Research
Assignment/RA-Emmanuel-Mulo.pdf.
G. Novacek, “Accurate Linear Measurement Using LVDTs,”
Circuit Cellar 106, 1999.
———, “Testing and Testability (Part 1): Design a Dedicated
Tester for an Electronic Device,” Circuit Cellar 274, 2013.
———, “Testing and Testability (Part 2): PCB Testing,”
Circuit Cellar 275, 2013.
W. R. Simpson and H. S. Balaban, “The ARINC Research
System Testability and Maintenance Program (STAMP),”
Institute of Electrical and Electronics Engineers, 1982,
www.testability.com/reference/Documents/ARINC%
201982%20Final%20REV1.pdf.
George Novacek (gnovacek@nexicom.net) is a professional engineer
with a degree in Cybernetics and Closed-Loop Control. Now retired,
he was most recently president of a multinational manufacturer for
embedded control systems for aerospace applications. George wrote
26 feature articles for Circuit Cellar between 1999 and 2004.
can develop many modules on a PC plat-
form. There, they can be tested for a
range of possible conditions and later
recompiled for the actual platform.
You’ll need to decide which manufac-
turing tests you can perform during PCB
testing and which must wait until the
ATP. Generally speaking, the sooner the
better.
In the example, you can test the exci-
tation generator’s output voltage and
frequency on the bed of nails. You can
test signal-conditioning modules by sig-
nal injection or you can run parametric
tests by the flying probe. You’ll want to
find and repair defects as soon as possible to avoid later rework,
which requires time- and labor-consuming disassembly.
Using real peripheral devices (e.g., the LVDTs in my exam-
ple) can be awkward. Some peripherals are expensive and
prone to damage in the manufacturing environment. Also,
setting them by hand precisely and repeatedly may be quite
difficult, especially when, as in the example, the LVDT vs.
the actuator tracking may have to be accurately measured.
Using a computer to simulate these peripherals facilitates a
fast, accurate sweep through the entire control range. With
a bit of ingenuity, you can use a little hardware and a PC to
simulate the most complicated peripherals.
CIRCUIT AND SOFTWARE MODULARIZATION
Circuit and software modularization is important for several
reasons. The engineering design verification and validation is
an obvious reason, but imagine you are experiencing failures
during EMC testing. Without access to the critical module sig-
nals, it is difficult to isolate and determine whether the prob-
lem is with the controller or a peripheral device (i.e., the LVDT
or the harness). Even if the problem’s root cause is outside the
controller, you will likely be responsible for resolving and fix-
ing it. But as long as you can demonstrate that the problem is
not with your design, someone else will be liable for the cost
of the correction and the retest. This can be expensive and
cause scheduling delays forwhich you don’t want to be
responsible.
Most customers have a repair and maintenance policy, which
can range from repair by replacement to a component-level
repair at an authorized depot. You must ensure good field testa-
bility, lest you want to send your technicians all over the world
for support. There is a growing trend toward repair by replace-
ment only. Even during the manufacturing, it may cost more to
troubleshoot and repair some PCBs than to replace them and
throw the bad ones away. To stay competitive, you must focus
on robust design, thorough testing, and a maximum effort in
manufacturing process control to ideally obtain a 100% produc-
tion yield.
PCBs to be repaired should include indicators to help quickly
determine the failing module. LEDs are inexpensive and, if
placed strategically throughout the PCB to indicate the fault,
repairs can be quickly accomplished. Figure 3 is an example of
why you need to consider testing early in the design process.
TAKE THE TIME TO TEST
Before micropower microcontrollers
were available, my company needed a
timer to trigger a function every 2 to 3 min.
The entire battery-operated device could
draw no more than 10 µA. As we were
building about 10 units a day, the circuit
with a programmable unijunction transistor
(PUT) worked well (see Figure 3). The test-
ing was time consuming, but acceptable.
Then the demand unexpectedly increased
to several thousand units a day, and we
were quickly up against a brick wall.
First, the aluminum electrolytic capaci-
tors C1, due to their previous time in
storage, needed several hours under power to reform for the
leakage to drop to the specification level and for the timer to
work correctly. Then, it took several minutes to verify its opera-
tion on the ATP. This was nearly impossible for the volume of the
production without expensive fixtures and many test stations.
The solution was simple. We replaced C1 with a polyester
capacitor, which decreased the timing period to several seconds,
and the timer was followed by a CMOS counter. This slightly
increased the current draw, but it remained below 10 µA. The
cost of material also increased, but it was offset by the time sav-
ings during the test.
Unfortunately, the implementation took time and some deliv-
eries were lost. We could have avoided all that trouble at the
beginning had we focused on testability rather than merely the
cost of material. Next month, I’ll discuss testability from the per-
spective of internal diagnostics. I
Figure 3—How do you test a circuit like this in volume?
Out
9 V
R4 R1 R2
R3
C2
C1
Q1
PUT
+
mailto:gnovacek@nexicom.net
http://e.conas-zg.com
http://swerl.tudelft.nl/twiki/pub/Main/ResearchAssignment/RA-Emmanuel-Mulo.pdf
http://www.testability.com/reference/Documents/ARINC%201982%20Final%20REV1.pdf
REGISTER ONLINE
www.FlashMemorySummit.com
Readers of Circuit Cellar Magazine: Enter priority code SPGP for a $100 discount.
Don’t Be Left Out of
Multibillion Dollar Markets
Are you struggling with crucial Solid State Drive (SSD) decisions? Can SSDs resolve your application bottlenecks?
How can you maximize SSD performance? Flash Memory Summit will explore new frontiers in enterprise storage
and help you make the right choices. Summit topics include:
NVMe and PCIe SSDs • Flash Memory Based Architectures • Flash in Data Centers
Enterprise SSDs • Enterprise Storage Design • SSD Technology • Controllers
Advances in SCSI • Enterprise Caching ª Enterprise Applications
Flash and Cloud Computing • Client Caching • PCIe Storage
Plus Keynotes by Facebook, EMC, Seagate, Intel, Micron,
SMART Storage, Skyera, LSI, and Microsoft
August 13-15, 2013
Santa Clara Convention Center
Santa Clara, CA
http://www.FlashMemorySummit.com
56
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
by Ed Nisley (USA)
ost of the time, we take small light
emitting diodes for granted: connect
one in series with a suitable resistor and voltage
source, it lights up, then we expect it to work
forever. A recent project prompted me to take a
closer look at commodity 5 mm LEDs, because
I intended to connect them in series for better
efficiency from a fixed DC supply and in parallel
to simplify the switching. Rather than depend
on the values found in datasheets, I built a sim-
ple Arduino-based LED Curve Tracer to measure
the actual characteristics of the LEDs I intended
to use.
Even though this isn’t a research-grade
instrument, it can provide useful data that helps
demonstrate LED operation and shows why you
must pay more attention to their needs.
MAKING LIGHT
The rainbow of curves in Photo 1 illustrates that
an LED’s forward voltage depends on the color it
emits: the energy required to produce light
varies with its wavelength and the semicon-
ductors used in the LED. You may be sur-
prised at the 3.5 V difference between the
IR and UV LEDs and, if you choose a series
resistor based on a higher voltage, a lower
voltage LED may be equally surprised at the
amount of current it must handle. In the
worst case, the overstressed LED may
become a Smoke Emitting Diode.
Another surprise, at least for me, came
from the white LED’s forward voltage. A
“white” LED contains either a blue LED coat-
ed with phosphors that emit colors toward
the orange-yellow side of the spectrum or a
UV LED coated with broad-spectrum visible
phosphors, both emitting a spectrum of energy
that human eyes perceive as reasonably white
light. As you can see from the curves; however,
the forward voltage of the white LED doesn’t
match that of either the blue or UV LED. In fact,
it lies well away from all the LED curves, so it
must have an unusual structure.
This demonstrates the value of actual meas-
urements: they not only verify things you know,
but point out things you think you know that just
aren’t so. As the saying goes, one careful meas-
urement trumps a thousand expert opinions.
Because LEDs are diodes, for example, the
usual ideal diode equation relating forward volt-
age and current applies:
However, because LEDs are optimized to emit
light, they carry relatively high currents through
non-ideal semiconductors. Not only does a
I e
qV
kT
F
= I 1
S
( )
−
LED Characterization
Not content with using datasheet values, Ed built a specialized curve tracer
to measure the actual characteristics of the LEDs in his collection.
Arduino-Based Curve Tracer
M
A
B
O
V
E
TH
E
G
R
O
U
N
D
P
LA
N
E
Photo 1—The semiconductor variations that produce different colors
also produce different forward voltages, as this rainbow assortment
demonstrates. The LED Curve Tracer circuit measured the LED voltage
at each of the 5 mA steps from 0 through 30 mA.
57circuitcellar.com • CIRCUIT CELLAR
®
and processed through Gnuplot. One advantage of that
process is that I can tailor the graphs to suit the data, rather
than depend on a single graphic format. One disadvantage is
that I must run a program to visualize the measurements.
Feel free to add a graphics display to your LED Curve Tracer
and write the code to support it!
The schematic in Figure 1 shows the components required
to drive a known current through the LED and measure the
resulting voltages. The Arduino connects to this circuit
through the off-page cross references: one PWM output, two
digital inputs, and four analog inputs. The source code avail-
able on the Circuit Cellar FTP site assigns the pin functions,
so you can change them to suit your needs.
Any circuit attached to an Arduino should provide its own
power to avoid overloading the Arduino’s on-board regulator.
I used a regulated 7.5 VDC wall wart for both the Arduino Pro
Mini board and the LED under test, because the relatively low
voltage minimized the power dissipation in the Arduino regu-
lator. You could use a 9 VDC or 12 VDC supply, although I
explained the reasoning behind lower voltages in my March
2013 column (“ArduinoSurvival Guide: Analog I/O”, Circuit
Cellar 272).
The Arduino’s regulator sets the microcontroller’s V
CC
supply
voltage, which limits the maximum permissible input voltage
and acts as the analog-to-digital converter’s reference volt-
age. The regulator produced 4.96 V, so I set the KA278RA05C
regulator in the LED circuit at 4.90 V to ensure the voltages
remained within the ADC range. That wastes about 10 LSB of
the ADC’s range, but also ensures that the microcontroller’s
protection circuitry won’t affect the measurement.
The forward voltage for blue and UV LEDs barely fit within
that range, as you can see in Photo 1, and testing them at
higher currents definitely requires more voltage headroom.
You could apply 7.5 VDC directly to the LED, use voltage
dividers to reduce the input voltages to the Arduino’s range,
then rescale the measurements back to the actual voltages.
Homework: Do it!
Because common 5 mm and 10 mm LEDs operate at about
resistive term enter the equation, but most of the “con-
stants” vary due to the temperature changes caused by
power lost in that resistance. Although you can derive an
empirical formula including all the effects, then collect
enough data to determine the coefficients, that’s practical
only for manufacturers and high-volume users; if you’re in
either of those situations, you’ll know it!
For my purposes, measuring the LED’s actual forward volt-
age at reasonable currents and ambient temperature will
provide enough information to proceed. Unlike the MOSFET
Tester I described last year, this circuit doesn’t require active
temperature control.
CONTROLLING CURRENT
The hand-wired circuit in Photo 2 applies a known current
to a single LED, measures the actual current and several
voltages, computes the forward voltage across the LED, and
dumps all the values through the Arduino’s serial port. A sin-
gle test run steps the current from 0 mA to a preset upper
limit, so that you can plot the LED’s operating characteristic
across a useful range of currents.
Although I think of the circuit as an “LED Curve Tracer,” it
does not present its data on a display. Instead, I create the
graphs with data files captured from the Arduino serial port
Photo 2—The Arduino Pro Micro clone in this hand-wired LED Curve Tracer
controls the LED current and measures the resulting voltage.
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
Figure 1—The microcontroller adjusts the MOSFET gate voltage with a
filtered PWM output, so that the LED current matches the desired value.
The LED voltage is the difference between the regulated 4.9 V supply and
the MOSFET drain voltage.
Photo 3—The IRLZ14 logic-level MOSFET has a R
DS
< 0.225 Ω for V
GS
> 3.5 V.
The gate voltage steps by 0.5 V between 2.0 V and 10.0 V.
58
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
20 mA continuously and generally have a 100 mA peak limit,
I used a 10.5 Ω current-sense resistor made by paralleling a
pair of 21.0 Ω 1 % resistors to get a maximum sense voltage
of about 1 V at 100 mA. The Arduino’s 5 mV ADC resolution
restricts the minimum current to about 5 mA, which produces
only 50 mV. You could, of course, use an op-amp to multiply
the voltage by a factor of 4 or 5 to improve the resolution, but
this simple circuit works well at the usual 20 mA = 200 mV
level.
The Arduino firmware applies a 32 kHz PWM signal to the
R4 and C1 low-pass RC filter that produces the MOSFET’s
gate voltage. Because the MOSFET source terminal voltage
varies with the LED current through the sense resistor, the
firmware measures the actual LED current and adjusts the
PWM output to produce the gate voltage for the desired
current.
Photo 3 shows the characteristics of the logic-level IRLZ14
power MOSFET, as measured by my MOSFET Tester. Because
the maximum LED current will be under 100 mA, the MOSFET
will operate as a voltage-controlled linear resistor over the
range of V
DS
used in this circuit.
V
GS
changes by 0.5 V between successive curves in Photo 3,
with V
GS
= 2.5 V producing the blue trace ending at ID = 0.25 A
and V
DS
= 0.30. This MOSFET has V
T
slightly under 2.0 V: V
GS
=
2.0 produced the blue line at ID = 0.0 A. Because V
S
will be
about 1 V at maximum current, the filtered PWM output should
be about 3.5 V.
The Arduino analogWrite() function defines the PWM
duty cycle using an 8-bit unsigned value with 0.4 % resolu-
tion, which means that the filtered voltage at the MOSFET
gate will change by 20 mV between successive PWM values.
The changes in I
D
(and, therefore, V
S
) means the actual V
GS
seen by the MOSFET will change by somewhat less than that,
but the PWM resolution does limit the resolution of I
D
and,
therefore, the LED current increments.
Figure 2 presents the data taken from the red LED appear-
ing in Figure 1. The filtered gate voltage V
G
changes by 80 mV
to 100 mV for each 5 mA I
D
current step, with V
GS
changing
by 20 mV to 40 mV. The results for other LEDs suggest that
a 1 mA change in I
D
corresponds to a 20 mV change in V
G
,
which means this circuit can’t quite achieve 1 mA current res-
olution. The small vertical offsets of the points in Figure 1
show the effect of the limited resolution: the circuit can’t
quite produce exact multiples of 5 mA.
However, the curves in Figure 1 show the overall LED
response, with sufficient resolution and accuracy for my
purposes.
Homework: Tweak the Arduino source code to see the
effect of smaller I
D
increments.
CHECKING THE RESULTS
Photo 4 shows a sanity check applied to a single “super-
bright” red LED that’s different from the red LED in Photo 1.
The graph has 10 separate and mostly overlapping traces, with
each data point representing the average of 10 successive ADC
samples, as shown in Figure 3. The smallest horizontal spacing
between adjacent points is about 5 mV, corresponding to the
nominal ADC resolution. The smallest vertical spacing is
approximately 1 mA and comes from the firmware’s inability to
set the current more precisely, as described above.
The code in Figure 3 repeatedly measures an input voltage,
computes the average value as an integer, then returns the
result as a floating point number. You could compute the aver-
age as a floating point number to increase the measurement
resolution, but that really doesn’t improve the accuracy very
much.
Figure 2—The Arduino firmware produces
output lines with tab-separated values that
work directly with spreadsheets and Gnu-
plot. It displays the measurement in milli-
volts and microamps to avoid dealing with
floating-point formatting.
Photo 4—Measuring the same red LED 10 times shows repeatability near the
theoretical limit. Each ADC value represents the average of 10 successive
samples and the plot has 10 overlapping curves.
# LED Curve Tracer
# Ed Nisley - KE4ZNU - March 2013
# Bandgap reference voltage: 1041 mV
# Insert LED, press button 1 to start...
# INOM ILED VCCLED VD VLED VG VS VGS VDS <--- LED 1
0 0 4892 3889 1002 0 0 0 3889
5 4613 4892 3264 1627 1990 48 1942 3216
10 10148 4892 3216 1675 2092 106 1985 3109
15 15223 4892 3182 1709 2199 159 2039 3022
20 19836 4892 3148 1743 2271 208 2063 2940
25 24910 4897 3129 1767 2354 261 2092 2867
30 30446 4897 3104 1792 2431 319 2111 2785
# Insert LED, press button 1 to start...
59circuitcellar.com • CIRCUIT CELLAR
®
Homework: Make it so.
The firmware computes the LED forward voltage from the
difference between the LED power supply and the MOSFET
drain voltage. Each measurement has an inherent ±5 mV
uncertainty, so subtracting those two values produces a
±10 mV uncertainty. The graph shows about 20 mV of jitter
at each current step, which is about right.
As I mentioned earlier, all of the semiconductor parameters
depend on temperature. An LED die heats up rapidly due to
resistive losses, which change its current vs. voltage charac-
teristics. For my purposes and for relatively low currents, this
doesn’t makemuch difference, but keep it in mind when you
require precise calibration.
VARIATIONS ON A THEME
Knowing that the Curve Tracer produces repeatable results
from a single LED, I fed it the nine different red LEDs shown
in Photo 5. My collection includes some very old LEDs with
gold-plated leads that may well have been MIL-SPEC items,
as well as commodity LEDs, so these cover a broad range of
semiconductor materials and designs.
The curves from those LEDS appear in Photo 6, where
they show that forward voltage definitely depends on LED
Figure 3—This function averages 10 successive ADC samples to reduce
spurious results. Computing the average as a floating point number,
instead of the integer used here, could increase the resolution.
#define NUM_T_SAMPLES 10
float ReadAI(byte PinNum) {
word RawAverage;
digitalWrite(PIN_SYNC,HIGH); // scope sync
RawAverage = analogRead(PinNum); // start average
for (int i=2; i <= NUM_T_SAMPLES; i++) {
RawAverage += (word)analogRead(PinNum);
}
digitalWrite(PIN_SYNC,LOW);
RawAverage /= NUM_T_SAMPLES;
return VCC * (float)RawAverage / 1024.0;
}
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
Photo 5—Each LED in this assortment has a different forward voltage char-
acteristic. Some of the leads have tarnished silver plating, others have pris-
tine gold plating, and most have ordinary tin or solder plating. Their order
here corresponds to the records in the data file used to create the graph in
Photo 6.
Find out more at www.pololu.com
Finding the right parts for your robot can be di�cult,
but you also don’t want to spend all your time
reinventing the wheel (or motor controller). That’s
where we come in: Pololu has the unique products
— from actuators to wireless modules — that can
help you take your robot from idea to reality.
Jrk USB Motor
Controllers
Highly configurable DC motor
controllers that offer four control
interfaces and can optionally be
used with feedback for closed-
loop speed or position control.
Zumo Robot
Arduino-controllable tracked
robot small enough for mini-
sumo (less than 10 cm × 10 cm)
and flexible enough for you to
make it your own.
With our custom part cutting
service, you can quickly and
economically realize intricate
designs.
Custom Laser
Cutting
Linear Actuators
Our 12 V linear actuators have
dynamic load ratings ranging
from 22 to 110 pounds and can
be used in a variety of heavy-
duty applications.
Finding the right parts for your robot can be di�cult,
With our custom part cutting
service, you can quickly and
economically realize intricate
designs.
Custom Laser
Cutting
Linear Actuators
Our 12 V linear actuators have
dynamic load ratings ranging
from 22 to 110 pounds and can
be used in a variety of heavy-
duty applications.
Jrk USB Motor
Controllers
Highly configurable DC motor
controllers that offer four control
interfaces and can optionally be
used with feedback for closed-
loop speed or position control.
http://www.pololu.com
60
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
their maximum power dissipation under control, but LEDs
designed for high brightness tend to operate close to their
maximum allowed current and will not survive high current
pulses.
The curves in Photo 7 represent 10 5 mm LEDs from a lot of
100 that I pushed to 100 mA, far beyond their normal 20 mA
DC operating current. Their forward voltages lie within a 1 %
range at 20 mA and 4 % at 100 mA, much tighter than the
menagerie in Photo 6, which isn’t surprising at all.
Similar data from the LEDs in my collection will allow me
to sort them by forward voltage at their actual operating
current, so that parallel strings will have similar forward
voltages and share current more equally.
CONTACT RELEASE
The data you see here represents a continuation of some
interesting experiments. I also want to measure how bright-
ness varies with current and duty cycle, as well as the rela-
tive efficiencies of simple DC supplies matched to the LED
characteristics. Plenty of data lies ahead before I build a
prototype!
The downloadable file for this month contains the Arduino
source code, the data files for the LEDs, and the Bash
scripts that produced the plots. I
PROJECT FILES
To download the code, go to ftp://ftp.circuitcellar.com/pub/
Circuit_Cellar/2013/276.
RESOURCES
gnuplot, www.gnuplot.info.
E. Nisley, “Arduino Survival Guide: Analog I/O,” Circuit
Cellar 272, 2013.
———, “Arduino Survival Guide: Digital I/O,” Circuit Cellar
271, 2013.
———, “Arduino Survival Guide: Power Supply,” Circuit
Cellar 269, 2012.
———, “MOSFET Tester: Peltier Temperature Control and
Results,” Circuit Cellar 267, 2012.
———, “MOSFET Channel Resistance: Tester Hardware,”
Circuit Cellar 265, 2012.
———, “MOSFET Channel Resistance: Theory and Practice,”
Circuit Cellar 263, 2012.
———, “LED Power,” Circuit Cellar 209, 2007.
SOURCE
KA278RA05C Regulator
Fairchild Semiconductor Corp. | www.fairchildsemi.com/
pf/KA/KA278RA05C.html
Ed Nisley is an EE and author in Poughkeepsie, NY. Contact him
at ed.nisley@pobox.com with “Circuit Cellar” in the subject line
to avoid spam filters.
chemistry, as they differ by 250 mV, about 12 %, at 20 mA.
Obviously, you’d never use such a variety of LEDs in a sin-
gle device, but you can expect to see a similar variation
between LEDs from different vendors over the lifetime of a
long-term project.
The two gray curves in Photo 6 represent the leftmost LED
in Photo 5, which I tested at the beginning and end of the
series to verify that the circuit hadn’t drifted. The voltage
and current differences between corresponding points in the
two curves lie within the limits I discussed earlier; the two
points at 30 mA differ by about 1 mA and 20 mV.
I need a red light source with a fairly large emitting area,
broad beamwidth, and low power for an application that
isn’t well-suited to a few high-brightness LEDs, so I’m
investigating whether an array of ordinary (pronounced
“cheap”) LEDs will suffice. LED brightness varies almost lin-
early with current, at least for reasonable currents, so you
can trade off duty cycle with current to achieve the same
brightness.
Ordinary LEDs have a relatively high peak-to-average cur-
rent ratio that allows such a tradeoff, as long as you keep
Photo 7—Ten red LEDs from the same batch show considerable forward voltage
variation at 100 mA, about five times their rated DC current. The variation is
much smaller at the normal 20 mA. The two gray curves represent the same
LED, measured at the start and end of the test sequence, to verify the circuit’s
stability.
Photo 6—Nine different red LEDs display a considerable variation in forward
voltage at typical currents. The two gray curves represent the same LED
measured at the start and end of the test sequence.
mailto:ed.nisley@pobox.com
ftp://ftp.circuitcellar.com/pub/Circuit_Cellar/2013/276
http://www.gnuplot.info
http://www.fairchildsemi.com/pf/KA/KA278RA05C.html
SPONSORED BY
@circuitcellar
@editor_cc circuitcellar
Each week, you’ll find a new snippet of
source code that contains one error.
If you can find the error, you could be a winner!
Follow Circuit Cellar on Facebook and
Twitter for information about each
week’s challenge, prizes, and winners
announcements.
For complete details, visit
circuitcellar.com/cc_weekly_code_challenge
>>>
sample code only
http://circuitcellar.com/cc-weekly-code-challenge/?utm_campaign=codechallenge&utm_medium=epub&utm_source=circuitcellar
nvy is a strong motivator. My wife bought a new
Toyota Prius and it had one exceptionally “geek-
worthy” feature: a built-in Bluetooth interface. Asif by
magic, when you start the car, it automatically connects to
her Palm Treo. She answers incoming calls by simply press-
ing a button on the steering wheel. The audio, which comes
in over the car’s stereo speakers, automatically mutes
whatever is playing when a call is received. All in all, it’s a
slick, simple interface.
Unfortunately, instead of a Prius, I have an old (2,700-lb.
tare weight) Acura, and its only upgrade is a radio with an
auxiliary input. My thought was that I should be able to build
a Bluetooth-to-aux-in adapter that functions much like the
Prius’s Bluetooth interface. However, I figured I should be
able to support playing MP3s from my smart phone with a
custom adapter. Plus, if I could access the phone’s voice com-
mand functionality, I thought I would really “out geek” the
Prius!
Thus, I started my project to construct a “2,700-lb. Blue-
tooth headset.” I had three goals for the project. The first
was to learn something about Bluetooth. The second was to
find a Bluetooth module I could use for this Bluetooth project
and others. My third goal was to one-up the Prius’s Bluetooth
functionality!
FINDING A MODULE
When I look for small-quantity parts, I tend to start
searching at SparkFun (www.sparkfun.com). I find them to
be a very DIY-friendly shop. They provide breakout boards
for their SMD parts, manuals, user guides, and even a sup-
port forum. They’re also one of the few parts sources that
offer low-cost U.S. Postal Service shipping, so you don’t have
to pay a $10 shipping fee for a $2 part! So, off to SparkFun
I went, and they had several different Bluetooth modules in
stock (all with breakout boards). Only one, however, the
Bluegiga WT32, supported anything more than simple “ser-
ial cable replacement.”
62
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
E
FROM THE ARCHIVES
by Tom Struzik
Circuit Cellar 240, 2010
In celebration of Circuit Cellar’s 25th year, we’re running an article from the archives each month that exemplifies something special
about this magazine, its contributors, and its readers. We hope you’ll enjoy reading (or perhaps rereading) these innovative projects
as much as we did preparing them. This month, we feature a 2010 article about building a Bluetooth headset.
Figure 1—The Bluegiga WT32 is a highly integrated device. In addition to
the radio, it contains multiple digital and analog I/O sources, a programma-
ble MCU, and a DSP.
Antenna
USART/USB
Flash
RAM
DSP
MCU
XTAL RESET
SPI
PCM, I2S, SPDIF
Audio in/out
PIO
I/O
2.4-
GHz
Radio
Building a Bluetooth-enabled device can be difficult if you don’t have
any experience with the technology. Finding the right module can
greatly simplify the process. The Bluegiga WT32 is a highly integrated
Bluetooth module that fits the bill. Here you learn how to put
Bluetooth to good use.
Wireless Data Exchange
Build a 2,700-lb. Bluetooth Headset
CIRCUIT CELLAR® • circuitcellar.com
http://www.sparkfun.com
indeed make a Bluetooth connection to
my phone. I also felt that I needed to
gain some experience with how the
WT32, iWRAP, and phone interact.
I started by reviewing the documen-
tation that SparkFun had available on its
website. This information consisted of
the WT32 datasheet, the iWRAP user
guide, and the circuit diagram for the
WT32 breakout board. With this in
hand, I thought I should be able to
power up and begin interacting with the
WT32 device.
One thing I noticed while working on
powering up the WT32 was that the
SparkFun breakout board has differ-
ences in the pin nomenclature and
wiring between it and the actual WT32
device. For example, the breakout board
has VDDIO and VDD_BAT wired together
and AGND and DGND have a solder
jumper.
With power to the board, the next step
was to gain access to the UART. The UART
has CMOS input/outputs, so a MAX3232
line driver chip was required for interfacing
to my PC serial port. With the UART con-
nected, I confirmed the basics were work-
ing by running HyperTerminal on my PC and connecting at
115,200 bps, 8N1 to the WT32 UART interface. When I applied
power to the WT32, HyperTerminal displayed the iWRAP boot
screen (see Figure 2). Success!
Now, with a live connection to the WT32’s iWRAP firmware, the
fun really began. The next logical step was to create an hands-
free profile (HFP) link between the WT32 and my smart phone.
With this link, I could explore the basics of Bluetooth link setup
and how the iWRAP firmware operated.
The iWRAP user guide was a bit light on how to actually
set up an HFP link, so I went over to the Bluegiga website
and signed up for their tech support forum. This move
turned out to be excellent, as the tech support forum had
not only firmware updates and PC tools, but also WT32
application notes like the “Hands-Free and Headset Profiles”
iWRAP application note. From this, there were two main
things required to configure an HFP link. The first was to
enable the required Bluetooth profile. The second was to
define the Class-of-Device (CoD).
63circuitcellar.com • CIRCUIT CELLAR
®
Further investigation revealed that the WT32 was quite a
find. Per the datasheet, it has one of just about everything.
On the analog audio side, it supports stereo input and output
with differential signal levels. On the digital audio side, it has
an integrated DSP with stereo codec and support for multiple
digital audio formats (PCM, I2S, and SPDIF). The digital I/O
interface has support for USB, RS-232, and SPI—and on top
of that, 10 individually programmable I/O pins. Most impor-
tantly, in the area of Bluetooth, it supports multiple Bluetooth
profiles (A2DP, AVRCP, HFP, HFP-AG, SPP, OPP, and HID) and
has an integrated antenna, giving the device a 30-m range.
And if all that wasn’t enough, throw in a built-in LiPo battery
charger!
On top of this massive hardware feature list, Bluegiga
loaded the WT32 with its iWRAP firmware. The programming
language provided by this firmware makes it possible to
build a complete Bluetooth application using nothing more
than the WT32 and its UART or USB interface. It appeared
that the Bluegiga WT32 was an almost-perfect candidate for
my project.
Figure 1 and Photo 1 show the WT32 module’s details.
Photo 1c shows the SparkFun breakout board.
GETTING STARTED
My initial goal for working with the WT32 was to breadboard
the simplest possible configuration and validate that I could
FROM THE ARCHIVES
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
Photo 1a—A WT32 module without its cover. The heart of the WT32 is a Cambridge Silicon Radio
BlueCore 5 Multimedia chip. b—The underside of the WT32 module. Don’t place bare copper on your
board underneath the WT32! See the WT32 datasheet for board layout recommendations. c—The
SparkFun WT32 breakout board with the cover intact on its WT32. I added the legs on the breakout
board in order to facilitate easy breadboard experimentation. d—This is the breadboard with the break-
out board on the left.
a)
Figure 2—When I applied power to the WT32, HyperTerminal displayed the
iWRAP boot screen. Success! (Source: Bluegiga Technologies)
WRAP THOR AI (3.0.0 build 165)
Copyright (c) 2003-2008 Bluegiga Technologies Inc.
READY.
b)
c) d)
Enabling and disabling profiles was straightforward. The
iWRAP command was SET PROFILE {profile_name}
[SDP_name]. Note that leaving out the SDP_name disables
the specified profile. For my simple HFP test, it appeared a
“SET PROFILE HFP ON” would work nicely. I knew that later
I’d need to enable multiple profiles in order to complete my
project; but for the time being, I only needed to enable the
HFP profile.
The more cryptic part of the application note was setting
the WT32’s CoD attribute. The application note said to use
200408 with no explanation what the number actually
meant. I took a trip to www.bluetooth.com and the official
specification documents hosted there to turn up informa-
tion. CoD is used during the Bluetooth device discovery
processand is how the queried device responds with its
device type and available services. In the Bluetooth
“Assigned Numbers—Baseband” document, CoD is defined
as three octets consisting of Major Service class (11 bits),
Major Device class (5 bits), and Minor Device class (6 bits).
Even the various bit definitions for the fields were included
in this document.
Another clue came from the iWRAP user manual. It refer-
enced a Bluetooth CoD generator webpage. The CoD generator
let me simply check boxes for services
and classes and then it displayed the
resulting CoD number. From this infor-
mation, I determined the CoD in the
application note—200408—actually
maps to Major Service: Audio; Major
Device: Audio/Video; and Minor
Device: Hands-Free device. Armed
with this knowledge, I could now issue
the required “SET BT CLASS 200408”
command and at least understand
what it was doing.
For my final configuration using both
the HFP and A2DP profiles, I would need
to use a different CoD. For that configu-
ration, I used the generator to produce
the CoD 200418 {Major Service: Audio,
Major Device: Audio/Video, Minor
Device: Hands-free and Headphones}.
With the basic HFP profile configured
and put into the iWRAP firmware, I
cycled the power on the WT32 and initi-
ated a pairing from my phone. During
the pairing process, I noticed that
changing the CoD altered how the WT32
appeared to the phone. Depending on
the CoD, the phone would use different
icons to represent the WT32 device.
Once the phone and WT32 were paired,
I called my phone from another number
and was able to see the incoming call
information through the iWRAP interface. At this point I
believed I had confirmed that everything was working prop-
erly. That was, until I power cycled the WT32. I could still see
that the devices were paired, but they were not connected.
The phone didn’t show an active head-set icon, and incoming
calls no longer displayed information in iWRAP.
After more digging in the iWRAP user guide, it became
apparent that there had to be a CALL command to open the
Bluetooth link between the phone and the WT32. Evidently,
the act of pairing just happened to also make the HFP link
active, but it was not a permanently active link. In fact, even
after a CALL was issued, if either the phone or the WT32 was
rebooted or moved out of range, the Bluetooth link dropped
and was not automatically reestablished.
I finally found a solution in the iWRAP user guide: the iWRAP
AUTOCALL command. Per the documentation, AUTOCALL will
automatically open the specified link to the first paired device
it finds and will even attempt to reopen the link if the link is
dropped. This sounded like just what I needed. The format of
the AUTOCALL command was SET CONTROL AUTOCALL {tar-
get} {timeout} {profile}, which was all relatively obvious,
except for the {target} field that was specified as “the UUID of
the target channel.” Both the iWRAP user guide and the Blue-
tooth “Assigned Numbers—Service
Discovery” document stated that the
UUID for the HFP-AG channel was
111F hex. The HFP-AG channel UUID
must be used rather than the HFP
channel UUID since it’s the handset
making the call to the gateway. Thus,
a “SET CONTROL AUTOCALL 111F
5000 HFP” appeared to be the answer.
Sure enough, after rebooting either
the WT32 or the phone, I could see
the connection being automatically re-
established (see Figure 3).
As a side note, it turned out that
the AUTOCALL function was a bit of
a double-edged sword. It provided
the connect/reconnect functionality;
however, it always tried to connect.
FROM THE ARCHIVES
CIRCUIT CELLAR® • circuitcellar.com
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
64
Figure 4—A more complex solution required using an
AVR processor to control the WT32 through the iWRAP
interface. The PC can still be connected to the system for
troubleshooting. The op-amp is used to convert the
audio-out signal from differential to single-ended mode.
Term
WT32
Op-amp AUX-IN
PBTNS
Mic
Car
stereo
Single-ended
Differential
ATtiny26L
PC
Figure 3—After rebooting the WT32 or phone, I saw the connection automatically reestablished.
(Source: Bluegiga Technologies)
WRAP THOR AI (3.0.0 build 165)
Copyright (c) 2003-2008 Bluegiga Technologies Inc.
READY.
HFP 1
CONNECT 0 HFP 2 00:17:e8:3f:d9:e2 <= Initial Autocall connect
<phone moves out of range>
NO CARRIER 0 ERROR 305 SDC_OPEN_SEARCH_FAILED_PAGE_TIMEOUT
NO CARRIER 0 ERROR 305 SDC_OPEN_SEARCH_FAILED_PAGE_TIMEOUT
<phone moves into range>
CONNECT 0 HFP 2 00:17:e8:3f:d9:e2 <= Autocall reconnect
http://www.bluetooth.com
www.cc-webshop.com
BOGO Sale!
CC G ld d li lifetime of
http://www.cc-webshop.com/CC-Gold-BOGO-CCGOLD-BOGO100.htm?utm_campaign=ccgoldbogo100_201307&utm_medium=epub&utm_source=circuitcellar
When working manually with iWRAP, if
the phone was unavailable, the recon-
nect attempts disrupted any typing into
the iWRAP interface. I found that it was
sometimes easier to quickly key in a
“SET CONTROL AUTOCALL” immediately
after the WT32 booted in order to dis-
able the AUTOCALL function.
At this point, I had verified that I could
successfully connect the WT32 to my
phone. However, the ultimate goal of
one-upping the Prius required establish-
ing A2DP and AVRCP links in addition to
the HFP link. The need for multiple links
quickly became another problem. The
AUTOCALL function only supported mak-
ing one CALL, and I needed to make
three. The only way to establish the addi-
tional links was to manually issue the
multiple CALL commands.
THE SIMPLEST OPTION
After digging through the documen-
tation and on-line forums, it appeared
there were potentially several solutions
to the multicall problem. The simplest
solution relied on a “trick” using the
programmable GPIO pins and the
iWRAP firmware command SET CON-
TROL BIND. Together, these functions
would allow me to automatically trigger
additional iWRAP commands based on
GPIO pin state transitions. Better still,
by specifying different priorities, multi-
ple BIND commands could be made for
the same pin transition.
The other critical iWRAP command to
make this option work was the SET
CONTROL CD command, which ties a
specified GPIO pin to the WT32’s Carri-
er Detect state. So, in theory, this solu-
tion would work thusly: AUTOCALL
would make (and maintain) the initial
FROM THE ARCHIVES
CIRCUIT CELLAR® • circuitcellar.com
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
66
Table 1—This is how I mapped the push-button functions to the various states.
Figure 5—What do you think of this solution? An ATtiny26 AVR controls the WT32.
State Button #1 Button #1 held Button #2 Button #3
Powerup Reset
Call Setup Answer Reject
In Call Mute Hangup
Idle Play Voice Cmd
Streaming Pause Voice Cmd Prev Track Next Track
67
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
HFP link. When this link was made, the WT32 Carrier Detect
state changes and the SET CONTROL CD raises a GPIO pin.
This action then triggers multiple SET CONTROL BIND com-
mands, one for each required CALL.
Even if the link was broken, the CD sig-
nal would be de-asserted. When AUTO-
CALL reestablished the HFP link, the CD
pin would be reasserted and the BIND
commands would then (re)CALL the
other links as well. It seemed like a
simple, elegant solution until I actually
tried to implement it. Several additional
problems arose during implementation.
First, unlike the AUTOCALL command,
the CALL command required that I spec-
ify the Bluetooth address of the destina-
tion. The address would of course change
any time a different phone was paired
with the WT32, and changing the address
would require using the iWRAP interface
to update the address string stored in the
CALL command that was in each SET
CONTROL BIND statement. While this
might have been fine for a one-off
device, I wanted to produce a more gen-
eral-purposesolution.
Second, once multiple links are active,
profile commands like ANSWER,
HANGUP, or AVRCP PLAY need to specify
which link ID should receive the command. The problem
resulted in the link ID appearing to be nondeterministic. It
depended on the order in which the CALL commands actually
completed, so in the end I could not guarantee which link ID
would end up going with which profile.
As the final nail in the coffin, on the simple option, with a
marginal signal, some links would drop while the others
remained active. If the HFP link wasn’t the one that dropped,
the other links never would be reestablished.
BETTER, BUT COMPLEX, OPTION
While the SET CONTROL BIND command could be extreme-
ly useful for a single-profile device, in my case it was not
enough. I needed to investigate other solutions. Thus, the
second solution (see Figure 4) was born, which consisted of
using an Atmel ATtiny26 AVR processor to control the WT32
directly through the iWRAP interface (see Figure 5). The con-
cept was that the AVR would monitor the WT32 state through
event messages displayed in the iWRAP interface and it
would monitor the state of several push buttons. The AVR
could then issue the necessary iWRAP commands to manage
the links and issue the commands to activate the various pro-
file functions such as ANSWER, HANGUP, and PLAY.
There were several advantages to this solution. For one, it
would be easy to simulate and troubleshoot the system by
using HyperTerminal on the PC connected to the iWRAP UART
interface. The AVR could remap push-button functions based on
the current WT32 state, which would have been impossible to
Figure 6—The AVR manages the state of the HFP, A2DP, and AVRCP
links. After the HFP Autocall, the AVR makes the other two calls. Error-
handling is brute-force at this point and just resets the device.
I:“<string>” represents the iWRAP text that the AVR watches for to
drive the state transitions.
Ready
connected
Ready
not connected
I: “READY”
Power-up
Pending
reset
Call
A VRCP
Call
A2DP
Issue
reset
I: “READY”
Button#1 held
I: “PAIR”
*Any*
I: “ERROR 409”
I: “CONNECT 0 HFP 2”
Link state management
I: “CONNECT 3”
I: “CONNECT 1”
I: “SYNTAX ERROR”
Figure 7—The exchange looked like this from the iWRAP interface. (Source: Bluegiga Technologies)
WRAP THOR AI (3.0.0 build 165) <= iWRAP begins booting
Copyright (c) 2003-2008 Bluegiga Technologies Inc.
READY. <= iWRAP completes boot
HFP 1 <= iWRAP invokes the autocall
CONNECT 0 HFP 2 00:17:e8:3f:d9:e2 <= iWRAP connect event
call 00:17:e8:3f:d9:e2 17 a2dp <= AVR placing the AVRCP call
CALL 1
CONNECT 1 A2DP 23 00:17:e8:3f:d9:e2 <= iWRAP connect event
HFP 0 STATUS "service" 1 <= iWRAP continuation
HFP 0 STATUS "call" 0 <= of the Hands Free
HFP 0 STATUS "callsetup" 0 <= profile startup
HFP 0 STATUS "callheld" 0
HFP 0 STATUS "signal" 5
HFP 0 STATUS "roam" 0
HFP 0 STATUS "battchg" 5
call 00:17:e8:3f:d9:e2 19 a2dp <= AVR placing the A2DP call
CALL 2
HFP 0 READY <= iWRAP HFP status continues
HFP 0 UNKNOWN (7): \r\n+COPS: 0,0,"AT&T"\r\n
CONNECT 2 A2DP 25 00:17:e8:3f:d9:e2 <= iWRAP connect for left
CONNECT 3 A2DP 25 00:17:e8:3f:d9:e2 <= and right channel
FROM THE ARCHIVES
68
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
do using the simple option.
There were three main things the AVR needed to track in this
option. The first was tracking and managing the state of the
links. The second was tracking the phone state (the HFP pro-
file). The third was tracking the streaming audio state (the
A2DP profile). With knowledge of the states, the AVR could
map the push buttons to the iWRAP commands necessary to
control the HFP and the A2DP functions. Refer to Table 1 to see
how I mapped the push-button functions to the various states.
I started with building a simple state diagram to outline
what the AVR would need to do. Using HyperTerminal and the
iWRAP interface, I watched the WT32 as it responded to the
various iWRAP events, link states, and phone actions. From
this information, I was able to produce a state diagram (see
Figure 6).
For managing the link state, I deter-
mined that I would still use the iWRAP
AUTOCALL function to control the HFP
link, and then the AVR could daisy chain
off the event messages coming from the
AUTOCALL. From the iWRAP event result-
ing from the successful AUTOCALL, the
AVR could also find the necessary Blue-
tooth address. The AVR could then issue
the two CALL commands, inserting the
Bluetooth address where necessary, to
make the A2DP and AVRCP links. The
exchange looked like Figure 7 from the
iWRAP interface.
Managing the phone call state was rel-
atively simple. An incoming phone call
that was answered and then disconnect-
ed looked like Figure 8 in iWRAP.
Managing the streaming audio was
even easier. The same AVR push button
would control both the PLAY and STOP
commands. The AVR would monitor the
streaming state to determine which
iWRAP command to issue. From iWRAP,
hitting the Play and then Stop button
looked like Figure 9.
The voice command was simple as
well. Since it’s done completely by the
phone, all the WT32 has to do is send
audio of the voice command to the
phone. The phone does the heavy lifting
of recognizing and acting on the voice
command. Refer Figure 10 for the iWRAP
exchange for voice command.
At this stage, I had completed the
design of my “2,700 lb Bluetooth
Headset” that would even beat the
Prius by providing streaming audio in
addition to regular phone headset
capability. I had also learned some Bluetooth basics and I
found a Bluetooth module, the Bluegiga WT32, which I
could use in my future Bluetooth projects.
Even though I only brushed the surface of the WT32 mod-
ule’s capabilities in this article, I hope this whetted your
appetite to investigate further. With a little work, you too can
easily add a Bluetooth interface to your next project.
ADDITIONAL NOTES
Don’t worry if your WT32 from SparkFun initially comes up
with a warning that the firmware is “evaluation only.” You just
need to upgrade the firmware. You can find the latest
firmware on the Bluegiga technical forum. Just sign up to get
access to the firmware, documentation, PC software, and
application notes. The support staff at Bluegiga was helpful
FROM THE ARCHIVES
Figure 8—An incoming phone call which was answered and then disconnected looked like this in
iWRAP. (Source: Bluegiga Technologies)
HFP 0 STATUS "callsetup" 1 <= incoming call, iWRAP start call setup
HFP 0 RING <= iWRAP, the phone rings
HFP 0 CALLERID "5551111234" "" 80 <= iWRAP, caller ID
HFP 0 RING
HFP 0 CALLERID "5551111234" "" 80
HFP 0 RING
HFP 0 CALLERID "5551111234" "" 80
< AVR Answer button pressed>
set 0 select <= the AVR selecting the HFP link
answer <= the AVR issues answer command
HFP 0 OK
HFP 0 STATUS "call" 1 <= iWRAP, successful answer, the call is made
HFP 0 STATUS "callsetup" 0 <= iWRAP, end call setup
RING 4 00:17:e8:3f:d9:e2 SCO <= iWRAP, incoming Audio link to support the call
< AVR Hang-up button pressed>
set 0 select <= AVR selects the HFP link
hangup <= AVR issues hang-up command
HFP 0 OK
HFP 0 STATUS "call" 0 <= iWRAP ends calls
NO CARRIER 4 ERROR 113 HCI_ERROR_OETC_USER <= iWRAP says phone dropped sco link
Figure 9—This is what it looks like when you hit the Play button and then the Stop button. (Source:
Bluegiga Technologies)
<AVR Play/Pause button pressed>
set 1 select <= AVR selects the AVRCP link
avrcp play <= and issues the play command
A2DP STREAMING START <= iWRAP sees streaming start
< AVR Play/Pause button pressed>
set 1 select <= AVR selects the AVRCP link
avrcp stop <= and issues the stop command
A2DP STREAMING STOP <= iWRAP sees streaming stop
Figure 10—The iWRAP exchange for voice command (Source: Bluegiga Technologies)
<AVR Voice Cmd button pressed>
set 0 select <= AVR selects the HFP link
AT+BVRA=1 <= AVR issues voice dial command
RING 4 00:17:e8:3f:d9:e2 SCO <= iWRAP incoming audio link(for voice cmd)
HFP 0 OK < voice command processing happens on phone>
NO CARRIER 4 ERROR 113 HCI_ERROR_OETC_USER <= iWRAP sees audio link close
69
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
when I had questions or problems that weren’t covered in the
FAQs or forums.
The WT32 firmware can be upgraded over UART or SPI.
However, to use SPI you need the necessary interface cable.
The circuit diagram for the SPI cable and the necessary soft-
ware drivers can be found on the Bluegiga forum.
One word of caution: it is entirely possible to configure
non-standard data rates with the iWRAP SET CONTROL
BAUD command. Verify your SET CONTROL BAUD command
before you hit the Return key. Make doubly sure you have
not mistyped the data rate parameter! The normal PC seri-
al port won’t do non-standard data rates. If you misconfig-
ure the WT32, you won’t able to communicate with iWRAP
via the serial port. However, it is still possible to use the
SPI and the PSTOOLS program (also available on the
Bluegiga forum) to reset the iWRAP data rate. Your only
other alternative is to find a serial terminal that will per-
form non-standard data rates. Or you can do as I did and
use a USBee SX signal generator to manually produce the
non-standard RS-232 signals! I
Author’s note: I thank Bluegiga Technologies for granting me
permission to show the header with its copyright statement
in some of this article’s figures.
FROM THE ARCHIVES
PROJECT FILES
To download a circuit diagram and code, go to
ftp://ftp.circuitcellar.com/pub/Circuit_Cellar/2010/240.
RESOURCE
WT32 User Guides, Application Notes, and More, Bluegiga
Tech Forum, www.bluegiga.com/support.
SOURCES
ATtiny26 Microcontroller and AVR assembler
Atmel Corp. | www.atmel.com
WT32 Bluetooth module
Bluegiga Technologies | www.bluegiga.com
Tom Struzik (tpstruzik@earthlink.net) has been building and
taking things apart from an early age. He built his first
Heathkit project at age 12 and sold his first computer program
at age 16. Tom has a BSEE from Purdue University. At the
time of publication, he worked for a Fortune-100 chemical
company in its engineering organization as an IT systems
architect. Tom continues to write software and build hardware
projects at home to “keep his hands dirty.” Visit Tom at
www.JenRathbun.com/Electronics/.
CONNECT WITH
Connect.
circuitcellar.com
mailto:tpstruzik@earthlink.net
http://www.JenRathbun.com/Electronics/
ftp://ftp.circuitcellar.com/pub/Circuit_Cellar/2010/240
http://www.bluegiga.com/support
http://www.atmel.com
http://www.bluegiga.com
http://circuitcellar.com
http://twitter.com/circuitcellar
http://twitter.com/editor_cc
http://www.facebook.com/circuitcellar
70
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
Serial Displays Save
Resources (Part 1)
You can use a dedicated microcontroller to create a user-friendly graphic
display. This microcontroller-based project utilizes a four-wire interface for
its graphic-touch LCD.
D
by Jeff Bachiochi (USA)
uring the 1960s, my uncle Dick used to
taunt me with the question, “What’s a
computer good for?” At the time, I believe he was
a stockbroker, and paper was his best friend (and
worst enemy). If your filing system failed, you
failed. It was easy for me to imagine how the new
desktop monolith could streamline the process for
him. Unfortunately, like many, I was at the mercy
of the huge software companies. As a teenager, I
couldn’t afford a computer, never mind write a spe-
cialized application.
Thanks to RadioShack and computer program-
ming book author William Barden, Jr., that was all
about to change. My best friend Bill Spivey and I
pooled our money and bought a TRS-80 desktop
microcomputer. Barden’s TRS-8 Assembly Language
Programming taught us how to make all the bits
move around inside our new acquisition. I’ve been
playing with bits every since. In 1982, the cult
movie classic TRON gave the world of bit manipula-
tion visual delight.
The complexity of the rapidly developing CPU has
made it almost impossible to program without the
use of higher-level languages. I was saved from a
life of “C” by the introduction of the microcontroller.
The microcontroller was developed to handle spe-
cial tasks instead of “doing it all.” While microcon-
trollers can look like their big brother, the micro-
processor, and accomplish many of the same tasks,
they are limited by their fixed amount of RAM, ROM,
and other peripherals all embedded on a single chip.
Today, it’s difficult to find an appliance that does
not contain a microcontroller. User I/O is a major
part of every appliance. The way in which a device
conveys its purpose is of great concern. Most peo-
ple like simplicity. If a user must defer to a manu-
al to interact with a device, this detracts from the
experience. It would be infuriating if your toaster
required you to set the heat range, the cooking
time, and the bread’s type, size, and the shape
every morning. I want to be able to drop my item
in the toaster and have it returned toasted to per-
fection. Since appliances have yet to implement
mind reading, some compromise is needed. An
entire field of study has been dedicated to how
buttons, levers, knobs, dials, indicators, displays,
and I/O are implemented. Today’s appliance
designers use ergonomics—the study of human
health, safety, and productivity—to improve the
user experience.
Almost every engineering project includes some
user I/O. This might come from a serial port,
where requests and confirmations are handled by
some external device (i.e., a PC with a keyboard
and video). Or, the interactions may be via local
inputs and outputs, not to be confused with other
I/O that may be required to perform the intended
function (i.e., sensors or motors). Requests are
often limited to buttons while confirmations may
range in complexity from simple indicators, to dig-
its, to actual text displays. The use of graphic dis-
plays, while visually appealing, is just too expen-
sive for simple projects. They also greatly
increase a microcontroller’s required workload.
Routines, Registers, and Commands
FR
O
M
T
H
E
B
EN
CH
71circuitcellar.com • CIRCUIT CELLAR
®
used a 16-bit interface, which limited
me to 65,536 colors, but I doubt you
can observe any difference.) The
Adafruit interface has a 3-V regulator
and its buffers handle level shifting,
so it can be used on any 3-to-5-V
system.
The parallel interface consisted of
three main signal groups: power,
LCD, and touch. The LCD group used
an 8-bit data bus and six control
inputs (including reset and back-
light). This follows an Intel 8080
memory bus architecture. Figure 1
shows how the control lines are used
to read and write to any of the
ILI9325’s internal registers. These
registers are used to set up the LCD
hardware and to read and write to
the display graphic RAM (GRAM).
Table 1 shows a few of the most
used registers. All ILI9325 registers
are 16 bits wide, so every read or
write operation must contain a most-
significant byte (MSB) transfer and a
least-significant byte (LSB) transfer.
The index register is written first with
the internal register of interest. Then,
any successive read/write operations are performed on the
indexed register.
PCB
The PCB uses four wires to interface to the project: TX, RX,
5-V (or 3-V) power, and ground. Two baud rates are available,
9,600 and 115,200 bps. Using some built-in ASCII commands,
this design can be treated as a serial device.
Figure 2 shows the circuitry between the four-wire interface
and the TFT module. This PCB can piggyback to the LCD module
or the two can be separated. There are two 20-pin connectors,
I wanted to create a user-friendly graphic display by offloading
the complexity to a dedicated microcontroller. I used a Microchip
Technology PIC24FV16KA302 microcontroller, a 2.8” display, and
Adafruit Industries’s breakout board, whichexposes a 3-to-5-V,
20-pin parallel interface via a standard 0.1” square pin header.
The total cost was approximately $40. Delicate surface-mount
technology (SMT) flex cable soldering was not necessary.
LCD
ILI Technology’s ILI9325 thin-film transistor (TFT) LCD pro-
vides a QVGA (240 × 320) display capable of 262,144 colors. (I
Figure 1—The RS line determines whether data is being transferred between the host and the Index register
(RS=0) or the Index register (RS=1). The nRD or the nWR line not only determine the data direction, but
also act as the data strobe. Sixteen bits of data are passed in separate bytes, transfers, most-significant byte,
and then least-significant byte.
Write to Register
nCS
RS
nRD
nWR
DB[17:10] 00h Write register index Write registerhigh-byte data
Write register
low-byte data
Read from Register
nCS
RS
nRD
nWR
DB[17:10] 00h Write register index Read registerhigh-byte data
Read register
low-byte data
Table 1—Here are a few of the internal registers. (The complete listing is available on Circuit Cellar’s FTP site.) All read and write operations are 16 bits
and require two byte transfers. The register of interest is written with RS=0 (Register Select). This identifies the internal register you will access when
RS=1. For example, a 0x0000 write with RS=0 sets the index register to register zero. This read (only) register contains the driver ID, in this case 0x9324
(ILI Technology’s ILI9325 driver).
# Register Name Read/Write Register Select Most-Significant Byte Least-Significant Byte
IR Index register W 0 0-0-0-0-0-0-0-0 Register #
0x00 Driver ID RO 1 1-0-0-1-0-0-1-1 0-0-1-0-0-1-0-1
0x03 Entry mode W 1 TRI-DFM-0-BGR-0-0-0-0 ORG-0-I/D1-I/D0-AM-0-0-0
0x07 Display control 1 W 1 0-0-PTDE1-PTDE0-0-0-0-BASEE 0-0-GON-DTE-CL-0-D1-D0
0x20 Horizontal GRAM address W 1 0-0-0-0-0-0-0-0 x-x-x-x-x-x-x-x
0x21 Vertical GRAM address W 1 0-0-0-0-0-0-0-x x-x-x-x-x-x-x-x
0x22 GRAM data W 1 16-bit color word
0x50 Horizontal address start W 1 0-0-0-0-0-0-0-0 x-x-x-x-x-x-x-x
0x51 Horizontal address end W 1 0-0-0-0-0-0-0-0 x-x-x-x-x-x-x-x
0x52 Vertical address start W 1 0-0-0-0-0-0-0-x x-x-x-x-x-x-x-x
0x53 Vertical address end W 1 0-0-0-0-0-0-0-x x-x-x-x-x-x-x-x
0x61 Base image display control W 1 0-0-0-0-0-0-0-0 0-0-0-0-0-NDL-VLE-REV
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
72 CIRCUIT CELLAR
® • circuitcellar.com
command has been entered.
Let me start with a simple command that doesn’t require any
intimate knowledge of the display: backlight[0/1}<CR>, which
is a command to control the backlight. The command structure
is the command backlight= followed by a value, 1 (one = ON)
or 0 (zero = OFF), and a closing <CR>.
If you must receive (or send) data while performing other
operations, you should use a separate ring buffer for received
characters and those characters to be transmitted. A UART
Receive interrupt is triggered each time a character is received.
The RX_Interrupt’s job is to use a RX_Head pointer to move
the character from the receiver to the ring buffer. Head and tail
pointers begin initialized to the same address. When they are
equal, there are no characters in the buffer. Received charac-
ters are added to the ring buffer and the RX_Head increments
until the buffer wraps around and sneaks up on the RX_Tail.
If the RX_Head kept increasing until it was equal to the
RX_Tail, it would look like there were no characters in the
buffer (i.e., an overrun). That’s why it’s necessary to check and
stop adding.
While handshaking (hardware or software) can be imple-
mented to prevent loss of data, this should not be an issue as
my commands are relatively short and new data shouldn’t be
sent before a reply is received. The Transmit interrupt is even
simpler. As data is added to the TX ring buffer, the TX inter-
rupt is authorized. This enables the TX interrupt to use
TX_Tail to pull out data from the TX buffer and place it into
one is a socket header for direct connections and the other is a
pin header for using a ribbon cable.
I used a couple of configuration jumpers to enable the user
to select the TX and RX line’s baud rate and polarity (so it can
be directly connected to a PC and commands can be entered by
using a serial terminal program). I added an SD card socket as
an afterthought, in case I want to play around with some graph-
ic files later. Right now, I’m interested in getting this interface
operating, so let’s dive in.
ILI Technology has some example initialization code to help
get you started. C code for Adafruit’s Arduino TFT LCD shield is
also available. The code written for this project is based on
these documents and the ILI9325 datasheet. It is available on
Circuit Cellar’s FTP site.
WHERE 2 START: SERIAL ROUTINES
If you’ve followed any of my projects in the past, you know I
like to start with serial routines, assuming they are a project
requirement. The serial interface is the heart of this project. I
chose a UART interface because it is easy to use and available
on most microcontrollers. Anyone who has written parallel inter-
facing routines for an LCD knows it can be tricky and take up
useful I/O—even more so when user push-button inputs are
added. Using a serial LCD module, as this project provides,
reduces a high-parallel I/O burden down to just two pins.
My design requires that each command be terminated with a
<CR>. This eliminated some confusion with determining when a
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
Figure 2—This schematic shows a four-wire 3–5 VDC interface to send and receive commands to the Microchip Technology PIC24FV16KA302 microcontroller.
The microcontroller handles an 8-bit data bus and six control lines for the ILI Technology ILI9325 TFT LCD driver (plus four more for the touch interface). I
also added an optional SD card interface. SD cards require 3.3 V, so I implemented some level shifting for 5-V operation to provide access to potential local
storage for some bitmap files.
73
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
the transmitter. Each time a character
has cleared the transmitter, another
interrupt is triggered and the buffer con-
tinues to empty. If the pointer TX_Tail
= TX_Head, then the buffer is empty and
further TX interrupts are disabled.
Removing received characters from the
RX buffer and adding characters to the TX
buffer are non-interrupt operations han-
dled by the main loop. The main loop’s
only duty is to look for user requests and
take appropriate action. The main loop’s
first operation is to check the RX buffer
for a character. This is where unloading
the RX ring buffer is handled. A flag bit
RXEmpty is set (or cleared) to indicate
that no character was available (or a
character has been removed and saved in
RXCharacter.)
The second operation is only neces-
sary when RXEmpty indicates a character
is available. Here, the character in
RXCharacter is added to the command
buffer. The command buffer is a linear
buffer that always begins empty and
continues to fill until a <CR> has been
transferred (or the buffer fills). When this
happens, the execution branches to the
MatchACommand routine, otherwise exe-
cution just returns to the main loop.
I used the MatchACommand routine to
determine what to do with data in the
command buffer. I used a command table
(static string in code space) to store legal
commands. The first command is
backlight=, as previously discussed. A
CompareStrings routine uses a pair of
pointers, one pointing to the command
buffer and a second pointing to the com-
mand table, to look for identical matches.
The command table uses uppercase let-
ters, so any letters in the command
buffer must be converted to uppercase
before comparison. If the command
buffer does not match the command, it
tries again until every command string in
the command table has been attempted.
If none are matched, it returns after
clearing the Match flag and resetting the
commandbuffer pointer (to empty the
buffer).
A match of a command to the com-
mand buffer causes a branch to a rou-
tine specific for the command found. In
backlight= I assume the next charac-
ters will contain a value (or a “?”). If a
value other than 0 or 1 is found, the
command is illegal and execution
returns with the Match flag cleared.
When a question mark follows a com-
mand, it indicates a request for the
command’s status. The response for this
request is to send the command back to
the user along with the present value of
that command (i.e., backlight=0<CR>).
If the value found was a 0, then the BL
output is cleared. A 1 value sets the BL
output. The response for bad values, or
no command match, is “?<CR>.” Other-
wise, OK<CR> is used to tell the user the
command was successful. There is
always a response, which adds a hand-
shaking level of confidence.
The code I have written so far initializes
the microcontroller’s I/O and UART. This
microcontroller can configure its UART
output to follow the normal convention
high idle or an inverted output low idle.
This can eliminate the need for a Maxim
Integrated MAX232 driver/receiver, which
also inverts the logic signal.
Most PC ports will work with transistor-
transistor logic (TTL) level communica-
tions. Remember, the signal coming from
the PC will be around ±12 V, so you
should protect the microcontroller’s TTL
input. This project can use the inverted
UART output to connect directly to the PC
and it can communicate with a serial ter-
minal program.
While my project’s object is to provide
a simple interface to a graphic LCD, I will
use a serial connection to a PC to simu-
late command entry. I often begin testing
code by feeding received characters
taken from the RX buffer back into the TX
buffer to test the UART for proper opera-
tion. On the PC I can see whatever I type
in, which helps verify my UART initializa-
tion and buffer code are working. This
test code can then be easily removed,
enabling the main loop code to actually
look for a command.
I always use Microchip Technology’s
MPLAB in-circuit debugger (ICD) when
writing code for PIC microcontrollers. It
programs the microcontroller with my code
and enables me to stop and start execution
for easy debugging. This way, I can stop
the code at various points to ensure
received data has been put into the RX and
Command buffers, matched properly with
a command, and appropriate actions have
been taken for a legal command.
http://massdesign.com
74
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
While the whole project may be defined in my head, my
approach is to start with simple things and build on success,
especially when attempting to use a new device. So, without
getting too deep into the TFT LCD’s workings, I was able use a
received command from the serial terminal program running on
the PC to turn the display’s backlight on and off. This may not
sound like much progress, but the project’s basic structure is
now totally implemented. Now I can spend time getting to know
this display without having to worry about household tasks.
REGISTERS OF INTEREST
With the basic communicating structure in place, I checked
the rest of the display interface by adding a test command to
dump the LCD’s register contents to the serial port. Since the
8-bit data bus is bidirectional, the port used must be correctly
configured as an input or an output for each read or write func-
tion (see Figure 1). This enables data to flow on the 8-bit data
bus in both directions and enables a particular data line to con-
trol the SD card when it is not communicating with the LCD. All
register access with the LCD is handled via a pointer, the Index
Register (IR).
In most cases, you will write to the IR first with the register
number you wish to access. Since there are fewer than 256 reg-
isters, the high byte of this 16-bit write is 0x00. There are times
when you may perform several functions on the same register;
in this case, you will not need to rewrite the IR until you wish to
access a different register. The only difference between the IR
write and a register write is the RS control output’s logic level
(see Figure 1 and Table 1).
A register write contains 16 bits of data, written to the regis-
ter pointed to by the IR. A register read contains 16 bits of data
read from the register pointed to by the IR. You will notice from
the ILI9325 datasheet that not every address has an associated
register. You could just dump all the LCD addresses (from
0–255), but a short table containing a list of the pertinent regis-
ters limits the dump to only those legal registers. Dumping the
LCD’s register set is a good way to check not only the code, but
also the hardware connections. How do you know the data you
are reading from the LCD registers is correct?
Note Register 0 is the driver ID and the only read-only register.
This register is fixed with “0x9325,” which is the hardware chip
number IL9325. If Register 0 displays as “0x9325,” you can have
Photo 1—In this photo of
the help command’s screen
output, the commands
BCOLOR=BLACK and
FCOLOR=WHITE define the
screen background and
foreground colors. The
foreground color is used to
display the characters. The
character set is defined as
6 × 8 pixels to take full
advantage of the complete
(IBM) character set,
including the graphics
characters.
some level of confidence in your code, since both write and read
functions are necessary to retrieve this value.
Now that the interface’s correct operation has been veri-
fied, I can describe how to initialize the LCD. I won’t bore
you with an explanation of every register and how to deter-
mine each one’s proper values. I admit many are a mystery
because they are dependent on which manufacturer’s dis-
play is used with the driver chip (e.g., the IL9325 datasheet
is for the driver chip). The values I used for initialization
have come from the reference material. However, let me dis-
cuss those registers I have found useful (see Table 1).
The Entry Mode register contains bits to set the display ori-
entation. With these bits, you can control the display’s look,
that is, mirror the image or rotate it by 90° increments. This is
like printing in portrait or landscape mode on paper.
The Display Control 1 register is used to turn the display
on/off. This could be useful as you can still perform other oper-
ations on the display while it is off (e.g., updating the screen)
and then turn it back on. Remember this has 240 × 320 pixels
(i.e., 76,800) that can be written to, so some images may
require large transfer times.
Since the screen is made up of 240 × 320 pixels (or vice
versa, depending on the rotation) every pixel has a horizontal
GRAM address; a vertical GRAM address; and red, green, blue
(RGB) GRAM data (i.e., a color word value). The GRAM data
holds a 16-bit color word made from a 5-bit red value, a 6-bit
green value, and a 5-bit blue value. This register also has the
special function of automatically incrementing the horizontal
Table 2—All commands require a terminating carriage return <CR>. The
@X and @Y commands set the pixel location. The PRINT command displays
a 6 × 8 pixel character based at the pixel location (upper left pixel of the
character). The TEXTSIZE variable increases each pixel’s size (to enable
larger characters using the same character set).
Command Description
CLS<CR> Clear the screen using BCOLOR
LF<CR> Y = Y + 1
CR<CR> X = 0
DISPLAY=b<CR> 0 = OFF, 1 = ON
INVERT=b<CR> 0 = Normal, 1 = Inverted
WRAP=b<CR> 0 = No wrap, 1 = wrap lines
BACKLIGHT = b<CR> 0 = OFF, 1 = ON
FCOLOR = hhhh<CR> or
name
hhhh = 16-bit hex value
(rrrrrbbbbbbggggg)
BCOLOR = hhhh<CR> or
name
hhhh = 16-bit hex value
(rrrrrbbbbbbggggg)
P = hhhh<CR> or name hhhh = 16-bit hex value
(rrrrrbbbbbbggggg)
@X = d<CR> 0-display width
@Y = d<CR> 0-display height
TEXTSIZE = d<CR> d = multiplier
ORIENTATION= d<CR> d × 90° (rotated screen)
TEST = d<CR> d = preconfigured routines
PRINT = characters<CR> ASCII characters (any quotes
are printed)
BUTTON = d,d<CR> width, height (button size in
characters)
BITMAP = d,d<CR> width, height (picture size in
pixels)
75
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
PROJECT FILES
To download the code, go to ftp://ftp.circuitcellar.com/pub/Circuit_Cellar/
2013/276.
RESOURCES
Adafruit Industries, library code, GitHub, https://github.com/adafruit.
W. Barden, TRS-80 Assembly Language Programming, RadioShack, 1979.
ILI Technology Corp., “ILI9325: a-Si TFT LCD Single Chip Driver with 240 RGB
× 320 Resolution and 262K Color,” Application Notes, 2008, www.icbank.com/
data/icbshop/board/ili9325an_v0.22.pdf.
SOURCES
Arduino TFT LCD shield
Adafruit Industries | www.adafruit.com
ILI9325 TFT LCD Single-chip driver
ILI Technology Corp. | www.ilitek.com
MAX232 Driver/receiver
Maxim Integrated | www.maximintegrated.com
PIC24FV16KA302 Microcontroller and MPLAB in-circuit debugger
Microchip Technology, Inc. | www.microchip.com
Jeff Bachiochi (pronounced BAH-key-AH-key) has been writing for Circuit Cellar since
1988. His background includes product design and manufacturing. You can reach him at
jeff.bachiochi@imaginethatnow.com or at www.imaginethatnow.com.
and vertical GRAM address. This enables
values to be written without having to
change each pixel’s address. These
addresses automatically wrap at the
ends of the defined boundary, which I
will discuss next.
The screen dimensions define the vis-
ible boundaries of the potential visible
image size. For a full-screen image, the
horizontal boundaries 0x00 and 0xEF
are set by the Horizontal GRAM Address
Start and Horizontal GRAM Address End
registers. Likewise, the vertical bound-
aries 0x00 and 0x1FF are set by the
Vertical GRAM Address Start and Verti-
cal GRAM Address End registers. These
register values define the boundaries
used when determining how to auto-
matically adjust the next pixel’s posi-
tion, performing a wrap at the end of
the boundaries both horizontally and
vertically.
Once you’ve defined the boundary,
data will remain within it. The rest of the
screen remains unaffected. These regis-
ters are also appropriate for designating
smaller areas of interest.
Finally, the Base Image Display Con-
trol register holds the REV bit, which
enables you to invert the display colors.
The complement of the color word value
stored at every screen address is used,
which inverts black/white, red/cyan,
green/magenta, and blue/yellow.
COMMAND LIST
Now it’s time to describe some addition-
al commands. Photo 1 shows the help
screen displayed on the LCD. This is the
default ROTATION=0 using TEXTSIZE=2 to
print multiple strings coming from a Help
table of static strings. This is meant as an
overview and does not fully explain each
command. Many commands require val-
ues, which might be binary, decimal, or
hexadecimal in nature (see Table 2). While
colors can be hexadecimal word values,
color names are also accepted. The prede-
fined colors are black, blue, green, cyan,
red, magenta, yellow, and white.
I chose the commands to provide flex-
ibility to positioning, color, size, and text,
with a special command enabling a sim-
ple implementation of user feedback
through the button display for use with
the integrated touchscreen. Stay tuned
for Part 2, where I will describe how this
is implemented. I
mailto:jeff.bachiochi@imaginethatnow.com
http://www.imaginethatnow.com
ftp://ftp.circuitcellar.com/pub/Circuit_Cellar/2013/276
https://github.com/adafruit
http://www.icbank.com/data/icbshop/board/ili9325an_v0.22.pdf
http://www.adafruit.com
http://www.ilitek.com
http://www.maximintegrated.com
http://www.microchip.com
http://mbed.org
76
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
1 2
3 4
5 6
7 8
9
10
11 12
13
14 15
16 17
18 19
20
Down
1. Theory applies input-to-state (ISS) to systems with
inputs
2. Produces a frequency below approximately 20 Hz
[three words]
4. Security method
6. aka, mantissa
8. They have a four-layer N- and P-type construction
9. Combines two single binary digits [two words]
10. A type of direct-view bistable storage tube [two words]
12. Electric field-buffer [two words]
14. Uses the same key to code and decode
19. Helped create the IEEE 754 floating-point computation
specification
Across
3. Seattle, WA-based supercomputer company founded
in the 1970s
5. A subprogram common to several states [two words]
7. Inverted bits’ value [two words]
11. Lacks processing and storage
13. Locks on an incorrect frequency [two words]
15. This signal is capable of taking on one of three
conditions
16. Known for advancements in telecommunications and
radar
17. XML messaging protocol (hint: prior to 2000)
18. Zero frequency [two words]
20. Moves data bit by bit [two words]
CROSSWORD
The answers will be available in the next issue
and are posted at circuitcellar.com/crossword
July 2013
http://circuitcellar.com/crossword
77
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
THE DIRECTORY OF PRODUCTS AND SERVICES
AD FORMAT: Advertisers must furnish digital files that meet our specifications (circuitcellar.com/mediakit).
ALL TEXT AND OTHER ELEMENTS MUST FIT WITHIN A 2" x 3" FORMAT. E-mail adcopy@circuitcellar.com with your file.
For current rates, deadlines, and more information contact Peter Wostrel at 978.281.7708 or peter@smmarketing.us.
The Vendor Directory at circuitcellar.com/vendor
is your guide to a variety of engineering products and services.
IDEA BOX
mailto:adcopy@circuitcellar.com
mailto:peter@smmarketing.us
http://circuitcellar.com/mediakit
http://circuitcellar.com/vendor
http://www.jyetech.com
http://www.picservo.com
http://www.crystalfontz.com
http://www.cantechno.net
mailto:support@cantechno.net
http://www.cc-webshop.com
RESEARCH
INTERNATIONAL
TRIANGLE
$229 and $295 $229 and $295
before OEM Qty Discount
tel : 1 877 TRI-PLCS
web : www.tri-plc.com/cci.htm
Integrated Features :
- ETHERNET / Modbus TCP/IP
- 16 or 32 digital I/Os
- 10 analog I/Os
- RS232 and RS485
- LCD Display Port
- I/O Expansion Port
- Ladder + BASIC Programming
LISTEN
TO YOUR MACHINES
Ethernet PLCs for OEMs
FMD88 -10
and FMD1616 -10
78
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
microEngineering Labs, Inc.
www.melabs.com 888-316-1753
PIC is a registered trademark of Microchip Technology Inc. in the USA and other countries.
Programmers for Microchip PIC® Microcontrollers
PC-Tethered USB Model (shown):
Stand-Alone Field Programmer:
Program in-circuit or use adapters for unmounted chips.
Zero-Insertion-Force Adapters available for DIP, SOIC, SSOP, TQFP, and more.
Starting at $79.95
microEngineering Labs, Inc.microEngineering Labs, Inc.microEngineering Labs, Inc.
.melabs.com 888-316-1753www
Programmers for Microchip PIC
.melabs.com 888-316-1753
ammerrogrield Plone FAtand-S
(shoodel ed USB MetherTTetherPC--T
Microcontrollers®Programmers for Microchip PIC
.melabs.com 888-316-1753
:ammer
:wn)
Microcontrollers
Starting at $79.95
Adapters available for DIPZero-Insertion-Force
Program in-circuit or use adapters for unmounted chips.
k of Mademared treristegPIC is a r
, TQFP, SOIC, SSOPP, TQFPrs available for DIPP, SOIC, SSOP
Program in-circuit or use adapters for unmounted chips.
. in the USA and other cncechnology ITTechnology Iochip icrk of M
, and more.PP, and more.
Program in-circuit or use adapters for unmounted chips.
.iestroun. in the USA and other c
http://www.tri-plc.com/cci.htm
http://www.melabs.com
http://www.mcc-us.com
http://www.ironwoodelectronics.com
http://www.allelectronics.com
http://www.cc-webshop.com
http://www.hexwas.com
http://www.flexipanel.com
79
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
circuitcellar.com • CIRCUIT CELLAR®
Mosaic Industries Inc.
tel: 510-790-1255fax: 510-790-0925
www.mosaic-industries.com
Tiny 2.5”x4” C-programmable SBC
16 lines of 10-bit resolution analog inputs
24 lines digital I/O with counter/timer and PWM
1 I2C communications port with onboard pull-ups
2 RS232 serial communications ports, 2 SPI ports
Full featured development environment with device
drivers for all I/O
Prototyping area for custom circuitry
Fast, Powerful, Low Cost
Single Board Computer
Only
$84/100s
1
2
3 4
5
6
7 8 9
10
11 12
13
14 15
16 17
18
19
20
L
I
S
S
A
J
O
U
S
C
U
R
V
E
S
U
K
T
N
E
N
O
N
M
A
S
K
A
B
L
E
T
I
L
B
H
F
V
B
L
C
E
V
I
S
I
T
O
R
P
A
T
T
E
R
N
L
R
E
N
N
O
M
D
B
C
A
S
C
O
D
E
C
I
R
C
U
I
T
M
R
N
O
K
O
O
I
T
A
N
R
O
E
N
T
G
E
N
D
D
H
P
D
A
I
E
G
F
I
E
L
D
E
F
F
E
C
T
T
C
L
E
N
U
N
L
I
V
I
C
G
S
I
A
N
A
N
L
E
P
M
G
L
G
I
R
F
M
V
E
L
R
E
T
F
I
E
N
C
R
O
N
T
R
U
N
T
I
M
E
P
S
E
L
S
Y
N
R
Across
2. UNIFIEDMODELING—Language that
standardizes software specifications
3. KELVINBRIDGE—Compares low resistance
values [two words]
6. THINCLIENT—A codependent program
[two words]
10. BANANAPLUG—Makes electrical connec-
tions [two words]
11. CONDENSER—aka capacitor
13. ASTABLE—A multivibrator circuit
15. FLIPFLOP—A fundamental building block
[two words]
18. AMMETER—Used to calibrate current
19. CLOCKGATING—Method of lowering
dynamic power dissipation [two words]
20. THERMIONICVALVE—Uses a vacuum to
control electric current [two words]
Down
1. VISITORPATTERN—Keeps an algo-
rithm away from an object structure
[two words]
4. RUNTIME—A program lifecycle phase
5. FIELDEFFECT—This type is unipolar
[two words]
7. LISSAJOUSCURVE—An oscilloscope
trace [two words]
8. NONMASKABLE—Cannot be ignored
9. CASCODECIRCUIT—Amplifier that
improves reverse transmission [two
words]
12. CRON—OS time scheduler
14. ROENTGEN—Radiation measurement
16. RETFIE—Instruction that enables new
interrupts to occur
17. SELSYN—aka self-synchronous
device
CROSSWORD ANSWERS from Issue 275
LOW cost
with HIGH quality
PCB, PCBA and More
INSTANT QUOTE AT:
www.myropcb.com
OR CALL:
1-888-PCB-MYRO
“Your reliable
outsourcing partner”
MyRO
Integrate Wi-Fi and Ethernet
capabilities into your products
through EZ Web Lynx modules
EZ Web Lynx
Wi-Fi module: $47 Qty.100
Ethernet module: $22 Qty.100
Development Kit: $149
http://www.mosaic-industries.com
http://www.myropcb.com
http://www.busboard.us
http://www.ezweblynx.com/ccjuly
http://www.maxbotix.com
http://www.pcduino.com
There are looming health care and education crises on the horizon.
Baby boomers are getting older and requiring more care, which puts
pressure on caregivers. The US nursing shortage is projected to
worsen. Similarly, the rapid growth of diagnoses of developmental
disorders suggests a greater need for educators, one that the educa-
tion system is struggling to meet. These great and growing shortfalls
in the number of caregivers and educators may be addressed (in
part) through the use of socially assistive robotics.
In health care, non-contact repetitive tasks make up a large part of a caregiver’s day. Tasks such as monitoring instruments only
require a check to verify that readings are within norms. By offloading these tasks to an automated system, a nurse or doctor could
spend more time doing work that better leverages their medical training. A robot can effectively perform simple repetitive tasks (e.g.,
monitoring breath spirometry exercises or post-stroke rehabilitation compliance).
I coined the term “socially assistive robotics” (SAR) to describe robots that provide such assistance through social rather than
physical interaction. My research is the development of SAR algorithms and complete systems relevant to domains such as post-
stroke rehabilitation, elder care, and therapeutic interaction for children with autism spectrum disorders (ASD). A key challenge for
such autonomous SAR systems is the ability to sense, interpret, and properly respond to human social behavior.
One of my research priorities is developing a socially assistive robotic system for children with ASD. Children with ASD are charac-
terized by social impairments, communication difficulties, and repetitive and stereotyped behaviors. Significant anecdotal evidence indi-
cates that some children with ASD respond socially to robots, which could have therapeutic ramifications. We envision a robot that could
act as a catalyst for social interaction, both human-robot and human-human, thus aiding ASD users’ human-human socialization. In
such a scenario, the robot is not specifically generating social behavior or participating in social interaction, but instead behaves in a
way known to provoke human-human interaction.
Enabling a robot to exhibit and understand social behavior with a child is challenging. Children are highly individual and thus tech-
nology used for social interaction needs to be robust to be effective. I developed an autonomous robot that recognizes and appropri-
ately responds to a child’s free-form behavior in play contexts, similar to those seen in some more traditional ASD therapies.
To detect and mitigate child distress, I developed a methodology for learning and then applying a data-driven spatiotemporal model
of social behavior based on distance-based features to automatically differentiate between typical vs. aversive child-robot interactions.
Using a Gaussian mixture model learned over distance-based feature data, the developed system was able to detect and interpret social
behavior with sufficient accuracy to recognize child distress. The robot can use this to change its own behavior to encourage positive
social interaction.
To encourage human-human interaction once human-robot interaction was achieved, I developed a navigation planner that used
the above spatiotemporal model. This was used to maintain the robot’s spatial relationship with a child to sustain interaction while
also guiding the child to a particular location in a room. This could be used to encourage a child to move toward another interaction
partner (e.g., a parent). The desired spatial interaction behavior is achieved by modifying an established trajectory planner to weigh
candidate trajectories based on conformity to a trained model of the desired behavior.
I also developed a methodology for robot behavior that provides autonomous feedback for a robot-child imitation and turn-taking
game. This was accomplished by incorporating an established therapeutic model of feedback along with a trained model of imitation
behavior. This is used as part of an autonomous system that can play Simon Says, recognize when the rules have been violated, and
provide appropriate feedback.
A growing body of data supports the hypothesis that robots have the potential to aid in addressing the needs of people through non-
contact assistance. My research, along with that of many others, has resulted in technical advances for robots providing assistance to
people. However, there is a long way to go before these systems can be deployed as a therapeutic platform. Given that the beneficiary
populations are growing, and the required therapeutic needs are increasing far more rapidly than the existing resources to address it,
SAR could provide lasting benefits to people in need.
Using Socially Assistive Robots
to Address the Caregiver Gap
80
Ju
ly
2
0
1
3
–
I
s
s
u
e
2
7
6
CIRCUIT CELLAR® • circuitcellar.com
David Feil-Seifer, a Postdoctoral Fellow in the Computer Science
Department at Yale University, focuses his research on socially
assistive robotics (SAR), particularly the study of human-robot
interaction for children with autism spectrum disorders (ASD). His
dissertation work addressed autonomous robot behavior so that
socially assistive robots can recognize and respond to a child’s
behaviorin unstructured play. David received his MS and PhD in
Computer Science from the University of Southern California and a
BS in Computer Science from the University of Rochester, NY. He
recently was hired as Assistant Professor of Computer Science at
the University of Nevada, Reno.
TECH THE FUTURE July 2013
Can anyone deny that we’re on the verge of some major
breakthroughs in the fields of microcomputing, wireless
communication, and robot design? Tech the Future is a
recurring section devoted to the ideas and stories of
innovators who are developing the groundbreaking
technologies of tomorrow.
by David Feil-Seifer
PICDEM™ Lab Development
Kit (DM163045)
FAST START
DEVELOPMENT TOOLS
PIC10F32X Development
Board (AC103011)
PICkit™ Low Pin Count
Demo Board (DM164120-1)
www.microchip.com/CLC
www.microchip.com/cip
Mitb-8
lotronocrci M
ith wserll
aregtnI
gon� Cdeta
og Lelbaurg
ciog
1CIs P’’s PpihocrciM
1FL/FF/61//121CInd PX a23FL/F01
d du aot yes lUCt Mib-X 8051
inghctiw sevorimp
. Tecpae sode cvas
o lc tiogl laitneuqes
e Llbraug�noe ChT
mund N) aGWC(
oe Llbaurg�onC
s fngiseur doin y
, ryy, rtilaonitcunf
1CIs PpihocrciM
er pelipult mssorc asiecniec� eing
fevay Wratnemelpmoe Chn teh. T
t yu, cytilanoitcnud fdu aoet yo l
wtfu sooe yvi) gsCLCs (llec Cioge L
or (tlailcsd Oellotrony Cllacierm
enemlomp, C)sCLCls (lec Cigo
e plbasopsit or dsoc-wor los f
t asoe cht tund c, aezie scude, r
1FL/FF/61//121CInd PX a23FL/F01
lylacierum Neh ttslih w;slaerhiper
u tos yple) hGWCr (otraenem Grof
t anuot cnenopmol canretxr euo
d nl aanoitanibmof cl ootrnoe craw
.)OCNor (
or taerenm Gorfevay Wraten
d raobth on-i, wstcudore p
on iptmusoner cwond pt a
d du aot yes lUCt MibX 8051
ly
ntempoleev Dab L™MEDCIP
ENMPOELVED
TT SSAF
)546301MD (tiKo u t
d nt a
d
SLOO TTEN
T RAT
ntempoleev DX23F01CIP
)110301CA (draoB
t Punoin cw plo
c.miww w tooG
pirM peWr Puoo ft
M6d 1roa-bnn oa
d PnX a23F/L0FF/L1CIP
is lnoitacilppr aof
alld OsciellotrnoC
inghctiw sevorimp
endepe indorth cis wUC® MCIt P
t morund oo � tpic//comc.pihocrc
t 6cpamoo ctnd iekcl pal. Aslraehp
peme, tDC, Arr, Aotallscil oanretnz iH
nibmos cUCX M051F/LF/61/21CId P
d bang anithgi, lsrotraenee gnoe tk
neuqerr faenis ledivor) pOCNr (ot
er pelipult mssorc asiecniec� eing
lsaerhpiert penend
t uobe at mor
.segakcn pai-p0o 2- tt 6
d un, aeluodr motacidni-erutrape
h tin woitpmusnot cnerruw coe ln
.lotrnot csalld ba
n oitulsoer rehgid hnl aotrnoy ccn
lylacierum Neh ttslih w;slaerhiper
p
w Po™ LtikCIP
hi
d u
h
n
ly
cormic.www
g�noC CLe CerF
MDd (raoo BmeD
t nuon Ciw P
CCL/moc.phi
:loon Toitrau
)1-021461M
the Microchip logo,The Microchip name and logo,
y Inc. All rights reserechnolog©2013 Microchip T Technolog
MPLAB and PIC are registered trademar dsPIC, the Microchip logo,
ved. 03/13y Inc. All rights reser
porated in the U.S.A. and other countries. y Incorechnologks of Microchip T Technolog MPLAB and PIC are registered trademar
porated in the U.S.A. and other countries. ks are the properAll other trademar
s. ty of their registered ownerks are the proper
http://www.microchip.com/CLC
http://www.microchip.com/cip
http://www.pcbnet.com
mailto:sales@pcbnet.com