Cover.qxp 3/3/2008 3:44 PM Page 1

LOW-POWER DESIGN TECHNIQUES P. 22 • TRIAC CONTROL P. 46 • INSIDE THE STM32 P. 80 w w w . c i r c u i t c e l l a r . c o m CIRCUITTHE MAGAZINE FOR COMPUTER CELLAR APPLICATIONS #213 April 2008 EMBEDDED PROGRAMMING An Embedded Linux Development Environment

Hardware Development from a Programmer’s POV

Build a Digital Potentiometer

A Video Display for Debugging Your Programs

A Simple Programmable USB DAC

The DIY Motion-Sensing System Continued

04>

7925274 75349 $4.95 U.S. ($5.95 Canada) C2.qxp 3/3/2008 11:16 AM Page 1

SERIAL TO ETHERNET SOLUTIONS

Simple Ethernet connectivity for serial devices Works out of the box - no programming is required

Device P/N: SB70-100CR Customize to suit any Kit P/N: NNDK-SB70-KIT application with low-cost $69 SB70 development kit 2-port serial-to-Ethernet server Features: Qty. 100 with TTL support 10/100 Ethernet TCP/UDP mode DHCP/Static IP Support Data rates up to 921.6kbps Web-based configuration Need a custom solution?

NetBurner Serial to Ethernet Development Kits are available Device P/N: SB72-EX-100CR to customize any aspect of Kit P/N: NNDK-SB72EX-KIT operation including web pages, data filtering, or custom network SB72EX $139 applications. All kits include 2-port serial-to-Ethernet server platform hardware, ANSI C/C++ Qty. 100 with RS-232 & RS-485/422 support compiler,TCP/IP stack, web server, e-mail protocols, RTOS, flash file system, Eclipse IDE, , cables and power supply.

Device P/N: PK70EX-232CR Information and Sales | [email protected] Kit P/N: NNDK-PK70EX232-KIT Web | www.netburner.com $269 PK70EX232 Telephone | 1-800-695-6828 4-port serial-to-Ethernet server Qty. 100 with RS-232 support 1.qxp 3/6/2008 10:27 AM Page 1 2.qxp 3/3/2008 10:49 AM Page 1

BEST SCOPE & LOGGER SELECTION!

20/40MHz AWG 100MHz DSO 100/200/300MHz DSO Scope + Analyzer 15/20MHz Wfm Gen Announcing ...a new name in high-end, NEW! NEW! NEW! NEW! NEW! RIGOL RIGOL RIGOL RIGOL RIGOL high reliability, value- priced test gear: RIGOL. (pronounced ‘regal’) 25/40MHz USB 14-bit ARB w. USB 100MHz 2-ch 400MS/s DSO 100/200/300MHz 2 ch, 2GS/s DSO 100MHz 2-ch /16 logic scope 15/20MHz USB 14-bit Function/ Formerly the partner of RS-232, LAN/GPIB. 10 built-in 2000 wfm/s refresh rate. 2000 wfm/s refresh rate. Ultra and logic analyzer. 2000 wfm/s Arbitrary wfm Generators. 10 built-in a large scope company we can't name, Rigol wfms; FM, AM, PM, FSK, SWEEP Ultra Compact Design with Compact Design with small footprint refresh rate. See waveforms and wfms; FM, AM, PM, FSK, SWEEP produces the best and BURST; 6 digit 200MHz small footprint saves bench saves bench space. DS1102A $1295 logic data simultaneously. Trigger and BURST; 6 digit 200MHz quality/value LCD scopes frequency counter. space. DS1202A $1595 on data or signal edge. frequency counter. FreeCase! available on the market today. DG2021A/DG2041A $995/$1495 DS1102C FreeCase! $999 DS1302A $1995 DS1102CD FreeCase! $1499 DG1011 / DG1021 $650 / $795 Color LCD Scope Low-Cost Scope PicoScope 3206 2/4ch 12-bit USB Scope World’s Fastest 60/100/120MHz AWG

Best NEW! RIGOL Seller Winner! Owon - 25MHz 2-ch + 2-ch 40/100/200MS/s 8-bit scope PS3206 - Is an impressive 2-ch Pico - New 2/4-ch 12-bit 20MS/s PS5204 - 2-ch 250MHz Scope with 60/100/120MHz USB 14-bit ARB trigger standalone USB bench range with 5/10/25MHz bandwidth 200MS/s 8-bit PC scope adapter USB2.0-connected/powered 128 MS/s and real-time sampling of w. USB RS-232, LAN/GPIB. 10 scope with 7.8” color LCD. and USB2.0 for fast screen - 10GS/s for repetitive signals! scope adapters. Scope, FFT, 1GS/s. Adv triggering. 250MHz spec. built-in wfms; 6 digit 200MHz Battery powered optional. updates. Inc. scope/FFT/logging No power supply needed, simple and meter displayed at once analyzer and 125MS/s waveform gen. frequency counter; opt. 16-ch PDS5022S SALE! $325 software, case, probes. USB 2.0 connection with included software. PS5203 32MS buffer $2237 gen. DG3061A $1895 PDS6062T $599 PS2203/4/5 from $318 PS3206 Bundle $1574 PS3424 / PS3224 $1398 / $793 PS5204 128MS buffer $3360 DG3101A/DG3121A $2795/$3995 6 in 1 Scope Automotive Testing Mixed -Signal PC Oscilloscope Handheld Scope Pen Scope

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

"Thanks for your excellent customer NEW! service and dedication Log and display temperature, Handheld Palm PC-based T&D - Networked logger for TTI - high speed/accuracy AC USB1.1/2.0/WiMedia analyzers to finding and humidity, voltage, event-time or 2.7GHz Spectrum Analyzer. remote ambient measurement. power analyzer to 16A for easy and now - EX260 can test pulse-counting data up to 100 Multiple sweep settings – store representing unique Send email or phone warnings if product power-compliance USB3.0 5Gbps too! Emulate meters away from base station. wfms, set-ups, etc. Use WiFi PC manufacturers ... " thresholds exceeded. Optional measurements. Measures/displays host/device, verify compliance. RTR-50 modules from $170 for email, reports, calculations. WiFi for remote installation. 1st - 40th harmonics in real time. TR110 / EX200 / EX260 RTR-57U base $401 PSA2701T $1990 K.R. TR-72W $489 HA1600A from $2899 $999 / $2999 / CALL Ultimate Temp Logger 8/16ch Voltage Logger Voltage Data Logger USB Temp Logging Thermocouple Logger DMM

NEW! RIGOL

PT104 - 4-ch temperature 20-bit 8-ch / 24-bit 16-ch USB Pico USB ADC-11 - USB DLP - Low cost, USB-powered Pico USB TC-08 - USB connected 6 1/2 digit 50KS/s, 2MS mem. Opt. logger with 0.001°C resolution, voltage logger w. control output. powered 11-ch voltage data digital sensor. Easily monitor and powered 8-ch thermocouple 16-ch mux. Automeasure DC/AC, 0.01°C accuracy using platinum Galvanic isolation from the PC logger - 10kHz sampling temperature/humidity/dew data logger. Samples at up to 2/4-wire R, C, Continuity, Diode, PT100 sensors. Also measure eliminates noise. rates with digital outputs for point from USB port. 10 readings/s with built-in Frequency, Period, Ratio, Temp, resistance and voltage. ADC-20 (20 bit) $321 control or alarm. CJC for -270oC to +1820oC. Sensor, High/Low Limit Math. PT104 $747 ADC-24 (24 bit) $747 USB ADC-11/10 $178 DLP-TH1b $88 USB TC-08 $466 DM3061 $795 Electronic DC Load EMC Spectrum Analyzer Logic Analyzer USB Logger Temp/Humidity Logger FREE COFFEE

Call 1-888-7SAELIG For testing dc power/battery sources EMC RF & EMF Spectrum - ZeroPlus - Intuitive full-featured 16-ch EL-USB-1 - Standalone USB temp HumidiProbe - PC-based Mention Offer# SBW Const. current, resistance, Analyzer 1Hz to 7GHz for measuring 4MB 200MHz sampling memory. o o data logger (-25 C to +80 C). $49 temperature and humidity to get a free conductance, voltage and power transmissions from radar, radio/tv 2 Data Loggers & Analyzers Sophistcated triggering. I C, SPI, El-USB-2 (+ humidity) $79 measurements are quick and Starbucks Card modes 0 to 80 V and 0 to 80 A 300W towers, WLAN, WiFi, WiMAX, and UART monitoring. Includes EL-USB-3 (voltage) $69 easy with RH-02 data logger. with your order! Transient generator. Variable drop-out. Bluetooth, microwave ovens, etc. clipleads, USB cable and software. EL-USB-4 (current loop) $69 USB2.0 connected and powered. While supplies last - LD300 $1555 from $299 / $1999 LAP-16128U $299 EL-USB-CO (Carbon Monoxide) $89 PP299 $279 not available with any other offers Also LOTS of other products such as: Antennae, Barcode Readers, Cables, CANbus/LINbus products, Data Loggers, Digital Audio / DSP Filters, Embedded PC's / Controllers, EMC shielding, enclosures and tents, Ethernet boards and serial cable converters, FATfile Chips / Boards, GPS loggers, engineering Software, I/O Boards & Modules, I2C boards and controllers, ICs (USB, Ethernet, RFID), Industrial PC's, OLED / LCD Displays kits, Logic Analyzers, Motor Control, MP3 boards, Panel Meters, Polystyrene Capacitors, Power Supplies, Radio/Wireless modules, Robots, RS232/422/485 Adapters, SMD Adapters, Surge Protection / Isolation, USB-serial and I/O boards, Video, VMEbus boards, Web Servers, etc. Check www.saelig.com for special offers, bargains, business hints, blog, etc. 3.qxp 3/3/2008 10:51 AM Page 1

UNIQUE PRODUCTS + FREE SUPPORT!

Serial-Ethernet Cable Ethernet to Serial Ethernet-IO Ethernet-Serial Gateway Serial Server Mini Web Server

Network your serial product easily WIZnet - Ready-to-go serial-to- Ether-IO - UDP/IP-controlled 24 Compact 80188 controller for RS232/422/485 device server for PicoServTM Miniature Web Server without a PC using this 28” cable. Ethernet Gateway. Simple set-up digital I/O board 3 x 8-bit TTL intelligent serial networking. TCP/IP network-enabling legacy serial allows remote I/O and servicing. Provides an instant IP address. for 10/100Mbps Ethernet - ports each independently features TCP, UDP, IP, ICMP, ARP, devices. 1/2/4/8/16/32 ports Collect analog & digital data over RS-232 port compatible with most 230kbps serial. Ethernet/ programmable. Connects to any RARP. 256/512kB SRAM/FLASH. 10/100Mbps-230kbps. Static a web connection. Remote sensing/ 10/100mpbs Ethernet hubs. Internet-enable any serial part. TCP/IP Ethernet network. Embedded Datalight RomDO. IP/DHCP/PPPoE. control, SCADA, building control. Ethernet eCOV-110-P $89 EG-SR-7150MJ $34 Ether-IO 24 $119 EX9188E1 $116 Portbase-3010/RS232 from $171 PP1001-V00 $205 USB to I2C Ethernet to I2C Ethernet to I2C I2C for PCs Blue & White LCD Saelig Alan Lowne says: "I started Saelig as an engineer - for PCI93LV: industry-standard I2C card engineers! Saelig - an Devasys - Provides a simple NM7010A-LF REV 2 - Complete, Fiveco - TCP/IP server with I2C, for PCs. WINI2C/PCI software Comfile - LED backlit 4 x 20 Olde English “drop-in” solution for connecting hardwired TCP/IP-I2C module. Offloads 19 x digital I/O, 5 x 10-bit A/D gives windows-interface to develop character display. CuNET, word meaning 'happy, prosperous,

I2C blessed' - which is what I want for your PC to 90kHz I2C + 20 I/O stack for hi-speed Internet-enabling inputs, and UART serial interface. and debug I2C bus systems. RS232 or I2C communication my customers, my staff, and 2 lines. Free software. Use multiple systems. Drop-in Connect I C devices/sensors UCA93LV is USB version. to 115Kbps. BASIC programmed. myself! See my blog for behind- boards for more I2C/IO. W3100A-based board for instant to an Ethernet network! Transparently monitor at 2.36” x 3.86” the-scenes company details, business hints, kudos, etc. " USB I2C/IO $79 network speeds to 8Mbps. $22 FMod-TCP from $250 400kHz! $499 CLCD420-B $49 Quantum WIZnet TCP/IP IC Servo IC USB On-The Go FATfile Storage USB - Serial

Quantum ICs - World’s best capacitive 10/100 Ethernet controller on a PIC-SERVO - complete PID servo Chesen - Sophisticated application Micro ALFAT-SD - Easily add FT232RL - FTDI USB1.1-serial IC with sensor ICs for switching & control. chip! Fully hardwired TCP/IP core. motion control system based interface. Quickly develops SD storage to your product. new "security-dongle" feature. Each ICs Patented Adj. Key Suppression, No OS required. TCP offload on PIC18F2331. PID servo filter, USB OTG memory- memory Serial data in - FATfile data unique ID and Internal EEPROM, Spread-spectrum. In use worldwide improves system performance. motion profiling, commutation, error devices without PC connection. out. FT232RL $2.36 (1K) by the world’s largest consumer/ W5100 (integrated PHY) $5.58 monitoring, communications, etc CSC3800 NEW! uALFAT-SD $40 FT232BL $3.21 (1K) appliance mfrs from $1 NM7010B+ Eval $22 PIC-Servo $30 OXDK-3800 CALL uALFAT IC $14 Check out the whole FTDI line! Isol USB485 USBwiz Security Tiny USB Serial 1/2/4/8/16 x RS232 Wireless USB2.0

KK Systems - Isolated USB- USBwiz - Easily add USB DLP - Programmable USB Security World's smallest USB Add COMports via your PC’s Wirelessly connect to your USB 2.0 RS422/RS485 converter. FTDI peripherals to your system. Includes Dongle based on FT232RL - log adapters. Ready-made USB Port. USB-COM-S $20 devices with our USB-IF Certified

USB chipset. Virtual COM port for all FATfile system for USB thumb & use/user/expiry, etc. Optional CP2101 miniboard USB USB-2COM $48 Wireless USB Hub at up to win32 applications. USB-DB9F. external USB hard drives. No sophisticated software allows interface to 1 Mbps. USB-4COM $105 480Mbps. For printers, scanners, USB knowledge needed. Plug-n-play! customizability. uUSB-MB $25 USB-8COM $195 memory, cameras, MP3s, (not webcams USB-485-K $99 IC $20 Demoboard $59 DLP-D $13 HR-USBUART $29 USB-16COM-RM (rackmount) $459 or Bluetooth). GUWH104KIT $185 Wireless Modules Transceiver Modules Antennae Bluetooth RF Modules Customers Join our huge list of satisfied customers:

Intel, Philips, Maxim, TM Easily create mesh networks at LPRS easyRADIO makes Antennae - Innovative internal Emxys microIceBlue - PIC16F877 RF TX/RX Modules - simultaneously GM, GE, NEC, Kodak, 910MHz - like Zigbee only better! wireless d a t a transmission and external specialized based emb. dev. system for shortest transmit composite video and Xerox, Nokia, TI, Harris, Complete RF solution for fast & simple for the US and Europe! miniature multiband antennas Bluetooth development. $139 stereo audio signals. 2.4 GHz Sony, Pelagic, Sandisk, reliable data transmission. Add wireless capability to your including Yagi for multiple PearlBlue - 100m-Bluetooth module ISM band. 4-ch RF, 5V operation HP, General Dynamics, B915FHtiny-plus/40-SMD-WA $63 project today! uses - 900/1800/2400MHz/GPS. (UART master/slave bridge). Connect AWM630TX $16 Wireless US Military, etc. B915FHtiny-plus/40-DIP-WA $82 ER900TRS from $38 (100) from $4 micro's to PCs, PDAs, phones, etc. $99 AWM634RX $27 CANbus RF Testing Easy OLED Display Custom SM PCB Adapters GPS Logger

Janz - Intelligent CAN connection Economical, portable RF test 4D Systems - Compact, economical Lorlin - Fantastic array of OM-Adapt SM miniboards have TrackStick II - Pocket-sized logger from PC’s USB port. Provides enclosures, for initial compliance smart OLED with graphics for stock and custom switching two footprints on each side. Now tracks position data for vehicles, plug’n’play opto-isolation. Other testing. from $1295 ‘stand-alone’ functionality to your devices choose from rotary use your ultra fine pitch SMD personnel, etc. Records date, time, Misc CANbus boards and systems Shielding Tents with external project - drive from USB or RS232. encoders, push, key, slide and components with more useful 0.1" location, route and speed. Shows available from Janz AG. frame, instant up/down for uOLED-96-G1 $101 rotary switches. Voltages up to inline spaced holes. data on Google maps! $175 CAN-USB from $299 emissions-free room. from $3500 uOLED-128-GMD1 $84 250V. CALL One-to-one pinouts. from $9.52 Super TrackStick II $239

We search the world for unique, time-saving products - see our website for 100s more: volt/temp data loggers, wireless boards, LCD display kits, Ethernet/IO, USB/RS232/485, USB-OTG, instant Ethernet-serial, CAN/LINbus, USB cables/extenders, line testers, logic analyzers, color sensors, motion controllers, eng. software, wireless boards, SMD adapters, I2C adapters, FPGA kits, GPS loggers, automotive testing, security dongles, video motion detectors, crystals/oscillators, custom switches, barcode scanners, robots, DSP filters, PLCs, Remote MP3 players. etc. Don't forget to ask for your FREE Starbucks card with order! Check www.saelig.com for special offers and bargains. Task_Masthead_213.qxp 3/6/2008 10:33 AM Page 4

TASK MANAGER

Smart Design & Intelligent Programming FOUNDER/EDITORIAL DIRECTOR CHIEF FINANCIAL OFFICER Steve Ciarcia Jeannette Ciarcia MANAGING EDITOR MEDIA CONSULTANT C. J. Abate Dan Rodrigues when we began planning this year’s Embedded Programming issue back in late 2007, our goal was to provide informative articles about WEST COAST EDITOR CUSTOMER SERVICE Tom Cantrell Debbie Lavoie embedded development, programming, debugging, and efficient system CONTRIBUTING EDITORS CONTROLLER design. To achieve this goal, our staff worked closely with the writers to Jeff Bachiochi Jeff Yanco concentrate their articles on these topics. Our project editors read Ingo Cyliax ART DIRECTOR through each article and then provided the writers with useful feedback Robert Lacoste George Martin KC Prescott in an effort to help them focus their work on the specific needs of our Ed Nisley GRAPHIC DESIGNER readers, most of whom are the professional engineers who are design- NEW PRODUCTS EDITOR Carey Penney ing and programming the world’s newest embedded technologies. It’s John Gorsky STAFF ENGINEER clear that the creative projects described in this issue highlight the ben- PROJECT EDITORS John Gorsky efits of combining sound design techniques with careful programming. Gary Bodley To kick things off, David Lynch thoroughly describes how he creat- Ken Davidson ed a virtual Linux environment on a Windows system (p. 14). In the first David Tweed article of his series on the topic, David introduces you to coLinux, a ASSOCIATE EDITOR handy version of Linux that serves as his platform for embedded cross- Jesse Smolin development. On page 22, columnist Robert Lacoste delivers several “Intelligent ADVERTISING Energy Solutions.” You probably recall that this special section was first 860.875.2199 • Fax: 860.871.0411 • www.circuitcellar.com/advertise introduced by Steve Ciarcia in his three-part series about his solar PV PUBLISHER system (Circuit Cellar 209, 210, and 211). In this article, Robert provides Sean Donnelly Direct: 860.872.3064, Cell: 860.930.4326, E-mail: [email protected] useful design techniques for building efficient, energy-saving electronic ADVERTISING REPRESENTATIVE systems. Shannon Barraclough If you’re interested in a programmable power source, Yoshiyasu Direct: 860.872.3064, E-mail: [email protected] Takefuji’s article is for you. On page 35, Yoshiyasu walks you through ADVERTISING COORDINATOR the process of constructing a simple programmable USB DAC, which Valerie Luster he built around an ATtiny45 and a MAX517. E-mail: [email protected] In the second part of his series about building a “DIY Wii,” Chris Coulston goes into the details about manipulating 3-D graphics (p. 40). Cover photography by Chris Rakoczy—Rakoczy Photography As you’ll see, the system can easily interact with a variety of graphics www.rakoczyphoto.com PRINTED IN THE UNITED STATES programs. Chris’s students use it to design their own games. Now you can, too. CONTACTS SUBSCRIPTIONS Need precise power control? Ed Nisley has the answer. This month Information: www.circuitcellar.com/subscribe, E-mail: [email protected] he describes how a triac behaves when confronted with an inductive Subscribe: 800.269.6301, www.circuitcellar.com/subscribe, Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 load (p. 46). Address Changes/Problems: E-mail: [email protected] Turn to page 52 to learn how Jose Sanchez uses his “Video Stamp” GENERAL INFORMATION 860.875.2199, Fax: 860.871.0411, E-mail: [email protected] system to debug his programs. The PIC-based system provides an Editorial Office: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] New Products: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] NTSC-compatible video signal to display content from his applications. AUTHORIZED REPRINTS INFORMATION Get ready to build your own. 860.875.2199, E-mail: [email protected] AUTHORS Are you a programmer looking to take on your first design project? Authors’ e-mail addresses (when available) are included at the end of each article. In “Simple Hardware Development,” longtime programmer Taylor Hutt

describes how he completed his first project with a Xilinx Spartan-3E CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) is published monthly by Circuit Cellar Incorporated, 4 Park Street, Vernon, CT 06066. Periodical rates paid at Vernon, CT and additional offices. One-year (12 issues) starter kit and the VHDL programming language (p. 60). subscription rate USA and possessions $23.95, Canada/Mexico $34.95, all other countries $49.95.Two-year (24 issues) sub- On page 73, Jeff Bachiochi describes his “touch slide digital pot” scription rate USA and possessions $43.95, Canada/Mexico $59.95, all other countries $85. All subscription orders payable in U.S. funds only via Visa, MasterCard, international postal money order, or check drawn on U.S. bank. Direct subscription orders project. He took mechanical parts out of the equation and designed a and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 or call potentiometer with no moving parts. 800.269.6301. Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650. In this issue’s final article, Tom Cantrell continues his examination Circuit Cellar® makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for the of 32-bit MCUs by taking a second look at the STMicroelectronics consequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of read- er-assembled projects, Circuit Cellar® disclaims any responsibility for the safe and proper function of reader-assembled projects based upon or STM32 (p. 80). Is the STM32 the “best” 32-bit MCU? Tom provides his 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 answer. What’s yours? build things based upon these ideas under patent or other relevant intellectual property law in their jurisdiction, or that readers have a right to construct or operate any of the devices described herein under the relevant patent or other intellectual property law of the reader’s jurisdiction. The reader assumes any risk of infringement liability for constructing or operating such devices. Entire contents copyright © 2008 by Circuit Cellar, Incorporated. All rights reserved. Circuit Cellar is a registered trademark of Circuit Cellar, Inc. [email protected] Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.

4 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 5.qxp 3/3/2008 10:59 AM Page 1

Any Design... Anytime. USA and in other countries. All trademarks mentioned herein are property of

Incredibly Versatile, Incredibly Low Power, 8- and 14-pin PIC® from Microchip.

Microchip’s latest low pin count PIC microcontrollers combine the simplicity of an 8-bit architecture with innovative features designed to add intelligence and functionality to a wide variety of applications. Whether you’re adding a keypad to a convection oven, an intelligent cooling fan to a power supply, or battery management features to a digital camera, these new PIC microcontrollers can handle the task. With available high-voltage variants and a footprint as small as 4mm x 4mm, this family of low-cost microcontrollers fits easily into any design. their respective companies. ©2008, Microchip Technology Inc. Microchip Technology their respective companies. ©2008, Purchase and program your microchip PIC® microcontrollers and DIRECT related development tools at... www.microchipdirect.com

Flash 10-bit Program Memory RAM I/O A/D Product Bytes (Words) Bytes Pins Channels Comparators Timers Packages PIC12F609* 1.75K (1K) 64 6 — 1 1-16 bit, 1-8 bit, 1-WDT 8 pin PDIP, SOIC, MSOP, DFN PIC12F615* 1.75K (1K) 64 6 4 1 1-16 bit, 2-8 bit, 1-WDT 8 pin PDIP, SOIC, MSOP, DFN PIC16F610* 1.75K (1K) 64 12 — 2 1-16 bit, 1-8 bit, 1-WDT 14 pin PDIP, SOIC, TSSOP, QFN PIC16F616* 3.5K (2K) 128 12 8 2 1-16 bit, 2-8 bit, 1-WDT 14 pin PDIP, SOIC, TSSOP, QFN *High-voltage variants available.

Visit us online to order

The Microchip name and logo, the Microchip logo, and PIC are registered trademarks of Microchip Technology Incorporated in the and PIC are registered trademarks of Microchip Technology the Microchip logo, The Microchip name and logo, FREE samples! www.microchip.com/PIC16F61X

Microcontrollers • Digital Signal Controllers • Analog • Serial EEPROMs

PIC16F61X ad for Circuit Cellar.1 1 2/20/2008 4:37:22 PM 213_TOC.qxp 3/6/2008 10:35 AM Page 6

April 2008: Embedded Programming FEATURES

14 Embedded Linux Development (Part 1) A Virtual Linux Environment on a Windows System David Lynch 35 Programmable Power Build a Simple USB DAC Yoshiyasu Takefuji 40 Do-It-Yourself Motion-Controlled Gaming (Part 2) Manipulate 3-D Graphics Display & Debug (p. 52) Chris Coulston 52 Video Stamp A Handy Display for Debugging Programs Jose Sanchez 60 Simple Hardware Development Taylor Hutt

A Programmer Tackles a Project (p. 60) COLUMNS

22 THE DARKER SIDE — INTELLIGENT ENERGY SOLUTIONS Get in Touch (p. 73) Low-Power Techniques Build Better Energy-Saving Electronic Systems Robert Lacoste 46 ABOVE THE GROUND PLANE Triac Behavior Triac Control Meets an Inductive Load Ed Nisley 73 FROM THE BENCH Digital Touch A Potentiometer with No Moving Parts Jeff Bachiochi 80 SILICON UPDATE More Than a Core Tom Cantrell DEPARTMENTS

4 TASK MANAGER 94 INDEX OF ADVERTISERS Smart Design & Intelligent Programming May Preview C. J. Abate 96 PRIORITY INTERRUPT 8 NEW PRODUCT NEWS What Makes an Engineer? edited by John Gorsky Steve Ciarcia 93 CROSSWORD

6 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 7.qxp 12/10/2007 12:18 PM Page 1 npn213.qxp 3/6/2008 11:06 AM Page 8

Edited by John Gorsky Visit www.circuitcellar.com/npn NEW PRODUCT NEWS for more New Product News. RTOS SCORES TOP MARKS IN PIC24 BENCHMARKS Benchmark results for the ThreadX/MCU RTOS, run- based designs where efficiency and a small, fast RTOS ning on Microchip Technology’s PIC24 16-bit microcon- makes a significant difference. troller, have been released and they are impressive. The The Thread-Metric benchmark suite source code is ThreadX/MCU performed up to 50% better than other available for free download. RTOSes measured by the The ThreadX/MCU RTOS Thread-Metric benchmark is a small (2 to 10 KB), fast, suite. The ThreadX/MCU’s high royalty-free, affordable RTOS performance is a result of its based on the highly popular advanced, highly optimized ThreadX RTOS. It is opti- architecture that has been fine- mized for 16-bit microcon- tuned over the course of its use trollers such as Microchip’s in over 450 million electronic PIC24 16-bit family and products. dsPIC digital signal con- The Thread-Metric bench- trollers (DSCs). All tests were mark suite is a free set of run on a Microchip 40-MIPS benchmarks that measures PIC24HJ256GP610 16-bit many aspects of RTOS perform- . ance, helping developers identi- The ThreadX/MCU is fy the bottlenecks in the real- available at license prices time performance of their appli- starting at $5,990 with no cations. Criteria such as inter- royalties. Free evaluation rupt response, context - copies may be downloaded ing, message passing, thread as well. scheduling, memory allocation, and synchronization are particular- Express Logic, Inc. ly important for microcontroller- www.expresslogic.com

8 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com npn213.qxp 3/6/2008 11:06 AM Page 9

NEW PRODUCT NEWS BRUSHLESS DC STELLARIS REFERENCE DESIGN KIT The Stellaris Brushless DC Motor Control Reference Design Kit (RDK- precise motor control using Hall effect, BLDC) with Ethernet and CAN is now available. Brushless DC (BLDC) quadrature, or sensorless operation modes. motors offer efficient operation, excellent torque characteristics, and The graphical control program enables durability. They are particularly suited for use in factory automation, users to experiment with varying drive medical instruments, robotics, electric vehicles and mobility devices, parameters and observe their effects on pumping and ventilation systems, and small appliances. With built-in motor performance. CAN and Ethernet interfaces, the RDK-BLDC represents an industry The RDK-BLDC design kit costs $219 benchmark in the integration of motion control with network-based com- and the MDL-BLDC control module costs munication, command, and control. $99 in 1,000-piece quantities. The RDK-BLDC is a four-quadrant controller for three-phase brushless DC motors rated at up to 36 V, 500 W, and 60,000 RPM. Key features of Luminary Micro, Inc. the RDK include a powerful 32-bit Stellaris microcontroller with 256 KB www.luminarymicro.com of single-cycle internal flash memory and embedded software to optimal- ly control a wide range of motors in diverse applications. The RDK-BLDC contains everything required to evaluate and develop brushless DC motor control designs. The kit includes a brushless DC motor control module featuring an LM3S8971 microcontroller (with on- chip Ethernet MAC+PHY and CAN), a three-phase brushless DC motor, a graphical control program for Windows, accompanying cables, source code, and documentation. The LM3S8971 microcontroller handles all PWM synthesis, position, and analog sensing. Only a few additional power ICs are necessary to complete the design. The entire circuit is built on a simple, two-layer PCB. The design includes an on-board braking cir- cuit, an optional power-managed fan for forced-air cooling, analog and dig- ital control inputs, and screw terminals for all power and signal wiring. Interrupt-driven embedded software provides four-quadrant operation for

w Ne Catalog!

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 9 npn213.qxp 3/6/2008 11:07 AM Page 10

NEW PRODUCT NEWS POSTAGE STAMP-SIZED ARM9 CPU MODULE The Stamp9261 CPU module brings together an AT91SAM9261 microcon- troller, 32/64 MB of SDRAM, and 16/64 MB of flash memory on a card measur- ing just 53 mm × 38 mm. Because all of the components are mounted on one side, the module boasts a thickness of just 4 mm. The compact form enables integration of the Stamp9261 into applications with minimal space availability. The Stamp9261 is an excellent base for developing mobile devices or embedded computing solutions. The module supports a 32-bit parallel bus, a JTAG port, two USB hosts, a USB device, four USARTs, SPI, TWI (I²C compatible), and 80 digital I/O ports. Also, an SD/MMC-card slot and/or a smart card slot can be used for recording and storing data. The Stamp9261 is Ethernet-capable when operated with the taskit Stam- pAdaptor. An LCD controller is integrated into the AT91SAM9261, offering reso- lutions of up to 2,048 × 2,048 pixels at 24-bit color depth. TFT and LCD displays can be operated in either monochrome or with up to 16 million colors. The Linux open-source operating system and U-Boot bootloader are preinstalled on the module. Standard GNU tools (included) are used to program the Stamp9261. They include, among others, the GNU compiler collection, the text editor GNU Emacs, and the GNU C library. The Stamp9261 costs approximately $150 and starter kits begin at approximately $833.

taskit www.taskit.de

ANALOG TRANSDUCER/SENSOR METERS The TDRO-10 is the industry’s smallest programmable meter for analog sen- sors/transducers with the first ever integrated diagnostics for both input and output. The meter features simple two-button English programming and a fast 67-ms update rate. It is just 3.78″ × 1.89″ × 1.0″. Only a quarter the size of con- ventional meters, it fits into a standard 1/8 DIN cutout. The meter provides a six-digit LED display with large 0.5″ numbers and a 6-ms refresh rate. Push-but- ton diagnostics enable fast determination of programming versus power supply problems. Beside direct sales, units can be supplied private label to large OEMs. Designed for standard sensor inputs of 0 to 10 V or 4 to 20 mA with overvolt- age protection, the meter comes in versions providing one 16-bit analog output, two or four programmable PNP digital outputs with 100% scalable analog retransmission, and read-only with no digital output. Simple intuitive programming requires no code and shortens startup and trou- ble-shooting. English prompts walk the user through programming sequences. The output can be scaled to match the full 0- to 10-V output of the transducer or only a selected portion. Programming capabilities include 100% adjustable zero and span, selectable num- ber of digits and decimal point location, programmable switch point for each digital output, and 100% adjustable analog output. Quantity prices start under $100 in quantities, which is competitive with a DRO or a good volt meter.

Transducers Direct www.transducersdirect.com

10 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com npn213.qxp 3/6/2008 11:07 AM Page 11

NEW PRODUCT NEWS HIGH-SPEED, CONTINUOUS-TIME SIGMA-DELTA ADC The 12EU050 is the industry’s first high-speed, continuous-time sigma-delta (CTSD) ADC. The 12EU050 is an eight-channel, 12-bit, 50-Msps ADC that offers an alias-free sample bandwidth of up to 25 MHz, while consuming 30% less power (350 mW) than competing pipeline devices. This low-power break- through enables manufacturers to extend battery life and reduce heat in portable medical ultrasound and industrial imaging equipment. The continuous-time architecture greatly simplifies system design, as it allows the integration of other signal-path functions, such as signal condition- ing, while incorporating antialiasing filtering. The 12EU050’s innovative CTSD architecture offers many advantages com- pared to traditional pipeline architectures: lower power dissipation; integrated low-pass, brickwall antialiasing filtering; an easy-to-drive, purely resistive input stage that does not require a sample-and-hold amplifier; an integrated PLL and voltage-controlled oscillator; and on-chip instant-overload recovery circuitry that recovers from saturation within one clock cycle if the input exceeds pre- determined limits. The 12EU050 reduces interconnection complexity by using programmable serialized outputs, which offer industry-standard low-voltage differential signaling (LVDS) and scalable low-voltage sig- naling (SLVS) modes. The device operates over the –40° to 85°C temperature range and is supplied in a 10 mm × 10 mm, 68-pin LLP package. The 12EU050 costs $64 in quanti- ties of 1,000.

National Semiconductor Corp. www.national.com

SELF-POWERED WIRELESS LIGHTING CONTROL The E8R-D12GP-1 is a wireless plug-in /relay receiver. The new RF receiver fits into any standard electrical outlet and allows dimming or ON/OFF control for lamps and other plug-in devices. Simply plug a lamp into the receiver and then plug the receiver into the wall. A patented self-powered wireless is used to dim and control the lamp. An 868-MHz plug-in dimmer and relay is also available, but the new unit operates on the less encumbered 315-MHz frequency and can function both as a dimmer and a relay (ON/OFF control). The migration to the 315-MHz operating frequency was due to the greater range and reliability that the ISM band pro- vides. The transmission range between a plug-in RF receiver and self-powered wireless light switch is up to 150′ (50′ is typical in indoor environments). A plug-in dimmer/relay receiver kit is now available and includes one receiver and one decorator-style self-powered wireless light switch. The switch looks exactly like the standard Decora switch found in homes and buildings all over the country, making it easy to have wireless and wired switches exist in the same environment. The E8R-D12GP-1 receiver costs $109.99. The kit costs $184.94.

Ad Hoc Electronics www.AdHocElectronics.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 11 npn213.qxp 3/6/2008 11:07 AM Page 12

NEW PRODUCT NEWS NEW USB CONNECTOR PROVIDES EMI & ESD PROTECTION The new USB-F and USB-E series of USB connectors incorporate EMI or ESD filters into an industry-standard USB package. The connectors satisfy the requirements of the USB 2.0 spec, which calls for EMI and ESD protection according to industry specifications. This protection has become more of a challenge, as less space is available for components and smaller IC chips are more susceptible to low-level damage. Inherent in the development of more plug-and-play devices with hot-plug capability is a greater risk of system exposure to EMI and ESD. These connectors are drop-in replacements for unfiltered connectors, making them ideal solutions for the ongoing miniaturization of peripheral devices. The connectors can also eliminate the need to redesign PC boards in the event of noncompliance during either EMC or ESD testing. Various models of these connectors meet the require- ments of USB 2.0 and USB On-The-Go (OTG) specifications and all are RoHS-compliant. The connectors have a working voltage of 5 VDC with a current rating of 1 A max and a contact resistance of 30 mΩ max. The EMI-filtered USB connectors are available with either a capacitive filter for USB 1.1 or with an inductive filter for USB 2.0. As system circuitry has gotten more com- plex to accommodate faster transfer speeds and smaller package sizes, greater potential exists for damaging EMI and ESD occurrences. Spectrum’s USB filtered connectors pro- vide the needed protection in these limited spaces, which makes them ideal for EMI/RFI-sensitive electronics, test and measurement equipment, notebook computers and multimedia, industrial controls, and data acquisition. The USB-F and USB-E series connectors cost from $1 to $3 depending on the quantities required.

Spectrum Control, Inc. www.specemc.com

12 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com npn213.qxp 3/6/2008 11:07 AM Page 13

NEW PRODUCT NEWS INTEGRATED POWER AND AUDIO MANAGEMENT UNIT The AS3658 is a highly integrated power and audio management unit with sophisticated audio features. It is ideally suitable for portable navigation devices, portable media players, smart phones, PDAs, and a wide range of other battery- powered hand-held devices. The AS3658 offers an integrated solution for power supply generation, monitoring, and bat- tery management including charging. The charger can manage up to a 1.6-A charging current, ideally suitable for fast charging of large batteries. USB, linear, and step-down charging is available and supported by the unique battery-isolation feature. The programma- ble power management functions significantly extend battery life with DC/DC efficiencies higher than 90%. The IC pro- vides three highly efficient DC/DC step-down converters, two DC/DC step-up converters, three low-noise LDOs suitable for RF applications, four digital LDOs, a low-noise charge pump, and a highly flexible backlight driver supporting a wide range of display sizes. At the same time, the AS3658 offers high-performance audio functions with an 18-bit audio DAC, a 16-bit audio ADC, a five-band equalizer, as well as headphone amplifiers, line-outputs, line-inputs, microphone inputs, an audio mixer, and several analog and digital audio interfaces. The unique ground-noise cancellation feature delivers excellent sound quality in in-car environments. Moreover, a real-time clock, a 10-bit general-purpose ADC, and a touchscreen interface are integrated to complete the extensive feature set of the AS3658. Due to customizable PROM programmable startup sequences, the IC matches a wide variety of application processors. The AS3658 costs $6.38 in 10,000-piece quantities.

austriamicrosystems www.austriamicrosystems.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 13 2803019_Lynch.qxp 3/6/2008 4:05 PM Page 14

FEATURE ARTICLE by David Lynch Embedded Linux Development (Part 1) A Virtual Linux Environment on a Windows System

Imagine this: a flexible embedded Linux development environment running under Windows. Now it’s a reality. David created a virtual Linux environment on a Windows system using coLinux. This is your platform for embedded cross development.

The development environment for that the developer will be running today, run Linux, GreenHills Software, my first system consisted of LEDs and Linux and is familiar with Linux µCosII, and often no OS. Pico provides switches. Today, embedded developers development tools and commands. But development environments for Linux, expect capable tools for the systems for the majority of embedded develop- OpenBSD, and Windows. But the over- they work with. ers, this is not true. whelming majority of clients use Win- Embedded systems are getting smaller, I have been fortunate. My experiences dows. This creates unique challenges, more powerful, cheaper, and faster. They have taken me into virtually every facet such as how to effectively perform are becoming a more ubiquitous part of of software development from writing embedded Linux development in a everyday life. They exist in single-pur- payroll systems to disk controllers and Windows environment. pose devices manufactured in the mil- programming PALs through web applica- Whatever the merits of Linux over lions, where fractions of a cent are criti- tions. I have been working with Linux Windows, requiring Windows developers cal to success. And they are increasingly and open-source for most of a decade. I to become Linux experts is a hard road. appearing in larger and more complex returned to embedded development in This article reflects my efforts to synthe- products with tight schedules where the past few years. Like most software size from existing resources a friendly, time to market is more critical. developers, I live primarily in a Windows powerful, flexible, and extensible embed- High-end embedded systems with world. I port Linux to embedded sys- ded Linux development environment for orders of magnitude more resources and tems. I use Linux file, mail, and web embedded engineers running Windows. performance than the Heathkit H8 per- servers. But my primary development sonal computer I started with in college system is a laptop running Windows XP. DEVELOPMENT TOOLS are a natural fit for Linux. Incorporating Embedded products from Pico Comput- There are two major facets to this: Linux as part of an embedded project ing, which constitute most of my work the general tools for embedded Linux creates new demands and compels software development and pro- embedded developers to broaden viding a friendly means for using their skills. Embedded Linux proj- them from Windows. This article ects still require talented develop- focuses on installing coLinux—a ers who work in the dark region light-weight real version of between hardware and software Linux that runs as a process that intimidates applications under Windows. Much of the developers used to the world of task of setting up coLinux is Visual Basic, Java, and .NET. But nearly the same as setting up it increases the requirements for Linux on an embedded device. familiarity and sometimes intimacy Editing colinux.conf and running with general-purpose operating sys- the Windows installer is unique, tems and applications development. but most every other task builds Linux has established a command- knowledge and skills that will be ing place in the field of embedded needed to set up an embedded systems. There is a presumption Photo 1—This is the coLinux installation Wizard initial startup screen. Linux device.

14 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803019_Lynch.qxp 3/6/2008 4:05 PM Page 15

task of building a Linux is operating system virtualization. kernel under Cygwin. The Open-source projects such as User primary difficulty of Mode Linux, Linux VServers, Open- developing under these VZ, and Virtuozzo lay a foundation for involves learning a large running Linux under Linux with near set of workarounds zero additional overhead. The coLinux unique to trying to devel- project, which borrows heavily from op for Linux under Win- these, implements Linux as a process dows. Numerous fre- running under Windows. quently used *nix fea- tures—such as case-sensi- WHY coLinux? tive file systems, incredi- Please note that coLinux is an bly long path lengths, and active open-source project. I deliber- hard and symbolic links ately used a development version for Photo 2—This is the coLinux setup screen to select optional coLinux that are poorly support- this article. Numerous advances have features—with options expanded. ed—work differently or do occurred recently and many fixes and not work at all under Win- features have been added. Everything The tools for embedded Linux devel- dows. Acquiring proficiency with within this article should work as opment are primarily Unix/Linux these workarounds does not con- described with the suggested down- tools. To use them, you need a tribute to knowledge of either Win- loads. However, I encourage you to Unix/Linux-like environment. There dows or Linux. use more current versions despite are numerous choices. An option The next major class of alterna- minor discrepancies with this article. under Windows is Microsoft Services tives is to actually run Linux. You Unlike Cygwin, SFU, and others, for Unix (SFU). SFU is available as a have several alternatives for accom- coLinux runs a real version of Linux free download and includes a fairly plishing this. You can run a Linux concurrently as a process under Win- complete set of Unix/Linux develop- server/workstation for software dows. To Windows, coLinux looks ment tools and resources. development on another computer exactly like any other Windows pro- A second option is Cygwin, as well and work remotely using a tool such gram. Because coLinux is real Linux as permutations such as Xilinx xyg- as Putty/SSH, XWindows, or VNC. (it uses a small collection of custom win. Cygwin attempts to map the This is the primary way that I per- Linux-to-Windows device drivers to Unix/Linux system to Windows form embedded Linux software provide Linux with access to Win- through a .dll that translates development. The downside is that it dows resources), it does not suffer Unix/Linux systems calls to Windows requires two machines, and more from any of the problems inherent to equivalents with a fairly high degree understanding of Linux. emulators. Like hardware virtualiza- of conformance to the expectations of Another alternative is using virtu- tion solutions, there are two operat- Unix/Linux programs. A significant alization to run Linux on the same ing systems running concurrently on percentage of open-source software, machine as Windows. Microsoft Vir- the same hardware. Unlike hardware including embedded development tual PC, XEN, and VMWare are virtualizers, there is minimal impact tools, have been “ported” to Cygwin. notable examples of hardware virtu- on the host OS. The installation of From the perspective of software built alization. There are numerous strong coLinux is much like the installation for Cygwin, Windows/Cygwin is just points for hardware virtu- another *nix. alization solutions; how- A third option is Mingw32, which is ever, they add a signifi- very similar to Cygwin, except it cant additional layer of builds native Windows applications complexity. They also without a dependence on an external require a deeper under- Unix/Windows .dll. Mingw32 is better standing of Linux and described as a Windows port of the knowledge of the virtual- GNU compiler collection. There is a ization software. They lot of overlap between Mingw32 and also make significant Cygwin, but they have differing goals resource demands on the and approaches. host hardware. If there SFU, Cygwin, and, to a lesser are independent reasons extent, MingW32 are all attempts to for developing proficiency make Windows look like Linux. It is with hardware virtualiza- possible to perform almost every tion, this may be a good Photo 3—This is the coLinux setup screen for selecting a prebuilt embedded Linux development task, choice. coLinux root file system image and a location from which to download including the particularly challenging A less explored alternative the image.

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 15 2803019_Lynch.qxp 3/6/2008 4:05 PM Page 16

immediate proficiency with Linux, or virtualization, or the idiosyncrasies of a simulated development environ- ment. coLinux has the added appeal that for an embedded Linux developer it is not much different from an running Linux inside their Windows machine.

GETTING STARTED The first step in my approach to embedded Linux development under Windows is installing coLinux. The coLinux project is hosted by Source- Forge (www.colinux.org). You can download the current coLinux installer. (When I wrote this article, it Photo 4—This is a DOS box coLinux startup screen showing coLinux startup NIC name matching. was colinux-0.7.1-20070101.exe.) This is run like almost any Windows of any other Windows program. The I was before. There are some limita- installer (see Photo 1). end result is Linux running as a tions, caveats, and idiosyncrasies of Expanding the coLinux tab shows a process on a Windows system. I keep coLinux, but overall, it is still the number of options that are enabled a copy of coLinux installed on my easiest, fastest, and friendliest way to by default. TAP-WIN32, SLiRP, and Windows workstation. Whenever I get a Linux development environ- WinPcap are all networking options. need to travel, I copy my current ment on a Windows machine. It is Although not mutually exclusive, Linux work from the Linux worksta- also an excellent way for an embed- you need only one (see Photo 2). I tion I normally use for embedded ded developer to become familiar prefer WinPcap bridged networking development and continue exactly as with Linux without demanding because it is the easiest to set up and getting the coLinux network working is usually the most difficult aspect of installing coLinux. Also, WinPcap is We Listen. Think. And Create. an essential component of Ethereal, WireShark, and many other Ethernet sniffers, which many embedded developers may already have Distributed installed. WinPcap can be found at Serial Digital Industrial HMI I/O I/O I/O Computing www.winpcap.org. The Linux con- soles, virtual serial device, and debug- ging are not essential. However, at least one Linux console • Digital & Analog I/O is typically needed to set up network- ing. The typical impression of a file • Connection via Ethernet, USB, system is as structure implementing RS-485, or RS-232 files and directories on top of the sec- • Daisy Chain Expansion tors on a hard disk. But there is no • Field Removable Terminal Blocks reason why a file system can not exist • Compact, Rugged Form Factor inside any type of storage (e.g., RAM, ROM, flash memory, or even a file on • DIN Rail or Table Mount Design another file system). Neither Linux • Robust Development and nor Windows require the file system Confi guration Tools to be stored directly to a hard disk. In Linux in particular, most file systems FCUS are independent of a specific type of Success On store. In Windows, there are many tools like WinImage or various CD burning tools that store disk images as files. coLinux takes advantage of this and implements virtual disk drives as

16 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803019_Lynch.qxp 3/6/2008 4:05 PM Page 17

files under Windows. Unless you are extremely ambitious (and intend to build your own Linux environment) or you already have an existing coLinux root file system, you will want to download a root file sys- tem (see Photo 3). You may choose from any of the listed Linux distribu- tions for the root file system. Each has its advantages. Debian is extremely common among embedded developers, and it is my distribution of choice and the basis of many other popular distri- butions such as Ubuntu and Linspire. However, I recommend selecting “none” and separately downloading Debian-20040605.ext3.1610mb.bz2. Linux distributions tend to differ substantially less than different releas- Photo 5—You can use Putty to establish an ssh network connection to coLinux running on the local computer. es of Windows, so moving from one to Login and list directory. another is fairly easy. The choice of distribution affects the installation more than the operation of Linux. The Windows less painful. A collection of default Debian file system does not coLinux root file system images are different sized coLinux swap files is have sufficient free space to build the preinstalled Linux images, substantial- available at http://gniarf.nerim.net/ cross-platform development tools. It is ly eliminating installation differences. colinux/swap. You can download the possible to expand the file system, but The remainder of this article will use coLinux tools from the main coLinux the simplest solution is to download the Debian root file system image. site and build any size yourself. The and mount an empty file system for Recent versions of coLinux use either command-line options or a text-con- figuration file to specify coLinux options. Software By convention, Linux devices with Development names starting with “co” are coLinux Tools devices to access Windows resources. cobd# is coLinux block device #. These are Linux block devices that The Leader in Microcontroller Development Solutions access Windows files as Linux disk images. cobd0 is normally the block C/C++ Development Kit including ULINK® 2 Adapter best-in-class compilers, genuine Keil for target debugging ARM device corresponding to the Linux root ® μVision , and royalty-free RTX RTOS. and Flash programming. file system (the rough Windows equiv- www.keil.com/arm alent of drive c:). Other block devices A/D I/O Ports Run- are used to access other virtual file Control systems or a swap file (much like Cx51 Timers Interrupts Debug pagefile.sys). If you downloaded the Channel www.keil.com/c51 Debian root file system image, you PWM Flash need to decompress it and rename it ROM CPU root_fs: UART RAM C166

bunzip2 Debian-20040605.ext3. I2 C/SPI RTC www.keil.com/c166 DMA 1610mb.bz2. USB CAN Ethernet SD Out-of-the box support bzip2/bunzip2 for Windows are for more than 1,400 available at www.bzip.org/downloads. Microcontroller devices. Keil RTOS and Middleware components are specifically html or as part of the GNUwin32 optimized for embedded systems and include TCP/IP, Flash File tools for Windows (http://gnuwin32. system, USB and CAN support. sourceforge.net), which will make Call 1-800-348-8051 for a free demo CD. www.keil.com moving back and forth from Linux to

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 17 2803019_Lynch.qxp 3/6/2008 4:05 PM Page 18

Franchised Distributor For

Photo 6—This is a putty session. Putty session edits /etc/fstab (file systems to mount on startup) with vi.

additional workspace. A collection of (optional), and Windows network empty coLinux file systems of vari- resources to conet# devices. A sam- ous sizes is at http://gniarf.nerim.net ple configuration is provided. It is /colinux/fs. I recommend at least 2 GB. critical that cobd0 is configured for a Like the swap file, coLinux tools can valid root file system image. Config- be used to build one to any size. If uring a swap device is also important the empty file system is created as a because coLinux can not use virtual Windows sparse file, the actual size memory without one. Otherwise, the will only be the space used. cofs# is defaults should work well enough to a file system driver that maps Windows get started. Getting network func- directory trees to coLinux directory tionality is important because the trees. Debian package manager—kind of As an example, you can assign like Windows update on steroids—is cofs1=c:\ and mount cofs1 as /win- extremely difficult to use without dows under coLinux and then access Internet access. The additional steps the whole Windows file system from needed to configure WinPcap net- coLinux. This is extremely useful for working are creating an eth# entry trivially moving files between Win- in the config file configuring eth# as dows and coLinux. It also has many pcap-bridge and assigning eth# to a other uses. However, Windows file Windows network adapter and system capabilities and attributes are assigning it a MAC address. The net- a subset of those of Linux. This is a work adapter name is the name that fundamental reason why SFU and is displayed in view networks, and Cygwin can not easily perform diffi- must match exactly. Alternately, you cult Linux tasks, such as building a can start coLinux from a DOS box kernel. Windows files accessed and review the messages as it through cofs are constrained by the attempts to match the adapter name same limitations. conet# maps (see Photo 4). Linux network device names to coL- The MAC address is 12 hexadecimal inux/Windows network resources. nibbles. It must be unique on your The coLinux configuration file is network, and it must be a valid MAC where you map virtual disk images, address. It must not contain all 0s or such as the root image downloaded all fs and the first byte should be even. by the installer to cobd# devices, In addition to establishing a connection Windows paths to cofs# devices through your normal wired network 1-800-573-2727 18 Issue 213 April 2008 CIRCUIT CELLAR®

All Americ 2803019_Lynch.qxp 3/6/2008 4:06 PM Page 19

PROBLEMS WITH RISC MANAGEMENT? not with AVR development tools from All American

volving product definitions, coarse design inputs, and feature creep can all make a mess of your product-design schedule. Unpredictable shifts in your product’s competitive landscape can Buy online at Eshred your product-lifecycle engineering plan. Manage the risks to www.onlinecomponents.com your RISC-processor development projects with Atmel AVR development tools from All American.

Atmel ATSTK500 - Starter Kit / Great Value Reduce days of hardware prototyping work to hours or minutes with Atmel’s ATSTK500 kit for 8-, 20-, 28-, and 40-pin AVR flash devices. Gain access to all AVR I/O ports through the ATSTK500’s headers. Speed prototyping further with the ATSTK500’s on-board LEDs and pushbuttons. Available from stock at All American.

Atmel ATJTAGICE2 - Very Powerful / Best Selling Kick your software development into high gear with Atmel’s ATJTAGICE2 on-chip debugger for all 8-bit AVR microcontrollers with either JTAG or debugWIRE interfaces. The ATJTAGICE2 performs a complete real-time emulation of the target controller while the target runs in your hardware. The ATJTAGICE2’s emulation reduces your risk from differences between prototype and production performance by providing the target processor’s exact electrical and timing characteristics and it’s available from stock at All American. Atmel AVR Studio Tie it all together with AVR Studio — the single integrated design environment that supports high-level coding and debugging across the full breadth of the 8-bit AVR line, speeding development, enhancing code reuse, and minimizing maintenance cycle times. Available as a free download at www.atmel.com. www.allamerican.com 1-800-573-ASAP

All American Ad CircuitCellar 3 08 indd 1 3/3/08 6:20:15 PM 2803019_Lynch.qxp 3/6/2008 4:06 PM Page 20

the Linux /etc/fstab. Aside from the root and swap partitions, this is optional, but it is convenient and easi- er to set up /etc/fstab than to manual- ly mount file systems. Linux does not have a concept of drive letters. There is always a root file system, which always starts at “/.” If you are con- stantly moving between Windows and Linux, be prepared to be constantly typing the wrong directory separator. You may eventually note that the “/” is supported under Windows in many instances—but not from a command prompt. To access files that are not on the root file system, you must mount them to a mount point—any empty Photo 7—Here I am displaying network interface configuration in a putty/ssh session: cat /etc/network/interfaces. directory of the root file system. Many ubiquitous Linux/Unix features (such adapter (WinPcap has difficulty with change passwords. “man passwd” pro- as mounting, hard links, and symbolic some wireless adapters), I suggest vides detailed help, but the prompts links) exist in some form under Win- installing the Microsoft Loopback should be sufficient. After the root dows, but most are infrequently used driver and creating a coLinux net- password has been changed, you should and tend to confuse a lot of Windows worked bridged connection through it. be able to putty to coLinux at applications. Another important If you set the address to 192.168.0.1, it 192.168.0.40 or putty to coLinux if you Linux tool to learn early is man. will be accessible from coLinux on the add 192.168.0.40 coLinux to c:\windows\ /etc/fstab controls what file systems initial boot. Networking through the system32\drivers\etc\hosts. That has are mounted on boot (see Photo 6). Loopback adapter will allow coLinux-to- the side effect of making putty connec- Generally “#” in a Linux text file Windows connections even when a tions faster. Once you have a single marks the start of a comment. The wired network is unavailable—as in an putty connection working, you can /dev/cobd0 and proc entries or an airport lounge. It also allows you to use open multiple concurrent putty con- equivalent must have been present to an ssh client such as putty (www.chiark. nections and dispense with the coLin- boot coLinux. The /dev/cobd3 entry greenend.org.uk/~sgtatham/putty) rather ux consoles altogether. Putty provides mounts the swap file. The sys entry is than either colinux console (http://geod a much more capable terminal. Fur- optional. The /dev/cofs1 entry soft.com/howto/ssh/putty.htm) (see ther, you have the basics of coLinux maps the Windows file system to coL- Photo 5). networking working, so adding other inux. In conjunction with the cofs1 A minimal colinux.conf file would network interfaces should be simple. entry in the colinux.conf file maps, be: The next step is to configure coLin- Linux references to /windows to Win- ux as needed to reflect your config file. dows accesses to c:\. You will also kernel=vmlinux Linux configuration is almost exclu- have to mkdir /windows to create the root=/dev/cobd0 sively text-based. Regardless of reli- /windows mount point. “man fstab” initrd=initrd.gz gious preferences for text editors, any- will bring up the Linux man pages cobd0=root_fs one using Linux/Unix should have describing the structure of the fstab cobd1=homefs minimal competence with vi. It is file. The basic loopback network cobd3=swap ubiquitous. Like it or not, it will should already be working. But net- cofs1=c:\ always be there, and it is substantially work access beyond the Windows eth0=pcap-bridge,"Microsoft more capable than Notepad or Edlin. machine requires additional changes LoopBack",12:48:de:ad:be:af Many other Linux programs have vi- to the colinx.conf as well as /etc/net- like commands. For a minimal Vi in a work/interfaces under coLinux. It is Additional help is available on the Nutshell, refer to www.petefreitag.com possible to configure the network by coLinux wiki (http://colinux.wikia.com /item/504.cfm. Vim is the most popu- issuing commands, but it is more con- /wiki/Network#WinPcap). After creating lar vi variant and has a following that venient to edit /etc/network/interfaces a coLinux config file, you can start coL- includes Jim Allchin at Microsoft. and permanently set the correct con- inux from the command line: colinux- The Linux equivalent of the Win- figuration. With few exceptions, daemon.exe @colinux.conf. This should dows registry is the /etc directory tree changes to a running Linux system do boot coLinux and start the coLinux con- of text files. Any cofs# or cobd# not require rebooting. Linux zealots sole. Log in as root with a password of entries in your config file probably take great pride and quote multiyear root. “passwd” is the command to should have corresponding entries in system uptimes. But Windows habits

20 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803019_Lynch.qxp 3/6/2008 4:06 PM Page 21

die hard, and unless you have a com- few tools beyond vi and GCC. Gentoo David Lynch ([email protected]) is a pelling need to establish 1,000-day Linux, while providing its own package partner at Pico Computing (www.pico uptime scores, it is frequently easier on manager, eschews binary packages and computing.com), the owner of DLA the user to just reboot after a configura- builds everything from source. If you are Systems (www.dlasys.net) software tion change than figure out exactly interested in that degree of knowledge consulting, and an architect, with what (if anything) is needed to make it and control, refer to www.linuxfrom projects ranging from automated take effect. The configuration of scratch.org and www.gentoo.org. warehouses to embedded OS ports. /etc/network/interfaces should be At this point, you should have a When he is not working (playing) understandable by inspection. If not Linux environment running under with computers, he is busy attempt- from a command prompt, you can Windows, networked through Win- ing to automate his home and coerce type man interfaces and get more dows to the world. Next month, you his two children away from screens than you wanted to know about inter- will create a platform for embedded and into the outdoors to help build faces. The Debian disk image does not cross development. I their home. have a dhcp client installed yet, so eth1 needs to be set to a fixed IP temporarily by adding something like /etc/network/interfaces (see Photo 7). Under Windows, you can find the gateway using ipconfig. It also may be necessary to replace 127.0.0.1 with the IP address of your DNS server in /etc/resolv.conf or disable the coLinux DNS server if you have DNS prob- lems. At this point, you should have coLinux installed and configured and all the desired file systems automati- cally mounting and network interfaces assigned and configured (see Photo 7). Set your hostname in /etc/hostname and /etc/hosts. You can now make sure that your Linux install is com- pletely up-to-date by executing:

swapon /dev/cobd3 apt-get update apt-get install dhcp3-client -o APT::Force-LoopBreak=true

apt is advanced package tool. It is the Debian equivalent of Windows update on steroids. If you prefer a text/GUI tool, dselect is a GUI wrap- per arround apt. After you have installed a DHCP client, the typical additions to /etc/network/interfaces for the common DHCP client are:

auto eth1 iface th1 inet dhcp

/etc/resolv.conf should be managed by the DHCP client.

THE NEXT STEP Using tools like apt is optional. It is quite possible to install, build, and maintain Linux systems, including coLinux, entirely from scratch with

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 21 28040005_Lacoste.qxp 3/6/2008 1:18 PM Page 22

INTELLIGENT ENERGY SOLUTIONS Low-Power Techniques Build Better Energy-Saving Electronic Systems

If you’re anything like Robert, you recognize that it THE DARKER SIDE is time to stop building power- by Robert Lacoste hungry applica- tions. In this arti- cle, he provides several useful tips for Welcome to the building energy-saving electronic Darker Side. Sim- SmartyCook systems. ple calculations can generate ° impressive figures, especially when calculating energy waste. According to Wikipedia, our worldwide energy consumption is around START STOP RESET 15 TW, which is 15,000,000,000,000 W. Considering that there are around 6.5 billion people on Earth, this is an astonishing number. Let’s assume that everyone is using Figure 1—Here is my imaginary example product. It is a cooking timer with a built-in oven temperature probe nicknamed “SmartyCook.” the same amount of power, including developing countries, this comes out to an average of 2,300 W per person. Think about it twice: the average four-person family (worldwide) uses the energy used to manufacture the goods you buy, the food nearly 10 kW, 24 hours a day, 365 days a year! This is, of you eat, the gas in your car, and more. But that’s still impres- course, not only your personal energy consumption, but also sive, isn’t it? And that’s for the average human. I would guess that Circuit Cellar readers are signif- icantly above average when it comes to energy consumption, no? The purpose of this introduction is to remind you that we are some- times unreasonable and to introduce the subject of this article. This month, I will present some tips and ideas that will help you build better energy-saving electronic devices. Let’s stay modest, but assuming that better engineering practices could reduce our energy bills by 0.1%, that’s still 15 GW worldwide, a sig- nificant number of nuclear plants. Energy savings are even more critical in battery-operated equip- ment. The same energy can be wasted in battery and line-powered products; but in the former case, it can be disastrous if you need to Figure 2—Your colleague has designed the SmartyCook around a nanoWatt Microchip Technology PIC16F914 microcontroller, a custom LCD glass, a platinum thermal sensor, a loudspeaker for an alarm, and a pair of AAA replace or recharge the batteries too batteries. Is it a power-optimized design? often. Moreover, in the case of primary

22 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com IE 28040005_Lacoste.qxp 3/6/2008 1:18 PM Page 23

a) through the RD1 software-con- trolled pin and R4 resistor, and fed Operating modes back to one of the PIC’s ADC Mode Description Duration Comment inputs. A reference voltage is Standby Device not used, LCD off, awaiting key press 84,600 s/day 24 h minus active measured on another ADC input Active Device in use, temperature measurement, LCD on, count down 1,800 s/day 2 × 15 min to counterbalance voltage drops. A Beep Loudspeaker active 60 s/day 2 × 30 s small loudspeaker is connected to b) an I/O pin. Three push buttons are Instantaneous currents (µA) wired to the RB port, which has Mode PIC16F914 LCD R1/R2/R3 R4/R5/R6/RT1 Speaker Total interrupt-on-change and internal Standby 2.300 — 10.000 — — 12.300 pull-up features. Lastly, three resistors, R1 to R3, provide the Active 320.000 100.000 10.000 545.455 — 975.455 LCD driving voltages, a 4-MHz Beep 320.000 100.000 10.000 545.455 10,000.000 10,975.455 crystal is included, and the device c) is powered by two standard AAA Daily energy requirements batteries. This colleague even told Mode Duration Instantaneous current Energy Percent total you that he has already developed Standby 84,600 s/j 12.300 µA 0.289050 mAh 30.1% power-optimized firmware, which Active 1,800 s/j 975.455 µA 0.487727 mAh 50.8% keeps the PIC in Low-Current Beep 60 s/j 10,975.455 µA 0.182924 mAh 19.1% Standby mode until it is activated Total per day (mAh/j) 0.959702 mAh 100.0% by the user. Your task is to check d) this design on the energy-saving side and improve it, if possible. Battery life estimation Caution: Don’t ask me for the Power source type AAA Zinc/carbon primary batteries software and don’t cry if the Supplier and reference Eveready 1212 schematic is wrong somewhere. It Capacity (mAh) Theoretical Design Derating is just a schematic drafted as an Theoretical capacity 464 mAh — — example for this article. It was Minimal voltage 1.0 V 1.2 V 20% never built. Lifetime 0.1 years 2.0 years 20% Supplier to supplier variation — — 20% High currents 16.0 mA 10.0 mA –5% BUDGET CALCULATIONS Minimal temperature 20.0°C 20.0°C 0% How would you start? You Estimated capacity — — 249 mAh first need to evaluate the battery Average daily energy consumption — — 0.960 mAh life of this design to find out Estimated battery life — — 260 j which areas must be improved and how far you are from the target. This is the energy budget Table 1—Here you see the four different steps required to evaluate the battery life of a design such as the SmartyCook. a—This calculation, which is a four-step is the identification of the different operating modes. b—This is the calculation of the instantaneous current for each operating mode. c—Here you see the summation of the daily energy requirements. d—This is the battery life assessment. calculation process for any project. The first step is to identify what I call the device operating (nonrechargeable) batteries, this also implies a large environ- modes. Each operating mode corresponds with one, and mental impact. Because the same engineering principles could only one, instantaneous current consumption. For the be used to build green line-powered products or good battery- SmartyCook example, I have identified three basic operat- operated systems, I will use a battery-based imaginary example ing modes (see Table 1a). You also need to estimate the for this article. Let’s assume that you are asked to design the time spent in each mode every day. This may be more or SmartyCook (see Figure 1), an innovative cooking timer with a less difficult to do, but you need an estimation. Here I have remote thermal probe and zillions of new and heavily demand- assumed that the cooking timer is used on average of two ed software features like automated foie gras cooking. Sorry for times per day, each time for 15 minutes and with a 30-s this example, but I have two excuses: I’m French and my wife loudspeaker activation. is a wonderful foie gras chef! The second step is to calculate or measure the current As you know, you could design such a product quickly drawn on the battery in each operating mode. The compo- with a microcontroller. Imagine that one of your colleagues nents’ datasheets are good starting points. Don’t forget to has already designed the schematic shown in Figure 2. He read them completely because the current announced on the has found a nano-power PIC variant with an on-chip LCD first page is often described in very optimistic conditions: no interface, the Microchip Technology PIC16F914, which could watchdog active, no (or few) internal peripherals active, lowest drive a custom LCD glass. The oven temperature is measured supply voltage, and more. Also, don’t forget to include the cur- with a 1,000-Ω platinum resistance thermometer, RT1, powered rents going through any wire or passive component of the

IE www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 23 28040005_Lacoste.qxp 3/6/2008 1:18 PM Page 24

The third step is the easi- est. Calculate the average daily energy consumption, in milliamperes per hour, by multiplying each instanta- neous current by the time spent in this operating mode and summing all of the modes. Take care of the units: seconds must be con- verted to hours and microamps must be convert- ed to milliamps (see Table 1). A little less than 1 mAh is needed each day, split as 50% for Active mode and 20% when the loudspeaker is on. The remaining 30% is devoted to Standby mode. Finally, you can calculate Figure 3—This schematic is nearly identical to Figure 2. However, its theoretical battery life is four times longer, thanks to reduced the lifetime of the batteries in operating currents! days by dividing their capaci- design, including pull-ups or non-perfect capacitors. The best ties by the previously calculated daily energy requirement. way is to check it systematically. Go through the schematic The only issue is that battery suppliers don’t provide the actu- wire per wire for each operating mode and ask yourself if it can al capacity of their products for your application; they provide have any current going through it. The result is Table 1b, with only “test-bench” capacities in usually optimistic situations. instantaneous currents going from 12 µA in Standby mode up So, you must include derating factors. In particular, you must to 10 mA when the loudspeaker is active. include the effect of the lowest voltage you may tolerate,

24 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com IE 25.qxp 3/3/2008 12:52 PM Page 1 28040005_Lacoste.qxp 3/6/2008 1:18 PM Page 26

pulses that could degrade the bat- tery faster than planned. These parameters are often unknown and need to be estimated, but an overall 50% derating is not uncommon. Starting with a pair of fresh 464-mA AAA zinc/carbon batter- ies, the estimated lifetime of the SmartyCook with your col- league’s design is 260 days. Not too bad, but let’s assume that you need a longer battery life. Remember that the daily energy requirement is the sum, for each operating mode, of the instanta- neous current times the time spent in this mode, including Standby mode. You have four dif- Figure 4—After a minor hardware change, just by powering R1/R2/R3 through a GPIO and a small firmware change on ferent ways to try to improve the thermal probe management, the battery life is doubled compared to Figure 3. situation, and I’ll give you some tips for each of them: which is often higher than the supplier’s minimum specified Energy =× Σ () Time I +× Time I decharge voltage. You also need to take care of the battery’s DAILY MODE MODE REMAINING STANDBBY autodischarge for long-life products, the minimal tempera- This equation gives the daily energy consumption of a ture in which your design may survive, the battery-supplier- device, which is the sum of the energies used in each to-battery-supplier capacity variation because your customer operating mode. This will enable you to identify four dif- may not buy the best batteries, and the effects of current ferent ways to save energy: you can either reduce the

26 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com IE 28040005_Lacoste.qxp 3/6/2008 1:18 PM Page 27

operating current (I ), reduce the MODE Figure 5—This trick enables you to time spent in each power-hungry implement a real zero-power Standby mode (Time ), reduce the standby Regulator Power to device MODE mode with little end-user impact. In current (ISTANDBY), or introduce new Standby mode, the main regulator is operating modes. switched off until you press a specific Forced on, from GPIO button, which pulls the regulator’s stand- Button status, to GPIO by pin high. The main microcontroller is Piles REDUCING OPERATING CURRENT then powered on. The firmware execution The first idea is to reduce the current starts and immediately switches a GPIO supplied by the energy source when the pin to a high-level logic state to maintain the regulator power even if the user releases the button. The device then operates normally and all of the buttons device is operating, and that’s a good are available to the application until the microcontroller decides to switch itself off by releasing the GPIO pin. idea. How do you do that? The first Make sure that the processor can tolerate a voltage on the button input pin that is higher than the regulated good option is to reduce the power sup- voltage, which isn’t an issue with 5-V-compliant inputs. ply voltage. If you look at the PIC16F914’s datasheet, you will find that its typical supply currents are 40% to 60% lower at 2 V than at 3 V, and that’s often the case! For example, its operating current in 4-MHz EC mode goes down from 320 to 180 µA. More- over, all resistive losses are also reduced at lower voltages. You can get this improvement either with a lower volt- age battery (but 2 V is not easy to get) or with a low-loss linear regulator, such as the MCP1700 from Microchip Technol- ogy, which has a self consumption under 2 µA. Adding this regulator to the original schematic will enable you to extend the battery life by 30%, with a daily energy requirement down from 1 to 0.7 mAh. This is a good start with such a small change. For more complex designs, you can check if a small, low- power, step-down DC/DC converter Professional Featu res – Exceptional Price can help. For example, a Maxim Inte- grated Products MAX1556 doesn’t need more than 16 µA to operate. You can 34 Channels sampled at 500 MHz also use a lower-voltage battery and a step-up DC/DC converter working Sophisticated Multi-levelTMulti-level Triggering with very low start-up voltages, such as the MAX1674, which starts at 1.1 V, Transitional Sampling /Timi/ Timing and State because this solution could also enable you to use the batteries more deeply. Connect this indispensable tool to your PC’s Clock frequency is another good USB 1.1 or 2.0 port and watch it pay for itself within hours! source of savings, because any CMOS circuit has a power consumption rough- 500 MHz Sampling / Timing Mode (Internal clock) Interpreters for I2C, SPI and RS232 ly proportional to its operating frequen- 200 MHz Sampling / State Mode (External clock) Integrated 300 MHz Frequency Counter cy. Here, your colleague has planned a Multi-level Triggering on Edge, Pattern, Event +6V to -6V Adjustable Logic Threshold Count, Group Magnitude/Range, Duration etc. supports virtually all logic families 4-MHz crystal, probably because it is a Real-Time Hardware Sample Compression Full version of software free to download common value for microcontrollers, Qualified (Gated) State Mode Sampling Mictor adapter available but do you think such a design actually needs so many MIPS? Because the LCD www.pcTestInstruments.com is managed in hardware, you need to Visit our website for screenshots, count down seconds and measure a specifications and to download the thermal probe from time to time so easy-to-use software. Intronix Test Instruments, Inc. you can replace the 4-MHz oscillator Tel:(602) 493-0674 Fax:(602) 493-2258 with a 32.768-kHz watch crystal and www.pcTestInstruments.com clock the PIC at that frequency. The

IE www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 27 28040005_Lacoste.qxp 3/6/2008 1:18 PM Page 28

Figure 6—This is the final version of the SmartyCook schematic. One more pin on the power supply regulator enables you to implement a real zero-power standby, which is presented in Figure 5.

good news is that the PIC operating current goes down from Finally, check each component systematically and think twice. 180 to 8 µA, providing another 10% improvement on the Is there a lower-current alternative? Look again at Figure 2. overall bill. Even if your design can’t tolerate such a low There are three easy improvements. First, your colleague clock frequency, you can still try to reduce the clock frequen- has used a PT1000 platinum sensor, which has a 1-kΩ cy when you don’t need the full power, thanks to the onboard resistance at ambient temperature. If you replace it with a clock prescalers or PLLs that are available in many chips. 10-kΩ sensor, namely a PT10000, the measurement current will be divided by 10. The same goes for the R1/R2/R3 voltage divider used to Circuit Cellar design contest generate the LCD voltages. Why 100 kΩ? entrants have received Because the PIC input impedance is high enough that you can safely use 470-kΩ thousands of valuable sensors, with a five times current reduc- development tools and tion. Lastly, the loudspeaker could be product samples. Because of replaced with a resonant piezoelectric their contest participation, transducer with the same audio volume, but with a current that is half as power- these engineers receive ful. After these first easy modifications, advance e-mail notice from refer to the schematic in Figure 3. It is Circuit Cellar as soon as new not very different from the initial one, samples become available. but your daily energy is reduced from 1 to 0.23 mAh. Another way to express Now you too can benefit from this 75% improvement is that the Smar- this early notification. @ tyCook’s lifetime on a single set of bat- teries is extended from 260 days up to 1,055 days!

REDUCE OPERATING DURATION Energy is proportional to current Designer's Notification Network multiplied by time. You have drasti- cally reduced the operating current, but can you do something regarding Welcome to the Designer's Notification Network. Print subscribers are invited to operating duration? One way would join the Network for advance notice about our new sample distribution programs. be to process more quickly, but that would require a quicker clock, which means higher currents. An alternative to processing-hungry systems is to

28 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com IE 28040005_Lacoste.qxp 3/6/2008 1:18 PM Page 29

select processors with built-in hardware accelerators. For optimized modes. The easiest example is when a processor example, a hardware multiplier can give a real energy waits for something: the end of a timer, the end of an bonus on DSP-like applications. Don’t forget that you can ADC cycle, or an external event. A power-conscious engi- increase battery life just by using a better compiler. A bet- neer will never leave the processor in the same operating ter compiler will give you optimized code and will not state; he will use the processor’s hardware resources (i.e., waste energy through extra clock cycles. The difference interrupts) to put the processor in a low-power idle or could be significant. Of course, you can also hand-optimize standby mode. However, on the SmartyCook design, the the critical sections of the code. gains will be minimal because the system clock is already But there are plenty of other ideas. For example, and even very low. if it is not applicable in this example, you may reduce power Another way to introduce new operating modes is to double- requirements going back to the user-interface level. If the check each component and the wiring of the design. Could it user can perform a task quicker with a better interface, then be switched off more often? This approach needs to be fully the power consumption will be lower. Do you know how systematic because you may forget basic components, such as many CPU cycles are needed to dig into a hierarchical menu structure on your phone? Wouldn’t it be easier to have one button dedicated to the feature you use the most? In the same spirit, you can also transfer data to external sys- tems more quickly (e.g., when using power-hungry RF links). Data compres- sion could help there. Another trick is to use “wasted” CPU cycles to do something useful. In particular, when using crystal oscilla- tors, there is a frequency stabilization delay that could be counted in millisec- onds. Often the boot code of the processor just waits for stabilization. The cycles can be used to do anything you want as long as they are not time- critical, such as variable initializations. If you can accept a little degradation in precision, you can also replace your crystal with ceramic resonators, which usually have a far shorter startup time. By the way, I have a column devoted to crystals in mind, so stay tuned. Going back to the SmartyCook, there is one operating mode where things can easily be done more quickly: Alarm Beep Generation. As part of the hypothesis, I stated that the alarm was 30 s long, but nothing prevents you from drastically reducing the alarm’s duty cycle. The res- onant piezoelectric transducer can be activated for 100 ms every 2 s or so, with the same functionality. It is a small modification, but because the Alarm mode was starting to be a significant waste after the previous optimizations, this gives you another 30% improve- ment, with the estimated battery life jumping from 1,000 to 1,500 days.

NEW OPERATING MODES You can also try to break power- hungry operating modes into more

IE www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 29 28040005_Lacoste.qxp 3/6/2008 1:18 PM Page 30

a) longer than the original design! Operating modes REDUCE STANDBY CURRENT Mode Description Duration Comment Now the operating modes are STANDBY Device not used, LCD off, awaiting key press 84,600 s/day 24 h minus active optimized and the standby power ACTIVE Device in use, temperature measurement, LCD on, count down 1,800 s/day 2 × 15 min consumption is starting to be sig- MEASURE Same, but thermal probe activated 1.8 s/day 1 ms/1 s nificant. This is the last savings BEEP Loudspeaker active 60 s/day 2 × 30 s you need to work on. You have b) already checked that you are Instantaneous currents (µA) using low-standby current com- Mode MAX1725 PIC16F914 LCD R1/R2/R3 R4/R5/R6/RT1 Speaker Total ponents and you have turned off STANDBY 0.700 — — — — — 0.700 any unused component or inter- ACTIVE 2.000 6.000 80.000 1.418 — — 89.418 nal peripheral (unused ADCs, MEASURE 2.000 6.000 80.000 1.418 36.364 — 125.782 timers, clocks, and more). You BEEP 2.000 8.000 80.000 1.418 — 250.000 341.418 have also double-checked that c) each pin is configured in its low- Daily energy requirements est current-consumption mode Mode Duration Instantaneous current Energy Percent total before entering Sleep mode. It is STANDBY 84,600 s/j 0.700 µA 0.016450 mAh 24.6% usually the “output” state, but it ACTIVE 1,800 s/j 89.418 µA 0.044709 mAh 66.8% can change from microcontroller MEASURE 2 s/j 125.782 µA 0.000063 mAh 0.1% to microcontroller. What else is BEEP 60 s/j 341.418 µA 0.005690 mAh 8.5% there to do? Because RAM is Total per day (mAh/j) 0.066912 mAh 100.0% usually preserved in sleep modes, d) a processor with a smaller RAM may be more power friendly than Battery life estimation Power source type AAA Zinc/carbon primary batteries a larger one, so don’t keep large Supplier and reference Eveready 1212 components if you don’t need Capacity (mAh) Theoretical Design Derating them. Theoretical capacity 464 mAh — — Another trick is that often a Minimal voltage 1.0 V 1.2 V 20% processor or its oscillator is kept Lifetime 0.1 years 2.0 years 20% active in Standby mode just to Supplier to supplier variation — — 20% enable a software-based real-time High currents 16.0 mA 10.0 mA –5 % clock to run. This may be a cost- Minimal temperature 20.0°C 20.0°C 0% effective solution, but it usually Estimated capacity — — 249 mAh isn’t power-efficient. Don’t forget Average daily energy consumption — — 0.067 mAh that a dedicated RTC chip, such Estimated battery life — — 3,728 j as the Maxim Integrated Prod- ucts DS1302, needs just 300 nA Table 2—Compare the energy budget calculation of the schematic in Figure 6 with the initial one. I got a 14-times improvement at 2 V to keep the time! of the battery life with globally minor changes! The best way to reduce stand- by power is to have zero standby pull-up resistors. Doing this exercise on the already opti- power, which usually means a small mechanical on/off mized SmartyCook schematic enables you to find two switch. That’s a very good solution, but you will dislike it possible improvements (see Figure 3). Have you found because it implies one more action before using the device them? The first one is the R1/R2/R3 network. It is always and because you will forget to switch it off 50% of the powered, but it is needed only when the device is operat- time. A better solution is to implement a real “zero power” ing, not in Standby mode when the LCD is off. Just power mode using one of the device’s buttons as a hard-wired it from a free GPIO pin and you can save 1.4 µA. That’s power-on. Look at the principle in Figure 5. The Smarty- few microamps, but it is still a 30% improvement on Cook design can easily use this trick by just replacing the standby current. The second improvement is related to MCP1700 regulator with a model equipped with a standby the thermal probe. Until now, I’ve assumed that it is pow- INPUT pin (i.e., the MAX1725) and a couple of diodes. The ered when the device is operating. But it needs to be pow- final schematic is shown in Figure 6. ered only when it is measuring the temperature and this could be as quick as 1 ms each second through the intro- WRAPPING UP duction of a new “measurement” operating mode. The The schematic is now a little more complex than the initial schematic in Figure 4 sums up all of these small changes. design, but compare the energy analysis in Table 2. The theo- It is still close to the initial one, but the estimated battery retical SmartyCook’s lifetime on two standard AAA batteries lifetime jumps to 2,391 days, which is nearly 10 times jumped from around 260 days to 10 years! Of course, these

30 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com IE 28040005_Lacoste.qxp 3/6/2008 1:18 PM Page 31

calculations are approximate and would need to be checked and wireless telecommunications. He has won prizes in on an actual prototype. You may also argue that the first more than 15 international design contests. In 2003, Robert design was not well optimized to let me write this article, started a consulting company, ALCIOM, to share his pas- and you would be right. But nevertheless, I guess that you sion for innovative mixed-signal designs. You can reach wouldn’t have bet on an improvement 14 times greater him at [email protected]. Don’t forget to write “Darker than when you started to read this article, no? Side” in the subject line to bypass his spam filters. In conclusion, I want to emphasize that all of the improve- ments I discussed must work together in a holistic manner. PROJECT FILES When operating modes are optimized, standby modes start to To download the OpenOffice energy budget calculation hurt and vice versa. If you are tracking the microamp, you spreadsheet, go to ftp://ftp.circuitcellar.com/pub/Circuit_ must take your time and check everything. I hope this article Cellar/2008/213. will help you design more energy-saving devices. You may also use it as a checklist for your next project. Even if the RESOURCES impact on our 15-TW global energy consumption may be Microchip, “PIC16F913/914/916/917/946 Data Sheet: limited, it will help our planet somehow. I also hope that 28/40/44/64-Pin Flash-Based, 8-Bit CMOS Microcontrollers with you are convinced that low-power techniques are not black LCD Driver and nanoWatt Technology,” DS41250F, 2007. magic, even if they are sometimes on the darker side. I Wikipedia, “World energy resources and consumption,” http://en.wikipedia.org/wiki/World_energy_resources_and_ Author’s Note: I first talked about the ideas presented in this consumption. article in Ivry-sur-Seine, France, on January 10, 2008, during an ecodesign seminar that was organized as part of the SOURCES ECO’TRONICS initiative. This program is managed by Jessica DS1302 Timekeeping chip France and financed by several French state and regional pub- Maxim Integrated Products, Inc. lic funds. I want to thank them for their support and action for www.maxim-ic.com better environmentally friendly devices. MCP1700 Voltage regulator and PIC16F914 microcontroller Robert Lacoste lives near Paris, France. He has 18 years of Microchip Technology, Inc. experience working on embedded systems, analog designs, www.microchip.com

IE www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 31 56-57.qxp 7/2/2007 10:52 AM Page 1 56-57.qxp 7/2/2007 10:52 AM Page 2 34.qxp 3/3/2008 4:00 PM Page 1

8DBE:I>I>DC :8A>EH:9 >bV\^cZVc^cYjhignÒghiB8JXVeVWaZd[deZgVi^c\Ydlcid%#.K#>bV\^cZ hdaji^dchi]ViVgZbdgZedlZgZ[ÒX^Zcii]Vcndji]dj\]iedhh^WaZ#>bV\^cZhbVaaZg [dgb[VXidghVcYadlZghnhiZbXdhih#>bV\^cZWZhi"^c"XaVhhiddahi]ViZcVWaZ ^bbZY^ViZhnhiZbYZh^\c#I]Vc`hidi]ZgZbVg`VWaZZc\^cZZg^c\\V^chd[djgcZla^cZ d[B8JÉh!ndjXVchide^bV\^c^c\VcYhiVgiXgZVi^c\ndjgcZmi\gZViegdYjXi#

MMM$I?B78I$9EC%FE?DJ/

BEM;IJ LEBJ7=; % =H;7J;IJ FEM;H ;;IJ

>CIGD9J8>C<I=:8-%*&;.mm/I=:;>GHIA>C:D;B8Jh 9:H>C

SIL-003_CC_8.375x11.125.indd 1 1/31/08 3:06:47 PM 2804015_Takefuji.qxp 3/6/2008 3:41 PM Page 35

FEATURE ARTICLE by Yoshiyasu Takefuji Programmable Power Build a Simple USB DAC

Yoshiyasu describes the step-by-step construction of a simple USB DAC around an ATtiny45 and a MAX517. You can use the system as a programmable power supply.

In this article, I’ll explain how USB communication can be implemented on an Atmel ATtiny45 eight-pin DIP with open-source software packages (libusb, Cygwin, WinAVR, and AVR- USB). WinAVR compiles the target firmware program under Windows. AVR-USB is an open-source USB pro- tocol stack for firmware, which can be compiled by a GNU C compiler under WinAVR. libusb is also an open-source USB protocol stack for a host PC, Figure 1—This is a circuit diagram of a programmable USB power supply using an Atmel ATtiny45 and a MAX517 8-bit DAC. which is used under Cygwin on Win- dows, to compile a USB application program. will be available for programming. The used to feed the ATtiny45. Because six With the open-source software pack- USB connector has four pins: 5 V, GND, ATtiny45 pins (5 V, GND, D–, D+, ages, the USB 1.1 or USB 2.0 low- D–, and D+. The D– and D+ pins are XTAL1, and XTAL2) are used, two speed function can be easily achieved used on the ATtiny45 for USB communi- pins are left for MAX517 two-wire without a USB chip. The size of a USB cation with another two pins for XTAL1 serial programming. The MAX517 is a protocol stack for firmware embedded and XTAL2 with a 12-MHz resonator. two-wire, 8-bit DAC. The necessary in the ATtiny45 is about 2 KB. There- Note that 1.5 Mbps of USB streaming commands must be supplied from an fore, more than 2 KB is available on data can be decoded by the open-source ATtiny45 for D/A conversion. the ATtiny45 for user programming. If AVR-USB package’s USB protocol stack. Figure 1 shows the circuit diagram you use an ATtiny85, 6 KB of space The open-source USB protocol stack of the programmable USB power sup- gives you a user-friendly API, ply. A female USB connector can be where usb_control_msg and custom-made for a user-friendly bread- Photo 1—This is a hand-made usbFunctionSetup functions are board (see Photo 1). Photo 2 shows the female USB connector for a breadboard. used for USB communication between a host PC and an ATtiny45. The circuit is built in a breadboard with a 1.5-kΩ resis- tor for the 5-V pullup of D– and two 68-Ω series resistors directly connected to PD0 and PD2 from D– and D+, respectively. The Photo 2—This is a completed programmable USB 3.3-V CMOS voltage regulator is power supply using an ATtiny45 and a MAX517.

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 35 2804015_Takefuji.qxp 3/6/2008 3:41 PM Page 36

complete circuit. Listing 1—This is part of a usbconfig.h file for hardware configuration where PortB, PB0 for D–, and PB2 for The system features an ATtiny45, a D+ are set. MAX517, a breadboard, a 3.3-V voltage regulator, a 12-MHz ceramic resonator, /* usbconfig.h */ and a female USB connector. It also #define USB_CFG_IOPORT PORTB Ω Ω /* This is the port where the USB bus is connected. When you includes one 1.5-k resistor, two 68- * configure it to "PORTB", the registers PORTB, PINB (=PORTB+2) resistors, and two 4.7-kΩ resistors. * and DDRB (=PORTB+1) will be used. The installed software packages on */ Windows include Cygwin (gcc-core, #define USB_CFG_DMINUS_BIT 0 /* This is the bit number in USB_CFG_IOPORT where the USB D- line gcc++, libusb, and other necessary * is connected. This MUST be bit 0. All other values will result libraries). Download the setup file and * in a compile error! double-click it to install the necessary */ packages (www.cygwin.com/setup.exe). #define USB_CFG_DPLUS_BIT 2 /* This is the bit number in USB_CFG_IOPORT where the USB D+ line WinAVR must also be installed. Down- * is connected. This may be any bit in the port. Please note load the latest WinAVR-xxx-install.exe * that D+ must also be connected to interrupt pin INT0! file and double-click the downloaded */ installation file (http://winavr.source forge.net/download.html). To install Cygwin first, double-click The usbFunctionSetup function is used described at www.obdev.at/products/ setup.exe in Windows and select the to send/receive data via USB between avrusb/index.html. root install directory (in my case, the host PC and the USB device In AVR-USB, usbconfig.h plays a key c:\cygwin is given). Next, pick direct (ATtiny45). The data mapping is detailed role in firmware configuration. The connection, choose the nearest site in Figure 2. Because usbFunctionRead USB configuration port is defined in from the list, and select the necessary and usbFunctionWrite are not used in Listing 1. usbconfig.h device descrip- packages for your system. You must at this article, those functions are tions are defined in Listing 2. least install gcc-core, gcc++, and libusb.

Listing 2—This is part of a usbconfig.h file for hardware configuration where VENDOR_ID, USB COMMUNICATIONS DEVICE_ID, VENDOR_NAME, and DEVICE_NAME are set and disabling FN_WRITE and USB 2.0 has three communication FN_READ. types: 1.5 Mbps (low speed), 12 Mbps (full speed), and 480 Mbps (high #define USB_CFG_VENDOR_ID 0x84, 0x13 #define USB_CFG_DEVICE_ID 0x88, 0x88 speed). I established 1.5-Mbps low- #define USB_CFG_DEVICE_VERSION 0x00, 0x01 speed communication using an #define USB_CFG_VENDOR_NAME ‘D', 'e', 'v', 'D', 'r', 'v' ATtiny45 with a 12-MHz ceramic res- #define USB_CFG_VENDOR_NAME_LEN 6 onator without a USB chip. /* These two values define the vendor name returned by the USB * device. The name must be given as a list of characters under An open-source software protocol * single quotes. The characters are interpreted as Unicode stack can take care of non-return-to- * (UTF-16) entities.If you don't want a vendor name string, zero inverted (NRZI) encoding, decod- * undefine these macros. ing, and bit stuffing for synchroniza- */ #define USB_CFG_DEVICE_NAME 'U', 'S', 'B', '-', 'K', 'O' tion. The conventional USB chip uses #define USB_CFG_DEVICE_NAME_LEN 6 NRZI encoding/decoding with auto- /* Same as above for the device name. If you don't want a device mated bit stuffing. In the bit-stuffing * name, undefine the macros. technique, each time a series of five */ consecutive “0” bits is transmitted, a Disable usbFunctionWrite and usbFunctionRead in this example. “1” bit is automatically added to #define USB_CFG_IMPLEMENT_FN_WRITE 0 force a transition. In this article, /* Set this to 1 if you want usbFunctionWrite() to be called for usb_control_msg and usbFunctionSetup * control-out transfers. Set it to 0 if you don't need it and * want to save a couple ofbytes. functions are used for USB communi- */ cations. usb_control_msg is used for #define USB_CFG_IMPLEMENT_FN_READ 0 host PC USB communications. usb- /* Set this to 1 if you need to send control replies which are gen- FunctionSetup is used for ATtiny45 * erated "on the fly" when usbFunctionRead() is called. If you only * want to send data from a static buffer, set it to 0 and return USB communications. * the data from usbFunctionSetup(). This saves a couple of bytes. */ FIRMWARE #define USB_CFG_DEVICE_CLASS 0xff The avrusb protocol stack is embedded #define USB_CFG_DEVICE_SUBCLASS 0 #define USB_CFG_INTERFACE_CLASS 0 in the firmware of the USB device. It pro- #define USB_CFG_INTERFACE_SUBCLASS 0 vides you with user-friendly APIs includ- #define USB_CFG_INTERFACE_PROTOCOL 0 ing the usbFunctionSetup function.

36 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 2804015_Takefuji.qxp 3/6/2008 3:41 PM Page 37

Listing 3—This is a full source listing of a USB device firmware program for an ATtiny45 and a MAX517. high-voltage serial programming must be used. /* Programmable USB power supply using TINY45 and MAX517 */ To compile the source program, #include #include type “make” in a Cygwin window or #include execute “Make All” on the program- #include mer’s notepad in WinAVR. After a suc- #include "usbdrv.h" cessful make operation, a da.hex file void delay(unsigned int p) should be generated. A da.hex file is { unsigned char i, j; //one loop is 3.8us with 12MHz for(i=0;i

void stop_strm() The MAX517 is an 8-bit DAC { PORTB = 0x20; //SCL=1 where two-wire programming is need- delay(1); PORTB = 0x22; //SDA=1 ed to set analog OUT0. Three bytes delay(1); } (slave address byte, command byte, void ack_strm() and output byte) must be sent to the { PORTB = 0x00; //SDA=0 delay(1); PORTB = 0x20; //SCL=1 MAX517 to set the analog output (see delay(1); PORTB = 0x00; //SCL=0 Figure 3). delay(1); } As you can see in Figure 1, /*------generate pulse stream------*/ AD1=AD0=1 makes the slave address void pulse_strm(unsigned char sda) byte 01011110. The command byte { unsigned char i,ret; for(i=0;i<8;i++){ret=(sda>>(7-i)); pulse(ret); } } becomes 00000000. The output byte is given by “data[2]” with a range of 0 to uchar usbFunctionSetup(uchar data[3]) { static uchar replybuf[1]; 255 in the usbFunctionSetup function usbMsgPtr = replybuf; in the firmware, which is equivalent to if(data[1] == 0){ replybuf[0]=55; the value of the parameter “i” in the start_strm(); pulse_strm(0x5E); //01011110 AD1=AD0=1 usb_control_msg function in the host ack_strm(); pulse_strm(0x00); //00000000 RST=PD=A0=0 program. ack_strm(); pulse_strm(data[2]); // data[2] is for voltage ack_strm(); stop_strm(); } Analog output can be determined by: else if(data[1] == 1){ : replybuf[0]=11;} ⎛ data[]2 ⎞ V ⎜ ⎟ else if(data[1] == 2) { REF0 ⎝ 256 ⎠ replybuf[0]=22;} return 1; } In Figure 1, the REF0 pin is con- int main(void) nected to 5 V and the DAC resolu- { DDRB = 0x22; // 0010 0010 PB1=SDA and PB5=SCL tion is 0.0195 V. Therefore, the ana- // are output PORTB = 0x22; //SDA=SCL=1 log output should be between 0 and usbInit(); 4.98 V. Figure 4 is a simplified DAC sei(); for(;;){ usbPoll(); } diagram. return 0; } /************************end of program**************************/ FIRMWARE, SOFTWARE, & LIBUSB The makefile is used to generate a da.hex file, which is written in the Two-byte data from the host is sent compiling the described source pro- ATtiny45’s flash memory. The make- to the target USB device using usb- gram. PB1 and PB5 (reset) are used for file is posted on the Circuit Cellar FunctionSetup to initialize the the MAX517 two-wire programming FTP site. MAX517 (two-wire, 8-bit DAC) and setting. Once the RESET pin is set up LibUsb-Win32 is an open-source set the voltage of the D/A output. The by writing the lfuse and hfuse, the USB protocol stack library for Win- first data byte sets the mode. The sec- conventional serial programmer can dows. There are two important func- ond data byte sets the voltage of the no longer write the ATtiny45’s flash tions: usbOpenDevice and usb_con- D/A output. A pulse stream from the memory because the reset function is trol_msg in this application. ATtiny45 is sent to the MAX517 to disabled. To reactivate the ATtiny45’s usbOpenDevice opens the USB device program a DAC. WinAVR is used for RESET pin for further programming, to ensure the target VendorID (VID)

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 37 2804015_Takefuji.qxp 3/6/2008 3:41 PM Page 38

called volt.exe, type “gcc volt.c –lusb continue. You have now successfully Host PC ATtiny45 –o volt” in a Cygwin window. You may installed the generated device driver usb_control_msg usbFunctionSetup USB view the code on the Circuit Cellar on your host PC. Two important files, mode data[1] FTP site. libusb0.dll and libusb0.sys, have been i data[2] libusb is an open-source project for the installed by the Hardware Update 2-Wire Linux, FreeBSD, NetBSD, OpenBSD, Wizard. SCL SDA Darwin, Mac, and Windows operating MAX517 systems (Windows 98, Win Me, Win- TESTING dows 2000, and Windows XP). Simple When you can successfully generate Figure 2—This is parameter mapping between a host data transfer in a libusb protocol stack volt.exe and write da.hex files in the computer and a USB device using an ATtiny45 and a package can be accomplished using a ATtiny45’s flash memory with the MAX517. usb_control_msg function for small fuse settings, type “volt 2.5” in the data transfer. The usb_bulk_write and Cygwin window and measure the and ProductID (PID) are there. VID and usb_bulk_read functions can be used voltage at a MAX517’s PIN1 with a PID are my unique commercial IDs, for transferring large data. Definitions voltmeter. but you may use them for your person- of the three functions are posted on In this article, I described a simple al use. usb_control_msg is a user-friend- the Circuit Cellar FTP site. programmable USB DAC featuring an ly function in the libusb protocol stack ATtiny45 and a MAX517, which can package. usb_control_msg sends and HOST DEVICE DRIVER INSTALLATION be used as a programmable power sup- receives the data between a host PC and When connecting the target USB ply. Because two-wire serial program- the ATtiny45. Two important parame- device to a host PC for the first time, ming is used to set the D/A data in a ters (mode and i) in usb_control_msg on the Hardware Update Wizard will ask MAX517, multiple channel DACs can the host application are transferred to you to connect the new device driver. be easily implemented with a MAX518 or a MAX519. I

Yoshiyasu Takefuji ([email protected]. jp) holds a PhD in Electrical Engineer- OUT 1 8 REF ing from Keio University in Japan, GND 2 Maxim 7 VDD SCL 3 MAX517 6 ADO where he is a tenured professor. He is SDA 4 5 AD1 also a tenured faculty member at Slave address byte Command byte Output byte Case Western Reserve University in SDA Cleveland, OH. Yoshiyasu’s design LSB ACK MSB LSB ACK MSB LSB ACK MSB interests include computer architec- SCL Start condition Stop condition ture, neural computing, and computer security.

Figure 3—This is a MAX517 8-bit DAC programming timing chart. PROJECT FILES To download code, go to ftp://ftp.circuit two parameters (data and data) via You must install the new device driver cellar.com/pub/Circuit_Cellar/2008/213. usbFunctionSetup on firmware. The at your own risk. parameter mapping between usb_con- First, connect your USB device to SOURCES trol_msg on your host PC’s software the host PC. The Hardware Update ATtiny45 Microcontroller and usbFunctionSetup on the Wizard will ask you for a new device Atmel Corp. ATtiny45’s firmware is illustrated in driver. Ignore this window for the www.atmel.com Figure 2. moment. Instead, open a Windows To generate the application program Explorer window and double-click AVR-USB c:\cygwin\lib\inf-wizard.exe. In its Objective Development Software window, select 0x1384 and click the www.obdev.at/products/avrusb/

– Next button. Click the Next button index.html R R R again and save the file as usb-ko.inf. + OUT_ Cygwin Now, go back to the Hardware Update 2R 2R 2R 2R 2R Red Hat, Inc. Wizard window and select “install D0 D5 D8 D7 www.cygwin.com/setup.exe from a list or specific location.” Check REF_* the “include this location in the WinAVR GND search” box. Click on the Browse but- SourceForge Start condition ton and browse to c:\cygwin\lib\libusb. http://winavr.sourceforge.net/ Figure 4—This is a simplified DAC diagram of a MAX517. Finally, click on the OK button to download.html

38 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 73.qxp 12/4/2007 11:49 AM Page 1

CC_RCM4300_Jan_FP_08019.indd 1 11/29/07 4:04:43 PM 2804017_Coulston.qxp 3/6/2008 3:42 PM Page 40

FEATURE ARTICLE by Chris Coulston Do-It-Yourself Motion-Controlled Gaming (Part 2) Manipulate 3-D Graphics

Chris concludes describing how to build your own motion-sensing controller that can interact with a variety of graphics programs on a PC. He shows you how to build complex graphics with OpenGL. Now you can design your own video games.

Since the release of Pong in the the goal is to keep a ten- 1970s, video games have captured the nis ball bouncing in the Viewport y z imaginations of people all over the air. x world. Most video gamers at one time Camera or another have probably wanted to PC SOFTWARE 3-D Scene try their hand at building their own As much as I like the video game. I try to leverage this elegance of a well-engi- intrinsic desire by having students in neered embedded system, my embedded systems class build there are times when I their own video game as part of their just can’t get enough com- course work. The inspiration for this puting cycles. To create Figure 1—This is an illustration of the relationship between the viewer design came from a student project realistic virtual worlds on (camera) and the graphics display device (Viewport) in OpenGL. If a ray and the dissection of a Nintendo Wii a computer display, you drawn from an object in the scene to the camera intersects the Viewport, then that ray contributes a pixel to the final graphics image. controller by the folks at SparkFun need the horsepower of a Electronics. The tear down revealed modern PC. For example, that the heart of a Wii controller is an the graphics programs described in serial connection. Analog Devices ADXL330 three-axis this article must manage a window, The PC-side software for this proj- accelerometer. The accelerometer display and update graphics, and read ect was written in Microsoft Visual senses movements and sends the information from the DIY Wii over a Studio 2005 in C++ on a Windows- information to the video console, which controls the on-screen action. Students in my embedded systems class built their own “DIY Wii” con- troller, based on a Microchip Technol- ogy PIC18F4520, which reads data from an ADXL330 and sends it to a PC over a serial communication link. Last month, I discussed the capabili- ties of the DIY Wii, its fabrication, and a simple pedometer application. In this article, I’ll show you how to build sophisticated graphics objects using OpenGL. Then, I’ll show you how these graphics objects can be used to build an application called Tennis Figure 2—Here, the color cube shows how red, blue, and green video colors combine to form every potential Bounce, a simple video game, where color hue.

40 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 2804017_Coulston.qxp 3/6/2008 3:42 PM Page 41

based PC. Before you hit the compati- properties. The color infor- bility panic button, note that all of the mation stored in the View- graphics routines were written in port is called the color OpenGL, a standardized cross-plat- buffer. Before objects are form graphics language that runs drawn glClear should be under a myriad of programming lan- called to “paint” the View- Ambient Ambient + Diffuse Ambient + Diffuse + Spectral guages and operating systems. Unfor- port with a default color tunately, the same cannot be said for specified by glClearColor. Figure 3—Combining different types of light sources reveals the depth the windows management routines To display an accurate of a sphere. Ambient light uniformly permeates the environment. Diffuse and serial communications routines, portrayal of the 3-D scene, light rays are parallel from a light source far away and spectral light comes from a nearby point source. which are specific to Visual Studio. OpenGL must know which With that said, let’s dive into the of the two objects is closer world of 3-D graphics, as described by to the camera. This process is called stack. After all of the work in the trans- the OpenGL standard. hidden surface removal because formed coordinate system has been OpenGL must not draw (remove) any completed, a call to glPopMatrix() OpenGL surfaces that are obscured (hidden) by will restore the original transforma- OpenGL is a specification for appli- objects closer to the camera. This is tion matrices. cations that produce 3-D graphics in accomplished by associating a depth Colors are represented using a com- an environment containing objects buffer with each pixel in the Viewport. bination of red, green, and blue colors. and light sources. Objects and light As each new object is drawn in the 3-D Figure 2, the color cube, shows how sources are placed at discrete posi- scene, its distance to the camera is the colors are combined to make new tions in the OpenGL world using a 3- computed and checked against its cor- colors. Each color can take on a value D coordinate system where up/down responding distance pixels in the View- between 0 (no color contribution) and is measured on the y-axis, left/right plane. If it’s closer than the existing 1 (full color intensity). A white pixel on the x-axis, and forward/back on pixel, it overwrites the color and depth is generated when red, green, and blue the z-axis. The scale of the coordi- buffers. Before a scene is rendered, a call are at their full intensities. A black nate system is the same for each axis, to glClear(GL_COLOR_BUFFER_BIT | pixel is generated when all three col- but it does not have an implicit mean- GL_DEPTH_BUFFER_BIT); clears the ors are at their minimum intensities. ing. One unit could be interpreted to color and depth buffers of the View- A fourth color parameter, alpha, is be 1 m, 1 km, or 1 µm. The choice is port. used to determine an object’s translu- up to you. To move the camera or objects in the cence. Translucence is simulated by OpenGL separates drawing the 2-D 3-D scene, OpenGL uses affine trans- blending pixels drawn in the Viewport image that is displayed on your screen formations—geometric manipulations, with any previously drawn pixels. The from the construction and manipula- which preserve parallel lines. The amount of blending is dependent on tion of the 3-D model. Imagine that glTranslatef(x,y,z) command caus- the object’s alpha value. A low alpha your computer screen is the rectangle es each axis to be shifted by (x,y,z). value means the object is transparent. called “Viewport” in Figure 1. When glRotatef(angle,x,y,z) rotates the A high alpha value means the object is an object is drawn in the 3-D scene, coordinate system around the vector. opaque. Once an object is colored, it rays are drawn from the object to the (x,y,z) by angle. glScalef(x,y,z) needs to be illuminated to be seen. camera (your eye). The pixels on the scales each axis by its corresponding OpenGL provides a variety of ways Viewport, which these rays intersect, parameter. Affine transformations are to specify the characteristics of sur- are colored according to the object’s accomplished with matrix multiplica- faces and lighting sources. Lights tion. OpenGL maintains several different sets of transform matri- ces on its system stack. Before making changes to the current transformation matrix, the glPushMatrix() command should be called to make a copy of the old Figure 4—These are two NURBs drawn on the same set of nine control points. The transformation Photo 1—This virtual tennis racket was built in NURB on the left has order nine. The NURB on the right has order three. matrices on the OpenGL and is controlled by the DIY Wii.

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 41 47.qxp 2/1/2008 11:51 AM Page 1 2804017_Coulston.qxp 3/6/2008 3:42 PM Page 43

come in three different flavors: ambi- NURB is defined by its control points, its the DIY Wii to control a virtual tennis ent, diffuse, and specular. order, and a knot vector. The order of a racket. Ambient light permeates the envi- NURB gives the number of control points Start by populating the virtual world ronment and comes equally from all that contribute to a segment of the curve. with objects. The outline of the tennis directions. Its light rays have Figure 4 shows two NURBs drawn on the racket’s head is built using the NURB bounced off so many objects in the same set of nine control points. The on the left side of Figure 4. The oval- room, its original source is no longer curve on the left has order nine, which shaped head is really a tube whose discernible. means that the position of each piece of cross section is a scaled-down version Diffuse light comes from a source the curve is influenced by all nine control of the NURB shown on the right side located at a discrete position. When points. The curve on the right has order of Figure 4. The handle is a texture- diffuse light encounters a surface, it three, which means the position of each mapped approximated cylinder. Its scatters uniformly in all directions, piece of the curve is influenced by the sides were constructed with eight flat creating a “soft” lighting effect. This closest three control points. planes. The end cap of the handle is a is in contrast to specular light, which The knot vector weights the control texture-mapped octagon that fits snug- also comes from a source at some points enabling some control points ly into the octagonal cylinder. The position. However, when specular to be “more important.” For a more strings of the racket are a set of lines. light encounters a surface, its angle of complete discussion of knot vectors, Getting them to terminate inside the reflection equals its angle of inci- check out the interactive applet at head of the racket is a tedious try it, dence. Figure 3 shows how the light- www.ibiblio.org/e-notes/Splines/Basis. eye it, and tweak it process. Adding a ing in a scene adds depth to a sphere. htm.[2] light source and a bouncing ball over Colors and lighting are window dress- To give an object a more realistic the racket gives the image shown in ing for the objects placed in the 3-D look, you may need to resort to tex- Photo 1. environment. OpenGL has a variety of ture mapping. Texture mapping is a The next step is to figure out how to object types that can be used to con- way to warp a 2-D image called the control the orientation and position of struct objects. Lines, triangles, poly- texture to cover a target object. For the racket using the three acceleration gons, spheres, cylinders, and disks are primitive objects, warping maps the values provided by the ADXL330. The among the primitive objects OpenGL vertices of the texture using the position of the racket is described by can display. For example, to draw a line, glTexCoord2f(x,y) command onto three variables and its orientation by a call to glBegin(GL_LINES) indicates the vertices of the target. two. Trying to determine five inde- that the subsequent list of vertex pairs pendent quantities from three known specified by glVertex3f(x,y,z) are SERIAL COMMUNICATIONS values results in an indeterminate sys- the endpoints of the lines. The list of It may seem as though writing code tem of equations. Without the aid of lines is terminated with a glEnd() to connect to a computer’s serial port something like Nintendo’s sensor bar statement. When you need to define is a trivial matter. Unfortunately, the and the controller’s optical sensor to more complex shapes, you can com- security measures in modern operating provide two additional quantities, bine primitive shapes or use non-uni- systems make the mole-hill task into a some simplifying assumptions must form rational b-splines (NURBs). mountainous problem. be made. The starting points for NURBs are Working with the serial port involves The default orientation of the DIY Bezier curves, which are parametric creating a handle for the serial port, Wii can be seen in Photo 1. In nor- curves constructed using a small num- configuring the serial port, and reading mal game play, the handle of the vir- ber of control points. The process of and writing to the port. The serial port tual tennis racket is always at the building a Bezier curve is similar to buffer on Windows computers is prone origin of the coordinate systems and building string art. In case you skipped to overflow. Sending data too quickly orientated towards the player. The fifth grade, you start by choosing three from the DIY Wii eventually results in two orientation parameters of the control points: P, Q, and R. You then program failure. On the other hand, racket are referred to as dip and tilt. draw a line between P and Q and sending data from the DIY Wii too Dip measures the angular drop of the another line between Q and R. Next, slowly merely causes the PC to wait. racket’s head from horizontal. Tilt drive a set of nails along each line and Hence, some tuning of the data rate measures the angular twist of the then start wrapping string. Start at P, from the DIY Wii needs to be per- racket along an axis running down go down to the nail at Q, and then go formed to get things working smoothly. the length of the handle. Both dip back to the nail next to P. You then and tilt are the rotations from a coor- loop around this nail, go back to the TENNIS BOUNCE dinate system placed on the center of nail next to Q, loop around it, and To demonstrate the capabilities of the tennis racket’s octagonal cap. In keep going until you connect Q to R. the DIY Wii, I’ll describe how I creat- addition to dip and tilt, you can also The boundary of the string forms a ed a simple video game called Tennis change the position of the racket Bezier curve. Bounce. The idea of the game is to see with the DIY Wii. A non-uniform rational b-spline is a how many times you can successfully When the DIY Wii is held steady, generalization of Bezier curves.[1] A bounce a tennis ball in the air using the vector sum of the acceleration

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 43 2804017_Coulston.qxp 3/6/2008 3:42 PM Page 44

component’s ax, ay, and Detecting a collision az points up (directly involves checking if the against the gravitational ball’s x and z coordinates Ball trajectory field) with a magnitude of are within the boundary of 1 g. When the magnitude the collision sheet and of this acceleration devi- checking if the top of the ates from 1 g, the excess ball is above the collision acceleration is being used sheet and the bottom 180 – 2θ to move the DIY Wii up θ below. Once a collision or down. Unfortunately, a Tilt = θ between the ball and the single accelerometer can- racket is detected, the Level orientation θ not untangle the force velocity vectors of the ball used to overcome gravity need to be updated. from the force used to In an ideal elastic colli- move the DIY Wii. All Racket sion, the incoming angle the ADXL330 feels is a of the ball relative to the combination of both racket equals its outgoing forces. A reasonable judg- Figure 5—The x-axis velocity component of a ball incident to the racket produces both x- angle. Determining the ment about the amount and y-axis outgoing velocities. mathematical relationship and direction of the force between the ball’s incom- being used to move the DIY Wii can Gravity provides a constant negative ing and outgoing velocities and the be made by subtracting 1 g from the acceleration in the y axis (i.e., the racket’s angles is simplified by sepa- magnitude of the overall acceleration velocity in the y axis is decreased rating the ball’s velocities and the vector. The length and direction of every time step by a constant racket’s angles. For example, Figure 5 the residual vectors represents the amount). The positions in all three shows the x-axis component of the direction and magnitude of the force axes are incremented by their respec- ball’s velocity incident to a racket being used to move the DIY Wii. For tive velocities at every time step. with tilt θ. The reflection off the rack- example, if the magnitude of the Besides gravity, the only other way to et preserves the outgoing angle and ADXL330’s acceleration is 1.4 g change a velocity vector is for a colli- imparts a y-axis velocity component pointing to the left, then the sion to occur. to the ball. accelerometer is assumed to be feel- Collision detection between the The outgoing velocity of the ball is ing a force of 0.4 g moving the DIY racket and the ball is accomplished by the sum of the x-axis and y-axis Wii to the left. Because acceleration drawing an invisible “collision sheet” velocity components. Some analysis is defined as the change in velocity above the racket head and checking to of Figure 5, along with knowledge of over time, you can assume that the see if the center of the ball is within basic trigonometry identities, gives acceleration occurred over one “time the perimeter of the sheet, and that the equations of motion due to the unit” and increment each velocity the top and bottom of the ball are on racket’s tilt: component by its corresponding opposite sides of the sheet. Ideally, acceleration—performing a discrete the sheet should follow the exact out- [1] integral. Likewise, the position of the line of the racket head, but instead racket is incremented by the velocity it’s approximated by a rectangle, at each time interval. Because the which closely fits the racket’s head. [2] ADXL samples at discrete times, Checking where the ball is in rela- there will be error in these discrete tionship to the collision sheet is A similar analysis of the racket’s integrals. Consequently, there will be greatly simplified by rotating the dip will give the complete set of some leftover velocity when the DIY racket, collision sheet, and tennis ball equations for the motion of the ball Wii is brought back to rest. To pre- back to the racket’s level orientation when it encounters the racket. The vent the racket from slowly drifting (see Photo 1). In this orientation, the only other obstacle that should be as a result of the errors, the velocity collision sheet will be level, its sides considered is the room where the of the racket is reset back to zero any parallel to the x and z coordinate game will be played. There are two time the magnitude of the overall axes. In reality, the collision sheet is good reasons to draw a floor. First, acceleration vector is close to 1 g. not rotated; its location is inferred shadows from the ball and the racket The position and orientation of the from the location of the end cap. can be drawn, giving the user some racket are only half the story in Ten- However, the ball must be rotated to depth queues to line up the racket. nis Bounce. You also need to consider get its relative location to the colli- Second, it gives the programmer the ball. sion plane correct. This rotation is some reference for a missed ball. The location of the ball is updated performed separately for dip and tilt Having the ball bounce off the floor using the laws of Newtonian mechanics. using simple coordinate transforms. (with some dampening) is an easy

44 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 2804017_Coulston.qxp 3/6/2008 3:42 PM Page 45

way to add some realism to the game. this article series may make it sound around Erie county and race on the like building a video game is a weekends. You can e-mail Chris at FUTURE IMPROVEMENTS straightforward endeavor, it’s a [email protected]. The DIY Wii was developed in process with many pitfalls. My stu- between semesters with a limited dents had to learn assembly tech- PROJECT FILES budget and even less time. As such, niques, hardware debugging, and To download code, go to ftp://ftp.circuit there is room for improvements that graphics programming on their way to cellar.com/pub/Circuit_Cellar/2008/213. will be incorporated into the second- building their own applications. Each generation DIY Wii. Being used to student faced their own doubts and REFERENCES DIP parts, I did not realize how challenges along the way. By the end of [1] Wikipedia, “Bézier curve,” http:// important it was to bring out the the term, I could see most of my stu- en.wikipedia.org/wiki/B%C3%A9z microcontroller pins to headers to dents had learned as much about ier_curve. enable students to attach different embedded systems as they had learned devices to the microcontroller. Incor- about their own abilities as engineers. [2] Ibiblio, “B-Spline Basis Functions,” porating a footprint for a nonvolatile The value of a hands-on education can- www.ibiblio.org/e-notes/Splines/ serial memory would open up all not be underestimated. I Basis.htm. sorts of data-logging capabilities. Finally, several students grew frus- Chris Coulston has a PhD in Computer SOURCES trated with their serial cable getting Science and Engineering from Penn State ADXL330 Three-axis accelerometer in the way of game play. Incorporat- University. He is an associate professor Analog Devices, Inc. ing a socket for a wireless communi- and program chair of Electrical, www.analog.com cation device (e.g., a MaxStream Computer, and Software Engineering PIC18F4520 Microcontroller XBee) would enable the exploration of at Penn State, Erie. Chris also runs Microchip Technology, Inc. wireless applications such as distrib- ATAN consulting, an electronics www.microchip.com uted sensor networks. development and manufacturing firm Sometimes it’s the unintended con- that provides instrumentation solu- OpenGL sequences of assignments that are the tions for local industry. In his spare OpenGL biggest take-away from a class. While time, he likes to ride his bicycle www.opengl.org

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 45 2804004_Nisley.qxp 3/7/2008 10:01 AM Page 46

ABOVE THE GROUND PLANE by Ed Nisley Triac Behavior Triac Control Meets an Inductive Load

Looking for more precise power control, Ed used a triac and a few supporting components to control high-power equipment. In this article, he describes everything you need to know about the circuits. The results might surprise you.

Back in the not-so-good old days, and current may then flow between and Gate positive. controlling high-power equipment the two Main terminals in either The Gate threshold current in Q-1 required big relays and motor-starting direction. and Q-3 tends to be much lower than contactors; an armature’s snap preceded The triac remains turned on until in Q-2 and Q-4, to the extent that the hum of large machinery and the the current between MT2 and MT1 datasheets discourage Q-4 operation whine of motors. Semiconductor power decreases below the holding current because of its poor sensitivity. The best control has removed mechanical threshold, typically a small fraction of triac triggering circuits operate in Q-1 motion, arcs-and-sparks, and all the an ampere, whereupon conduction and Q-3 where the Gate polarity drama from high-current switching. abruptly ceases. The triac remains off matches the MT2 polarity. Operation While it’s entirely possible to con- until the next Gate-triggering pulse. in Q-2 and Q-3 with negative Gate trol a resistance heating unit with a Many low-power triac applications current trades off Q-2 sensitivity for simple relay, I decided to recycle the provide fractional-cycle control by trig- the simplicity of a unipolar Gate bias triac and some supporting compo- gering at a specific delay after the start power supply. nents, as well as the hulking power of each half-cycle of the AC power A triac driving a resistive load such transformer, from a microwave oven line; that’s how fan speed controls and as an oven heater behaves largely as in order to get more precise power incandescent lamp work. you’d expect from the datasheet, control. In contrast, microwave ovens and while a reactive load like a motor or a My February column described the high-power heating applications use capacitive power supply poses some transformer’s properties (“Transform- duty-cycle modulation by turning the interesting problems. If you’ve ever ers,” Circuit Cellar 211, 2008). In this triac on for a specific number of com- tried to control a ceiling fan with an column, I’ll examine how a triac plete AC power-line cycles, then hold- ordinary light dimmer, you have some behaves when confronted with a high- ing it off for another group of cycles. idea of how nasty things can get. ly inductive load, which isn’t as obvi- The average output power depends on Figure 1 shows a Spice simulation of ous as the datasheets lead you to the ratio of on cycles to total cycles, the voltage and current on the pri- believe. If you’ve ever wondered what with the load’s thermal mass averag- mary side of my rewired transformer makes a triac tick (or how to make ing the pulses. This may cause a buzz after a single Gate trigger pulse at the one tick!), read on. or produce audible thumps as the load start of a power-line voltage cycle. switches at a fairly low frequency; The triac starts conduction normally, TRIAC BASICS you’ve certainly noticed that in your but it turns off at the current’s second At the simplest level, a triac is a own microwave oven. zero crossing. The initial current three-terminal bidirectional power Unlike NPN or PNP junction tran- waveform is nearly all positive, not switch. No current flows between its sistors, a triac is inherently an AC- symmetric around the X axis as a good two high-power (“Main”) terminals operated device. The datasheets refer sine wave should be. MT1 and MT2 until a specified mini- to the four possible combinations of A good Spice model is the first step mum current flows between its Gate Gate and MT2 polarity with respect to in figuring out what’s happening. terminal and MT1. When the Gate MT1 as “operating quadrants”: Q-1 current exceeds the triac’s triggering with both positive, Q-2 with MT2 posi- CIRCUIT MODELING threshold, the voltage between MT2 tive and Gate negative, Q-3 with both The circuit in Figure 2 divides and MT1 abruptly drops to about 1 V negative, and Q-4 with MT2 negative neatly into three sections: the resistive

46 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 2804004_Nisley.qxp 3/7/2008 10:01 AM Page 47

heating load on the far right, represents the real trans- the transformer and triac in former’s magnetizing induc- the middle, and a stack of trig- tance from the magnetic field gering controls on the left. that actually couples energy While this schematic can serve between the windings. LI1 and as the basis for an actual cir- LI2 model the primary and cuit, some components repre- secondary leakage inductances sent pure simulation fictions. caused by stray fields that do I chose a 25-mΩ load resistor not link the windings. I to set a load current of 200 A included the winding resist- and an output power of 1 kW, ances as series resistance based on the nominal 5-V sec- within the Lm and LI2 Spice ondary voltage and the original Figure 1—A single trigger (blue) turns the triac on, but the inductive load models. causes false triggering on the second half-cycle. The current lags the voltage microwave oven’s power rat- L1 and L2 form an ideal by about 63 electrical degrees. ing. The properties of a resist- transformer with tight cou- ance-soldering joint depend on pling (K1 = 0.9999) and a turns the workpiece’s condition, but this in other circuits. ratio matching the actual trans- should be in the right ballpark. Finding the values in Table 1 former’s voltage ratio. I set L1, the The standard Spice transformer required a few minutes. I measured primary winding, to 1 H so that its model consists of two inductors and a the transformer’s voltage ratio with a 60-Hz reactance greatly exceeds that coupling coefficient, a simplification relatively low primary voltage to of Lm, the 18-mH inductor represent- ignoring many of the real-world avoid core saturation. I then applied a ing the real transformer. details that make transformers so puz- 2-A DC current to the windings and X == 2πΩ f L 6.8 Lm m [1] zling. I used a more accurate π-model measured the voltage drops with a incorporating actual measurements Kelvin-connected DVM to get better X == 2πΩ f L 377 while excluding the core’s nonlineari- accuracy than my simple ohmmeter’s L1 1 [2] ties and hysteresis that you saw in my display. Finally, although my induc- The turns ratio relates L1 and L2: February column. tance meter uses a 1-kHz test signal, V1 N1 L1 I found a good explanation of the the inductances should be close to == = 22.5 [3] V2 N2 L2 transformer π-model in ON Semicon- their 60-Hz values. ductor application note AN-1679-D, Homework: Run my numbers from L ==1 L2 1.9 mH [4] which includes the equations convert- Table 1 to verify the Spice component 22.52 ing measurement into Spice compo- values in Figure 2. Bonus: Measure nent parameters. The application note your own transformer and derive a The ideal transformer losslessly covers switching converters, but its model. converts voltage and current, while transformer models work equally well Based on those calculations, Lm the components surrounding it model

Figure 2—This Spice circuit provides precise triac gate current control. The load resistor on the transformer secondary simulates a kilowatt-class resistance sol- dering or welding unit: 200 A at 5 V. The multiple current sources on each tran- sistor base simulate one-time or periodic drive pulses from a single optoisolator, which is much easier than writing Spice rules for a microcontroller.

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 47 2804004_Nisley.qxp 3/7/2008 10:01 AM Page 48

Parameter Primary Secondary place, but keeping them visible may replace Lm with that model, and see Voltage 33.65 1.496 be a better idea. what happens. R - DC 222 mΩ 1 mΩ The inductor models exclude core The components around the triac in L - other open 19.3 mH 37.6 µH effects, which seemed a reasonable the middle of Figure 2 model some L - other short 2.6 mH 5.4 µH trade-off for this column. Most cores parts salvaged from the microwave do not operate as far into saturation as oven. A snubber package includes C1 Table 1—These are the measured values for my rewound 1-kW transformer. this transformer, making the results and R5, while C2 and R6 represent a you see here more typical of normal capacitor soldered between the Gate designs. and MT1. R7 models a simple resistive the real transformer’s coupling (about Homework: SwitcherCAD includes clamp, with 1 kΩ having little effect. 0.93) and resistive losses. You could, if an inductor with core effects. Derive Although I managed to find a you wish, build a π-model Spice com- the critical H and B values from the datasheet for the microwave oven’s ponent with all these effects in one measurements in my February column, triac, it does not have a Spice model and, in fact, predates the era of cheap Spice simulation. I used a model for a similar triac from Teccor Electronics, hoping that any differences will be minor compared to other circuit effects. The standard method of triac trig- gering uses a small optically isolated triac between the main triac’s MT1 and Gate terminals. A trigger pulse across the optical barrier fires the small triac and dumps current into the larger triac’s Gate terminal. The potential across the small triac drops and it turns off when the main triac fires. That method has four key advan- tages: one isolated device delivers in- phase (Q-1 and Q-3) trigger pulses without an additional power supply. Other methods require more compo- nents or more design time, both in short supply for commercial products. Those limits don’t apply here, so I used a more complex trigger. Transistors Q1 and Q2 apply about 120 mA of current (negative and posi- tive, respectively) to the Gate, while Q3 and Q4 clamp the Gate terminal to MT1. The current sources at the tran- sistor base terminals represent opto- couplers: 2 mA corresponds to an LED driven with 20 mA and a current transfer ratio of 10% from its isolated transistor. Your couplers will certainly differ from those values! Each transistor has only one optocou- pler in the real circuit, but I find it easier to use multiple Spice current sources for starting, periodic, and ending current pulses rather than fiddle with one source’s configuration values. The real firmware will drive four microcon- troller output pins, each controlling an optoisolator’s LED, at the proper times.

48 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 2804004_Nisley.qxp 3/7/2008 10:01 AM Page 49

a) until “it works.” With that in mind, watch what happens!

LIVE SWITCHING I’m sure that engi- neers most often associate the adjec- tive “zero-crossing” with “triac.” Trig- gering a triac when the voltage across it b) is zero ensures that the current is also zero, at least for a resistive load. Elimi- nating abrupt volt- age and current tran- sitions helps reduces high-frequency ener- gy coupled into deli- cate circuits or radi- ated into free space. Although both the c) current and voltage start out at zero in Figure 1, the current waveform quickly lags behind the volt- age. That’s what you expect for an induc- tive load: the voltage and current zero- crossing points sim- ply don’t coincide. Figure 3—The top two graphs (a and b) show how power flows through the As a result, zero-volt- transformer. The bottom graph (c) displays the Gate control signals that trigger age switching isn’t triac conduction and hold it off during the last half-cycle. desirable for highly inductive loads. It’s important to remember that a The top plot in Figure 3 shows the Spice simulation can show why a cir- triac triggering at 90 electrical degrees, Hundreds of complete cuit might not work, but it cannot the maximum voltage point, after the prove that a circuit will work. When a voltage zero-crossing. The resulting embedded projects. circuit design violates electrical rules current waveform is a nearly perfect and component operating conditions, sine wave with only a small initial DC Spice can show you what’s wrong. offset and no huge peak. In round num-

However, Spice models do not include bers, the current is 27 Apeak and 19 Arms. all the subtle real-world effects that The apparent power drawn by the can prevent proper operation, even circuit is the product of the voltage when you think you know what you’re and current values: doing and the model works perfectly. =× 23. kVA 120 Vrms 19 A rms [5] As you’ve seen, this model excludes transformer core saturation, many par- Calculating the real power, howev- asitic effects, and the precise values of er, requires the phase angle, which Start with many components. The simulated you can measure from the plot by www.circuitcellar.com/ waveforms should serve as a guide, comparing the peaks of the current not a justification to tweak compo- and voltage waveforms. I measured microchip2007 nent values to five significant figures the times of the second positive peaks

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 49 2804004_Nisley.qxp 3/7/2008 10:01 AM Page 50

as 20.7 ms and 23.9 ms, making the is so small, the voltage and current Notice how the primary and second- phase angle: waveforms are almost precisely in ary voltages are in phase even though phase. The secondary’s apparent and the primary current lags by 65°. The ⎛ 23. 9 − 20.7⎞ 65°= 360 °⎜ ⎟ real power are, therefore, essentially real component of that current is, by ⎝ 16. 7 ⎠ [6] identical. Their RMS values give: definition, in-phase with the primary The real power is then: voltage, because it represents the real 855 W =× 4.6 V 185 A [8] power in the load as well as heat dissi- 960 W =° () 2.3 kVA cos() 65 [7] The combined circuit losses out- pated in primary-side losses. Figure 3b shows events on the sec- side the core account for 105 W. ondary side of the transformer. Compared to the 76 W of actual core GATE CONTROL Because R8, the simulated resistance- loss I measured in February, it’s obvi- Figure 3c shows that, contrary to heating load, is a pure resistance and ous that this model excludes some the tidy explanations found in IL2, the secondary leakage inductance, significant real-world effects! datasheets, voltages and currents at the Main terminals do have a signifi- cant effect on the Gate. For example, the Gate voltage and current move in opposite directions when the MT2 cur- rent passes through zero at 11.1 ms. Despite the –120 mA Quadrant-3 trig- ger current applied through R1, the Gate voltage becomes more negative and the Gate current more positive. No triac datasheet specifies the par- asitic capacitance between the triac’s MT2 and Gate terminals. Instead, you’ll see an upper limit on the rate of change of MT2 voltage, typically a few volts per microsecond. Voltage transi- tions faster than that will drive enough current through the parasitic capacitance to falsely trigger the triac. At the moment of switching near 11.1 ms, the voltage on MT2 begins falling from nearly zero toward –150 V. That change pulls current through the parasitic capacitor and spikes the Gate current from –140 mA to –86 mA. If the driver transistor weren’t supplying sufficient current (as in Figure 1), that current must come from MT1. Think about it: negative voltage on MT2 combined with 50 mA of current flowing from MT1, past the Gate ter- minal, to MT2. That’s exactly what happens in Quadrant-3 triggering: nega- tive MT2 voltage and MT1 current. The fact that the MT1 current doesn’t flow through the external Gate circuit has no effect; the semiconductor layers don’t care where the current originates. Actively clamping the Gate to MT1 can prevent this type of false trigger- ing, as shown after transistors Q3 and Q4 turn on at 25 ms. The Gate cur- rent spikes from –70 to 24 mA as the triac turns off at 28 ms, but that cur- rent flows from the driver transistors through the parasitic capacitance to

50 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 2804004_Nisley.qxp 3/7/2008 10:01 AM Page 51

MT2, rather than from MT1 through by assuming the power is applied Thyristors: Teccor Electronics, Inc., the Gate layers. Without any Gate-to- continuously at the measured values. “Thyristor Design Guide,” www.teccor. MT1 trigger current, the triac shuts Homework for purists only: find the com/data/en/Application_Notes/01_ off as you’d expect. differences! I trigg.pdf. The usual false-triggering solution Transformer modeling and measure- is a simple snubber similar to C1 and Ed Nisley is an EE and author in Pough- R5 that resonates with the circuit’s keepsie, NY. Contact him at ed.nisley@ ment: C. Basso, “How to Deal with inductance to limit the dV/dt across ieee.org with “Circuit Cellar” in the Leakage Elements in Flyback Convert- the Main terminals. Unit cost and subject to avoid spam filters. ers,” ON Semiconductor, AN1679/D, control complexity generally prevents 2005, www.onsemi.com/pub/Collateral active gate clamping, but sometimes PROJECT FILES /AN1679-D.PDF. you must combine both snubbing and To download code, go to ftp://ftp.circuit Triac basics: J. B. Calvert, “Electronics clamping to get enough control. cellar.com/pub/Circuit_Cellar/2008/213. Keep that trick up your sleeve! Index: Thyristors,” http://mysite.du.edu RESOURCES /~etuttle/electron/elect5.htm. CONTACT RELEASE Wikipedia, “Magic smoke,” http://en. While a Spice model provides the Fairchild App Note AN-3008 on snub- wikipedia.org/wiki/Magic_smoke. easiest way to understand triac trigger- ber design: Fairchild Semiconductor, “Application Note AN-3008: RC ing behavior and also reduces the risk SOURCES of venting the triac’s magic smoke, Snubber Networks for Thyristor there’s not enough room here for all of Power Control and Transient Suppres- Linear Technology simulation tools the variations. You should download the sion,” 2002, www.fairchildsemi.com/ Linear Technology Corp. model from the Circuit Cellar FTP site an/AN/AN-3008.pdf. www.linear.com/designtools/software/ and do some exploration of your own. Purists will quibble that my power Littlefuse, “Teccor Triac App Notes,” Teccor Triac Spice models calculations ignore the distorted www.teccor.com/cgi-bin/r.cgi/en/know Littlefuse waveforms and fractional cycles. I’m _content.html?ContentID=86&Which www.littelfuse.com/data/en/PSPICE_ approximating the long-term value App=6. Models/libtriac.zip

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 51 2803016_sanchez.qxp 3/7/2008 10:04 AM Page 52

FEATURE ARTICLE by Jose Sanchez Video Stamp A Handy Display for Debugging Programs

Jose uses his “Video Stamp” system to debug his programs and display video from various applications. A PIC18F2520 microcontroller and three resistors form a rudimentary DAC to generate the NTSC-compatible video signal. Read on for the hardware and software specifics.

Back in 1971, my first project as a reasons, every time a new generation There were also other approaches, hardware design engineer was a of components has come out, I have such as using a TTL counter to drive “dumb” video terminal that displayed mentally tried to redesign and shrink my the address lines of a PROM. The 64 characters per row and 32 rows. first project using the new components. PROM’s data output then drove the When finished, the logic and power In the mid-1970s, when micro- sync signal generation and synchro- supply filled a 12″ × 10″ × 8″ metal processors and bipolar memory nized the data flow between the char- box. For those who do not remember, became available, there was a turning acter memory, the character generator, it was the time when the only avail- point in video display design. Then, and the shift register. able active components were discrete the now legendary Don Lancaster in This project was an attempt to TTL and memory was implemented his book, The Cheap Video Cookbook, recreate that spirit. I produced a using recirculating MOS shift regis- pioneered the unorthodox use of micro- design that displays composite video ters. Since then, and for sentimental processors to design video displays. with only a few components.

OBJECTIVE My project receives serial data in an asynchronous format, 8 bits, 1 stop bit, and no parity bits at 9,600 bps (other rates are possible) and displays it on a conventional video monitor or a TV that has a composite video input (see Photo 1). The display has a capac- ity of 38 characters by 16 rows. An additional row is at the bottom of the screen. This is the Parameter row. It displays a blinking dot (I am alive), the last character received (both in ASCII and Hexadecimal), the receiving data rate, and a message area 20 char- acters long. The received data is entered at the screen’s current position in the bot- tom row. When the thirty-eighth char- acter is received, all rows in the screen scroll up one position, the bot- tom row is cleared, and the following Photo 1—This is a Welcome screen that shows when the program starts. The message in the bottom line can be received character will be entered at customized to identify your application. position 1 of the bottom row.

52 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803016_sanchez.qxp 3/7/2008 10:04 AM Page 53

All of this is accomplished composite video input in my using only a Microchip Tech- home TV. By changing the nology PIC18F2520 micro- input with the remote con- processor and three resistors trol, I was able to see all the that form a rudimentary DAC data collected by the monitor- to generate the NTSC-compati- ing module. ble video signal. Connect one 0.1-μF capacitor between 5 V THE VIDEO SIGNAL and Ground for decoupling The standard NTSC video purposes and all this can be signal can be interlaced or mounted in a 2″ × 1″ prototyp- non-interlaced. I chose non- ing board. It is a far cry from interlaced because it simpli- my first design (see Photo 2). fied the generation of the hor- izontal sync and does not MOTIVATION change the quality of the dis- As I was considering the play. Figure 1 shows the char- Microchip PIC18F2520 for an Photo 2—This image shows the hardware built in a piece of prototype board. acteristics and timing of the unrelated project, I also The total area is 2 square inches. horizontal raster line. looked at the possibility of The horizontal line has a using it as the only compo- duration of 63.5 μs. This gives nent to implement a video display. As I unplug the Video Stamp and put it in you a horizontal scanning rate of the details fell into place, I realized a safe place until next time. 15,748 Hz. To keep the vertical and that besides the challenge of cram- The second situation is to add video horizontal sync locked together, gener- ming all of the functions into this one display capabilities to a given project ate the vertical sync based on a count part, there was a practical reason. I fig- when there is a lot of data to be dis- of 262 horizontal lines. By changing ured I could use the final design every played. That was the case in a home- the duration of line 262, you can day as a debugging tool. brew “environmental/alarm monitor- obtain an almost perfect rate of 60 Hz When developing a new application, ing module” that displayed about for the vertical sync. it is very useful to know the state of 500 characters of information. For An important limitation is the several variables when the program this application, I added the PIC and video signal’s maximum bandwidth. runs through a particular part of the the three resistors to the PCB. For It should not exceed 3 or 3.5 MHz. code. It is also useful to see how the $5, I had a display capability. I then Its value is equal to one-half of the variables change as we change an routed the video output to an unused frequency of the clock that shifts data input. Of course, that can be done using breakpoints, but it is slow and cumbersome. If you are using C lan- guage, a printf statement or, as in my case, HSEROUT in PICBASIC PRO, the final product will display four or five variables to a line in the video display. Then, a trace of several lines will most likely pinpoint the cause of the problem. To do this, I plug the Video Stamp into my prototyping board and then connect the TX side of the micro- processor being debugged to the RX input in the Video Stamp and connect the video output of the Video Stamp to a suitable video display. In my case, the video display is a small camper style TV that I bought at a local appli- ance store for $19. Refer to Photo 3 for a picture of the setup. I also use my PC video display that has a composite video input, but it is inconvenient to switch inputs and I prefer the small Photo 3—The Video Stamp can be temporarily plugged into another project prototype to display debugging TV set. Once I have finished the project, information.

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 53 2803016_sanchez.qxp 3/7/2008 10:04 AM Page 54

Video prescaler. The timer is at the heart of all the video generation timing. It is 4.7 µs set up to invoke an interrupt every 4.7 µs 63.5 μs. 52.6 µs The master synchronous serial port (MSSP) module is a parallel to the seri- al interface that can be programmed to HSYNC 63.5 µs HSYNC execute two of the most common seri- al communication protocols in use today, I2C and SPI. I configured it to Figure 1—Check out NTSC signal timing for a horizontal line. This timing must be respected to get a stable screen display. work in SPI Master mode to imple- ment the Video Shift register. This is somehow an unorthodox implementa- out of the Video Shift register. We are peripherals and features needed for tion, but it works for my purposes. very close to this limit, but given the this implementation. The clock is The PIC18F2520 has 32 KB of pro- built-in tolerance in TV design, it internally generated at 8 MHz and then gram memory and 1,536 bytes of does not present a problem in actual multiplied with an internal PLL to RAM. This is more than enough for practice. reach 32 MHz. At this frequency, the this application and there is plenty of instruction rate is 8 MHz and the room to add more features. Only half IMPLEMENTATION instruction cycle is 0.125 μs. This is of the RAM is used to hold the pro- Conventionally, video generation logic important because all the timings are gram variables and data memory. The contains several blocks (see Figure 2). generated using this frequency and it program memory holds the program Data memory contains the data to be is very handy to have this kind of and the character generator. Again, displayed. It is addressed by the micro- granularity. The generated frequency there is plenty of room for expansion. processor to write the data to be dis- is accurate and very stable, provided For more details on the operation of played and by the timing module to that the 5 V is well regulated and noise these modules, refer to the read the data and feed the addresses to free. It is important to add a 0.1-μF PIC18F2520 datasheet. the character generator. decoupling capacitor between pins 19 Wiring a three-resistor voltage The character generator is usually and 20. divider as a simple DAC has been ROM that contains the dot pattern for The USART module provided serial extensively used in hobby projects. I each character. It is addressed by the data communication using the stan- have recomputed the resistor values to concatenation of the binary value of dard RS-232 protocol for asynchronous produce the theoretical voltages the character to be displayed and the communications. It is programmed at required by the NTSC signal for black, timing module with the current raster initialization time to work at 9,600 bps, white, and sync levels. Then I chose line. I chose a 5 × 7 pattern because 8 data bits, 1 stop bit, and no parity the closest standard resistor value legibility is good and it enables me to bits. Other configurations are possible, available. display more characters than a 7 × 9 as noted in the software description. pattern. Only the receiver side of the USART SOFTWARE The output of the character genera- is used. The program was developed using tor feeds the Video Shift register and is The Timer0 module can operate as a the PICBASIC PRO (PBP) compiler shifted out in serial form to the DAC. timer or a counter in 8-bit or 16-bit tightly integrated into a Microchip This video and the vertical sync added mode and has an optional prescaler. I Technology MPLAB IDE. This enabled together form the NTSC composite selected Timer mode, 8 bits, and no me to use the editing and debugging video signal. My implementation closely follows this model. Note that all Microprocessor of the different blocks, except Video Composite video out for the DAC, are contained Hor/Vert sync DAC inside the PIC18F2520.

Character HARDWARE Data memory Shift register generator Figure 3 reveals the extreme simplicity of the hardware: one PIC18F2520 microprocessor, Clk three resistors, and one capaci- Timing module tor. That is it. The PIC18F2520 was selected Figure 2—This is a video generation block diagram. The conventional block diagram is used to implement the video display. because it contains all the All the different modules are inside the PIC, except for the DAC.

54 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 57.qxp 1/29/2008 8:33 AM Page 1 2803016_sanchez.qxp 3/7/2008 10:04 AM Page 56

DATA ACQUISITION address beyond the 5 V 0.1 actual program and its location is also hard- GND HIGH 20 wired. Serial data in 18 Extensive use of PERFORMANCE indirect addressing is PIC18F2520 Video out 390 made to access these MULTIFUNCTION 16 6 locations. The PIC18F 819 1kΩ series has expanded GREAT VALUE 82 the number of index registers and enabled GND the post-automatic increment of the index Figure 3—One PIC, three resistors, and one decoupling capacitor are all that registers value. With- you need to implement a 608 character (i.e., 38 × 16) display. out this feature, it USB-1616HS Series would have been more 1-MHz, 16-bit multifunction facilities of MPLAB and to write part difficult to implement some of the DAQ modules of the code using the MPLAB assem- tight timing in the character’s display bler. Mixing PBP and assembler in this routines. Data is not moved inside the Outstanding performance with particular application was absolutely ScreenBuffer as you scroll up. Only synchronized analog, digital, and frequency I/O in a compact package. essential because of the tight timing pointers held in the index registers are constraints in some parts of the code. modified to display the correct data. I Highlights: With that said, it is not for the faint will now describe the different sections. INCLUDES • 8 differential/16 of heart because many subtle bugs single-ended may be introduced in your program— INITIALIZATION analog inputs ™ in particular, when you are using When the program starts, set the • Any analog input DAQ LOGGER & INSTRUMENT interrupts. Also, MPLAB enables the internal oscillator to run at 8 MHz can measure SOFTWARE SUITE use of ICD-2, a low-cost debugger/pro- and enable the internal PLL to run at a voltage or thermocouples grammer sold by Microchip, which final frequency of 32 MHz. Then, all • Over-sampling mode, including helps immensely in the development ports are initialized, although only line-cycle rejection for ultra cycle. PORTA is used. stable TC and low-level voltage The program can be divided into The USART is initialized by default measurements three different sections: initialization, at 9,600 bps, 8 bits, no parity bits, and • 24 high-speed digital I/O interrupt handler, and main loop. But 1 stop bit, but an option is given to • 4 counter inputs capable of before I describe the program, I will set a lower speed by reading some measuring frequency, period, pulse describe the data structures used: straps located in PORTA. The avail- width, or quadrature encoders up “RXdata” is a first in first out (FIFO) able speeds are 1,200, 2,400, and to 20 MHz circular buffer that is 16 bytes long. It 4,800. The SPI is then initialized to USB-1616HS...... $1399 is used to temporarily store the char- Master mode. USB 1-MHz, 16-bit multifunction module acters received from the USART dur- The ScreenBuffer is filled with a USB-1616HS-2...... $1499 ing the interrupt. The characters are welcome screen, copied from a preset Adds two 16-bit analog outputs retrieved by the background and message located in program memory, USB-1616HS-4...... $1599 stored in the ScreenBuff. and the parameter row is set to dis- Adds four 16-bit analog outputs “ScreenBuffer” is a linear area of play the selected USART speed and AI-EXP48 ...... $599 RAM that occupies Bank1, Bank2, and other relevant data. In the data area, Quadruples the number of AI channels part of Bank3. This allocation is hard- the pointers to the Rxdata are reset wired and assumes that the variables and the rest of the variables and CALL Call us today at and other memory areas allocated by pointers are initialized to the starting OEMS FOR PRICING (508) 946-5100 the compiler will never exceed Bank0. values. It contains the characters that will be Finally, Timer0 is enabled. The displayed in the screen. interrupts are set so only the interrupt “ParamsBuffer” is an array 38 bytes from Timer0 overflow is allowed. mccdaq.com long that contains the data to be dis- played in the bottom line of the A complete selection of low-cost DAQ INTERRUPT HANDLER hardware—and software for every skill set screen. “Chargen” is the character This piece of code generates the hor- ©2008 Measurement Computing Corporation generator data that stores the dot pat- izontal and vertical sync signals and 10 Commerce Way, Norton, MA 02766 tern that defines each character. It is displays the video corresponding to (508) 946-5100 • www.mccdaq.com located in program memory at an the raster line. In addition, it reads the

56 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 2803016_sanchez.qxp 3/7/2008 10:04 AM Page 57

USART and places the characters to by TBLPTR and places its content in horizontal space. So, I disable the SPI received, if any, into the Rxdata FIFO the register TABLAT. I use TBLPTR to when shifting out the sixth bit and buffer. It is written entirely in assem- access the character generator. TBLPTRH reenable it immediately afterwards. bler to meet the tight timing require- holds the current raster line of the This unorthodox method saves one ments of sync signals and video gener- current row and TBLPTRL holds the dot per character, or 38 dots, and ation. It is useful to have the charac- binary value of the character at this allows six more characters per row to teristics of the NTSC video signal position. Therefore, TBLPTR points to be displayed. Finally, I move the next available when examining the code the dot pattern that needs to be dis- dot pattern that I have in register W to (see Figure 1). played next. I then read the dot pat- the SPI transmit register and start The routine starts by reloading the tern and move to the W register. shifting it out. Timer0 with a value that will cause If you leave the SPI to work as Note that there is a NOP in the mid- the next interrupt after 63.5 μs by designed, it will shift out eight dots dle of the sequence. The move from overflowing the timer. It then saves per character, wasting some of the TABLAT to SSPBUF is done with two the internal registers used by the interrupt. Start the generation of the horizon- tal sync. It must last 4.7 μs while you check for end of frame. If that is reached, generate the vertical sync. You must ignore a certain number of raster lines after the vertical sync to allow for the blanking interval and to vertically center the display inside the screen. Also processed here are the “special lines,” such as the white line that separates the video display from the parameters row. Once it is determined that a stan- dard display raster line will be processed, initialize the pointer to access the first of the 38 contiguous characters in the screen buffer and wait to complete a further 4.7 μs before starting the display. Then, enter a part of the program that runs 38 times (once per character) the sequence of instructions exhibited in Listing 1, which is perhaps the most time-criti- ® cal of the entire program. ProtoMat S-Series For readers who are not familiar PCB Milling Machines with the PIC18F family, I will briefly Electrical engineers agree: with a Protomat S-Series describe the instructions used here. prototyping machine at your side, you’ll arrive at the The PIC has three 16-bit wide index best solutions, fast. These highly accurate benchtop registers, which can access the entire PCB milling machines eliminate bread-boarding and range of RAM available without pag- allow you to create real, repeatable test circuits— ing constraints. A special operational including plated vias—in minutes, not days. mode enables you to read the data • Declare your independence from board houses byte pointed to and then automatical- ly increment the index register. This is • Affordable, entry-level price tag the POSTINCx instruction, where x is • The best milling speed, resolution, and accuracy the register used, which is FSR0 in in the industry this case. Another special register, TBLPTRx, • Single-sided, double-sided, and multilayered machining without hazardous chemicals For complete details visit: points to program memory. It is also www.lpkfusa.com 16 bits wide (both are wider) and formed • Optional vacuum table and autosearch camera or call: by the concatenation of TBLPTRH and for layer alignment 1-800-345-LPKF TBLPTRL. Executing a tblrd * instruction reads the location pointed

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 57 58.qxp 3/7/2008 11:11 AM Page 1

Conference: May 11-16 Exhibition: May 13-14 Holiday Inn Select Hotel & Convention Center Tinley Park, IL.

PCB East 2008 highlights: • 11 Professional Development courses • 33 Technical Conference courses • Industry-leading speakers, including Lee Ritchey, Rick Hartley, Happy Holden, Andy Kowalewski, and Gary Ferrari • Next – Generation EDA Tools Panel Session • Keynote by Emad Isaac of The Morey Corp. • Free Tuesday sessions and events • Numerous networking opportunities • And much more!

Download Your Brochure Today! www.pcbeast.com 2803016_sanchez.qxp 3/7/2008 10:04 AM Page 59

Listing 1—This sequence of instructions is key to accessing a character in the screen buffer, retrieving the dot pattern for that raster line, and moving it to the Shift register in only 1.25 ms.

;------This sequence repeats 38 times to display video for a given raster line

movff POSTINC0,TBLPTRL ; Load TBLPNTL with next char in Screen Buffer

; tblrd * ; Read the Character Generator movf TABLAT,W ; Move the dot pattern to W for a fast transfer ; to the SPI shift Register later on Nop ; Let the SPI shift out 2 more clocks ; Bcf SSPCON1,5 ; disable SPI to stop shifting out Bsf SSPCON1,5 ; enable SPI Movwf SSPBUF ; and load Shift Register with new dot ; pattern

instructions when it could have been several times, there is no actual cursor Jose Sanchez started working in com- done with one. All of this is part of displayed. It would be quite easy to puters in his native Spain doing the delicate equilibrium of the timing add either as an underscore or a white installation and maintenance on in this sequence. The same can be said box, blinking or static. mainframes. After moving to the U.S. of the fact that a loop is not used and Another function of the main loop and graduating from Southern the 38 copies of the same sequence are is to display a blinking dot in the Methodist University with an M.Sc. executed one after the other. Fortu- first location of the parameters row. in Computer Science, he worked for nately, there is plenty of unused pro- The implementation is very simple. many years developing embedded gram memory. A 16-bit counter is incremented at applications as a contractor for a Just before exiting the interrupt each iteration of the main loop and lengthy list of companies. After a long routine, I check if a character has depending on the value of bit 15, a interlude in managerial tasks, Jose been received in the USART. If so, it different character is displayed at retired and returned to his original is read and inserted in the FIFO that location. All it shows is that the calling for fun and profit. You can e- buffer to be retrieved later by the background is up and running at the mail him at [email protected]. background. This is simpler than hav- expected cadence. ing a separate vector for a USART PROJECT FILES interrupt and as reliable, because we DISPLAY AWAY sample every 64 μs and the maxi- You now know that it’s possible to To download code, go to ftp://ftp.circuit mum rate that a character can arrive design an inexpensive display for cellar.com/pub/Circuit_Cellar/2008/213. is 1 ms. Finally, it exits after restor- debugging and other simple applica- ing all of the system registers used. tions. All you need are a few parts RESOURCES and the .hex file that’s posted on the K. Jack, Video Demystified: A Hand- MAIN LOOP Circuit Cellar FTP site. book for the Digital Engineer, The main loop is the actual program Given the simplicity of the hard- Newnes, Burlington, MA, 1955. that runs in the background. Its func- ware, no attempt was made to design tion is to process the characters that a PCB. A small piece of prototyping D. Lancaster, The Cheap Video Cook- arrive in the USART and place them board should be sufficient. You will book, Howard W. Sams, Indianapolis, in the screen buffer. also find the program listing on the IN, 1978. First, a received character is displayed FTP site, but bear in mind that you Microchip Technology, Inc., in the parameters row, both in ASCII will need PICBASIC PRO to compile “PIC18F2420/2520/4420/4520 Data and hexadecimal. If the received charac- any changes. There is still plenty of Sheet,” DS39631A, 2004. ter is a control character (i.e., in the memory and computing power left to range of 00 to 20 hexadecimal), it is implement a few more features (e.g., saved in the screen buffer and displayed escape sequences to clear the screen SOURCES as a white square. The only exceptions and position the cursor in any loca- MPLAB IDE and PIC18F2520 micro- are the carrier return and line feed. Car- tion). You can implement character controller rier return moves the cursor to position attributes such as italics, reverse Microchip Technology, Inc. one of the current row. Line feed scrolls video, and blinking video or other www.microchip.com up the entire screen one row and clears fonts (e.g., Cyrillic or Greek). the bottom row. The cursor remains at I will leave that challenge to your PICBasic PRO Compiler the same position. inventiveness and ingenuity. I’ll be glad microEngineering Labs, Inc. Although I mentioned the cursor to hear about any improvements. I www.melabs.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 59 2804014_hutt.qxp 3/7/2008 10:17 AM Page 60

FEATURE ARTICLE by Taylor Hutt Simple Hardware Development After nearly three decades of programming, Taylor recently decided to focus his attention on learning how hardware is developed. He tackled his first project with a Xilinx Spartan-3E starter kit and the VHDL programming language.

After 27 years of programming and FPGA, one 10/100 Ethernet connec- “wait until something happens” state- increasing apathy toward new “tech- tor, one VGA port, one PS/2 connec- ments, which have no analog in a syn- nology,” which is generally nothing tor, a 2 × 16 LCD, one rotary push thesized circuit. more than variations on existing button switch, one 100-pin Hirose When the board finally arrived, I themes (Ruby and Python are new expansion connection, two nine-pin greedily unpacked it (see Photo 1). I scripting languages, but not significant- serial ports, three six-pin expansion half expected to have it producing ly different than Perl, C# is a variation connectors, four slider switches, eight music in a few days using nothing of Java, OpenOffice is a Microsoft LEDs, 128 Mb of parallel flash memo- more than an old-line printer. But I Office “clone,” and more), my continu- ry, 16 Mb of SPI flash, and 64 MB of was in for a series of surprises, which ing desire to learn new things and to be DDR SDRAM. That’s a pretty full-fea- considerably slowed me down, but did amazed by elegance and simplicity was tured board for $150. not dampen my enthusiasm one bit. nagging me. One day, that nagging led to a full-blown concept. I wanted to NESTING FOR A NEW GADGET SOFTWARE INSTALL finally learn something about how After placing the order, both the The software installation is large. hardware is created. I did not want to giddy excitement and mandatory The 1.5-GB version 9.1 distribution of learn about the low-level, 7400-series impatience of waiting for a new gadg- the Xilinx ISE WebPACK fits only on gate-style hardware creations of yester- et began. At that point, I realized a DVD, or it can be downloaded year (certainly not like the amazing that I was uniquely unqualified to do directly from the Xilinx web site. I engineering at www.homebrewcpu.com). anything with the board. I didn’t prefer a stable machine, and I don’t My focus was real, honest-to-goodness know Verilog or VHDL, and I didn’t like to install software on my primary hardware creation using a hardware have a chance of ever creating any- Linux box, so I used VMware’s Work- programming language like Verilog or thing meaningful with schematics— station to create a virtual machine VHDL. How hard could it be? They’re except maybe a BCD-to-eight-seg- with Red Hat Enterprise Linux 3 just programming languages, aren’t ment-display design. I had to do (RHEL3). I installed the Xilinx soft- they? some research. ware on the virtual machine. In fact, I In this article, I’ll describe how I A trip to DigitalGuru Technical created two virtual machines, one tackled my first project. With a few Bookshop in Sunnyvale, CA, yielded with version 8.1 and one with version inexpensive Xilinx parts and a lot of several expensive books, which even- 9.1 of the WebPACK software. perseverance, I achieved my goal. tually got me through the basic semantic and lexical learning curve of THE PURCHASE VHDL: The Designer's Guide to To get started, I turned to a long- VHDL by Peter Ashenden and Digital time friend with vast years of experi- Logic and Microprocessor Design with ence building hardware from the VHDL by Enoch Hwang. Both books ground up. He pointed out that Xilinx are good for someone new to VHDL. I had an incredible deal on its Spartan- learned the basics pretty quickly. My 3E (S3E) starter kit ($150). With that only complaint about all of the writ- kit, you get Xilinx’s IDE, called ISE, ing on VHDL is that it’s heavily and a fabulously full-featured demo geared toward writing designs for sim- board. ulation rather than synthesis. As a The demonstration board, which runs at result, the designs in these books use Photo 1—This is the Xilinx Spartan-3E board running 50 MHz, contains: a 500,000-gate S3E constructs, such as indefinite loops or the “Hello, world!” program.

60 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 2804014_hutt.qxp 3/7/2008 10:17 AM Page 61

I use Linux because the set of tools VMware user interface to connect the available with a base install of the Xilinx board to the virtual machine operating system covers all of the after the board is powered on. work I need to do, but don’t worry, After starting the ISE software, both Xilinx software works on both Linux versions transported me back to 1995, and Windows. The Windows version, as one of those unpopular, stay-on-top as far as I can tell from seeing it in splash screens popped up to announce action once, is exactly the same as that it was loading, and loading, and the Linux version. I imagine that the loading. The most annoying thing Windows install is probably better about the splash screens, of course, is than the Linux version, if not because that even if you switch to another of market size, then because of the application while it is loading, the Photo 2—These are the four slider switches (SW0 static nature of the target. (If you splash screen obscures your newly through SW3) and eight LEDs (LD0 through LD7) on the install on Windows XP, there is only focused application. Spartan-3E demo board. The parenthetical labels are used when constraining the design to the physical pins. one kernel and one distribution to support.) SAMPLES On Linux, the software requires The first thing I did was look for The board is labeled with the con- “root” access, so it can attempt to samples. ISE has plenty of samples straint location for each I/O pin, but install a module, which enables the from which to choose, right under the the text is necessarily small given the USB connection to the FPGA demo “File|Open Example” menu item. It’s size of the board (see Photo 2). The board. I say “attempt” because, a curious choice to put this as a menu constraint locations for the LEDs and although RHEL3 is listed as a support- item, because after successful comple- slider switches are shown in paren- ed host for its software, neither the 8.1 tion of the presented dialog box, you theses. Fortunately, the documenta- nor the 9.1 versions were able to are presented with a brand new direc- tion also contains a complete listing install the windrvr6 module because tory with a copy of the sample. Given of each I/O port and its characteris- the kernel version didn’t match their the slow load time and bloated nature tics. Unfortunately, as far as I can tell, expectations. So, the windrvr6 source of ISE, I strongly believe that this they don’t ship a suitable text file for must be recompiled to match the cur- menu option would have been better use in your projects. Good fortune, rently running kernel. In this case, to suited to a utility program, which however, shines on you because I have a complete install requires down- would create the project and then took the time to extract the con- loading an additional 554-KB ZIP file launch ISE with the newly created straint information from the Xilinx and the invocation of a few com- sample project. documentation and produced a single mands. It’s beyond me why Xilinx Before discussing running the sam- file containing all of the constraints. doesn’t attempt to automatically ples, it’s important to understand how Unfortunately, it’s not possible to use recompile the module when a kernel designs are developed using the Xilinx this file directly in any project mismatch is found. tools. First, a design is created in Ver- because the Xilinx tools produce Another oddity of the software ilog, VHDL, schematic, or a combina- errors for each item in the constraint installation is that the default installa- tion of the three. The top-level entity file that does not correspond to an tion location is the home directory of of the design will contain input pins identifier in the design. To use the the account performing the install. and output pins, which need to be con- constraint file I created, copy just the Because root is required, the default nected to the physical world. This is desired constraints to another file and location prohibits any normal user on accomplished via “user constraints.” place that new file in your project your system from using any of the Although ISE has an interface to directory. tools. Does Xilinx do all of its work as enable the entry of constraints, they As you’ve probably deduced by now, root? end up being nothing more than a text each board produced by Xilinx—and My strategy, because I’m the only file stored with the project. For exam- there are many—has a different physi- person using these virtual machines, ple, the 50-MHz clock of the board is cal location for each constraint. In was to install it in the home directory defined like this: other words, the system clock loca- of the “thutt” account and then tion on the S3E board will probably change the ownership of all the files NET "CLK_50MHZ" LOC = "C9" not be the same as the clock location in the install directory to myself. This IOSTANDARD = LVCMOS33 ; on the Spartan-3 board. And herein worked well. lies the problem with the sample To enable the Xilinx software to CLK_50MHZ is an arbitrary identifier, designs that come bundled with the upload designs to the FPGA board which must be present in your design. ISE: none of them appear to be for the using the windrvr6 module, the virtu- The LOC specifier constrains CLK_50MHZ S3E board. al machine must be given access to a to a specific location on the S3E board. So, as a resource for learning to use my host USB port. This is a trivial matter The remaining text provides addition- new board, the provided samples were, at of selecting a menu item in the al characteristics of the port. the time, absolutely out of the question.

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 61 2804014_hutt.qxp 3/7/2008 10:17 AM Page 62

QUICK START TUTORIAL This sidebar is intended to help you get the “ISE 8.2i Quick Pin Location Constraints.” Changes are a definite must Start Tutorial” working with your new Spartan-3E board here because the pinouts of the S3 and the S3E are not the (http://toolbox.xilinx.com/docsan/xilinx82/books/docs/qst same. I found the pin numbers for the LED outputs by /qst.pdf). Because the tutorial is written for the Spartan-3 reading the parenthetical values next to each LED on the board, it won’t work as designed on the Spartan-3E board, board. I discovered that these parenthetical values were but it’s pretty close—basically, the only changes necessary pin numbers by examining the pinout diagram I found in are the product specification and the pin configuration. the depths of Xilinx’s web site. So, follow the written text in the QST.pdf and take notes The clock was trial and error. I grabbed the first clock sig- of my changes here. nal I could find on the board by looking at the pinout dia- After you have determined that your are in compliance gram—and that happened to be position A10. Happenstance with the software requirements, the second section is “Create led me to see that A10 is parenthetically labeled on the board a New Project.” Change the “Family” to “Spartan 3E,” for the mini-coaxial-style auxiliary clock input. I doubt that change the “Device” to “XC3S500E,” this clock signal would have worked. and change the “Package” to I then noted that C9 is associated CLOCK “FG320.” Everything else remains Loc : C9 (fill in) with the master 50-MHz clock, as the same, as the tutorial states. The Bank : Bank0 (automatic) parenthetically noted on the board I/O Std. : LVCMOS33 (fill in) next section is “Create an HDL Vref : N/A (automatic) (near the coax-style connector). Source.” The first subsection is “Cre- Vcco : 3.3 (automatic) The tutorial doesn’t give the full ating a VHDL Source.” I used this everything else leave alone constraint information for the pins, instead of the Verilog path, and I did- COUNT_OUT<0> but the “Spartan-3E Starter Kit Board n’t need to make any changes. The Loc : F12 (fill in) User Guide” shows the full con- Bank : Bank0 (automatic) second subsection is “Using Lan- I/O Std. : LVTTL (fill in) straint. I don’t know if the full con- guage Templates (VHDL).” No Vref : N/A (automatic) straint is necessary, because the Vcco : 3.3 (automatic) changes are necessary. The third sub- Drive Str : 8 (fill in) attempt previous to the working sam- section is “Final Editing of the VHDL Slew : Slow (fill in) ple used A10 as the clock and did not Source.” No changes are necessary. everything else leave alone have the full constraint. It’s probably Take it step-by-step because I missed COUNT_OUT<1> a good idea to always give the full the text in the first step by trying to Loc : E12 (fill in) constraint, so I’m advocating it here. Bank : Bank0 (automatic) see the differences between my file I/O Std. : LVTTL (fill in) Also, due to the lousy UI layout and the file listed on the page. The Vref : N/A (automatic) of this product, I had no strong Vcco : 3.3 (automatic) fourth subsection is “Creating a Ver- Drive Str : 8 (fill in) indication that more fields existed ilog Source.” Skip this subsection. Slew : Slow (fill in) on the “I/O Pin” input area. The fifth subsection is “Using Lan- everything else leave alone Notice the scroll bar at the bottom guage Templates (Verilog).” Skip this COUNT_OUT<2> of the input area! You can either Loc : E11 (fill in) subsection. The sixth subsection is Bank : Bank0 (automatic) scroll the window or widen it to “Final Editing of the Verilog Source.” I/O Std. : LVTTL (fill in) get the full list of data fields, Vref : N/A (automatic) Skip this subsection. The last subsec- Vcco : 3.3 (automatic) which you can alter (see Figure 1). tion is “Checking the Syntax of the Drive Str : 8 (fill in) The seventh section is Reimple- Slew : Slow (fill in) New Counter Module.” No changes ment Design and Verify Pin Loca- are necessary. The fourth section is everything else leave alone tions. No changes are necessary. “Design Simulation.” The first sub- COUNT_OUT<3> The single subsection is Verify Loc : F11 (fill in) section is “Verifying Functionality Bank : Bank0 (automatic) Design using Timing Simulation. using Behavioral Simulation.” No I/O Std. : LVTTL (fill in) No changes are necessary. Vref : N/A (automatic) changes are necessary. The second Vcco : 3.3 (automatic) The last section is Download subsection is “Create a Self-Checking Drive Str : 8 (fill in) Design to the Spartan-3 Demo Slew : Slow (fill in) Test Bench Waveform.” No changes Board. No changes are necessary. are necessary. The last subsection is everything else leave alone Mentally replace “xc3s200” with “Simulating Design Functionality.” DIRECTION “xc3s500e.” Loc : H13 (fill in) No changes are necessary. The fifth Bank : Bank1 (automatic) It will take a moment to pro- section is “Create Timing Con- I/O Std. : LVTTL (fill in) gram and then the running LCD Vref : N/A (automatic) straints.” No changes are necessary. Vcco : 3.3 (automatic) text will freeze. When the orange The sixth section is “Implement Termination : pulldown (fill in) below the “configuration jumpers” Design and Verify Constraints.” The everything else leave alone (below the female serial connector) first subsection is “Implementing the lights up, the board is programmed. Figure 1—This is information that you will fill in on a dialog box. Design.” No changes are necessary. It is related directly to the QST PDF, which you will receive with At this point, the four rightmost The second subsection is “Assigning your demo board or download directly from the Xilinx web site. LEDs should begin shining.

62 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com

2804014_hutt.qxp 3/7/2008 10:18 AM Page 64

Further digging through the docu- Listing 1—This is a modified quick start tutorial (QST) from the Xilinx documentation. It continuously counts mentation produced a “quick start from 0 to 15 using four LEDs. tutorial” (QST) design, which imple- ments a four-bit counter that is dis- library ieee; use ieee.std_logic_1164.all, ieee.numeric_std.all; played on four of the eight LEDs. However, like the samples provided in entity main is ISE, this tutorial is for a different Port ( CLK_50MHZ : in std_logic; board. Discouraged, but ornery and DIRECTION : in std_logic; COUNT_OUT : out std_logic_vector(3 downto 0)); determined, I set out to make the end main; tutorial work. After a few hours of poking around, I had the changes nec- architecture Behavioral of main is essary to get the QST working. Refer begin to the “Quick Start Tutorial” for more process (CLK_50MHZ) information. subtype counter_t is natural range 0 to 15; As you can see in Listing 1, there are variable i : counter_t := 0; three interface pins to the main entity. begin if rising_edge(CLK_50MHZ) then The input clock is CLK_50MHZ. The if DIRECTION = '1' then i := i + 1; direction of the counter is provided by else i := i - 1; DIRECTION, and the connection to the end if; LEDs is provided by COUNT_OUT. end if; COUNT_OUT <= std_logic_vector(to_unsigned(i, 4)); The code in Listing 1, which I sim- end process; plified from the original Xilinx ver- end Behavioral; sion, counts up or down, depending on the value of the DIRECTION input. Then it assigns the low-order 4 bits to BASIC OPERATION OF TOOLS they never work the way I do, that I the output LEDs. As an introduction After working with ISE to input the needed to understand how the tools to VHDL, this is a pretty gentle easing QST, I quickly realized, as someone could be used from a traditional build into the pool (see Photo 3). who eschews IDEs mainly because system using “make.”

64 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 65.qxp 1/28/2008 4:14 PM Page 1 82.qxp 2/1/2008 11:05 AM Page 1

LEARN TODAY. DESIGN TOMORROW.

Conference: April 14 – 18, 2008 Expo: April 15 – 17, 2008 McEnery Convention Center, San Jose, CA

Embedded Systems Conference Silicon Valley delivers a comprehensive technical program focusing on 15+ critical topics that affect your designs. Learn how to solve your engineering issues today.

register today at www.embedded.com/esc/sv 2804014_hutt.qxp 3/7/2008 10:18 AM Page 67

load projects and compile aa them. Of course, it’s your responsibility to make sure that each and every clk-signal - b -- b - - b - one of the clients of the diagnostic LED design are recompiled. Figure 1—This is a 50-MHz waveform showing rising edges (a) every 20 ns (b). The creation of the cus- tom build process yielded five commands, which are was an “expert.” I undertook a person- required to convert a al goal of displaying “Hello, world!” design from schematic, on the first line of the LCD. The LCD Photo 3—This is Xilinx’s ISE showing the VHDL source, pin constraints, Verilog, or VHDL into a has very specific timing constraints for and a portion of the schematic of the synthesized design. loadable binary image. initialization and use. They are also Although there are many the aspects that created the most diffi- I spent a couple of weeks determin- more commands for things such as culty for me in creating a suitable ing which command-line tools are power utilization and converting data design. My first two lessons came from actually required to convert a VHDL to RAM or ROM, they are all topics the realization that a 50-MHz clock— source file into a rudimentary image, that I have not needed to investigate. that is, the clock cycles 50 million which can be uploaded to the S3E Several commands take arguments times per second—is equivalent to a board, and create a build process, in non-Windows and non-Linux style. 20-ns clock cycle (one is the inverse which will automatically build all of While it’s a bit unwieldy, it is possible of the other) and programming in my designs at once. A command-line to script an entire build process VHDL based on the “rising edge” of build process is far superior to an IDE around them. the clock means that the rising edge because it’s simpler and more robust. “xst” is the program that trans- of the clock is present every 20 ns Here’s why: consider a situation forms Verilog, VHDL, and possibly (see Figure 1). where I have a low-level design, which schematics into an intermediate rep- With this knowledge, it’s fairly easy is used by all of my sample programs. resentation, which is taken as input to convert from clock cycles to time For example, I have a design that mul- by the ngdbuild program. It does not and back again. For example, if the tiplexes the eight LEDs into 16 sets of contain an implementation of the full documentation for a device says that LEDs by using the slider switches. If I VHDL language, but it’s sufficient to 15 ms must pass after power-up before change the interface to this design, an get the job done for someone of my the device will accept commands, it’s automated build process recompiles experience level. I have found several easy to calculate how many clock only the designs affected by the internal errors and several deficien- cycles must be expended: change. After all of the newly intro- cies in the language. Most of the duced compilation errors are fixed, the attributes that can be applied to enu- entire set of software is once again meration types are not supported. For- ready for use. However, accomplishing tunately, so far, I’ve found the same thing with an IDE would workarounds for all of the internal mean a lot of manual intervention to errors that I’ve encountered. Note that 15 ms is 15,000,000 ns. “ngdbuild” is the program that The Xilinx documentation for the reads the output from the XST pro- LCD interface alternately gives times

CLK SF_D (11:8) gram and produces a Xilinx native and clock cycles, so it’s nice to be able LCD LCD_E generic database (NGD) file. The out- to convert clock cycles into times so Initializer ENABLE LCD_RS put file contains a logical description the numbers can be double-checked

LCD_RW of the design and the original hierar- with the LCD specifications (which RESET BUSY chy. “map” is the program that maps can be easily downloaded from the the logical design to a specific FPGA. manufacturer). For example, 15 clock The “par” program places and routes the design given the constraints CLK SF_D (11:8) provided. “bitgen” is the program that COMMAND (1:0) SF_D (11:8) DATA (7:0) LCD LCD_E Writer takes the placed and routed design and DATA (7:0) LCD LCD_E ENABLE LCD_RS Controller generates a binary image, which can CLK LCD_RS MODE LCD_RW be uploaded to the FPGA board. RESET LCD_RW RESET BUSY BUSY “HELLO, WORLD!” VHDL STYLE Figure 2—Take a look at the block-level interface for Of course, with the QST success Figure 3—This is the block-level interface for the over- the LCD initializer and writer. and a build process under my belt, I all LCD controller.

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 67 2804014_hutt.qxp 3/7/2008 10:18 AM Page 68

Listing 2—This is the programmatic interface to the “Hello, world!” design. BTN_NORTH is reset. The remaining out parameters connect directly to the LCD hardware.

6 entity main is 7 Port (CLK_50MHZ : in std_logic; 8 BTN_NORTH : in std_logic; 9 SF_D : out std_logic_vector (11 downto 8); 10 LCD_E : out std_logic; 11 LCD_RS : out std_logic; 12 LCD_RW : out std_logic); 13 end main;

cycles can be converted into 300 ns by on was to split the initialization of the following: and writing to the LCD into two sepa- rate VHDL entities. Figure 2 shows the “Initializer” and “Writer” entities. These entities are tied together with a With this knowledge and after read- “Controller” (see Figure 3), which takes ing the documentation for the LCD sev- a “command” input, which differenti- eral times, the design I finally settled ates between “idle,” “initialize,”

Listing 3—This is a portion of the state machine in the “Hello, world!” design that controls the LCD controller in Figure 3.

32 begin 33 handler : process (CLK_50MHZ, BTN_NORTH) is 34 variable state : state_t := s_init; 35 variable data : std_logic_vector (7 downto 0) := "00000000"; 36 variable mode : lcd_types.mode_t := lcd_types.initialize; 37 variable idx : integer := 0; 38 begin 39 if BTN_NORTH = '1' then 40 -- reset 41 state := s_init; 42 mode := lcd_types.idle; 43 idx := 0; 44 elsif rising_edge(CLK_50MHZ) then 45 case state is 46 when s_init => 47 mode := lcd_types.initialize; 48 if lcd_busy = '1' then 49 state := s_init_wnb; 50 end if; 51 when s_init_wnb => 52 if lcd_busy = '0' then 53 mode := lcd_types.idle; 54 state := s_function_set_0x28; 55 data := "00101000"; -- function set 0x28 56 end if; 57 when s_function_set_0x28 => 58 mode := lcd_types.command; 59 if lcd_busy = '1' then 60 state := s_function_set_0x28_wnb; 61 end if; 62 when s_function_set_0x28_wnb => 63 if lcd_busy = '0' then 64 state := s_enable_display; 65 mode := lcd_types.idle; 66 data := "00001111"; -- display on, show mem, show cursor 67 end if; 68 when s_enable_display => 69 mode := lcd_types.command; 70 if lcd_busy = '1' then 71 state := s_enable_display_wnb; 72 end if;

68 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 2804014_hutt.qxp 3/7/2008 10:18 AM Page 69

Listing 4—This is a continuation of Listing 3. Here you see lines 73 through 112. PRESTO 73 when s_enable_display_wnb => 74 if lcd_busy = '0' then The First USB In-Circuit 75 mode := lcd_types.idle; Multipurpose Programmer 76 state := s_clear_screen; 77 data := "00000001"; -- clear screen 78 end if; 79 80 when s_clear_screen => 81 mode := lcd_types.command; 82 if lcd_busy = '1' then Very fast and flexible in-system 83 state := s_clear_screen_wnb; 84 end if; programmer for many devices: 85 when s_clear_screen_wnb => x Atmel AVR, 8051 architecture 86 if lcd_busy = '0' then x Microchip PIC, dsPIC, rfPIC, ... 87 mode := lcd_types.idle; x Texas Instruments MSP430 88 state := s_display_char; x ARM MCUs by Atmel, NXP 89 data := string(idx); (Philips) - including debugging 90 idx := idx + 1; x FPGAs, CPLDs & SCPs 91 end if; by Xilinx, Altera, Lattice, ... 92 when s_display_char => x Serial Flash, EEPROMs, ... 93 mode := lcd_types.char; 94 if lcd_busy = '1' then 95 state := s_display_char_wnb; SIGMA 96 end if; 97 when s_display_char_wnb => Unique Logic Analyzer 98 if lcd_busy = '0' then With Extremely Large Memory 99 mode := lcd_types.idle; for more than 14,000,000 events, 100 if idx > string'high then up to 16 inputs, up to 200 MHz 101 state := s_quiesce; sampling, flexible triggering, ... 102 else 103 state := s_clear_screen_wnb; ...and more 104 end if; 105 end if; MU Beta - unique PIC emulator 106 when s_quiesce => USB modules - parallel & serial 107 mode := lcd_types.idle; SPINET - Ethernet-SPI interface 108 end case; Development boards and kits, ... 109 end if; 110 lcd_data <= data; For developers by developers. 111 lcd_mode <= mode; [email protected] 112 end process handler; [email protected] tools.asix.net “write a command,” and “write a processing the last command, the character.” “busy” signal is asserted. When it’s As you can see in Figures 2 and 3, complete, the signal is deasserted. four outputs are physically connected The important parts of the code that to the LCD on the board: SF_D con- output “Hello, world!” to the LCD tains the data or command provided using the previously mentioned enti- to the LCD; LCD_E is LCD enable; ties are included in Listings 2, 3, and and LCD_RS is register select. When 4. Lines 6 through 13 define the “0,” the LCD interprets the SF_D as a physical interface to the sample pro- command. When “1,” it interprets it gram. The CLK_50MHZ signal is the as data. LCD_RW is read/write. When input clock signal. BTN_NORTH is “1,” it enables reading data from the used as a Reset button. (Pressing it display. When “0,” it enables writing causes the design to reset and start to the display. over.) The remaining four output sig- Because I am an amateur at writing nals are connected directly to the VHDL code, and because both the LCD pins on the S3E demonstration LCD Writer’s and LCD Initializer’s board. All of the symbols used in this entities are very slow compared to the entity declaration must be declared speed of the S3E board, I opted to have in the “constraint” file, so the tools an output from my designs called can make the actual connections. “busy.” As long as the entity is still You need an enumeration, which is

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 69 2804014_hutt.qxp 3/7/2008 10:18 AM Page 70

used to describe the different states of places where I could shorten and overall quality. If the software industry the finite state machine. Call it improve the code, but it would serve did not turn into such a competitive state_t. While each state is not little purpose for me to do so. The horizontal market, the quality of those shown here, symbols beginning with an foremost reason against revisiting this tools would certainly be much lower s_ prefix, such as s_init, are all code is that it’s extremely cumber- now. So, the best thing to cause the members of the state_t enumeration. some to write to the LCD using hard- FPGA vendors to improve their prod- Moreover, the string that you desire ware. It’s easier to write to the LCD ucts would be for the market demand to output “Hello, world!” is defined using software, which requires a CPU to go up. in a constant array, which is called of some sort! As many other markets have real- “string.” The state machine imple- ized, a better product means better mentation, which is shown, outputs MOVING FORWARD sales. We can hope that the FPGA each character, in turn, from this To more easily write to the LCD, I market will also recognize that it’s in constant. will design a CPU that will enable me its best interests to improve its tools Lines 32 through 112 define the to experiment and recreate the enjoy- in a timely fashion. I process that implements the state ment of 25 years ago. To that end, I’ve machine to control the LCD entity created a specification based heavily Taylor Hutt ([email protected]) (see Listings 3 and 4). It’s a fairly on the MIPS processor. I’ve begun grew up in Hawaii, attended college straightforward state machine once implementing parts of the design. in Ohio, and has worked for various the syntax is mastered. The state Notably, I have a register file and an Silicon Valley companies, such as variable contains the current state of ALU. To create a full-fledged comput- Borland and VMware, doing low- the machine. On each clock cycle, er, I’ve got a keyboard, serial transmit, level development work. Recently, the section of code, which is preced- and serial receive designs under my bored with the tack of the software ed by the current value of the state belt. industry, he decided to teach himself variable, will be enabled. Because I’ve tested everything using the hardware design (with some guid- state is initialized to the state onboard LEDs and the serial port. The ance from a hardware veteran). He is s_init in line 34, the code in lines advantage of testing using the serial currently implementing a full com- 47 through 50 will be active at port is the tests are automatable and puter, using the Spartan-3E board, power-on. Once the LCD entity sets reproducible by everyone. If I learn from the design of the MIPs-influ- the lcd_busy flag, the state machine new techniques for implementing an enced processor, through the assem- transitions to state s_init_wnb. (On ALU in VHDL, or if I decide to learn bler, linker, and bootstrap loader all line 49, wnb is shorthand for wait Verilog and reimplement it in Verilog, the way up to I/O devices. until not busy.) I can rerun the design, which validates Lines 85 through 105 implement the ALU, after such changes. If the the loop, which will output all of the results still match the expected PROJECT FILES characters from string to the LCD results, I can be confident that I have To download code, go to ftp://ftp.circuit device (see Listing 4). This is accom- not broken an existing feature. Finally, cellar.com/pub/Circuit_Cellar/2008/213. plished by iterating over the length of after testing, the new design change the string and setting the LCD enti- can be incorporated into the full CPU ty’s mode to lcd_types.char, without fear of correctness regres- RESOURCES which means to output a character to sions. The details of those achieve- P. Ashenden, The Designer’s Guide to the display at the current cursor posi- ments will be for another article. VHDL (Systems on Silicon), Morgan tion. When the whole string has been You can now start designing your Kaufmann Publishers, San Francisco, output, the machine enters the own pet project using inexpensive CA, 2002. s_quiesce state. parts from Xilinx. All it takes is a lit- E. Hwang, Digital Logic and Micro- The s_quiesce state is terminal for tle perseverance, a dash of patience, processor Design with VHDL, CEN- the state machine. There are no transi- and a lot of recompilation. GAGE-Engineering, Belmont, CA, tions from this state, so the state 2005. machine will stay there forever. To SYNTHESIS TOOLS IN GENERAL ensure that the LCD is also quiesced, My basic impression is that the Xilinx, Inc., “Spartan-3E Starter Kit the mode is set to idle. The imple- world of tools, which can be used to Board User Guide,” UG230, 2006, mentations of the low-level LCD inter- develop hardware, is stratospherically www.xilinx.com/support/documentation face, which are available for down- expensive. The Xilinx tools are an /boards_and_kits/ug230.pdf. load, count clock cycles at 50 MHz to excellent value. However, when com- implement the intricate timing paring the tools used to generate hard- required to write to the LCD. ware designs to the tools used to SOURCE With the limited additional experi- develop software, the hardware tools Spartan-3E (S3E) starter kit ence I now have under my belt after are about 20 years behind in ease-of- Xilinx, Inc. writing to the LCD, I see several use, reliability, documentation, and www.xilinx.com

70 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 71.qxp 2/28/2008 11:16 AM Page 1

The Newest Embedded Technologies

New Products from:

VDIP1 Module www.mouser.com/ftdi/a

RCM4000 RabbitCore® Modules www.mouser.com/rabbitsemi/a

MatchPort™ b/g Embedded Device Server www.mouser.com/lantronix/a

The ONLY New Catalog Every 90 Days

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

Flexis™ DemoQE128 Demo Board www.mouser.com/freescale/a The Newest Products For Your Newest Designs

www.mouser.com (800) 346-6873 Over 930,000 Products Online

Mouser_CircuitCellar_4-1.indd 1 2/26/08 11:08:59 AM 72.qxp 3/10/2008 10:40 AM Page 1 27804002-Bachiochi.qxp 3/7/2008 10:44 AM Page 73

FROM THE BENCH by Jeff Bachiochi Digital Touch A Potentiometer with No Moving Parts Tired of replacing your mechanical parts? Jeff has the solution: eliminate them. His design provides user input and a digital potentiometer for resistance or voltage output.

Living in a material world has its Digital potentiometers aren’t new, benefits and drawbacks. You can but their use hasn’t greatly impacted either choose to become wrapped up the number of mechanical potentiome- in possessions with a possibility of ters used in today’s products. That may becoming a King Midas or you can use be due to the fact that they require technology to improve your life and additional hardware. This can be as those who share this neighborhood we simple as mechanical switches that call Earth. When I see the imbalance directly step the digital potentiome- of opportunity in the world, I feel ter’s wiper up or down or a microcon- guilty to be living in the U.S. Howev- troller and another user input device to er, this will be true only if I squander support the up/down control. my good fortune without any attempt This month, I will show you how to to improve life for others, either create a potentiometer with no mov- directly or indirectly. ing parts (see Photo 1). That’s right: no At times, I wonder if some advances mechanical parts to wear out or break. in technology are really improve- The design features a Quantum ments. Is an electronic switch that Research Group (QRG) QT411-ISSG replaces a mechanical one an improve- QSlide touch slider IC, which provides ment? Is medicine that brings relief, user input and a digital potentiometer along with side effects, an improve- for resistance or voltage output. It also ment? How about a spray that pro- features a small microcontroller to tects a fruit tree from disease, but ster- convert data and display position. ilizes the bee population? We can’t always predict how technology will TOUCH SLIDER IC affect future generations. That’s why Quantum Research Group has pack- there are strict controls on DDT, aged three capacitive sensors in a single asbestos, and lead-based paint. IC. The sensors can perform 128-bit res- Mechanical wear is viewed as a weak olution position translation by compar- link in designs. Anytime you have two ing the inputs. Each of the three sensor materials that rub against one another, circuits requires two pins: a drive pin you will have wear. We go to great and a receive pin. The receive pin is lengths to reduce this by using bearings the common connection of an RC or material coatings. When an electri- network. The free end of the sampling cal connection is necessary between capacitor goes to the drive output and materials, as in potentiometers, any the free end of the resistor becomes the wear will affect the device. How many sensing detector. When a grounded stereo systems have been junked object (i.e., a finger) approaches the because the audio controls became sensor, it places added capacitance to scratchy? At high volumes (where I ground. When it approaches the resis- Photo 1—By keeping all of the components on the sol- like to listen), this is like listening to tor toward the sensor input, there is der side of the PCB, the top side remains free of parts fingernails drag across a chalkboard. minimal resistance. At the opposite that would otherwise interfere with a nice graphic label.

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 73 27804002-Bachiochi.qxp 3/7/2008 10:44 AM Page 74

Figure 1—By combining the QSlide linear position sen- sor with a Microchip Technology PIC16F882 microcon- troller and a digital potentiometer, you can create a con- trol with no moving parts to wear out. Potentiometer position is reflected by a value on an LED display.

end of the resistor, there is maximum resistance. Not only is there an RC timing difference at opposite ends of the resistor, there is an RC timing dif- ference at all points between the two extremes. If the sensing resistor ele- ments are connected between sensor inputs, then a comparison of inputs can be used to mathematically deter- mine the position of a grounded object approaching the sensor between the two sensing inputs. Because there are three inputs, there are three exclusive sensing elements. Detection takes place when an element (between two inputs) senses an object. Large objects that approach multiple elements are rejected. The QT411 has a simple SPI. Few commands are necessary to establish a working sensor. Figure 1 shows that the interface uses two additional out- puts to the normal SDI, SDO, SCLK, and *SS signals. A low DRDY output indicates a busy state. This is when the QT411 is making its acquisition bursts. When a burst recognizes an input at up to two of the sensors, the

74 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 27804002-Bachiochi.qxp 3/7/2008 10:44 AM Page 75

~31 ms ~31 ms Acquire burst

Less than 1 ms Less than 1 ms

Sleep mode Awake Low-power sleep Awake Sleep

400 µs typ 3-state if left to float

DRDY from QT Greater than 13 µs, Less than 100 µs

Greater than 12 µs, Less than 100 µs Greater than 20 µs Greater than 12 µs, Less than 100 µs

SS from host Less than 35 µs Greater than 1 µs Less than 5 µs Sleep until automatic wake (~3 s) Data sampled on rising edge Wake up on *SS line CLK from host Data shifts out on falling edge

Less than 10 µs delay edge to data Data hold greater than or equal to 12 µs after last clock

Host data output (Slave input - MOSI) ? 76543210 Command byte

Response byte QT data output 3-state 3-state ? 76543210 (Slave out _ MISO) Output driven less Output floats before than 12 µs after *SS goes low DRDY goes low

Figure 2—Besides the QT411’s SPI, the device has two additional outputs, DRDY and DETECT. The latter can be monitored for touch without SPI communication. However, you must use the SPI communication to read the touch value.

DETECT input is driven high. This default values, unless you want to The DRIFT command is used periodi- optional output can be used in Free change these, you may never use these cally to enable the device to “self Run mode where the IC makes period- special commands. Once an error-free adjust” to environmental changes. ic acquisitions without operator inter- calibration has occurred, the NULL To produce a linear element that vention. Otherwise, a detect status bit and DRIFT commands are the only you can use for detection purposes, holds the same information and is ones necessary. The commands return you don’t need to use a continuous returned with each command transfer. a status byte that indicates whether a resistive element, such as iridium-tin- The lowest power can be imple- touch has occurred (MSBit = 1) and, if oxide (ITO) ink. The element can be mented using the Polled mode because so, what the value is (0–127 LS6–bits). made up of segments connected an acquisition is performed only after the device has been selected and dese- lected (*SS). There are three modes: Forced Acquisition (when *SS goes high), Free Run (approximately 30 ms after *SS is held high), and Sleep (*SS is held low). If you are familiar with SPI communications, you know that data can be clocked in both directions at the same time (see Figure 2). This means that if you are asking for information, you must wait until the next command to receive a reply. The QT411 has only five commands and three are special and used for initialization. Because the Photo 2—Segments on this prototype are about 0.25″ wide. They are 0603 SMT resistors hand-soldered between device initializes on powerup with segments.

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 75 27804002-Bachiochi.qxp 3/7/2008 10:44 AM Page 76

together with discreet on its own PCB and resistors (see Photo 2). The VDD PB0 mounted on the compo- capacitive nature of an nent side of the PCB, flush VSS Wiper Register object (e.g., a fingertip) is register array 0 with the top (component- linearly divided by adjacent Control less) touch side. Although logic segments when each seg- it is a bit more expensive, ment is sized appropriately PA0 the cost of an extra PCB, PW0 to the object doing the it would enable the graph- touching. The total resis- *CS 16-bit ic label to cover the top Shift tive value of the element register side of the PCB, with a should be approximately SI transparent window for 400 kΩ. The three sam- the display. SCK pling capacitors’ (men- The timing for multi- tioned earlier) values can plexing the digits is based Figure 3—This digital potentiometer has a 256-tap resistor array totaling 10 kΩ. The be varied slightly to attain wiper (tap position) is set via a SPI. The digital potentiometer is totally isolated from the on persistence of vision. proper sensitivity based on rest of the circuitry. Note that 60-Hz AC light- insulator material and ing is continuously going thickness. In this case, the material is *CS line. A data value of 0x00 is the off and on but it happens faster than .063 FR4 PCB, possibly with a thin minimum position (B) and a data your eye can respond. If it happens too acrylic label on top. value of 0xFF is the maximum posi- slowly, you begin to see a very distract- tion (A). This device defaults to mid- ing flicker. To prevent this with the DIGITAL POTENTIOMETERS position during powerup. seven-segment display, each digit is Mechanical potentiometers wear enabled at a rate above this minimum. out over time, rotary potentiometers CONTROL AND FEEDBACK Many video gamers consider 30 frames are fairly well sealed, and slide poten- One advantage of using a mechani- per second (fps) to be an absolute min- tiometers have an inherent “open” cal potentiometer is that the knob or imum. This project uses an internal 2- slot where environmental contami- slider position gives you feedback MHz oscillator giving a 2-µs instruc- nants can enter. Worn potentiometers about the present position of the con- tion cycle. Configuring Timer0 to use add noise that will make an audio buff trol. Once you remove your finger a divide-by-eight prescaler, the 8-bit cringe, as if listening to AM radio dur- from the touch control, you have no timer will overflow about every 4 ms ing a thunderstorm. Digital poten- feedback about where the control is or 4,096 µs (i.e., 2 µs × 8 × 256). There- tiometers have no moving parts. set. This could be presented in a num- fore, Timer0 will cause an interrupt Therefore, they can provide years of ber of ways with LEDs. You can put a every 4 ms. The interrupt deselects service without the breakdown of the row of LEDs along the touch area to the present digit, gets the next digit’s mechanical wiper/element connec- give some kind of feedback or present data, and enables the new digit. tion. They use a digital value to con- the user with a number representing Because there are four digits in this nect the wiper to a corresponding the potentiometer’s position. I chose system, each digit is flashed for 4 ms position on a chain of discreet resis- the latter, because I can make this out of every 16 ms. That’s a refresh tors. Figure 3 is a block diagram of a value represent various data. For rate of 62.5 Hz (0.0625 ms = 62.5 Hz). Microchip Technology MCP41010 dig- instance, I might want to show a per- Take a look at the flowchart for this ital potentiometer. centage (0 to 100%) or the actual bina- application in Figure 4. A SPI command to the MPC41010 ry data from the QSlide. The main routine of this application consists of 16 bits. The first 8 bits I have an inexpensive four-digit waits for a 64-ms flag to be set (by the contain a command and the last 8 bits seven-segment display that will give display routine). It then looks for an contain the wiper’s data value. While three digits with a spare that I might indication of touch from the QT411. If the shutdown (0x20) command does use to present a minus sign (more on no touch is sensed (QT411Reply.7 = not require any data, 16 bits must be that later). The display requires eight 0), the application checks the configu- transmitted for each command, so the row and four column connections. ration jumper settings for auto-zero. data in this case is “don’t care.” Shut- With a Microchip Technology Auto-zero initializes the P0Value to down will disconnect the “A” termi- PIC16F882 microcontroller, I can “zero” (or 0x40, mid-scale for zero- nal from the top of the resistor chain source eight segments (rows) directly, centered output) whenever the touch and connect the wiper to the “B” ter- as long as I multiplex the digits using detection is removed. Otherwise, the minal (bottom of the resistor chain). a (column) transistor that will support P0Value equals the actual touch value The WR command will set the wiper the current of eight (potential) seg- (0x00–0x7F). state during the rise of the *CS line. ments. My prototype has the display The Percentage routine checks The wiper value can be set during a mounted on the touch side of the the configuration jumper settings to shutdown condition, but it will acti- PCB. I now realize that the cool factor determine which of the three modes vate the device during the rise of the would be increased if the display was to use, Actual Value (0x00–0x7F),

76 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 27804002-Bachiochi.qxp 3/7/2008 10:44 AM Page 77

Percentage (0–100), or Zero-Centered command every so often. When and if data is clocked in and out (rising or (±0–100). The Actual Value mode to use this command is up to you and falling edge of the clock). When multiple requires no conversion and the per- it is based on how the potentiometer devices are used, each must have a sepa- centage is equal to the P0Value. Per- will be used. In an application where rate CS (chip enable). This enables a sin- centage mode uses two integer math the control is used for more than gle device to be active while all the oth- routines (multiplication and division) intermittent use, drift compensation ers lay idle on the SPI bus. For devices to calculate a percentage of the full- during lingering contact will attempt that require different parameters, you scale value (P0Value × 100/127). The to cancel what it sees, so perform drift can initialize the SPI bus differently for zero-centered value is similar to the compensation less often. each device prior to enabling (*CS) percentage calculations except P0Val- The MPC41010 can only be spoken to. communication with it. Once the digi- ues less than 0x60 are considered neg- Its 10-kΩ potentiometer is set based on tal potentiometer is set, the main loop ative and must be subtracted from the second 8 bits of a 16-bit command. is finished and the application loops 0x60 prior to determining the percent- The 0x00–0xFF value for the digital back, awaiting the next 16-ms flag. age. Other P0Values are considered potentiometer is twice the resolution of positive and must have 0x60 subtract- the QT411. Therefore, a translation must VALUE TO DIGITS ed from them prior to determining the be made between the value read from the This application is based on a single percentage. When a P0Value is deter- touch slider and the value written to the timer-overflow interrupt. Every 4 ms, mined to be negative, a flag bit is set digital potentiometer. In this case, a sim- the Timer0 interrupt overflows. This to indicate this. The zero-centered ple shift (times 2) does a nice job. interrupt routine is responsible for dis- value (not to be confused with the A note here on SPI use is in order. abling the row driver for the present auto-zero) treats the linear poten- Not all SPI communication uses the digit, selecting the next digit, figuring tiometer as a balance adjustment same configuration. To use a SPI out what data should be displayed for (left/right or plus/minus). device, you need to know if it requires the digit, and enabling the column The QT411 can correct for tempera- an idle high or idle low clock level. In driver before leaving. ture and environmental influences if addition, you need to know how the A digit counter keeps track of the you give it a compensation (DriftComp) device reads and writes data or when enabled digit 1 to 4, right to left (units,

Initialize Timer0 Int QT411

N Disable present digit's driver. Initialize SPI for QT411. Enable QT411. 64 ms ? Get next digit's seven-segment data from lookup table. Send QT411Command. Get QT411Reply. Enable new digit's driver. Disable QT411. Y

Call QT411 (error status) Return Return from interrupt

N Touched

Y N AutoZero ? MCP41010 Y P0Value = QT411Reply & 0x7F P0Value = P0ResetValue Initialize SPI for MCP41010. Enable MCP41010. Send WriteCommand. Send (P0Value × 2). Disable MCP41010.

Call percentage Return

Decrement DriftCount

DriftCount=0? Y Percentage N N CenterOff? Call QT411 Call QT411 (Null) (DriftComp) Y

N P0Value > 63? Y CalError Y Percent = (64-P0Value) *100/63 (Minus Sign) N Percent = (P0Value-64) *100/63 Percent = P0Value *100/127

Call Call QT411 MPC41010 (calibrate) Return

Figure 4—Most of the application is devoted to handling the multiplexed 4 × 7 display. The remaining three tasks are reading SPI data from the QT411, calculating what to display, and updating the position of the digital potentiometer.

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 77 27804002-Bachiochi.qxp 3/7/2008 10:44 AM Page 78

100 eliminating flaws or weaknesses can jus- Antilog tify the attempt. Mechanical wear and 90 Linear environmental exposure are two of the most desirable improvements. Any Log 80 replacement with no moving parts could Commercial log 70 inherently solve both needs. While an application like this project has more 60 parts and a higher cost than a mechani- cal part, the total cost of the electrical Percent 50 output parts is only approximately $15 (in sin- 40 gle-piece pricing). Trip, Scotty, Geordi, and B’Elenna (chronological by star 30 date) would really appreciate not hav- ing to constantly replace the mechani- 20 cal controls that will proliferate the 10 future versions of the Star Trek Enter- prise. Imagine spilling your caffeinated 0 beverage without panic as the liquid 0 30 60 90 120 150 180 210 240 Degrees rotation rolls off the controls without damage. Ever done this to your keyboard? Figure 5—This chart demonstrates how the potentiometer resistance at the wiper might change based on its position. Will this kind of innovation help While this is a fixed function of the resistive element on a mechanical potentiometer, it can be changed via software feed those starving in less developed in this application. (Source: Elliott Sound Products, http://sound.westhost.com/pots.htm) countries? Indirectly, it might improve the mean time between failure tens, hundreds, and sign). One column the slider. Although I’ve chosen to use (MTBF) of equipment that supports driver (digit) is enabled at a time a vertical sensing area (0x00 = bottom relief efforts. History has shown that (PORTC), while data for that digit is to 0x7F = top), this can be easily we cannot predict how a single tech- latched onto the row output port inverted by swapping two connections. nology will affect the present course (PORTB). The data for that digit comes Horizontal as well as curved sensing of man. Moreover, it’s the combina- from a table holding the byte values areas can be used in the design. Note tion of many technology bits that can that will display the digits 0 to 9 plus that small guard traces on the outside make the largest strides in improving “blank” and “-.” The order of the table of the segments can be used to limit the standards of all. I makes for an easy conversion from a interference with additional sensors number value to the offset in the table that might be used in larger multi- Jeff Bachiochi (pronounced BAH-key-AH- that holds the data representation of potentiometer applications, such as key) has been writing for Circuit Cellar that value for the seven-segment dis- audio mixers or graphic equalizers (see since 1988. His background includes play. Simple integer division deter- Photo 2). product design and manufacturing. He mines the appropriate number to dis- Data conversion (QT411 data to may be reached through the magazine play based on the unit, ten, or hun- MPC41010 position) does not have to be ([email protected]) or his dredths position of the percent value linear. Conversion algorithms can be web site (www.imaginethatnow.com). (calculated in the main loop). For digit used to apply a nonlinear function 4, a “blank” (table entry 10) is dis- between the slider and the digital poten- PROJECT FILES played unless the negative flag bit is tiometer’s value. For instance, you can To download code, go to ftp://ftp.circuit set. Table entry 11 holds the data give MPC1010 an audio (logarithmic) cellar.com/pub/Circuit_Cellar/2008/213. value for the minus sign. taper when used in volume control (see Figure 5). This digital device also comes LINEAR SEGMENTATION in a dual-potentiometer version. The SOURCES Be careful when you lay out the MPC42010 has two isolated devices LTC-4727 LED QT411 linear slider input sensor seg- that may be used in applications where LITE-ON Electronics, Inc. ments. By placing the segments on the a dual-ganged potentiometer is required. www.us.liteon.com bottom side of the PCB, you can place MCP41010 Digital potentiometer and surface-mount resistors between seg- WORTH IT PIC16F883 microcontroller ments and still get a perfectly smooth Change for the sake of change isn’t Microchip Technology, Inc. surface to touch (top side of the PCB), necessarily an improvement. There must www.microchip.com not to mention the insulation factor of be a redeeming value to the change the PCB. For smooth linear interpola- before it can be considered an improve- QT411-ISSG QSlide Touch slider IC tion, the segment size should be no larg- ment. The simplicity of a mechanical Quantum Research Group er than the smallest object used to touch potentiometer is tough to challenge, but www.qprox.com

78 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 81.qxp 1/4/2008 3:04 PM Page 1

What’s the difference?

Price!

You’re correct, the one on the right costs less because should find a lower print-advertised price for it’s from Jameco! When you’re looking to purchase a product Jameco offers, just let them know and major name brand passives or semiconductors, be they’ll offer that product for 10% less than the other sure to check out Jameco first. They also offer company’s price, right down to Jameco’s cost! money-saving generic equivalents at about Wouldn’t it be worth your time to check out Jameco 20% less, so you’ll save even more! And if you today at www.Jameco.com? • Both Major Name Brands and Generic Products for Additional Savings • Over 99% of Catalog Products are in Stock for Immediate Delivery • Only Jameco Guarantees the Lowest Prices

Click or call today for a FREE Jameco Catalog Visit www.Jameco.com/CCX and start benefiting from Jameco’s Awesome Prices! Call 1-800-831-4242 2804003-Cantrell.qxp 3/7/2008 10:45 AM Page 80

SILICON UPDATE by Tom Cantrell

More Than a Core While examining 32-bit microcontrollers last month, Tom decided that the STMicroelectronics STM32 was worth a second look. With the new ARM Cortex M3 core, good peripherals, integration, and energy efficiency, this could be just the MCU for your next project.

Having covered the territory last debates have become less relevant, thought these shining stars would month (“More Bits, Less Filling,” especially for blue-collar embedded burn out so fast? Circuit Cellar 212, 2008), it’s not my apps. Maybe it’s just battle fatigue, The microprocessor was barely born intention to get stuck on the topic of having seen so many architectures before it headed into battle. Early 8-bit 32-bit MCUs. Believe me, there’s march off to war. Remember way back skirmishes foreshadowed the epic plenty of other neat stuff going on in the mainframe years (1960–1970s) struggle between the Intel ’x86 and with FPGAs, wireless, sensors, and when companies like Univac, the then Motorola 68K, a battle that other wonders of the silicon age. Burroughs, and Honeywell challenged counted a myriad of upstart architec- Nevertheless, if you have anything to IBM with “better” architectures? All tures as collateral casualties. May the do with embedded systems, you need dead and gone. 88K, i860, Clipper, 29K, and all of the to stay up to speed with the latest hot Then there were the fabulous mini- others rest in peace. rod chips or you’ll get left behind. computers such as the Data General True believers are entitled to pitch In some ways these fast and furious Nova and the Digital Equipment VAX. their favorite architecture and poo-poo MCUs remind me of the brand new Like teenagers, they seemed invinci- the others. Taking nothing away from Tesla Motors high-performance elec- ble. “Nova” indeed. Who would have Cortex M3, the fact is that all of the tric vehicle just now hitting the streets. It’s got the efficiency and ICode green aspects of a golf cart, but can Flash interface Flash smoke the tires when you punch it. DCode memory Cortex-M3 The big difference is that the 32-bit System MCUs don’t cost an arm and a leg,

but in fact are a luxury any designer SRAM

can afford. DMA

So this month, you’re invited to Ch. 1 AHB system bus Bridge 1 look over my shoulder as I pop the Ch. 2 Bridge 2 APB2 APB1 hood on the STMicroelectronics STM32 (see Figure 1). You’ll recall Ch. 7 GPIOA USART1 USART2 WWDG GPIOB SPI1 USART3 CAN from last time that its main claim to GPIOC ADC1 SPI2 BKP fame is the use of the new ARM GPIOD ADC2 I2C1 PWR GPIOE TIM1 I2C2 TIM2 Cortex M3 core. Sure, that’s newswor- EXTI AFIO USB TIM3 thy, but there’s more to the STM32 IWDG TIM4 than that.

WORLD BEYOND CORE DMA Request Indeed, over the years, I’ve come to Figure 1—The ARM Cortex M3 core is the attention-getter in the new STM32 MCU from STMicroelectronics. But the conclusion that “core wars” there’s more to an MCU than a processor core, including lots of flash memory, fast SRAM, and a bunch of I/O.

80 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 2804003-Cantrell.qxp 3/7/2008 10:45 AM Page 81

Package pins 36 36 48 48 48 64 64 64 100 100 Flash 32 KB 64 KB 32 KB 64 KB 128 KB 32 KB 64 KB 128 KB 64 KB 128 KB SRAM 10 (6) KB 20 (10) KB 10 (6) KB 20 (10) KB 20 (16) KB 10 (6) KB 20 (10) KB 20 (16) KB 20 (10) KB 20 (16) KB General-purpose 2 3 2 3 3 2 3 3 3 3 timers Advanced control 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) timer SPI 1 1 1 2 2 1 2 2 2 2 I2C 1 1 1 2 2 1 2 2 2 2 USART 2 2 2 3 3 2 3 3 3 3 Full-speed USB 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) 2.0 CAN 2.0B 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) 1 (0) 12-bit 1-µs A/D 2 (1) × 10 ch 2 (1) × 10 ch 2 (1) × 10 ch 2 (1) × 10 ch 2 (1) × 10 ch 2 (1) × 16 ch 2 (1) × 16 ch 2 (1) × 16 ch 2 (1) × 16 ch 2 (1) × 16 ch General-purpose 26 26 37 37 37 51 51 51 80 80 I/Os CPU Frequency 72 (36) MHz 72 (36) MHz 72 (36) MHz 72 (36) MHz 72 (36) MHz 72 (36) MHz 72 (36) MHz 72 (36) MHz 72 (36) MHz 72 (36) MHz

Table 1—STMicroelectronics blasts off the starting line with a full complement of 20 STM32 parts, divided equally between “Performance” and “Access” lines. In this table, the “Access” line features are shown in parenthesis where they differ from the “Performance” line. Another difference is that both lines come standard with a –40° to 85°C tempera- ture range, but the “Performance” parts also have an extended temperature range (–40° to 105°C) option.

major 32-bit MCUs (including the can lead to the awkward situation a curse if the I/O traffic clogs available ARM7 and ARM9 chips ST also offers) where more “megahertz” means less bus bandwidth and demands a lot of are fully capable of getting the job performance. It’s no surprise that handholding by the processor. The done in most applications. most 32-bit MCUs devote silicon to STM32 avoids that pitfall with multi- Look at a die photo of any 32-bit the cause of getting around the flash ple on-chip I/O busses to boost band- flash MCU and what you’ll find is a bottleneck. The STM32 is no excep- width and a powerful seven-channel little processor core stuck in the cor- tion, using a 64-bit wide flash bus in DMA controller that offloads the ner, dwarfed by surrounding memory conjunction with two 64-bit prefetch processor of I/O grunt work. and I/O silicon. The fact is, while the buffers to hide the flash latency. Even Another way to boost bus band- architecture chosen for the core may though this simple prefetch scheme is width is to demand less of it in the be the sizzle, it’s the implementation relatively unobtrusive, there may be first place. As I went through the of an entire chip that’s the steak. times when you’d prefer to turn it off, specs, I was impressed with the way which the STM32 allows you to do. the STM32 uses “smart” I/O devices FLASH FOR CASH If you really need max MIPS, take that take care of their own dirty laun- Sure architecture has an impact on advantage of the fact that the STM32 dry rather than bugging the processor performance, but so do a lot of other allows execution of code from the on- to do it for them. things starting with bus bandwidth. chip SRAM at full speed. You can use Even the simple stuff such as serial The differences (relatively minor actu- the SRAM as a “programmer directed and parallel I/O is pretty fancy these ally) in the way competing architec- cache,” preloading it with perform- days. Every STM32 I/O line is indi- tures choose to deal with instructions ance-critical routines such as DSP vidually programmable as input (pull- and data don’t matter nearly as much inner loops and interrupt handlers. up and pull-down options) or output as how fast a particular chip can actu- Just remember that a MIPS rating is (push/pull or open collector with out- ally do it. only half the story. You can crank put drive strength options). I/O lines In the blue-collar space these chips through all of the instructions you are also 5-V tolerant and can target, we’re generally talking about non- want, but nothing useful happens source/sink a whopping 25 mA, with cache implementations. That means flash until data makes its way to and from the not unexpected caveat that total (i.e., instruction fetch) bandwidth is a crit- the pins. As a practical matter, the on- chip power is limited to 150 mA. A ical limiting factor. The STM32 comes in chip I/O devices are just as important measure of port-remapping capability two flavors, “Access” and “Performance,” as the processor core itself in achiev- enables juggling peripheral pin with a major difference being that the for- ing peak system performance. assignments to best fit a particular mer runs up to 36 MHz and the latter to application. 72 MHz (see Table 1). Just keep in mind I/O U As I’ve noted before, the traditional that higher clock rates require 0, 1, or 2 I/O throughput starts with the num- RISC load/store architecture is prob- flash wait states for clock rates up to ber and performance of the on-chip I/O lematic for “atomic” bit operations 24, 48, and 72 MHz, respectively. devices themselves. The STM32 has a because an interrupt might occur If something isn’t done, wait states lot of fast I/O, but that can actually be between the load and the store. The

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 81 82.qxp 2/26/2008 3:38 PM Page 1 Sensors08 CircuitCellarAd.qxd 2/11/08 12:07 PM Page 1

June 9 - 11, 2008 sensors expo Donald E. Stephens Convention Center Rosemont, Illinois & conference www.sensorsexpo.com

Advances in Measurement, Monitoring, Detection and Control

New Approaches • New Technologies • New Applications • New Ideas

Featuring Nine Research-Based Technical Tracks: OPENING KEYNOTE • Novel Approaches to Measurement & Detection • Wireless Sensing • Systems & Embedded Intelligence • Power Management, Battery Technology & Low-Power Sensing James • Sensor Standards • Emerging Technologies & Applications McLurkin MIT Roboticist, Inventor, Including Three ALL-NEW Tracks Examining: Researcher, Teacher • Transportation Infrastructure & Structural Health Monitoring • Machine Health & Predictive Maintenance “Engineering • “Green” Sensing Technologies & Applications Creativity”: Exercises for And Three Optional Pre-Conference Symposia: • Digital Data Acquisition & Analysis Symposium the Right Brain • Nanotechnology & MEMS/MST/Micromachines Symposium • Energy Harvesting for Powering Sensor Applications Symposium

Register Today & Take Advantage of the Early Bird Rates or Sign-up Now for Your FREE Expo Hall Pass! Register at www.sensorsexpo.com or call 877-232-0132. Please use your source code: 303M

Produced By: Official Publication: Gold Sponsors: Silver Sponsor: Media Sponsor: 2804003-Cantrell.qxp 3/7/2008 10:45 AM Page 83

Forward Jitter Backward Jitter Forward

TI1

TI2

Counter

Up Down Up

Figure 2—Smart timers are needed to enable real-time applications to handle tasks in hardware that would otherwise bog down the processor core. The Encoder mode of the Advanced Control Timer (ACT) included in STM32 “Performance” parts is a good example. It automatically monitors the phase relationship of two inputs and keeps track of the cumulative count.

Cortex M3 architecture takes a crack fast), and standards (e.g., SM Bus 2.0). message filters so it can screen mes- at the problem with a “bit-banding” No surprise that the USARTs are fast sage traffic by itself without bothering capability that provides atomic access (up to 4.5 Mbps) and capable (e.g., the processor. to single bits. In addition, the STM32 LIN, IrDA) as well. Note that any or If you want to do real-time, you also incorporates “set/reset” shadow all of these serial I/Os work with the need plenty of timers. General house- registers for I/O, a solution that has DMAC, taking advantage of its intelli- keeping is handled with an RTC, a the advantage of being able to deal gence (e.g., 8-, 16-, and 32-bit bus free-running “SysTick” counter, and with multiple bits at a time. matching, circular buffer manager), two separate watchdog timers, while In safety-critical applications (e.g., which leaves the processor free for three 16-bit units with input capture, transportation, medical, and industri- more important tasks. output compare, and PWM do the al), a single lowly I/O line can have The “Performance” parts include heavy lifting. “Performance” parts go life and death riding on its shoulders. USB 2.0 (full-speed, 12.0 Mbps) and even further by throwing in an The STM32 has a unique capability to CAN interfaces. This seems like a “Advanced Control Timer” that has “lock” the configuration of an I/O line rather unlikely pairing and indeed the even more bells and whistles (see against unintended reprogramming to datasheet reveals that you can really Figure 2). help keep a software crash from lead- only use one function at a time (they Analog capability is another differ- ing to a real one. share the use of a 512-byte buffer). ence between the two STM32 lines. Moving on to serial I/O, every Once again, you’ll find that these The “Access” parts include one con- STM32 includes a SPI port, an I2C interfaces have the “smart” features verter while the “Performance” line port, and two USARTs while the larg- that make life easier for the processor has two converters with the simulta- er parts add an extra one of each. and programmer. For instance, the neous sampling capability required for That’s a total of up to seven fast and CAN controller has programmable many applications (e.g., motor control full-featured serial ports, quite impres- sive for an entry-level part.

The SPI ports run at up to 18 MHz 1st Tr ig as master or slave in half- or full- duplex mode. Besides the usual options (clock rate, mode, 8- to 16-bit ADC1 reg CH0 CH1 CH2 CH2 CH3CH3 CH4 frame), there’s hardware that takes ADC1 inj CH0 care of the CRC for flash cards (e.g., SD Card). Likewise, the I2C port han- dles different modes (e.g., Slave, Figure 3—Automatic scanning of a group of analog inputs is a common feature in modern ADCs. The STM32 Multi-Master), speeds (standard and takes the concept a step further with the ability to interrupt one group scan by “injecting” another.

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 83 2804003-Cantrell.qxp 3/7/2008 10:45 AM Page 84

and power factor correction). While DMAC can work together to handle complicate the design or otherwise the basic converter specs (12 bits, 1 µs, high-speed timing critical tasks in compromise the application. up to 16 channels) are competitive, it’s hardware. Purists will argue that no Traditional RISCs, reflecting their the sophisticated CPU cycle-savers MCU can match a DSP or specialized “computer” (versus “controller”) that set this ADC apart from most. chip for applications like motor con- background, can be pretty lame when Many ADCs include a “scan” capa- trol, but I bet the STM32 might sur- it comes to interrupts, but not so for bility to automatically convert a prise them. the STM32. In addition to the Cortex sequence of channels. The STM32 M3 architectural improvements (e.g., takes it to the next level by adding a REALITY SHOW built-in vectored interrupt controller second scan group that can be “inject- There is no doubt that the processor and “tail-chaining” to minimize stack ed” into (i.e., interrupt) the regular and peripherals are the attention-get- operations), the STM32 includes dedi- scan (see Figure 3). An “analog watch- ters for any MCU. But there are also a cated hardware to configure up to 19 dog” capability provides independent lot of nuts and bolts required to lash I/O lines as external interrupt/event threshold comparison for any/all pins together a real-world design. Some par- inputs. in either the regular or injected scan ticular little piece of “glue logic” may While it sometimes seems that all groups, or both. seem insignificant, until you need it of the focus is on MIPS and mega- Above and beyond their individual and it’s not there. Then all of a sudden hertz, there is also the small matter of capabilities, the timers, ADC(s), and it’s a big deal with the potential to power consumption. “Small matter”

8-MHz USB 48 MHz USBCLK HSI RC HSI Prescaler to USB interface /1, 1.5 /2 72 MHz max HCLK to AHB bus, core Clock enable (3 bits) memory, and DMA

/8 to Cortex system timer SW PLLSRC FCLK Cortex PLLMUL free running clock HSI ..., x16 ... AHB SYSCLK APB1 36 MHz max x2, x3, x4 Prescaler Prescaler PCLK1 PLL PLLCLK 72 MHz /1, 2...572 /1, 2, 4, 8, 16 to APB1 Max peripherals HSE Peripheral clock enable (13 bits)

to TIM2, 3, CSS TIM2, 3, 4 and 4 x1, 2, Multiplier TIMXCLK Peripheral clock enable (3 bits) PLLXTPRE

OSC_OUT 4–16 MHz APB2 72 MHz max HSE OSC Prescaler PCLK2 OSC_IN /1, 2, 4, 6, 16 to APB2 peripherals /2 Peripheral clock enable (11 bits)

/128 TIM1 Timer to TIM1 OCS32_IN LSE to RTC x1, 2 Multiplier TIM1CLK LSE OSC RTCCLK 32.768 kHz Peripheral clock OSC32_OUT enable (1 bit)

ADC to ADC RTCSEL[1:0] Prescaler /2, 4, 6, 8 ADCCLK LSI To independent watchdog (IWDG) LSI RC 40 kHz IWDGCLK

/2 PLLCLK Main clock output HSI MCO Legend: HSE HSE = High-speed external clock signal SYSCLK HSI = High-speed internal clock signal LSI = Low-speed internal clock signal MCO LSE = Low-speed external clock signal

Figure 4—Some may consider it mere “glue logic,” but the clock generator on a modern MCU such as the STM32 plays a critical role in achieving system price, power, and performance goals.

84 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 2804003-Cantrell.qxp 3/7/2008 10:45 AM Page 85

pin) is detected. And while better than nothing, a sin- More evidence gle watchdog timer always raises the that the STM32 question of who will watch the takes the nuts and watchers? Taking advantage of the bolts seriously is the additional clock, the STM32 inte- clock generator (see grates two independent watchdog Figure 4). Make that timers for a level of protection only clock(s) generator(s). true redundancy provides. This chip’s got so Together the power and clock sys- many clocking tems give you a lot of power-saving options I thought I options. Embellishments to a trio of was in Switzerland. low-power modes (Sleep, Stop, and The primary 8-MHz Standby) include the ability to tweak oscillator (factory various dials on the clock generator trimmed for accura- and the voltage regulator (run, power cy) drives a PLL to down, off). The lowest power mode generate the myriad (Standby) takes advantage of the sepa- of high-frequency rate backup supply domain to shut clocks required for primary power off yet retain the abili- the processor and ty to wake up from an RTC alarm or peripherals. the independent watchdog. Photo 1—Drape this gadget around your neck and you’ll be the life of the Alternatively, you And just how low power are we party! A good MCU needs a good starter kit and those provided by the likes of Raisonance (the STM32 primer shown here), Keil, IAR Systems, and Hitex can provide an exter- talking? According to the datasheet, Development Tools make it easy and inexpensive to check out the new nal 4- to 16-MHz even running full bore at 72 MHz STM32 MCU. clock, in which case with all peripherals enabled, you’re the internal clock looking at just 0.5 mA per 1 MHz typ- as in your design had better consume serves as a monitor and backup should ical (i.e., 36 mA at 72 MHz at room a small amount of power, or else. the external clock fail. temperature). And here’s another rea- After all, a main claim to fame for all There’s a separate low-speed (40-kHz) son to put your most frequently exe- of the new-age 32-bit MCUs is that clock that’s powered from the VBAT cuted routines in RAM: not only is it they can go head-to-head with 8-bit backup power supply. It’s not accurate fast (zero wait states), but running parts and that means battery-powered enough for real time, but it does fill code from RAM also consumes less applications. the key role of providing an on-chip than half the power (e.g., 14.4 mA at Powering the chip couldn’t be sim- wakeup source when the MCU core 72 MHz) of running code from flash pler. Just hook it up to anything from 2 (i.e., 1.8-V domain) is powered down. memory. Another power-saving trick to 3.6 V and it springs to life. An on- chip regulator supplies 1.8 V internally while power-up/power-fail RESET and Flash memory 128 KB over- and under-voltage interrupts are 0x0801FFF built-in. The ADC features a precise on-chip 0x08015000 1.2-V reference voltage, but you can Application 3 4 KB connect an external reference if you 0x08014000

wish (noting that using the ADC boosts Application 1 8 KB

the minimum required chip voltage 0x08012000

from 2 to 2.4 V). Finally, just hang a 1.8- here 96debug KB RAM 20 KB to 3.6-V battery on the VBAT supply 0x0800A000 0x20004FFF Get full version to upgrade to to Getupgrade full version Application 2 4 KB OS 4 KB pins if you want to take advantage of 0x08009000 the RTC and related backup features. 0x20004000 0x08008000 Switchover between the primary and Debugable application Application data battery backup supplies is handled auto- 8 KB 16 KB 0x08006000 matically on-chip. OS

24 KB debug 32 KB 32 debug Besides the RTC, VBAT also pro- version Free vides power for 10 16-bit “backup” 0x08000000 0x20000000 registers (i.e., RAM). A unique protec- tion option automatically clears the Figure 5—The STM32 primer may look like a toy, but under the hood is a “Circle OS” that supports application contents of these registers if “tamper- development and experimentation. There’s plenty of room in the STM32 on-chip flash and SRAM for both “Circle ing” (i.e., unexpected activity on a OS” and application code and data.

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 85 2804003-Cantrell.qxp 3/7/2008 10:45 AM Page 86

I got a chance to play around with pretty face. Behind the looks of a the cute little “STM32 Primer” gadget flashy new core is a down-to-earth courtesy of STMicroelectronics and chip that’s sophisticated, but not frag- Raisonance. Although the evaluation ile or high maintenance. version of the Raisonance RIDE7 tool- And this is a supermodel that’s chain (GNU-based) that comes with the accessible to mere mortals. Judging primer is limited to debugging 32 KB (a from all of the promotion commotion full-function upgrade is available from and third-party support, it is clear that Raisonance) at just $32, the kit is still STMicroelectronics is serious about quite a bargain. going after the mass-MCU market, Photo 2—Small is beautiful, except when it comes to A close look reveals two MCUs (see not just a few big-ticket focus cus- hand-wiring a tiny surface-mount chip. The STM32- Photo 1). At the top is the STM32 of tomers. Wise move, because staying H103 header board from Olimex makes it quick and interest, a 128-KB flash unit. On the power in the MCU business is as easy to prototype your own STM32-based design. left is an ARM7 MCU acting as a much a matter of seats (i.e., number debug interface between your PC USB of designs) as sockets. is to take advantage of the fact that port and the STM32 software/JTAG Is the STM32 the “best” 32-bit every peripheral has its own power debug pins. A benefit of the two-chip MCU? Who knows, and who cares? switch (i.e., clock gate) and the approach is that it leaves the STM32 What matters is that it is a great datasheet helpfully itemizes the power USB port free for application use. MCU that leverages an entire ecosys- consumption of each. The savings can In the upper left is a part that raises tem of chips, tools, and third-party add up considering the higher-power the primer’s fun quotient, a three-axis support. Bottom line for designers peripherals (e.g., timers and ADCs) low-g MEMS accelerometer enabling a shopping 32-bit MCUs? If you’ve got a consume a milliamp or two each. “tilt-o-whirl” user interface. Scrolling short list of favorites, it just got a lit- Beyond active power consumption, and menu selection is accomplished tle longer. I low-power modes are where batteries by tilting the gadget. The display live and die. The STM32 Sleep mode automatically switches between Tom Cantrell has been working on cuts power consumption roughly in Portrait and Landscape mode depend- chip, board, and systems design and half yet remains functional enough ing on orientation. marketing for several years. You may (i.e., many fast wakeup options) to use Taking advantage of the accelerome- reach him by e-mail at tom.cantrell@ routinely. Taking a big step down the ter, the Primer comes preprogrammed circuitcellar.com. ladder, Stop mode specs at just 15 to with some simple maze and breakout 25 µA or so depending on the particu- games. But it’s more than a toy. Indeed, lars (e.g., voltage regulator on/off, tem- under the hood is a “Circle OS” that SOURCES perature). That’s not bad considering includes a simple task scheduler and a Cortex M3 core the on-chip RAM is kept alive and it’s variety of I/O libraries for both the ARM relatively easy to wake up (e.g., via STM32 on-chip peripherals and the www.arm.com pin, interrupt, USB). If you don’t need primer add-ons (MEMS accelerometer, STM32 Development tools to preserve the contents of RAM, graphics LCD, button, buzzer, and Hitex Development Tools Standby mode slashes power to little more) (see Figure 5). You can find the www.hitex.com more than 1 µA, yet still gives you source code for Circle OS and example some tools to work with besides just applications at www.stm32circle.com. STM32 Development tools RESET (e.g., RTC wakeup alarm and The primer documentation walked me IAR Systems the backup registers). through the process of creating my own www.iar.com “Hello World” application in a matter STM32 Development tools ONE LAST THING of minutes, and everything worked Keil I think you can see that the STM32 without a hitch. www.keil.com is firing on all cylinders (i.e., good Rolling your own prototype is another core, good peripherals, good integra- option, but not always an easy one with STM32 Evaluation boards tion, and good energy efficiency). fine-pitch surface-mount parts. Olimex Olimex Guess what? A good chip is useless provides a handy solution with a “head- www.olimex.com unless it’s got some good tools to go er board” that includes the STM32 STM32 Development tools with it. Fortunately, the STM32 gets MCU, a USB connector, and easy access Raisonance to ride on the ARM bandwagon, which via standard headers to the chip’s I/O www.raisonance.com is standing room only with third-party lines (see Photo 2). tool suppliers including ARM and Keil STM32 Cortex M3-based 32-bit flash (owned by ARM), Raisonance, IAR MOST SMARTEST MCU microcontroller Systems, and Hitex Development In the reality show, that’s the MCU STMicroelectronics Tools with no doubt more to come. business: the STM32 is more than a www.st.com

86 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com ib-213.qxp 3/7/2008 11:19 AM Page 87 IDEA BOX THE DIRECTORY OF PRODUCTS AND SERVICES

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

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



 Á ® UUSSBB phyCORE OEMable Single Board Computers Add USB to your next XScale: PXA270, PXA255 project—it’s easier than you AARM:RM: LPC3180 (ARM9); LPC22xx, LPC229x, AT91 (ARM7) might think! PPowerPC:owerPC: MPC5554, MPC5200B, MPC565, MPC555 Â  v USB-FIFO up to 8 mbps CColdFire:oldFire: MCF5485 x86: Elan SC520     v USB-UART up to 3 mbps C166/XC16x/ST10/8051 CCANAN  Ã ÃÁ v USB/Microcontroller boards BBlackfin:lackfin: BF537 *DEPENDING UPON DESIGN COMPLEXITY Faster-to-Market: Save time by pre-programmed with firmware integrating a PHYTEC Single Board Computer Module into Ä     v 2.4GHz ZigBee™ & 802.15.4 your target circuitry. Make -or - Buy: Why make RAPID PROTOTYPES v RFID Reader/Writer your own when you can buy PHYTEC off-shelf solutions, CUSTOM HARDWARE cost-effective to 1000s units/year? Absolutely NO driver software Integrated Support Services:Let PHYTEC assist you in the design of your MCU FIRMWARE end product: from tools and RTOSes to production. Our hardware is development required! bundled with leading compilers (Keil, IAR, CodeWarrior), RTOSes (WinCE, Linux) and . Immediate Support: Talk to PHYTEC technical staff with every call. No www.dlpdesign.com waiting for answers.    Your OEM solution: With 20 years design, production, and integration experience, PHYTEC is your OEM partner.       ÿ PHYTEC America, LLC I 203 Parfitt Way SW, G100 I Bainbridge Island, WA 98110 USA ÁÂÃÄÃ www.phytec.com I (800) 278-9913 I www.phycore.com

www.teamfdi.com VISA/MC/Amex

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 87

³)',´LQORZHUO IWF ULV³+DQGHO*RWKL %7 RQW %ROG WDOLFV  ib-213.qxp 3/7/2008 11:19 AM Page 88

CC-ad-March-mx.pdf 3/6/08 2:31:36 PM

88 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com ib-213.qxp 3/7/2008 11:19 AM Page 89

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 89 ib-213.qxp 3/7/2008 11:19 AM Page 90

Freescale 9S12C m i crocontroller DIP modules

M68MOD912C32

24-pin

32-pin

40-pin

www.nanocore12.com Toll-free: 1-877-963-8996

90 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com ib-213.qxp 3/7/2008 11:19 AM Page 91

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

www.schmartboard.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 91 ib-213.qxp 3/7/2008 11:19 AM Page 92

Digital Storage Oscilloscopes Mixed Signal Oscilloscopes Arbitrary Waveform Generators Digital Multimeter Virtual Instruments

Electronics Kits and Adapters

Freeduino (ArduinoTM Compatible) kits and shields Special breadboard and protoboard Adapters:

SOIC to DIP SOT-23 to DIP Lantronix XPORT XBee Module

DIN connectors RS232 to TTL kit JTAG ICE clone kit www.nkcelectronics.com stores.ebay.com/NKCElectronics Official Rigol Distributor Global Shipping

® ARM® E t n

e 8051

R ® m

p COLDFIRE o l

A Three quality tool suites e

v *

e G C/C++ D

W G Code Wizards d

e G Debugging d S d

e G Simulation S b G Support m

E * Embedded C++ for ARM and ColdFire only r O o f

Advanced software s R l tools since 1984 o

o www.crossware.com T C 360-812-2397

92 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com crossword2.qxp 3/7/2008 11:23 AM Page 93

CROSSWORD

1 23

4 56

78

9 10 11

12

13

14

15

16

17

18

Across Down 1. A cool, dark spot on the sun that has a strong magnetic 2. Parameterized cell field 3. Software that adds few features to a system and 3. The color of “magic smoke” takes up a lot of memory 4. Hypothetical product 6. A program that translates data into different computer 5. Memory or RAM languages 7. A path of clicks 8. A line that connects points with the same barometric 13. A hybrid robotic system pressure 14. Multiplexer 9. Open-source OS developed in Amsterdam 16. The American engineer (1890–1954) who invented FM 10. Right-angle wiring radio 11. L337 17. Think: absolute thermometric scale 12. Manages and updates a web site 18. System request 15. To downsize source code without disrupting the program

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

www.circuitcellar.com CIRCUIT CELLAR® Issue 213 April 2008 93 94-advertiser's index.qxp 3/13/2008 10:08 AM Page 94

INDEX OF ADVERTISERS The Index of Advertisers with links to their web sites is located at www.circuitcellar.com under the current issue.

Page Page Page Page 91 AAG Electronica, LLC 26 ezPCB 56 Measurement Computing Corp. 55, 63 Renesas Technology

24 AP Circuits 87 FDI-Future Designs, Inc. 90, 91 Micro Digital, Inc. 2, 3 Saelig Co.

88 ARC-USA, Inc. 90 FlexiPanel Ltd. 92 Micro Digital, Inc. 24 Saelig Co.

69 ASIX 90 FlyPCB China Co., Ltd. 5 Microchip 91 Schmartboard

18, 19 All American Semiconductor, Inc. 90 Futurlec 1 Micromint USA, LLC 89 Scidyne

92 All Electronics Corp. 51 Grid Connect 92 microEngineering Labs, Inc. 16 Sealevel Systems

88 Apex Embedded Systems 88 Hagstrom Electronics 71 Mouser Electronics 11 SEGGER Microcontroller Systems LLC

7 Atmel 89 HI-TECH Software LLC 88 Mylydia, Inc. 82 Sensors Expo & Conf.

87 BayTech Engineering 49 HobbyLab LLC 92 NKC Electronics 34 Silicon Laboratories, Inc.

95 Bitscope Designs 13 IMAGEcraft C2 NetBurner 91 Systronix

65 CWAV 91 Intec Automation, Inc. 68 Nurve Networks LLC C3 Tech Tools

50 CadSoft Computer, Inc. 27 Intronix Test Instruments, Inc. 58 PCB East 91 Technical Solutions, Inc.

12 Calao Systems 9 Ironwood Electronics 31 PCB-Pool 32, 33 Technologic Systems

74 Comfile Technology, Inc. 64, 91 JKmicrosystems, Inc. 90 PTLogica 90 Technological Arts

92 Crossware Products, Inc. 79 Jameco C4 Parallax, Inc. 89 Tern, Inc.

92 Custom Computer Services, Inc. 68 Jeffrey Kerr, LLC 87 Phytec America LLC 8 Tibbo Technology, Inc.

87 DLP Design 17 Keil Software 72 Pico Technology Ltd USA 89 Tin Can Tools, LLC

69 Decade Engineering 57 LPFK Laser & Electronics 92 Pioneer Hill Software 87 Trace Systems, Inc.

89 Designnotes 68 Lakeview Research 10 Pololu Corp. 90 Triangle Research Int’l, Inc.

45 EMAC, Inc. 88 Lawicel AB 91 Pulsar, Inc. 45 WCSC (Willies Computer Software Co.)

66 ESC-West 9 Lemos International 21 R4 42 Wiznet

89 Earth Computer Technologies 64 Linx Technologies 12, 39 Rabbit, A Digi International Brand 90 Zanthic Technologies, Inc.

26 Elprotronic 89 MCC (Micro Computer Control) 88 Rabbit, A Digi International Brand

48 ExpressPCB 25 Matrix Orbital 29, 89 Reach Technology, Inc.

Preview of May Issue 214 ATTENTION ADVERTISERS Theme: Measurement and Sensors June Issue 215 Parts Depth Measurement: Build an Ultrasonic Snow Depth Sensor Deadlines Where Analog and Digital Collide: An Easy-to-Use LCR Meter Space Close: Apr. 14 Material Close: Apr. 21 Electronic Seizure-Monitoring System

AIS Transmission Decoding Theme: Ray Tracing Made Simple: A Ray Tracer Implemented on an FPGA Communications MCU-Based Gaming: A Dot-Matrix Game That Targets C Coding Efficiency

Embedded Linux Development (Part 2): Create an Embedded Development Environment Call Shannon Barraclough LESSONS FROM THE TRENCHES Making Changes: A Look Into the C Compiler now to reserve your space! 860.875.2199 FROM THE BENCH Control Circuitry e-mail: [email protected] SILICON UPDATE Designer’s Best Friend

94 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com 63.qxp 12/4/2007 10:30 AM Page 1

PC Oscilloscopes & Analyzers

DSO Test Instrument Software for BitScope Mixed Signal Oscilloscopes

4 Channel BitScope 2 Channel BitScope Pocket Analyzer

Digital Storage Oscilloscope BitScope DSO Software for Windows and Linux Up to 4 analog channels using industry standard  probes or POD connected analog inputs. BitScope DSO is fast and intuitive multi-channel test and measurement software for your PC or notebook. Whether it's a digital scope, spectrum analyzer, mixed signal scope, Mixed Signal Oscilloscope logic analyzer, waveform generator or data recorder, BitScope DSO supports them all. Capture and display up to 4 analog and 8 logic Capture deep buffer one-shots or display waveforms live just like an analog scope.  channels with sophisticated cross-triggers. Comprehensive test instrument integration means you can view the same data in different ways simultaneously at the click of a button. Spectrum Analyzer DSO may even be used stand-alone to share data with colleagues, students or Integrated real-time spectrum analyzer for each customers. Waveforms may be exported as portable image files or live captures replayed  analog channel with concurrent waveform display. on other PCs as if a BitScope was locally connected. BitScope DSO supports all current BitScope models, auto-configures when it connects Logic Analyzer and can manage multiple BitScopes concurrently. No manual setup is normally required. 8 logic, External Trigger and special purpose Data export is available for use with third party software tools and BitScope's networked  inputs to capture digital signals down to 25nS. data acquisition capabilities are fully supported.

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

Networking Flexible network connectivity supporting  multi-scope operation, remote monitoring and data acquisition. Data Export Export data with DSO using portable CSV files or www.bitscope.com  use libraries to build custom BitScope solutions. steve_edit_213.qxp 3/7/2008 11:24 AM Page 96

PRIORITY INTERRUPT

by Steve Ciarcia, Founder and Editorial Director What Makes an Engineer?

A couple of weeks ago, I was having the screened-in lanai at the “cottage” converted to a Florida room. Since this involved considerably more than slapping in a couple of windows from Home Depot, I called in a contractor. On the building permit, I had to certify that I was just replacing the screens with windows and that I wasn’t air conditioning or heating the room. Doing that would have been adding more (taxable) square footage to the house and a simple lanai screen/window swap was considered tax free. One of the ironies of home improvement these days is how much the government really doesn’t trust us. Putting in a glass window on a screened porch became a major project. Even though I was just replacing screens with windows, because everyone else supposedly lies and actually makes it into an added room, the law required that the renovation be constructed like a genuine addition and structurally equivalent to any other supporting wall in the house.The new glass enclosure had to follow current building codes that included adding inside and outside elec- trical outlets and lighting where none had been before. This was considerably more than just rerouting the one existing floodlight, so the contrac- tor sent a couple of electricians to rewire the whole place. The electricians arrived like the chosen ones. Their trucks blocked the whole driveway and their equipment was spread all over the place. The lanai was filled with ladders, extension cords, and tools with no regard for the convenience of the occupants. No one even asked me how or where I wanted switches or outlets. Soon there was just a trench along the side of the foundation, a new conduit pipe sticking out an adjacent wall of the house, and two guys merrily drilling large diameter holes in all of the structural stuff that the contractor had already installed. I came out on the lanai and watched them for a few minutes. I started to wonder about the effect of drilling holes in the support beams and how close these holes could be before it actually affected support calculations. I noticed that they were daisy-chaining all of the outlets and I won- dered about the attenuation between outlets at 120 kHz used for X-10 and the voltage drop from one socket to the next with applied loads. I saw that they had found the CAT-5 cable for one of my web cams and wondered, despite its twisted-pair conductors, how much induced EMF there would be when these guys stuffed all of the AC and DC wires into the same wiring tract. Finally, when I noticed one electrician using the space between my rain gutter downspout and the house as the fulcrum of a 20′ piece of conduit pipe he was trying to bend, I did a quick calculation on the length of the moment arm and force about to rip off my gutter and said, “Should I be concerned about only using one circuit for these three plugs?” He instantly realized I was watching and stopped using my gutter pipe as a bending tool. Obviously disturbed at my questioning whether he was following code (he was), he replied, “The AC power has a lot of juice and it will take care of anything you need to plug in. In fact, please step back, Sir. One hundred twenty volts is a lot of power and I wouldn’t want any electrical arcs hurting you while these boxes are open.” Talk about gratuitous putdowns. I stared at him and said, “By the way, I’m an electrical engineer. Given the dry air and drought conditions, I suspect you’d have to put a bloody screwdriver across the wires to get a spark today. I guess the ‘juice’ just isn’t what it used to be.” He scowled and went back to work. As he turned, I could swear I heard him utter, “Great, all I need is an engineer.” I went back in the house and tried to forget the surly man who might be a great electrician but probably had no concept of my other observa- tions. For that matter, even though I am an engineer, I wasn’t sure I could still calculate all of the answers anymore.There was a time when I could calculate the induced EMF of twisted and non-twisted wires, but I think my current knowledge got rusty after figuring the voltage drops along the daisy chain. Heaven forbid we throw in the capacitive effects of the loads and do it for 120 kHz. Certainly, management tasks have dulled the sharpness of my math skills, so I determined to refresh some of that lost expertise by going back to school—not literally, but virtually. A quick search on “college video lectures” revealed hundreds of free online college courses, including engi- neering classes. For the last couple of weeks, I’ve been watching electrical engineering and physics classes at MIT (http://ocw.mit.edu/) and other colleges. The good news is that I’m actually remembering a lot. The bad news is that I’m also remembering how much I hated some of those equations the first time around. So, just how much does a guy have to know to still call himself an engineer? My conclusion is that engineering is qualitative, not quantitative. Engineering is a mindset and training to know there are losses in electrical conductors, stresses in support members, and electrically induced energy in magnetically coupled conductors. Until I finish all of these courses again, however, knowing exactly how to calculate it is an exercise for those who remember all of the equations.

[email protected]

96 Issue 213 April 2008 CIRCUIT CELLAR® www.circuitcellar.com C3.qxp 3/30/2007 1:38 PM Page 1 C4.qxp 3/3/2008 11:22 AM Page 1