<<

Cover.qxp 6/9/2008 8:34 AM Page 1

Photovoltaic Power Generation p. 22 • Coil Launcher Project p. 38 • The “32-Bit Gate Crasher” 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 #216 July 2008 INTERNET & CONNECTIVITY A Design For Delivering Targeted Web Site Content Do-It-Yourself Internet-Based Timekeeping Create A Modbus Slave For Data Intercommunication Decode & Transmit Magnetic Card Data Sound Effects Processing Made Easy Advanced Analog Design Techniques Theory Explained

07>

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, debugger, 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 4/10/2008 12:50 PM Page 1 35.?AD?%$PDF  !- 56-57.qxp 7/2/2007 10:52 AM Page 1 56-57.qxp 7/2/2007 10:52 AM Page 2 Task_Masthead_216.qxp 6/9/2008 8:51 AM Page 4

TASK MANAGER

Energy Costs Drive Design Ingenuity FOUNDER/EDITORIAL DIRECTOR CHIEF FINANCIAL OFFICER Steve Ciarcia Jeannette Ciarcia ast July, I told you about my earliest experiences with the Internet. Since MANAGING EDITOR MEDIA CONSULTANT L C. J. Abate Dan Rodrigues the mid-1990s, my daily ’Net time has increased dramatically. Like most of you, I now use it for researching engineering topics, reading the news, fol- WEST COAST EDITOR CUSTOMER SERVICE Tom Cantrell Debbie Lavoie lowing stocks, interacting with friends and coworkers, ordering gifts, securing reservations, scheduling travel, and more. Hmm. I wonder what new ’Net- CONTRIBUTING EDITORS CONTROLLER Jeff Bachiochi Jeff Yanco related features I’ll be using in July 2009. Ingo Cyliax If gas prices continue to rise, I’ll probably be using the ’Net even more in an Robert Lacoste ART DIRECTOR KC Prescott effort to keep my monthly drive time to a minimum. I’ll increase my use of online George Martin Ed Nisley financial services rather than truck to the local bank branch (3.1 miles round GRAPHIC DESIGNERS Grace Chen trip) or investment consultant (21.74 miles round trip). I’ll watch movies on the NEW PRODUCTS EDITOR John Gorsky Carey Penney ’Net rather than drive to the nearest theater (7.28 miles round trip). I’ll buy more STAFF ENGINEER clothes online than offline at the local mall (14.24 miles round trip). I’ll order PROJECT EDITORS Gary Bodley John Gorsky wine from online distributors at bulk discount rates rather than hit the local Ken Davidson liquor shop (8.36 miles round trip). There are countless other examples. David Tweed Hopefully, by increasing my ’Net time and decreasing my drive time, I will ASSOCIATE EDITOR reduce my monthly cost of living, if only by a bit. At least the psychological Jesse Smolin effect of cost cutting should be more positive than negative. (Fingers crossed.) Trading in a four-wheeled shopping cart for a virtual shopping cart is only ADVERTISING one example of how average consumers are dealing with the price increas- 860.875.2199 • Fax: 860.871.0411 • www.circuitcellar.com/advertise es associated with rising energy costs. In the U.S., “hybrid” and solar tech- PUBLISHER nologies are all the rage (or at least conversations about them are). This Sean Donnelly Direct: 860.872.3064, Cell: 860.930.4326, E-mail: [email protected] augurs well for engineers, particularly the embedded designers and pro- grammers who read this magazine. In the coming months and years, you will ADVERTISING REPRESENTATIVE Shannon Barraclough use your ingenuity and design/programming prowess to develop the systems Direct: 860.872.3064, E-mail: [email protected] and programs that will advance these technologies—and you will be well ADVERTISING COORDINATOR paid for your services. Whether you design ’Net-connected systems that Valerie Luster enable remote access, build energy-efficient solar systems that cut monthly E-mail: [email protected] utility costs, or create advanced embedded systems for next-generation elec- tric vehicles, you will be improving the lives of countless consumers while Cover photography by Chris Rakoczy—Rakoczy Photography slowing the depletion of important natural resources. In this issue, we pres- www.rakoczyphoto.com ent articles about designs that can serve as starting points for such projects. PRINTED IN THE UNITED STATES If you’re interested ’Net-related technologies, turn to page 12, where DJ CONTACTS Delorie begins describing how he planned and designed an Internet-con- SUBSCRIPTIONS Information: www.circuitcellar.com/subscribe, E-mail: [email protected] nected alarm clock. The PIC-based design features automatic time setting, Subscribe: 800.269.6301, www.circuitcellar.com/subscribe, Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 streaming MP3 music, and remote management. Another handy Internet- Address Changes/Problems: E-mail: [email protected] connected design is Fernando Jordan’s SwissJazz system (p. 30). He uses GENERAL INFORMATION 860.875.2199, Fax: 860.871.0411, E-mail: [email protected] it to pull song title/artist information from an Internet radio station and display Editorial Office: Editor, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] it without the use of a PC. You can build a similar system to gather and dis- New Products: New Products, Circuit Cellar, 4 Park St., Vernon, CT 06066, E-mail: [email protected] AUTHORIZED REPRINTS INFORMATION play the content of your choice. Although these two designs don’t directly 860.875.2199, E-mail: [email protected] AUTHORS reduce energy consumption, you can apply the basic design techniques to Authors’ e-mail addresses (when available) are included at the end of each article. other projects.

Feature writers aren’t the only members of the Circuit Cellar community CIRCUIT CELLAR®, THE MAGAZINE FOR COMPUTER APPLICATIONS (ISSN 1528-0608) is published monthly by Circuit Cellar focused on tackling the problem of rising energy costs. Two of our columnists Incorporated, 4 Park Street, Vernon, CT 06066. Periodical rates paid at Vernon, CT and additional offices. One-year (12 issues) subscription rate USA and possessions $23.95, Canada/Mexico $34.95, all other countries $49.95.Two-year (24 issues) sub- have stepped up to the challenge. In the first part of a series titled “Living And 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 Working Off The Grid,” George Martin describes how he designed and and subscription-related questions to Circuit Cellar Subscriptions, P.O. Box 5650, Hanover, NH 03755-5650 or call installed a photovoltaic power-generating system at his New Mexico-based 800.269.6301. hideaway (p. 22). And finally, on page 74, Jeff Bachiochi examines electric Postmaster: Send address changes to Circuit Cellar, Circulation Dept., P.O. Box 5650, Hanover, NH 03755-5650. Circuit Cellar® makes no warranties and assumes no responsibility or liability of any kind for errors in these programs or schematics or for the motor technology. He covers electric motor theory, construction, and usage. consequences of any such errors. Furthermore, because of possible variation in the quality and condition of materials and workmanship of read- er-assembled projects, Circuit Cellar® disclaims any responsibility for the safe and proper function of reader-assembled projects based upon or from plans, descriptions, or information published by Circuit Cellar®. The information provided by Circuit Cellar® is for educational purposes. Circuit Cellar® makes no claims or warrants that readers have a right to [email protected] 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. We thank The National Institute of Standards and Technology for allowing us to use the Entire contents copyright © 2008 by Circuit Cellar, Incorporated. All rights reserved. Circuit Cellar is a registered trademark of Circuit Cellar, Inc. screenshot on the cover of this issue. For info about the NIST, visit www.nist.gov. Reproduction of this publication in whole or in part without written consent from Circuit Cellar Inc. is prohibited.

4 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 5.qxp 6/5/2008 12:03 PM Page 1

USB Mixed Signal Oscilloscope

Inventing the future requires a lot of test gear... Analog + Digital ...or a BitScope Digital Storage Oscilloscope Dual Channel Digital Scope with industry  standard probes or POD connected analog inputs. Fully opto-isolated. Mixed Signal Oscilloscope Capture and display analog and logic signals  together with sophisticated cross-triggers for precise analog/logic timing. Multi-Band Spectrum Analyzer Display analog waveforms and their spectra  simultaneously. Base-band or RF displays with variable bandwidth control. Multi-Channel Logic Analyzer Eight logic/trigger channels with event capture  to 25nS. BS100U Mixed Signal Storage Scope & Analyzer DSP Waveform Generator Innovations in modern electronics engineering are leading the new wave of Optional flash programmable DSP based function inventions that promise clean and energy efficient technologies that will  generator. Operates concurrently with waveform change the way we live. and logic capture. It's a sophisticated world mixing digital logic, complex analog signals and Mixed Signal Data Recorder high speed events. To make sense of it all you need to see exactly what's Record to disk anything BitScope can capture. going on in real-time.  Supports on-screen waveform replay and export. BS100U combines analog and digital capture and analysis in one cost User Programmable Tools and Drivers effective test and measurement package to give you the tools you need to Use supplied drivers and interfaces to build navigate this exciting new frontier.  custom test and measurement and data acquisition solutions.

Standard 1M/20pF BNC inputs Smart POD Connector Opto-isolated USB 2.0 12VDC with low power modes

BitScope DSO Software for Windows and Linux BS100U includes BitScope DSO the fast and intuitive multichannel test and measurement software for your PC or notebook. Capture deep buffer one-shots, display waveforms and spectra real-time or capture mixed signal data to disk. Comprehensive integration means you can view analog and logic signals in many different ways all at the click of a button. The software may also be used stand-alone to share data with colleagues, students or customers. Waveforms may be exported as portable image files or live captures replayed on another PC as if a BS100U was locally connected.

www.bitscope.com 216_TOC.qxp 6/9/2008 8:52 AM Page 6

July 2008: Internet & Connectivity FEATURES

12 ’Net-Enabled Alarm Clock 38 Launch Control DJ Delorie Build A Coil Gun Controller And Launcher Second Place Microchip 2007 Design Contest Andrew Sterian 30 Internet Information Retrieval 46 Card Connection Target And Display Web Site Content Magnetic Card Data Decoding And Transmission Fernando Jordan Carlo Tauraso 54 Create A Modbus Slave Aubrey Kagan 62 PSoC Design Techniques (Part 1) Build An Eight-Channel Mixer Chris Paiano 69 Sound Effects Processing Robert Papp

’Net Time (p. 12)

Grab & Display Web Site Content (p. 30) Coil Gun Control (p. 38) Project “Card Reader USB” (p. 46)

COLUMNS 22 INTELLIGENT ENERGY SOLUTIONS — LESSONS FROM THE TRENCHES Living And Working Off The Grid Part 1: Planning And Design George Martin 74 FROM THE BENCH Electric Motor Technology Theory, Construction, And Requirements Jeff Bachiochi 80 SILICON UPDATE Go Grid Free (p. 22) MIPS For The Masses Tom Cantrell DEPARTMENTS

4 TASK MANAGER 93 CROSSWORD Energy Costs Drive Design Ingenuity 94 INDEX OF ADVERTISERS C. J. Abate August Preview 8 NEW PRODUCT NEWS 96 PRIORITY INTERRUPT edited by John Gorsky A Real Rube Goldberg Solution 10 TEST YOUR EQ Steve Ciarcia

6 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 7.qxp 12/10/2007 12:18 PM Page 1 npn216.qxp 6/9/2008 8:54 AM Page 8

Edited by John Gorsky Visit www.circuitcellar.com/npn NEW PRODUCT NEWS for more New Product News. STELLARIS MICROCONTROLLERS OFFER USB ON-THE-GO AND HOST CAPABILITY Thirty new Stellaris family members, including the first with USB On-the-Go (OTG) and Host capability in the ARM Cortex-M3 architecture, are now available. Each of the 30 new devices ships with the Stellaris Peripheral Driver Library and Bootloader conveniently preprogrammed in ROM, and each integrates the ARM PrimeCell 32-channel configurable µDMA controller, which was designed and specifically optimized by ARM for use with the Cortex-M3 processor. The group includes six members of the Stellaris LM3S3000 USB series and 14 members of the Stellaris LM3S5000 CAN+USB series. Together with large on-chip memories, enhanced power management, and expansive I/O and control capabilities, the new Stellaris family members are optimized for industrial applications requiring reliable connectivity. USB improves industrial connectivity by providing the advantages of hot swapping capability and power over a fast and standardized serial interface. With its USB Host and OTG support, the new MCUs enable new applications of USB technology such as using flash memory sticks for device configuration and storage logging information. The devices feature a USB controller that can be configured for USB Host mode or USB Device mode in compliance with the USB 2.0 specification for full-speed operation. Several members of the series also allow the USB con- troller to be configured in the new USB On-the-Go-mode, allowing for usage in Host mode or in Device mode depending on the desired configuration in a given system state. The controllers start at a suggested cost of $2.79 (10,000 quantity), along with the LM3S3748 USB Host+Device Evaluation Kit, which costs $109.

Luminary Micro, Inc. www.luminarymicro.com

8 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com npn216.qxp 6/9/2008 8:54 AM Page 9

NEW PRODUCT NEWS PORTABLE 1-g HANDHELD SHAKER FOR SENSOR TESTING The 699A02 is a portable, lightweight, battery-powered, handheld shaker designed to conveniently verify accelerometer and vibration system perform- ance, as well as confirm the operation of interconnecting cables, switching devices, and monitoring systems. The unit operates at 159.2 Hz and delivers a controlled, 1-g RMS or 1-g peak acceleration to test accelerometers and vibration sensors weighing up to 250 g. The 699A02 is ideal for field troubleshooting, predictive maintenance, and condition-based monitoring systems. It can be used to verify sensor calibration and performance right at the machine, including permanently mounted accelerometers. Additional features of the 699A02 include automatic shut-off to preserve battery life, an external power jack for AC compatibility and extended operation, mechanical stops for over- load protection, and the capability to perform up to 1,600 operating cycles in the field. The 699A02 is a stock product available for expe- dited delivery and comes standard with a durable carrying pouch with a belt loop. The unit also meets NIST traceability require- ments. The 699A02 costs less than $2,500.

IMI Sensors www.imi-sensors.com

NET+ARM MICROPROCESSORS INCLUDE FIMS The NS9215 and NS9210 are the industry’s first microprocessors to include flexible interface modules (FIMs) that provide different hardware interfaces based on the needs of the product or application. FIMs reduce product design complexity and cost by cutting the number of electronic components in a product. Based on a powerful ARM926EJ-S core capable of operating at speeds up to 150 MHz, the NS9215 and NS9210 also provide enhanced security through an on-chip 256-bit AES accelerator. The accelerator encrypts and decrypts datas- treams up to 10 times faster than a software-only solution. It provides strong data privacy for any customer information stored or transmitted by the proces- sor. Additionally, the family features Digi Dynamic Power Control, a complete set of hardware and software features for product designs that demand low power consumption and advanced power management. The NS9215 also features a 10/100 Ethernet MAC, four high-speed UARTs, SPI, I2C, four PWMs or 10 timers, a 12-bit ADC, a quadrature decoder, up to 108 GPIOs and access to 2 FIMs. FIM support is available now for SD/SDIO, CAN bus, 1-Wire, and additional UARTs. FIM support for USB low-speed devices, par- allel bus, I2S, and Wiegand interfaces is in development. The NS9215 is available in a 265-pin BGA pack- age. The NS9210 is available in a 177-pin BGA ver- sion that offers a smaller footprint with access to a subset of the NS9215 interfaces. The NS9215 costs $11.95 and the NS9210 costs $9.95 in 10,000-piece quantities. Development kits are also available.

Digi International, Inc. www.digi.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 9 eq-216.qxp 6/12/2008 10:36 AM Page 10

Test Your EQ CIRCUIT CELLAR Edited by David Tweed

L1 BG1–BG2: E1 3002 Problem 1—What is the pur-

V1–V5: 1N4007 C5 pose of C1 and L1? 47 n 400 V B R4 R2 C4 V2 V1 1n0 120 VAC 200 K From C1 PTC BG1 630 V Problem 2—What is the purpose screw 47n 2n2 C6 4 T base 250 V C2 of the component marked V4 V3 15 u 1,200 V L2 R1 200 V V5 “PTC”? 330 K 10 T R3 V6 C3 C7 Problem 3—How does the BG2 22n 2n7 4T 100 V 1,200 V oscillator circuit work in the steady state?

A recently-failed compact fluorescent lamp (CFL) offers a Problem 4—How does the oscillator circuit get started great opportunity to exercise one’s reverse-engineering in the first place? skills. A trace of the single-sided PCB found inside reveals the following circuit. Unfortunately, R3 and R4 were Problem 5—Why did R3 and R4 burn up? burned beyond recognition, which presumably had some- thing to do with why the lamp failed. L1 is a small “drum” style inductor, while L2 is a larger unit that looks something like a small audio coupling transformer, except Contributed by David Tweed that it has a ferrite core rather than laminated iron. “B” is a small toroidal transformer with three windings, phased What’s your EQ?—The answers are posted at as shown. V6 is a small blue unit with an www.circuitcellar.com/eq/ STMicroelectronics logo and the markings “DB3.” You may contact the quizmasters at [email protected]

10 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 11.qxp 6/5/2008 11:26 AM Page 1

USB Connectivity for Microcontrollers Embedded Designs D Controllers gtlSignal igital A nalog S EEPROMs erial s. © 2008, Microchip Technology Incorporated. All rights reserved. n line 2nd M

If you need Full-Speed USB 2.0 device, embedded host, dual role and USB Kits accelerate development Direct... icrochip On-The-Go solutions, Microchip Technology has them available today. of USB designs using 8-, 16- or 32-bit MCUs We offer 8-, 16- and 32-bit MCUs with USB connectivity, providing easy starting at only $59.98 migration with a single development environment. This maximizes pin compatibility and seamless code migration from 20 to 100 pins, enabling you to scale your USB design with ease. IC are registered trademarks of Microchip Technology Incorporated in the USA and in other countrie DownloadFREEUSBsoftwareincludingsourcecode: t Host Stack t Thumb Drive Support (Mass Storage t OTG Stack Driver,SCSIInterface,16-bitand32-bit t Device Stack File Management, Application Software) t Class Drivers (HID, Mass Storage and CDC Drivers) he Microchip name and logo, the Microchip logo and P

T Core Flash Program Memory Pins USB Type 8-bit Up to 128 Kbytes 20 - 80 Device 16-bit Up to 256 Kbytes 64 - 100 Device, Embedded Host, Dual Role, OTG 32-bit Up to 512 Kbytes 64 - 100 Device, Embedded Host, Dual Role, OTG

www.microchip.com/usbwww.microchip.com/usb

Microchip USB Ad for Circuit Cellar.indd 1 5/13/2008 12:57:56 PM 2807016_Delorie.qxp 6/10/2008 4:17 PM Page 12

FEATURE ARTICLE by DJ Delorie

SECOND PLACE CONTEST WINNER ’Net-Enabled Alarm Clock Unlike old-school mechanical alarm clocks that you have to set manually, DJ’s Internet-con- nected alarm clock provides three primary features: automatic time setting on power-up, streaming MP3 music, and remote management. The PIC24FJ64-based clock is connected to an ENC28J60 Ethernet chip, an MP3 decoder chip, an organic LED graphical display, and a 24LC512 EEPROM for storage.

My wife is a morning person. She chip has sufficient hardware resources chip with 64 KB of instruction memo- gets up at the crack of dawn and goes to connect to the Microchip ENC28J60 ry and 8 KB of RAM. The 28-pin DIP to bed early. I’m more likely to wake Ethernet chip and an STMicroelectron- package is compatible with bread- at the crack of noon and work late ics STA013 MP3 decoder. It has 64 KB boards and the evaluation board, into the night. What do we have in of EEPROM, a 128 × 64 pixel OLED which enables you to move chips common? Like most people, we both display, seven buttons, volume con- between the various stages of develop- use an alarm clock to make sure we trol, power control, and a photocell. ment without having to reprogram get up when we need to. My old alarm That’s a lot of peripherals for such a them. Every pin is needed, and some clock was, well, old, and needed to be small chip, and I use every resource serve dual purposes. The reconfigurable replaced. So, I recently designed an available to talk to them. pin feature ensures that no pins are alarm clock with features to suit my The PIC24FJ64GA002 is a 28-pin wasted and that signals can be routed high-tech lifestyle (see Photo 1). Most alarm clocks use a radio, beep- er, or CD player to wake you up. My a) b) clock accesses my MP3 collection on the server in my home office via an Ethernet port. The network connec- tion enables me to remotely manage the clock as well. I can easily set alarms and choose music from my office without waking up my wife. The clock also has a built-in GUI so I can manage it locally. Its OLED dis- c) d) play and photocell enable it to adapt to different lighting conditions (from bright sun to pitch black). Now you too can build a cus- tomized alarm clock. In this article, I’ll describe the design process from start to finish.

SYSTEM OVERVIEW I built my clock around a Microchip Photo 1a—This is the finished clock in its wooden case. It’s ready for morning duty. The OLED display is bright Technology PIC24FJ64 processor (see during the day, but dims at night, so it’s always readable. b—Take a look at the back of the clock. The network Figure 1). I chose the DIP package for connection enables me to manage the clock remotely. c—The finished board fits nicely in the enclosure. The OLED display is visible to the left of the circuit board for the six front switches. You can see the orange flex easy prototyping (see Photos 2a and cable going to it. d—This is a view from above the alarm clock. You can see the circuit board that holds the tac- 2b). The Microchip 24LC512 EEPROM tile switches for the snooze bar and one of the two “mini-monitor”-type speakers.

12 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2807016_Delorie.qxp 6/10/2008 4:17 PM Page 13

Figure 1—The core of the clock is a PIC24FJ64 microcontroller, which is connected to everything else in the clock: ADCs (for the switches, photocell, and volume), a SPI for the display, I2C for the EEPROMs, and an in-circuit programming jack that doubles as a serial port. The SPI and I2C signals also connect to the Ethernet and MP3 modules. (A full schematic is posted on the Circuit Cellar FTP site.)

to the closest pin for a clean layout. I chose the PIC24FJ64 for its large busses, one I2C bus, three ADC inputs, For example, the 32-kHz clock circuit amount of RAM. The MP3 decoder one serial port, and seven GPIO pins. is sensitive to switching noise, so the chip has a small buffer, and you can’t The serial port shares pins with the pin next to it is assigned to a signal rely on the TCP stream to provide in-circuit programming jack (with that never changes after the clock data fast enough. Thus, half of the series resistors to protect against starts. Normally, that pin would have PIC24FJ64’s RAM is dedicated to a shorts), and one of the ADCs doubles been part of the high-speed oscillator, buffer for the MP3 stream, leaving 4 KB as a mute control. but I use the internal RC oscillator to for the remaining tasks. The CPU pins Most projects are all about doing free up two more pins. are configured to provide two SPI one thing well. This project is about

a) b)

Photo 2a—The use of DIP packages and adapters for surface-mount parts allows the entire project to be prototyped on a solderless breadboard. The power module was pro- totyped separately on a custom circuit board. b—One of the problems with using surface-mount parts is figuring out how to prototype circuits with them. In this photo, you can see two of my adapters. On the left is a crystal oscillator circuit. On the right is an interface for the OLED cable.

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 13 2807016_Delorie.qxp 6/10/2008 4:17 PM Page 14

one response packet, and can use broadcast UDP.[1] ENC28J60

Photocell SPI1 DISPLAY The display for an alarm clock SPI2 MP3 PIC24FJ64 Display has to work in conditions that most displays never encounter. I2C It has to be visible in bright day- light, but shouldn’t shine too Amplifiers EEPROM Buttons brightly in a dark room. Most alarm clocks have seven-seg- ment LED displays, which can be dimmed as needed. LCDs are either not visible at night or Figure 2—This project seems complicated only because of the require a backlight that appears number of modules that need to talk to each other. This block as a grey rectangle at night. I diagram shows the relationship between the modules and the wanted the advantages of LEDs busses used to connect them. with the flexibility of LCDs, so I turned to OLED technology. The doing many things well enough, with OLED display I chose uses a SPI bus, the PIC24FJ64 controlling everything so any display that uses SPI (OLED, (see Figure 2). LCD, and VFD) can be used without Now let’s examine each module major changes in the schematics. If you connected to the PIC24FJ64 and what want to use a display with a parallel the processor does with it. bus, you can use a PIC with more pins. The OLED display is a matrix of tiny NETWORK LEDs. Each can be set to one of 16 bright- The ENC28J60 Ethernet chip han- ness levels. In addition, the drive cur- dles networking (again in a 28-pin rent can be set to one of three levels. DIP package). The magnetics are con- During the day, the drive current is tained in the RJ-45 jack, leaving only maximized and the pixel values are a 25-MHz crystal oscillator and some used to control the brightness of the discretes to complete the circuit. display, according to the photocell Because the two LEDs are inside the readings. At night, in addition to using cabinet to avoid light pollution, the lowest (non-off) pixel value, the they’re reprogrammed to indicate drive current is reduced to its lowest transmit and receive traffic instead of level, resulting in a dim display, which link and activity. is suitable for night viewing. The PIC24FJ64 talks to the network One catch with the OLED display is chip via a SPI bus running at 4 MHz, that you can’t apply drive power until which is shared with the MP3 chip. the controller chip is running. So, the While the Microchip TCP/IP stack is PIC24FJ64 has one GPIO that controls used, the default parameters (buffer size and timeouts) weren’t aggressive enough to smoothly stream MP3 data. The receive buffer was made much larger (600 bytes) than the transmit buffer (100 bytes). The retry timeout was decreased well below the “stan- dard” value to 5 ms. If a packet is missed, there may not even be a gap in the music. In addition to the MP3 stream, there’s also a DHCP module to config- ure the network stack and an SNTP Figure 3—The resistor network’s high impedance enables the microcontroller to monitor the volume module to retrieve the current time. through its ADC or override it by reconfiguring that pin SNTP is the “simple” form of NTP; it as a logic-low GPIO output. The op-amp provides a requires only one request packet and low-impedance copy of the signal to the amplifiers.

14 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2807016_Delorie.qxp 6/10/2008 4:17 PM Page 15

depends on the room brightness. The other two formats are a 4-bit- per-pixel image and a 1-bit-per-pixel image. The format used depends on the image. The internal functions allow any format for any image. For debugging, there’s also a con- sole emulator. It uses the smallest font to provide an 8 × 21 character screen and a printf-like function.

MP3 The MP3 chip is an STA013 MP3 decoder, which is actually a Photo 3—A separate circuit board and some screws epoxied custom DSP chip. It talks over into holes in the wood provide an adjustable mounting point both an I2C bus and a SPI bus. for the tactile switches. Attaching the screws to the PCB The I2C bus is used to configure before gluing holds them in place to ensure alignment. The the DSP and control it, such as nuts are adjusted so the wooden buttons don’t rattle. changing the volume. The SPI bus provides only MP3 a pair of transistors that switch on the data. Because it is smart enough to skip 12-V power for the OLED, after it’s had over non-music data, the PIC24FJ64 does time to come out of reset. The power rail not need to interpret the MP3 stream—it also has extreme current swings, so it is just feeds it to the decoder, so you can bypassed with both a large electrolytic use unmodified MP3 files. There are two and a low-ESR tantalum. such files stored in the EEPROM. One is Note that ceramics can’t be used here! a moment of silence to help reset the Ceramic are piezoelectric, so DSP’s sequencer. The other is the default those types of current swings cause the “beep” sound the alarm uses if it can’t capacitor to move like a tiny piezo contact a music server. The MP3 decoder speaker. I wanted to make the clock as has the third crystal oscillator in the noiseless as possible. It took me a while project: a 14.318-MHz clock circuit. to find the source of the noise because I The output of the MP3 decoder is a expected the coils in the switching serial digital audio stream, which is power supply to be the problem source. fed into a serial DAC chip. The chip’s If you choose to use an LCD, this two outputs are level-adjusted and fed power switch could be used to control into a pair of differential-drive ampli- the backlight, either as a simple on-off fiers, which can provide 5 W into an switch or by reprogramming the PIC pin 8-Ω speaker and will run off up to 18 V, to be a pulse-width-modulated output. so no regulator is required. The ampli- The OLED routines write to the dis- fiers have a separate volume control play exclusively with bit-blit (BITBLT: pin, so a single voltage reference can BITwise block transfer) routines, copy- control both channels. ing font elements or stored images to the The voltage reference is created by the display as needed. (Refer to the oled.c file volume control potentiometer R307; it is on the Circuit Cellar FTP site.) Because offset to a range of 0.4 to 1.0 V by R306 the display uses 1 byte for every two pix- and R308. This matches the useful range els, all images are an even number of pix- of the amplifier’s control pin. The voltage els wide. To save space in the EEPROM, at this point is fed into one of the ADC all images are compressed, with one of inputs of the PIC24FJ64, so it can monitor three run-length compression algorithms. the volume setting (see Figure 3). In addi- The “main font” used for the primary tion, the PIC24FJ64 can turn that pin time display is stored as a 2-bit- per-pixel into an output, set it low, and the image, with pixel values representing volume control low enough that the background, foreground, and shadows. amplifier goes into a low-power standby They are dynamically replaced with mode. This gets rid of the tiny residual pixel values based on the photocell. noise that the amplifier produces when Thus, the main display’s brightness it’s active. The resulting voltage is

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 15 2807016_Delorie.qxp 6/10/2008 4:17 PM Page 16

buffered by U304, so the load from the Write Read Meaning amplifiers doesn’t distort it. 52 — “R” to start a read command The audio module also uses the great- 04 00 — Read from address 0x0004 est range of power sources. The STA013 04 — Read 4 bytes runs off 3.3 V, but it needs an isolated — 80 00 The configuration data is at address 0x0008 supply for its PLL, which is provided by — 05 00 ... and is 5 bytes long two 4.7-Ω resistors R303 and R304 and 57 — “W” to start a write command bypass capacitor C306. These form a 80 00 — Write to address 0x0080 high-current low-pass filter. The DAC 01 — Write 1 byte chip runs off 5 V so it can produce an FC — The new timezone—signed, it’s –4 (EST summer time) output of sufficient amplitude. The 00 Read a NUL when the write cycle is complete amplifiers run off the raw power from Table 1—The remote protocol can be used to locate the configuration block in the EEPROM and write a new time- the wall wart, which ranges from 16 V zone offset. The remote application can access the entire EEPROM contents, but it must break reads and writes at idle to 12 V under full load. into 256-byte chunks.

ADC monitor the seven push buttons. To save software requires the same switch read- Three ADC inputs are used to moni- on pins, each switch connects a different ing multiple times in a row. Only a stable tor the ambient light, volume setting, valued resistor into a resistor divider. The value is used to trigger a button event. and push buttons. The photocell is used resistor values were carefully selected The mounting of the switches was with R110 to produce a light-sensitive so the ADC values produced are evenly somewhat of a challenge. I use tactile voltage divider. More light increases the spaced and halfway between multiples of switches, which have a small range of reference voltage, which is read as a 64. Thus, I can simply use the high 8 bits motion but a good “feel.” To adjust higher value by the ADC. Each ADC as the “switch number.” For debouncing, their spacing relative to the wooden input includes a small capacitor to keep there are two mechanisms. First, capac- buttons activating them, I mounted the ADC’s sample and hold circuitry itor C101 acts as a low-pass filter. Its them on a circuit board, and held that from distorting the input signal. value is small enough that the signal can board with two nuts on a screw (see In addition to the photocell and vol- pass through each switch’s “zone” within Photo 3). The screw head is epoxied to ume control, the ADC is also used to one cycle of the ADC. Second, the the case. The nuts can be adjusted to control the spacing between the board and the case accurately.

MEMORY The alarm clock has five different types of memory. In addition to the 64 KB of flash memory and 8 KB of RAM in the PIC24FJ64, there is a small buffer in the MP3 decoder (it holds only one MP3 frame at a time) and 8 KB of RAM in the Ethernet chip. However, I needed somewhere to store the alarm settings, fonts, images, and other data. I chose a 24LC512 EEPROM, which holds 64 KB of data. The design allows for two EEPROMs, in case I need more room for MP3s, but so far I’ve needed only one. These EEPROMs live on the I2C bus. There’s a table of contents at the beginning of the memory, which holds the size and location of each block of data in the chip. There’s a block for each font, a block for alarm settings, a block for each music source, a block for URLs, and more. Because the EEPROM is 64 KB, addresses are 2 bytes, which is con- venient. In addition to providing data to the various routines in the clock, the EEPROM module listens on a

16 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2807016_Delorie.qxp 6/10/2008 4:17 PM Page 17

TCP port for remote management. input voltage drops below 12 V. As a minute, the alarm module is called to The protocol is simple. The remote result, the display continues to oper- check for new alarms and update the program can simply read or write ate, although dimmer, rather than snooze timer. If a new alarm is trig- blocks of data to the EEPROM. This blinking off when the music is loud. gered, the alarm task starts setting up allows an arbitrary range of remote the TCP connection for it. management software, from down- SOFTWARE The volume task watches for signif- loading fonts to alarm settings (see The PIC24FJ64 handles many tasks, icant changes in the volume control Table 1). and it uses a main polling loop to man- setting (from the ADC task). If it age them. Each task has a poll function, changes, the main display is changed POWER which gets called repeatedly from to show a bar graph of the volume set- Most people plug in a wall wart and main(). The main loop also calls the ting. If it stops changing, the main forget about power. However, this GUI each time a button is pressed. display reverts. Because the muting project requires a range of power A modified Microchip TCP/IP stack can be controlled via the GUI, this sources, each with varying require- checks for incoming packets and enables you to set the volume without ments for efficiency and quality. timeouts, looking for requests to con- needing to have music playing. There are three separate regulators. nect to the remote management ports As you can see, it’s not about doing The input is an unregulated 12 V DC and manage the MP3 streams. The one complex task, but many simple from a wall wart. What most people real-time clock module manages the ones. don’t realize is that “unregulated” means NTP requests and updates the time One of the unique features of the “could be anything.” In reality, the volt- display and snooze and sleep timers. PIC24FJ64 is its ability to map most of age ranges from 17 V at no load to 12 V The ADC is configured to run in the pins to many of the internal periph- at its rated current. Mine can provide up Auto-Poll mode. This means all three erals. However, this also means that you to 1 A, so it is normally providing about channels are continuously sampled have to configure all of those mappings, 15 V when the clock is running. A and one of two buffers is filled with as well as all of the peripherals you’re Schottky prevents damage from the results. The ADC task checks to using. This is done in config.c. To keep incorrect wiring, and a 220-µF capacitor see if a new buffer is ready. If so, it things straight, I configured the pins in guards against problems due to contact reads the data and converts it into numerical order. The first time a periph- glitches in the power jack. This raw useful ranges, including debouncing eral was connected to a pin, I configured voltage is used for the amplifiers and the button channel and smoothing the it as well. This file also has the global feeding the other regulators. photocell channel. configuration bits and sets the internal The main power bus is the 3.3 V. The MP3 task is a bit complicated, clock. While there are three crystals in Because this is a large voltage drop and because it needs to keep track not only this project, none of them run the it is heavily used, a high-efficiency of what it’s doing, but also of what it’s PIC24FJ64 itself—it runs off its internal switching regulator is used to produce supposed to be doing. First and foremost, RC oscillator and has a 32-kHz crystal it. L400/C402 and L402/C405 form low- if data can be moved from the for keeping track of the time of day. pass filters that help keep the high-fre- PIC24FJ64’s RAM to the MP3 chip’s To help keep track of the pin map- quency switching noise away from the buffer, it is. The task also checks for new pings, the pins.h file has macros for other circuits, and D401 guards against incoming connections on the MP3 port, each function that map to the pins it’s switching transients leaking to the other processes incoming data for currently assigned to. When I built the proto- regulators. D401 probably isn’t needed, open ports (which is stored in the type, I assigned pins as I needed them. but inductors can generate wild spikes PIC24FJ64’s RAM buffer), and checks for Later, when I laid out the circuit in unusual circumstances, so I kept it to time outs. If MP3 data stops showing up board, I remapped all of the pins to satisfy my paranoia. but the alarm is supposed to be on, the keep the layout clean. I just had to The 5-V supply for the DACs must internal “beep” sound is used instead. update config.c and pins.h. be as ripple-free as possible, so it is The EEPROM task manages the Once the PIC24FJ64 is configured, produced using a standard linear regu- remote EEPROM socket. When a the next step is to reset and power up lator with a large output filter capaci- remote computer connects to the clock the remainder of the board. The GPIO tor. The OLED needs a 12- to 15-V to update its settings, the EEPROM task assigned to reset is pulsed. After a supply, so there’s an optional 12-V checks for data on that socket and acts delay, the OLED’s power is enabled. low-dropout regulator for when the on it, reading and writing the EEPROM Next, each module is initialized: the input voltage exceeds 15 V. It can be and sending the results back. OLED, timer, TCP/IP stack, Ethernet bypassed if the input voltage is regu- The alarm task is responsible for chip, MP3 decoder, and real-time clock. lated to 12 V regardless of load. setting up connections to the remote Because the unregulated input can web servers to obtain MP3 data. This TIME drop below 12 V when the amplifiers includes looking up IP addresses and Of course, the most important fea- are running, the carefully selected 12-V handling the HTTP protocol. The trig- ture of an alarm clock is the clock. I regulator has a low drop-out voltage. gering of alarms happens as part of the use the built-in real-time clock to keep In addition, it acts like a shunt if the RTC task. At the start of each track of the current time (running off

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 17 2807016_Delorie.qxp 6/10/2008 4:17 PM Page 18

the 32.768-kHz oscillator). One of the mask has 1 bit set for each day of the way, the GUI can decide where to put configuration bytes in the EEPROM is week for which the alarm is enabled. it but let the RTC module maintain it. the calibration setting for the RTC, so One extra bit as a global “enable” bit, When the ADC determines that no you can adjust the “speed” of the so you can disable the alarm without button has been pressed in a while, it clock, if needed. erasing it. If the month byte is zero, pretends you pressed “timeout.” This Rather than expect the user to set the day-of-week mask is used to gives the GUI an opportunity to time the clock each time power is applied enable the alarm; otherwise, the out and reset back to the main display. (or reapplied after a blackout), the month and day are used and the clock uses SNTP to get the current weekday mask is ignored. This way, REMOTE PROTOCOLS time. SNTP enables you to request the you can have an alarm that goes off The alarm clock includes useful time with a single UDP packet sent to only on weekdays, plus alarms that go remote management features. There your network’s broadcast address. A off on specific days. are two TCP sockets that the clock lis- single reply packet gives you the time Each alarm indexes into a table of tens on. The first is an MP3 socket. A without having to configure an NTP web sites, or “destinations.” Each remote computer can connect to this client or keep track of the state of the entry includes a pointer into a string socket and send MP3 data that the protocol. The clock checks the time at table for the MP3 stream’s URL, and a clock will play. This lets you have 30 s past each minute, keeping it second pointer for a descriptive string. “alarms,” which are determined by the within 1 s of the correct time. The GUI lets you choose from the list remote computer, rather than triggered The clock does not know about of destinations for each alarm, but to by the clock itself. The remote stream time zones. Another configuration change the list of URLs itself, you need can be terminated by the same button byte keeps track of the offset from to use the remote management protocol. that ends a local alarm. SNTP’s UTC zone, but you could have The second socket allows for EEP- your SNTP server update that byte as GUI ROM access by the remote machine needed, without any user interaction. The clock uses a simple GUI to man- (see Table 1). This lets you do every- Based on the SNTP time and time age the clock locally. This includes set- thing from remote reprogramming to zone, the RTC module is updated. ting the alarms (and silencing them!), checking the time zone and setting The RTC module interrupts the using the snooze and sleep features, alarms. The protocol is a simple PIC24FJ64 once per second, sets a flag, and listening to music. Each time the read/write protocol. To read a range of and decrements the sleep timer. The ADC module determines that a but- EEPROM addresses, send an “R” char- next time the RTC’s task runs, it ton has been pressed, the GUI is acter followed by 2 bytes of address checks the flag to see if the time called to handle that button. (LSB first) and a 1-byte count (0 255). needs updating. The SNTP socket is The GUI uses a simple state The clock responds by sending always checked. The sleep timer and machine to keep track of where it is, bytes back: its display are updated every second. If without having to stop the main loop. the minute also changes, the main dis- I use a feature of GCC where you can R addrL addrH count play is updated and the alarm module assign the address of a local label to a ... is called. In addition, if the photocell variable. There’s a GOTO(x) macro value has changed, that a main that stores the address of the given To write to the EEPROM, send a W display update. This way, the clock can label into a static variable and then followed by the address and count, respond to ambient light changes quick- returns. The next time the GUI is followed by bytes. The clock ly, without wasting time to redraw the called, it jumps to the given label to sends back a NUL byte when it’s display when it’s not needed. Even perform the next step. You can also done: though the PIC24FJ64 always runs at use a standard goto if you need to full speed, it’s important to leave as jump to a common setup routine for a W addrL addrH count much processing power available as screen, which would use GOTO(x) to possible for streaming the MP3 data. set up the next state. ... As each screen is set up, icons are NUL ALARMS drawn next to each button so you Once a minute, the list of alarms is know what they’re used for. Some As long as the remote program knows scanned to see if any of them match buttons have common meanings, such the format of the EEPROM, this lets the current time. Each alarm setting as the upper-right button is always it read or modify pretty much any- uses 7 bytes of the EEPROM, for a “off” or “cancel.” Others, such as the thing in the EEPROM. maximum of about 7,000 alarms with lower buttons, have different mean- my current EEPROM load. The bytes ings for each screen, so the icons are CONSTRUCTION & PACKAGING are: hour (0–23, BCD encoded), needed. Depending on the screen, the The schematics for this project were minute, a weekday mask, month GUI can tell the RTC module how (or created using the gschem program from (1–12), day (1–31), and the address of a if) the time (wall time or sleep time) is the gEDA suite (S. Brorson, “Optical web site descriptor. The weekday to be displayed on the screen. This Proximity Sensor for Robots Part 1:

18 Issue 216 July 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 2807016_Delorie.qxp 6/10/2008 4:17 PM Page 20

Simple PCB Design with the gEDA used to it, it’s easier than through-hole development tools for Red Hat. He is Suite,” Circuit Cellar 188, 2006). The because you don’t have to keep flip- also the creator of DJGPP and a con- board was designed using the pcb pro- ping the board over. My technique is tributor to the gEDA project. Visit his gram (S. Brorson, “Optical Proximity Sen- to use a stencil to apply solder paste blog at www.delorie.com/electronics/ sor for Robots Part 2: Open-Source PCB to the right parts of the circuit board, alarmclock. Layout Editor,” Circuit Cellar 189, 2006). manually place all of the SMT parts, While the board is a four-layer board, and use an electric hotplate to reflow PROJECT FILES there are a number of PCB fabrication the solder. I got this idea off of the To download code and additional files, Internet, but it’s proven to be easy and companies that offer affordable four-layer go to ftp://ftp.circuitcellar.com/pub/ boards, such as PCB-Pool, Advanced Cir- reliable. If there are any solder bridges, Circuit_Cellar/2008/216. cuits, and Sierra Proto Express, some of it’s easy to use desoldering braid Circuit Cellar which advertise in . to remove them. After all of the SMT REFERENCE I chose to use a four-layer board for parts on the top are soldered this way, this project because I wanted solid the SMT parts on the bottom can be [1] D. Mills, “RFC2030: Simple Net- ground and power planes for reliability added using solder paste as before, but work Time Protocol (SNTP) Version 4,” and simplicity. With prototype fab using your iron to reflow the paste. To ww.rfc.net/rfc2030.html. prices dropping regularly, there’s little do this, apply the iron to the board excuse for avoiding four-layer boards and/or part and let the heat melt the RESOURCES when the project calls for them. Having paste under the part. Lastly, the S. Brorson, “Optical Proximity Sensor a solid ground plane under the majority through-hole parts are added. for Robots Part 1: Simple PCB Design of the signals helps reduce crosstalk and with the gEDA Suite,” Circuit Cellar provide cleaner power to the chips. SMART COMBINATIONS 188, 2006. However, there are some exceptions to Complexity is what you get out of a this. There is no ground plane under project, not what you put into it. Each ———, “Optical Proximity Sensor for the switching power supply because you hardware module connects to some Robots Part 2: Open-Source PCB Lay- don’t want the ground plane to pick up other module via one of the busses, out Editor,” Circuit Cellar 189, 2006. the spikes from it. The three crystal cir- and each software module performs gEDA Project, www.geda.seul.org. cuits have no ground plane either, both its task. It’s when you put all of these to avoid stray capacitance and to keep together to perform coordinated tasks Microchip Technology, Inc., “ENC28J60 noise on the ground plane from getting that it appears to be doing something Data Sheet: Stand-Alone Ethernet Con- into the clock circuits. complex. This project is an example of troller with SPI Interface,” DS39662C, The power plane is divided into the this. The MP3 decoder module is fair- 2008. 3.3-V region and the raw “15-V” ly simple, but when you coordinate it ———, “MCP6001/1R/1U/2/4: 1 MHz, region. The raw power region passes with the TCP module, alarm module, Low-Power Op Amp,” DS21733G, under each of the regulators to provide and GUI, you get an MP3 alarm clock. 2007. full power to those, as well as to each Each peripheral in the PIC24FJ64 is amplifier. The 3.3-V region passes simple by itself, but by combining ———, “PIC24FJ64GA004 Family under everything else, except of course them you get a complex set of function- Data Sheet: 28/44-Pin General Pur- the crystals and switcher. ality in a simple package. pose, 16-Bit Flash Microcontrollers,” The traces used for the switcher are Having the ability to choose DS39881C, 2008. large and close together. This reduces PIC24FJ64 peripherals and the pins ———, “24AA512/24LC512/24FC512: their and the “loop area.” they’re assigned to—combined with a 512K I2C CMOS Serial EEPROM,” The circuitry forms a crude antenna, new era in EDA tools and services and DS21754H, 2007. so reducing its area reduces the software development tools—will amount of noise it transmits. enable you to create interesting projects PJRC, “How To Use The STA013 MP3 To prepare for debugging and poten- with little investment other than your Decoder Chip,” www.pjrc.com/mp3/ tially modifying the circuit, I made own time. I sta013.html. sure that all of the vias were untented. This means that they’re not covered Editor’s note: Additional schemtics, SOURCES with solder resist, so they can be sol- diagrams, and photos for this project ENC28J60 Ethernet chip, dered to later, and the hole size is just are available at www.circuitcellar.com/ PIC24FJ64GA002 microcontroller, and right for wire wrap wire. I also laid out microchip2007/winners/second.html. 24LC512 EEPROM a number of bare grids on the back Microchip Technology, Inc. where SOIC and 0603-sized compo- DJ Delorie ([email protected]) holds an www.microchip.com nents can be soldered in case more E.C.E. degree from Clarkson University. parts needed to be added later. He has experience designing PC mother- STA013 MP3 Decoder Contrary to popular belief, soldering boards and network management STMicroelectronics SMT parts is not hard. Once you get software. DJ now writes embedded www.st.com

20 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 21.qxp 5/23/2008 10:11 AM Page 1

The Newest Semiconductors

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 366 leading suppliers.

The Newest Products For Your Newest Designs

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

Mouser_CircuitCellar_7-1.indd 1 5/20/08 1:42:09 PM 2807013 martin.qxp 6/10/2008 4:19 PM Page 22

INTELLIGENT ENERGY SOLUTIONS Living And Working Off The Grid Part 1: Planning And Design

George is going solar by installing an off- the-grid photovoltaic (PV) power-generat- ing system at his workshop/apartment in LESSONS FROM THE TRENCHES New Mexico. In the first part of this series, he describes how he planned and by George Martin designed the system.

My wife and I are getting to the age at which we are can spend time in New Mexico and see if we want to make looking for a place to retire. We live in Connecticut and the move permanent. The property has an existing well, have heard lots of stories about friends who sold their which took a big risk out of the decision to purchase. We homes and left the state to retire only to regret the deci- could theoretically drill at about $20 per foot and hit nothing. sion. So, our plan has been to find an area that we would So, having the well in place removed a big gamble in my mind. consider for retirement and try it out by living there on a My wife is a trusting soul or I’m very convincing. I assured part-time basis. Well, to make a long story short, we ended her that we could build a house and I could get the water and up near Silver City, New Mexico, with a nice plot of land solar working like you would never know we were off the grid. suitable for a retirement home (see Photo 1). No fuss, no muss, no problem. Well, a lot is really riding on Located where the Rocky Mountains come to their southern this project. Let’s call it domestic tranquility. And I also don’t end, the area is beautiful with four moderate seasons. We pur- want to give up my day job designing embedded systems. chased the land at a good price. Our property is only 2 miles How does one go about planning for an off-the-grid solar from the Gila National Forest. The New Mexico portion of system? After reading through some books and magazines the forest is about the size of the entire state of Connecti- on the subject, I soon realized that this was just another cut. To say we are out in the middle of nowhere is an project, like many others I’ve completed in my career. The understatement. You can hear the crows breathe as they fly books and magazines didn’t have the engineering details by. It is a perfect place for an off-gird solar home. that I required. As we visited the property and talked to The plan is to build a small workshop/apartment so we builders, we met our neighbors, who were also off the grid.

a) b)

Photo 1a—Our land is located near Silver City, NM. It’s a perfect spot for living off the grid. b—It didn’t take too long to get started. Here you see the guest house taking shape.

22 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com IE 2807013 martin.qxp 6/10/2008 4:19 PM Page 23

90˚ Lat: 32; long: –108 (Solar)Time zone: –8 12 P.M. 80˚

11 AM. 1 P.M.

70˚

10 A.M. 2 P.M. 60˚ J M u n a .

y 2 . 1 2 A 1 9 A.M. p 3 P.M. r . 50˚ 2 0

M a r . 40˚ 2

Solar elevation 0 8 A.M. 4 P.M.

F e b . 2 30˚ 0 J a n D . 7 A.M. e 2 5 P.M. c 1 . 2 20˚ 1

6 A.M. 6 P.M. 10˚

5 A.M. 7 P.M. 30˚ 60˚ 90˚ 120˚ 150˚ 180˚ 210˚ 240˚ 270˚ 300˚ 330˚ 360˚

East <--Solar azimuth--> West

Figure 1—This is a six-month chart of the sun’s path for our latitude and longitude. Note that July to December is the mirror of December to June.

Perhaps it was not impossible. site. How many kilowatt hours are you using? And where Let’s treat this as a normal design project. What are the is all that being used? project requirements? We need to design and install an off- I thought I had a handle on how our lifestyle consumed elec- grid system that we can afford and that does not change trical energy, so I created a column for our new home. Actual- our lifestyle significantly. ly two columns. One for phase 1 of the project. We’re building a workshop/apartment type home so that we can have a start- POWER USAGE ing point for living out west and if we don’t like it, we can get I first needed to determine if the project was financially out probably at no financial loss. So, one column is for the feasible. I started with our current electric usage. Typically, workshop and the other is for the final home. You can see some our electric bill is 24 kWh per day. It is more in the sum- of the assumptions that we made for each. We need 7.9 kWh mer with air conditioning and also in the winter with more for the workshop and 11.4 kWh for the home. I look at these lighting, heating, and indoor living. This is about $120 per numbers with some reservation because we are not actually month ($1,440 per year) at current rates. To reconcile the living out there and they are estimates. But on the positive bill with our usage for each appliance, I purchased a P3 side, appliances are getting more energy efficient each year, so International Kill A Watt meter on the Internet for about

$30 and began to record the power usage for each and every Solar radiation (W/m2) appliance I could measure. It is a great little meter that measures volts, amps, frequency, watts, and kilowatt 12/22/07–12/23/07 700 hours. I left the meter connected to major appliances for a week to get our general pattern of usage. Some appli- 600 ances, such as the electric stove and heating system, 500 could not be measured. The stove is 220 V and the heat- 400

ing system is hard-wired with no place to use the meter. 300 I next went to the Internet to get typical usages for 200 items such as the dishwasher, clothes dryer, and oven. I then estimated usages for the oil burner, circulating 100 pumps, and lights. Bottom line: I could account for 22.15 0 of the billed 24 kWh. I feel comfortable that I know 10:00 P.M. 2:00 A.M. 6:00 A.M. 10:00 A.M. 2:00 P.M. 6:00 P.M. 10:00 P.M. where our current usage is spent. This data is in a spread- Figure 2—Here you see the actual solar radiation recorded by Western New Mexico University sheet (EnergyAudit.pdf) posted on the Circuit Cellar FTP in Silver City about 30 miles to the west of the house site.

IE www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 23 2807013 martin.qxp 6/10/2008 4:19 PM Page 24

PS2AC

Add NEU/GND bond wire when using PS2AC as load center

X-240 120/240-VAC

Neutral loads

#4 #2&3 #1 L1 N L2

On On On On On On On On On On On On On

Off Off Off Off Off Off Off Off Off Off Off Off Off Off Off Off 50A 50A 50A 50A 50A 50A 25A 25A 15A 20A 15A 15A 15A 15A 15A 15A Bypass Out House loads Bypass Output Input X-240 let

AC In 120-VAC X-Fan AC In LEG 1 AC In LEG 2 AC AC Out LEG 1 AC Out LEG 2 AC 120/240-VAC AC Source generator or grid Ground

Figure 3—This is an OutBack Power Systems installation diagram of my type of system. Note the current shunt located on the battery’s negative (black) lead. This measures current in and out of the battery. We’ll use this to analyze system operation.

new purchases should be less than what I’ve measured. site for weather (http://weather.wnmu.edu). It displays solar radiation in watts per square meter. If you look at ESTIMATING SOLAR RADIATION any of the solar radiation charts on the Internet, you will The University of Western New Mexico—which is find that the southwestern United States is great for pro- located in “Silver,” as the locals call it—has a great web ducing solar power. It is even better than islands like

24 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com IE 2807013 martin.qxp 6/10/2008 4:19 PM Page 25

MX60

All GNDs are bounded to the back plate through the mounting screws Shown with PV and BAT negatives internally connected together

PV+ PV+ GND ROD B– PV– B– PV– B+ PV+ B+ PV+

FX 2024 AC Out

AC In

On On

On On On On On On On Off Off Off Off Off Off Off Off Off 60A 60A 60A .5A 60A 60A 60A Hub 4 Mate 175A 175A

OBDC-GFP/2

FX 2024 Copper bus AC Out

+

12-V Fan DC Positive

PS2DC RTS

Batteries

PS2 System

Hawaii. The University of Oregon has a great sun chart resource maps on the Renewable Resource Data Center’s web program (http://solardat.uoregon.edu/SunChartProgram.html). site (http://rredc.nrel.gov/solar/old_data/nsrdb/redbook/atlas) Figure 1 shows the sun path for our location in New Mexico. to estimate the solar radiation for our location using a fixed Next, let’s assume that we have no buildings, trees, or mount tilted at the latitude for the month of December. The mountains to block the sun. This is a good assumption result was 5 to 6 kWh/m2/day (typical) and 3 to 4 kWh/m2/day because we are in the middle of nowhere and cloudy days (minimum). I figured December with its minimal sunlight should be our only issue. I also used the U.S. solar radiation should be the worst-case design. There are plenty of reports

IE www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 25 2807013 martin.qxp 6/10/2008 4:19 PM Page 26

on the Internet for solar planning. I’ve just mentioned a business where chips are speed graded and priced accordingly. few that I found useful. My cost estimates are a bit old, so you’ll need to run the numbers with today’s prices. Let me add that I found solar EQUIPMENT panels to be in tight supply, so when you begin your design, I had great fortune in this area. First, I’m an engineer—and look to secure the panels at a good price early in the game. an electrical one at that (except my degree is so old that it The 3,000 W in my design was derived from the sun’s reads “DC ONLY!”). In addition, my neighbors in New Mexi- availability in the winter. Figure 2 represents the solar radi- co already have systems up and running. Jeff and Pat live up ation for an actual cloudless winter day. The peak radiation the road in a handmade log home. Jeff is a former engineer for is 600 W/m2. Let’s estimate that the shape of the curve is a General Motors (Pontiac GTO, Avanti, and Saturn to his cred- sine function so that the area under the curve is its average it). That makes for some interesting discussions about how value (2/π, or 0.6366 times the peak value) multiplied by electronics will revolutionize the car industry, but I digress. its width. So, that is 600 W/m2 × 0.6366 × 8 h (9 A.M. to He’s a mechanical engineer who doesn’t fully embrace all of 5 P.M.), or 3,055.7 Wh/m2. Therefore: this electrical stuff. He has a minimal system with four panels 170 W/panel of about 150 W each. Another neighbor’s system has about 18 panels ×× 3.0557 kWh/m2 = 9,350.442 kWh 1,000 W/m2 3 kW of panels. Armed with the idea that it could be done, I started to match up equipment with our requirements. Close to 10 kWh per day is good enough for the workshop, The equipment I selected falls into four main categories: but not enough for the house when it’s built. And 3 kW of solar panels, inverters, charge controllers, and batteries. In panels is what one neighbor is using. fact, you could consider each independently and not get too We also need to account for cloudy days. The energy to far off an ideal system. There are, however, some areas of con- run the workshop would need to come from the battery or cern when mating equipment from different manufactures, backup generator. Another concern is hot summer days so I stayed with one manufacturer for the control devices. when the panel efficiency drops because of the heat. But the days are longer in the summer. Actually, it’s still a 24-hour SOLAR PANELS day, but there is more available sunlight each day. I don’t Solar panels convert solar energy into electrical energy. Again, have test results for summer generation (because I’m writ- there is a lot of literature available about how this is accom- ing this in February 2008 after getting the system put plished. But what about some hard code conversion details? together in October 2007), so stay tuned. Standard test conditions require a temperature of 25°C and The last point to watch out for in panel selection is cold- an irradiance of 1,000 W/m² with an air mass of 1.5 (AM1.5) weather open-circuit voltage going into the charge con- spectrum. They correspond to the irradiance and spectrum troller. In the cold, with no current drawn, the open-circuit of sunlight incident on a clear day on a sun-facing 37° tilt- voltage of the solar panel will rise. If several panels are con- ed surface with the sun at an angle of 41.81° above the nected in series (for efficiency), this voltage may damage the horizon. This condition approximately represents solar input to the charge controller. This is a well-known situation noon near the spring and autumn equinoxes in the conti- and your equipment dealer will be able to guide you in this area. nental U.S. with the surface of the cell aimed directly at the sun. Thus, under such conditions, a solar cell with a INVERTERS 12% efficiency and a 100 cm2 (0.01 m2) surface area can be I must confess that I find inverters boring. They are not expected to produce approximately 1.2 W of power.[1] as exciting as solar panels, charge controllers, or even bat- This gives you an idea of what’s involved in rating and teries. I thought I would not find much difference in avail- selecting solar panels. Look at the University of Western able inverters and that probably was due to my lack of New Mexico’s weather site for solar radiation and you’ll enthusiasm. I selected inverters from OutBack Power Sys- get a feeling for the actual solar radiation for the area. tems. I wanted the inverter/charge controller combination There is another consideration when selecting a panel, to be from one manufacturer. As I looked at the literature, namely cost per watt. If you start looking, you will find OutBack seemed to have covered all of the issues for my panels of different wattages and different prices. In March installation. I ended up with two OutBack VFX3648 invert- 2004, I started a spreadsheet listing panels from 125 to 195. ers (see Photo 2). They are 3.6 kW (continuous) with con- Note pricing from March 2004, purchased equipment in nections for a 48-V battery and vented. You will find vent- 2005, installed in 2006–2007, and operational in October ed and sealed inverters. I selected vented because they typi- 2007. Then, I added the costs different suppliers were cally have a larger power rating and I’m not in a harsh envi- charging for each panel and calculated a price/watt number. ronment. Also, the inverters are located in an area that is My results range from $4.35 to $4.76 per watt. I estimated protected from the elements. Another option is a fan on the that I would need 3,000 W of panels, and came up with inverter. The fan also gives you more capacity, but what $13,320 for the cost of the BP Solar SX 170B. will you do when the fan fails, and you know it will? Our More polysilicon is currently being used in solar panel system is a normal 220-V home application. So, there are manufacturing than all other usages combined, so this is big two inverters, one for each phase. OutBack has a neat option business. It also seems that the larger-power-rating panels that includes a transformer to supply the second phase so command a higher price per watt. It is sort of like the CPU the second inverter can remain in a low-power operating

26 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com IE 48.qxp 4/9/2008 9:31 AM Page 1

Exclusively at Jameco… The Lowest Prices… Guaranteed!

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

3 Levels of Choice 3 Levels of Savings

Other Jameco Advantages:  We offer over 300 Major Manufacturers  99% of catalog products ship the same day.  Lowest prices guaranteed, or we pay 10%. Order 24 hours a day, 7 days a week www.Jameco.com Or call800-831-4242 anytime

SEMICONDUCTORS • PASSIVES • INTERCONNECTS • ELECTROMECHANICAL • POWER 2807013 martin.qxp 6/10/2008 4:19 PM Page 28

a ) b ) c )

Photo 2a—This is where it all began: the placement of the Outback System next to the feed into the normal house distribution panel. b—This was a truly do-it-myself project. Here I’m hoisting up inverters to mount. c—I was very pleased when the AC side was wired. From left to right: AC box, inverters, DC box.

mode. When the power requirements become large enough, different. Each cell is removable and replaceable. In our bat- the main inverter will signal the second (slave) inverter to tery, each cell measures 6″ × 6″ × 21″ and holds 1.7 gallons of start up and handle the increased load. This is a good setup electrolyte. It certainly isn’t like your car battery; it’s more for our application. We can install a normal commercial like a submarine battery. heating/cooling system and power up only the second invert- The capacity of the battery needs to be sufficient to run er when the load is calling for it. the workshop for three days. And as a matter of efficiency, Let me also add here that OutBack has great installation the larger the battery voltage, the less current flowing in and diagrams on its web site. Figure 3 is the diagram that I used out of the battery for a given load. We ended up selecting the to configure our system. SO-6-85-17/48 battery from Solar-One. This is a 48-V battery The other feature I was looking for in selecting an invert- with 845 Ah (20 h) and 32,448 usable watt-hours (20 h). It er was the ability to work seamlessly with a back-up gener- weighs 2,968 lb and has a 9,600-A short-circuit rating. Sun- ator. Again, OutBack looked good. The system controller light might give you a sunburn, perhaps even skin cancer in has the ability to start the generator when the batteries get the long run, but this battery could kill you in a heartbeat. I low, warming up the generator under no load, then charg- cannot stress the importance of following all of the safety ing the batteries, and finally letting the generator cool precautions when you’re around one of these creatures. down under no load before shutting off. Also, the amount of The dealer recommended that I get a larger battery, but I held current drawn from the generator is programmable. And back based on price alone. (Don’t tell my wife.) The cost of the finally a generator bypass switch is convenient so we can battery was $7,000. Time will tell if that was a wise decision. bypass the system and run the workshop from the generator Let me add another factor I’m still trying to get a handle in emergencies or during scheduled maintenance periods. on: battery efficiency. This is the amount of power you put The more I looked into the inverter, the more I became into a battery compared to the amount of power you get impressed with all that was available in such a boring out of it. Normal lead acid batteries are charged up to the device. Inverters just don’t get no respect. “bulk,” or “absorption,” levels (same meaning just differ- ent names). This is a slight overcharge that is good for bat- CHARGE CONTROLLER tery life but wastes energy. So, I’m not sure how much of OutBack offers the MX60 charge controller, which is a the energy produced by the panels will be available to be real-time maximum power point tracking (MPPT) system. returned from the battery. This will be measured after the So, as the sun travels across the sky, clouds pass by, solar system is up and running. panels age, or other real-world events occur, the MX60 adjusts the current drawn out of the panels to maximize MISCELLANEOUS ITEMS the power produced. That sounds good. Now that it’s up Now all of this has to meet code and be installed in a and running, it’s neat to watch it work. cost-effective manner. I decided to use OutBack Power Sys- The controller’s other significant feature is its efficiency. It’s tems equipment panels for mounting the inverters, charge a buck converter and it will take solar panel output (say 100 V controllers, AC connections and breakers, and DC connec- and 5 A) and convert it to battery input (say 50 V and 10 A) at tions and breakers. 95% to 99% efficiency. There are many areas to lose power For the solar panels, I went with pole mounts from because of inefficiencies in your solar system. This is no longer POWER-FAB. There are other items, such as lightning one of them with the advent of MPPT charge controllers. arrestors and relays to start the generator, that I have not mentioned. A good dealer or installer will keep you pointed BATTERY in the right direction when it’s time to purchase your system. The battery is where power is stored for overnight opera- tion and cloudy days. The best cost/performance battery for SYSTEM COST off-grid applications is still the lead-acid type. However, these OK, so how much did all of this cost? That’s a difficult batteries are not your typical car or golf cart battery. The number to come up with. I can tell you that the equip- chemistry is the same but the construction is significantly ment, including all of the miscellaneous items, costs

28 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com IE $36,000. That does not include the poles for mounting communications system that announces highway information. the solar panels, the backhoe for digging the holes to George is a nationally ranked revolver shooter. plant the poles (I ended up with a bigger backhoe than Steve’s and that gets me in even bigger trouble, as you PROJECT FILES To additional files, go to ftp://ftp.circuitcellar.com/pub/Circuit will see next time), the trencher for digging the trench to _Cellar/2008/216. bury the cabling to the panels, the wiring to connect all of the equipment, and the electrician to connect every- REFERENCE thing to code. But seeing the smile on my wife’s face [1] Wikipedia, “Solar cell,” http://en.wikipedia.org/wiki/Photo when her hair dryer works on a cold winter morning is, voltaic_cells. well, priceless. All joking aside, these details can eat into any budget. SOURCES But I am here early on a winter morning writing this arti- SX 170B Photovoltaic module cle, working on the Internet, watching the sun about to BP Solar shine on the panels and recharge the batteries for another www.bp.com day of living and working off the grid. MX60 Charge controller and VFX3648 inverters Next time, I’ll describe the installation process and OutBack Power Systems, Inc. explain the system’s performance measurements. So, www.outbackpower.com until then, do your energy analysis and start researching equipment. I Pole mounts POWER-FAB George Martin ([email protected]) began his www.power-fab.com career in the aerospace industry in 1969. After five years at Kill A Watt meter a real job, he set out on his own and co-founded a design P3 International Corp. and manufacturing firm (www.embedded-designer.com). www.p3international.com George’s designs typically include servo-motion control, graphical input and output, data acquisition, and remote con- SO-6-85-17/48 Battery trol systems. George is a charter member of the Ciarcia Solar-One Design Works Team. He’s currently working on a mobile www.hupsolarone.com

I E www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 29 2807014_Jordan.qxp 6/10/2008 4:23 PM Page 30

FEATURE ARTICLE by Fernando Jordan Internet Information Retrieval Target And Display Web Site Content

Fernando’s SwissJazz system retrieves artist and song title information from an Internet radio station’s web site without a PC. Information is shown on an LM3S811 evaluation board’s display and updates every time a new song begins.

a) What type of music do you listen to? b) Here in Switzerland, I listen to Radio Swiss Jazz, which plays jazz music around the clock. The problem, howev- er, is that the station doesn’t announce artist and title information for the songs it plays. That information is available only on the station’s web site. So, about two years ago, I solved this problem by Photo 1a—This is the system displaying artist/title information on the LM3S811 evaluation board. On the left are the button designing and building the “SwissJazz” to view previous/next music, an LED showing Internet activity, and the power switch. b—The system connects to the Internet system. The compact device retrieves via a Netgear MA701 802.11b wireless CompactFlash card, which is attached to the Luminary LM3S811 evaluation board. artist and song information from a radio station’s web site and displays it on a choice. In this article, I’ll explain how. I could retrieve the artist and song Luminary Micro LM3S811 evaluation title information from Radio Swiss board’s display (see Photo 1a). FROM IDEA TO DESIGN Jazz and display it in my living room You can build a similar system to Before beginning this project, I without a PC. It wasn’t until I read retrieve the Internet-based data of your spent a long time thinking about how two of Fred Eady’s articles in Circuit

Figure 1—The system features a Luminary LM3S811 evaluation board, a buffer to hold the address- es, and the CF connector for the MA701 card. I didn’t include the connections to the LCD interface board used on the second version.

30 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2807014_Jordan.qxp 6/10/2008 4:23 PM Page 31

Cellar—“Uncomplicated Wireless Net- using a microcontroller to connect to got an LM3S811 evaluation board and a working,” Issue 170, 2004, and the Internet. After studying up on the Netgear MA701 CF wireless card and “Embedded Wi-Fi with TRENDnet,” topic (F. Eady, Implementing 802.11 started working on my design. Issue 174, 2005—that I got the idea of with Microcontrollers, Newnes, 2005), I HARDWARE The design features an LM3S811 eval- Listing 1—This code shows the creation of the UDP frame to request the actual date and time. Each packet uation board, a CF wireless card, and an element is a 16-bit word. Positions 20 and 21 hold the time server IP address. Position 23 holds the IP port for interconnecting PCB. The PCB has a the time protocol (port 37). 40-pin connector for the LM3S811, an void createRfc868request(void) 8-bit latch to keep the address’s eight { most significant bits, and a 3.3-V exter- int i; nal regulator. The CF card needs 300 mA. for(i=0;i<3;i++) According to Luminary’s documenta- packet[1+i] = destMAC[i]; tion, the internal 3.3-V supply was up to 300 mA. So, to avoid any problems, for(i=0;i<3;i++) packet[4+i] = macaddri[i]; I decided to add the external regulator and a compact flash connector, as you // SNAP can see in Figure 1. packet[8] = 0xAAAA; packet[9] = 0x0003; During the development phase, 5 V packet[10] = 0x0000; come from the USB connection. Dur- packet[11] = 0x0008; // IP protocol ing normal operation, 5 V come from // IP an external power supply via J2. To packet[12] = 0x0045; have the USB’s 5 V going to the board, packet[13] = 0x1d00; I used pin 1 from the evaluation board packet[14] = 0x96df; packet[15] = 0x0000; connector, which was not connected. packet[16] = 0x1180; (Well, actually, it doesn’t exist! It packet[17] = 0; // IP hdr xksum exists only in my 20-pin connector.) packet[18] = make16(ipaddrc[1],ipaddrc[0]); packet[19] = make16(ipaddrc[3],ipaddrc[2]); As an external supply, I used an old packet[20] = udpTimeServer[0]; mobile charger (5 V at 500 mA). To packet[21] = udpTimeServer[1]; develop the interconnecting board, I // UDP used PCB123 as the PCB manufacturer packet[22] = 0x2500; because it had reasonably good packet[23] = 0x2500; // port 37 schematic/layout software (although it packet[24] = 0x0900; packet[25] = 0; // UDP xksum had a slightly salty price for the two packet[26] = 0x0020; prototype boards). The parts and fin- ished “sandwich” are shown in Photo 1b. packet[0] = 26 * 2; // len in bytes (little endian) packet[7] = swapbytes(packet[0]); // len (big endian) The “definitive” version, which I use every day, appears at the bottom-right. CalcCksum(PROT_UDP); The first version used the evaluation } board’s display. For daily use, I realized where: the design needed a bigger display. I unsigned short udpTimeServer[2] = {(6<<8)+129,(28<<8)+15}; opted for a 2 × 20 backlit LCD. // UDP time: 129.6.15.28, port 37 There were not enough GPIOs remaining in the LM3S811 board, so I used a two-line synchronous connec- Listing 2—The date and time are received as a 32-bit unsigned number of seconds since January 1, 1900. tion from PC6/7 to a Microchip Tech- The number is converted to date and time, taking into account the local daylight savings time period (via ConvertSecondsToDatetime), and saved into the internal clock structure (via SetClockEx). nology PIC16F84 microcontroller, as the LCD interface. The small board } else if(packet[UDP_destport]==0x2500) { has a four-pin (5 V, GND, SerClk, and // RFC868 response SerDat) connector to the Luminary seconds = make32( (packet[26] & 0xff), ((packet[26]>>8) & 0xff), (packet[27] & 0xff), ((packet[27]>>8) & 0xff) ); board, as well as the usual connec- ConvertSecondsToDatetime(seconds, &dateTime); tions to the LCD via a 4-bit data bus. SetClockEx(dateTime.tm_mday, dateTime.tm_mon, dateTime.tm_year, The PIC16F84 has a four-pin con- dateTime.tm_hour, dateTime.tm_min, dateTime.tm_sec); nector for in-circuit programming (it my_seqnum = seconds; // startup seq # was bread-boarded and there are no schematics for it), a crystal, some return 2; } capacitors, the connections (the afore- mentioned pins plus 10 pins for the

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 31 2807014_Jordan.qxp 6/10/2008 4:23 PM Page 32

usec2gymdhms function, which is in my ConvertSecondsToDatetime.[1] The same routine called IsSum- mertime, which is a crude approach for checking if daylight savings time (DST) should be used. The acquired date was checked against the dates for the start and end of the DST in Switzerland. It is valid only until 2009! The seconds value returned in the response frame was converted to date and time in the udp routine, and the internal clock was updated by SetClockEx (see Listing 2). A small timer interrupt that runs every 250 ms kept the time inter- nally in the clock array. If the clock is not accurate, this is not a problem: the device is supposed to be off before bedtime. It should be on the next day when the time is read again! Photo 2—This is the Radio Swiss Jazz web page. The circled frame contains the important information. (Source: Radio Swiss Jazz, www.radioswissjazz.ch/cgi-bin/pip/html.cgi?m=playlist&v=d). The next step was the actual TCP part. This is the protocol used to transport the HTTP protocol, which is connection with the LCD), and a sim- and my “problem” was fixed. The used for the “www” transactions. I ple NPN transistor for the SerClk. next step was to get the time. will not talk about the TCP protocol The LM3S811 is a 3.3-V device. The The LM3S811 board doesn’t have an itself because this would require PIC16F84 is a 5-V device. The port pin RTC and I did not want to add an IC another article. I will say only that used for the SerClk has a Schmitt trigger and a battery to keep the time. So, I Eady’s original code worked as a telnet input, which means that it won’t under- opted to get the time using RFC 868, TCP server and I needed a TCP client. stand the 3.3 V as high. It needs at least which defines the time protocol, a The normal way to get music 4 V. This is the reason for the transistor. UDP-based protocol where the server information is to use a browser and returns the time in seconds since mid- connect to a web site such as SOFTWARE night on January 1, 1900. www.radioswissjazz.ch. The page that Porting Fred Eady’s CF wireless The UDP portion of Eady’s code ran opens has a few frames (a frame is firmware to the Luminary processor beautifully. (The request was created in more or less a web page inside a “rec- was straightforward. Only a minor createRfc868request() in Listing 1.) tangle” in a web page). The middle glitch from my side gave me a I got the seconds since January 1, one is important (see Photo 2). headache: I forgot one line of code (to 1900. To convert that to usable time, Usually, to request pages from a enable the WEP security) and couldn’t I used the algorithm from Peter Ack- web site, the web browser connects, at first find the reason for the unsuc- lam’s “Time Utilities” for the via TCP, to its IP address (a procedure cessful connection. I almost went mad. Without the budget to purchase a) b) a wireless sniffer, I had to find some- thing else. Fortunately, I came across an evalu- ation sniffer from TamoSoft in New Zealand. The CommView for Wi-Fi is c) not constrained to one wireless d) adapter like the one Eady used in his book (Netasyst). It supports quite a number of them. The sniffer’s evalua- tion version does not show all hex Photo 3a—When the system powers up, it connects to the wireless network while displaying the connection phases. frames (every other one only), but this b—After connecting, the date and time are requested via UDP.The received date/time is shown and updated every did not pose a serious problem because second while the initial music information is received from the web page. c—Music and time information are shown when the next music starts and every 10 s thereafter. The display shows the music’s start time, the current time, most of the information is in the and the music’s end time. d—The current music/artist information is displayed. A small right arrow in the title or decoded frame window. Finally, I artist line indicates that the line is longer. Pressing the button or waiting about 10 s will show the remaining information could see that WEP was not enabled scrolling to the left.

32 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 33.qxp 5/28/2008 10:39 AM Page 1 57.qxp 4/9/2008 9:30 AM Page 1 2807014_Jordan.qxp 6/10/2008 4:23 PM Page 35

called DNS translation converts the Listing 3—The main loop for the program is shown here as pseudocode. All of the processing happens in an endless loop, which implements the main state machine. “www” name to an IP address), sends an HTTP Get request, and int main(void) waits for the HTTP response. In this { case, because the IP address is fixed, // do the processor initializations // start the Timer there is no need for a DNS transla- // configure the UART for debugging messages tion. (Refer to the Future Enhance- // initialize the LCD display ments section at the end of this arti- // initialize the CF card // start the wireless Ethernet connection cle.) The HTTP response returns a // and finally… web page with HTML code that doMainLoop(); looks like what you see in the } HTML code.doc file on the Circuit short main_state; Cellar FTP site. void doMainLoop() I don’t need all of the page’s data. { This shows about 24 hours of music main_state = S_GET_TIME; (names and artists). I need only the while(1) { switch ( main_state ) { data near the current time: what is case S_GET_TIME: playing at the current time, what was // gets the time on startup playing prior to the current time, and case S_TCP_CONNECT: // starts a TCP connection, if data is needed the four titles that are going to play case S_SEND_HTTP_GET: after the current time. But, because // starts a TCP request for the HTTP data the TCP protocol is connection orient- case S_ALL_RECEIVED: ed, I have to keep receiving until the // if it has nothing to do, check the button case S_SHOW_INFO: TCP FIN frame is handled (i.e., the // if a button is pressed or the music changed end of the TCP connection). Other- // shows the information in the LCD wise, there will be an open TCP con- case S_ERROR_TIME: // error in the UDP connection: nection that will finally time out, // dislays it in the LCD and tries to get the time again which is not elegant. case S_ERROR: I rewrote the entire TCP part from // error in the TCP connection: Eady’s code. He had a TCP server // shows it in the LCD and tries again } and I needed a TCP client. The actu- al HTTP frame treatment is made in if ( waiting for response from server ) { application_code() during the if ( there was a timeout waiting for the response ) { reception of the TCP frames in if ( main_state==S_WAIT_TIME ) // UDP error tcp(). This is where the informa- main_state = S_ERROR_TIME; tion shown in bold in the HTML else code.doc file on the Circuit Cellar // TCP error main_state = S_ERROR; FTP site is retrieved. Because this is not a time-constrained task, I have a } else { big loop (doMainLoop), which runs // gets an Ethernet frame from the CF wireless card receive forever in my main function. Refer // buffer and treats it temp = get_frame(); to the pseudocode in Listing 3. switch ( temp ) { case PROT_UDP: TCP TRANSACTIONS // date/time received (udp()) main_state = S_TCP_CONNECT; To make the TCP connection (state break; S_TCP_CONNECT), I first send a SYN, wait for an ACK/SYN, and then ACK case PROT_TCP: it (in tcp()). The connection is creat- // treats the TCP frame (tcp()) if ( no error receiving frame ) { ed in createTcpConnection(), main_state = S_ALL_RECEIVED; which fills the communication buffer } else { packet with all of the data required by main_state = S_ERROR; the TCP protocol, including the desti- } break; nation IP address, 146.159.231.17 } (ipDestAddr). This is similar to what } you see in Listing 1 for the UDP request. } } Next, in the state S_SEND_HTTP_GET, } I send the HTTP request. The buffer is completed with the data required by the

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 35 2807014_Jordan.qxp 6/10/2008 4:23 PM Page 36

TCP protocol in createGetRequest(): Listing 4—This is the frame the Luminary board sends to the PIC board with the position and text to be displayed in the LCD. GET /cgi-bin/pip/html.cgi?m=playlist 0xAA X Y C ... C &v=d HTTP/1.1\r\nHost: 0xAA is a frame start byte www.radioswissjazz.ch\r\n\r\n” X: 0..19 column or 0xFF for 'clear screen' Y: 0..1 row The received frames are treated in C: the ASCII bytes to display (if X is not 0xFF) tcp() until a FIN is received and ACKed (S_ALL_RECEIVED). The application_code() func- internal states of a state machine after connection, the current connection is tion called from tcp() parses the the wireless connection is successful abandoned and a new one is started received HTTP frames looking for the (see Photo 3a). After successfully con- from a different source TCP port. After information shown in bold in the necting to the wireless network, the all, this is not a life-threatening device! HTML code.doc file on the Circuit time is requested with the following The music information is saved in Cellar FTP site. It uses a simple state states: S_GET_TIME, S_WAIT_TIME, the musicInfo array: time, title, machine, which looks for the time S_TCP_CONNECT, and S_ERROR (in artist, and the longest length of the (R_GET_TIME), music name case of error). two (for display purposes). (R_GET_TITLE…), and artist name After receiving the time, the data is The S_ALL_RECEIVED state waits (R_GET_ARTIST…). Refer to the requested using the states shown in the for the current time to match a time Response Frame.doc file on the Cir- Data Request states.doc file on the Cir- in the musicInfo array or the user cuit Cellar FTP site. At the end of cuit Cellar FTP site. During this process, button to be pressed. If you push the R_GET_ARTIST, it checks if the time the current date and time are shown (see button quickly, the current music is around the current time and, if it is, Photo 3b). Then, every 10 s, the music information is shown. If you press it it saves it in the array musicInfo. and time information are shown using until the LED illuminates, the previ- the states in the Display of Data.doc file ous music information appears. If you MAIN LOOP OPERATION posted on the Circuit Cellar FTP site. press and hold it after the LED lights, As you can see in Listing 3, the main There is a basic error treatment. If the next music information is shown. loop doMainLoop goes through the there is any error during the TCP When a time matches or the button

36 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2807014_Jordan.qxp 6/10/2008 4:23 PM Page 37

A: x x x x LCD3 LCD2 LCD1 LCD0 a 32-byte queue. Engineering more than 30 years ago. B: x x LCDrw LCDrs LCDe x SerDat SerClk The main routine waits He has designed hardware and soft- for a byte from the queue ware for Apple II peripherals, IBM PC- Table 1—For the LCD interface PIC board, LCD data is in port A, LCD and processes it based on a compatible boards, PIC-based devices, control is in port B, bits 3 to 5, and the interface to the Luminary board four-state state machine, Texas Instruments DSP-based devices, is in port B, bits 0 and 1. which treats the incoming and ARM-based devices. Fernando has frame and defines the posi- also written PC applications in VB, is pressed, the information is shown in tion and the characters to be displayed. VC++, and C#. He is currently working the display. The time (see Photo 3c) is A simple frame is used for sending with FPGA-based boards for train data followed by title/artist information (see the data from the LM3S811 to the communications. When Fernando isn’t Photo 3d). PIC16F84 (see Listing 4). The connec- working on electronics projects, he After the fifth piece of music infor- tions to the PIC ports are shown in enjoys cooking, drinking good wine, mation appears, a new TCP connec- Table 1. and listening to jazz. tion (with a different port number) begins to update the musicInfo array FUTURE ENHANCEMENTS PROJECT FILES with new data. The implementation is The current version of my design To download code, go to ftp://ftp.circuit divided into five sets of files. has a fixed SSID, WEP, client IP, and a cellar.com/pub/Circuit_Cellar/2008/216. The first set of files (swissjazz.c, default gateway MAC address. The swissjazz.h) contains the main applica- next step is to make this information tion: start-up, “clock,” and the main variable so I can use the system some- REFERENCE state machine. where other than in my house. [1] P. Acklam, “Time utilities,” 2005, The second set (airdrop.c, airdrop.h) In addition, instead of giving the http://home.online.no/~pjacklam/ of files contains the wireless func- gateway MAC address, it would be shell/programs/time. tions, as in the original code from helpful to give its IP address, which is Eady, except for a few changes like immediately available. This would tcp() and application_code(). require an extra step using ARP to RESOURCES The third set (cf_driver.c, cf_driver.h) convert the gateway’s IP address to its F. Eady, “Embedded Wi-Fi with of files contains the CF access func- MAC address, which is needed in the TRENDnet,” Circuit Cellar 174, 2005. tions (transferred from the original Ethernet part of the sent frame. airdrop.c). ———, Implementing 802.11 with The fourth set (lcd.c, lcd.h) contains NO PC, NO PROBLEM Microcontrollers: Wireless Networking the code to interface the system to the In addition to having a lot of fun for Embedded Systems Designers, display controlled by the PIC16F84. building and programming the Swiss- Newnes, Burlington, MA, 2005. And finally, the fifth set (dsp-PIC.c, Jazz system, I also gained a better ———, “Uncomplicated Wireless Net- dsp-PIC.h, LCD1.C) of files contains the understanding of the CompactFlash working,” Circuit Cellar 170, 2004. PIC code for the 2 × 20 LCD. structure and wireless network com- The application_code() also munications. The project demon- Radio Swiss Jazz, www.radioswissjazz.ch. implements a small state machine for strates that a PC is not always needed the reception of the music information, to connect to a wireless LAN and to which spans in more than one HTTP (or process TCP frames and the HTTP SOURCES TCP) response frame. The code is posted protocol. It opens the door to other LM3S811 Evaluation board on the Circuit Cellar FTP site. applications based in the same hard- Luminary Micro, Inc. ware and firmware. I www.luminarymicro.com 2 × 20 DISPLAY PIC16F84 Microcontroller For the 2 × 20 LCD, the original Editor’s notes: Fernando Jordan’s “Swiss- Microchip Technology, Inc. OSRAMXxxx functions were replaced Jazz” design won Honorable Mention in www.microchip.com by LCDXxxx functions in my code. the Luminary Micro Designstellaris2006 The functions in the LM3S811 shift a Contest. For more information about MA701 CF Wireless card bit from the byte to be transmitted in the winning projects, visit www.circuit Netgear GPIO_PIN_6 (SerDat) and pulses high- cellar.com/designstellaris2006. We www.netgear.com low GPIO_PIN_7 (SerClk). On the want to thank Radio Swiss Jazz for per- PCB PIC16F84 side, SerClk goes to RB0 as mitting us to use the screenshot of its PCB123 PCB Manufacturer an interrupt on the high to low transi- web site: www.radioswissjazz.ch. www.pcb123.com tion and the SerDat is shifted-in in RB1. Every interrupt (SerClk high to CommView Network monitor and low), the bit (SerDat) is shifted in the Fernando Jordan ([email protected]) analyzer least-significant bit of dataIn. After has been working with electronics TamoSoft the eighth clock, dataIn is pushed in since receiving his B.Sc. in Electronics www.tamos.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 37 2806016_Sterian.qxp 6/10/2008 4:25 PM Page 38

FEATURE ARTICLE by Andrew Sterian Launch Control Build A Coil Gun Controller And Launcher

Andrew’s educational system works as a controller and data recorder for a dual-coil coil gun. Use the LM3S811-based controller to experiment with various aspects of the coil gun, including timing and voltage control.You can also measure the real-time voltage and current.

A coil gun is an that students followed my lead by designing accelerate. When the reaches can fire metal like a regular and building their own coil . We the center of the launching tube, turn off gun, but without any explosives, loud then held a competition to see which the coil current, as shown in Figure 2c, noises, or moving parts, apart from the gun could shoot a projectile the farthest. and the projectile’s inertia will contin- projectile itself, of course. Energy con- ue to propel it out of the open end of straints limit such a gun’s use as a COIL GUN BACKGROUND the launching tube. handheld weapon, but the largest, Like any electromagnet or , Coils can be constructed in a wide most powerful coil gun is capable of a coil gun comprises a wire-wound variety of diameters and with anything moving a lot of mass. Some people coil and a ferromagnetic movable from 32-gauge wire to thick have even proposed using coil guns for , or slug. But while electro- 12-gauge copper. The bigger the wire, launching payloads into space. and limit the range the lower the resistance and the greater My interest in coil guns is educational. of motion of the slug, a coil gun the current that can be pumped into the I teach a course in circuit analysis, enables it to move freely and eventu- coil, because Ohm’s Law tells you that which is full of equations and abstract ally exit the coil, thus becoming a pro- I = V/R. Higher currents translate concepts, at Grand Valley State Univer- jectile (see Figure 1). So, if you’ve ever directly into stronger magnetic force, so sity in Grand Rapids, MI, so I know well wound wire around a tube to build an Newton’s Law tells you that the pro- that a practical design project goes a long electromagnet, you’ve built half of a jectile’s acceleration, given by a = F/m, way to help bring the hard stuff down to coil gun. The other half is either a will increase directly with the magnetic Earth. A coil gun is a perfect project for timing or feedback circuit to turn the force F. my course because it doesn’t include electromagnet off at the right time. To get high currents flowing, a 2-A too many parts and it demonstrates the When a current is applied to the coil, bench DC power supply is not going to behavior of basic components such as the projectile is attracted to the center of cut it. You have to pump out 20-A cur- resistors, capacitors, and inductors. Plus, the coil, no matter which side it starts rents and maybe even higher. The com- it’s much easier to get young engineers on. Thus, if you just turn on the coil mon solution is to use capacitors to store excited about a coil gun than it is to get current and leave it on, the projectile energy from a DC supply, and then them enthusiastic about a typical intro- will quickly come to rest in the middle quickly discharge that energy at a cur- ductory circuit, such as an LED flasher. of the coil. That isn’t what you want at rent level limited only by the resistance I built a two-coil coil gun launcher all! If you can time it just right, howev- of the coils, internal capacitor resistance, capable of operating at up to 60 V and er, and turn off the coil when the projec- and interconnecting wire resistance. The 25 A (see Photo 1a). I also constructed tile has reached maximum velocity on bigger the capacitors, the better, because a controller/datalogger for the launch- its way to the coil center, it will shoot you can sustain high currents through- er that features a Luminary Micro out of the coil gun in an impressive dis- out the length of the coil firing time. LM3S811 microcontroller (see Photo 1b). play of electrical-to-kinetic energy con- Coils can be well modeled as induc- Since finishing the project, I’ve success- version. Figure 2 illustrates this process. tances. The inductance depends on fully used the design—which includes a The coil current creates a magnetic the number of turns of wire in the lot of protection circuitry that makes it field around the launching tube, which coil, the length of the coil, and the as “student-proof” as possible—as a lab- makes the projectile start to move (see cross-sectional area of the coil. There oratory demonstration/experimentation Figure 2a). In Figure 2b, the projectile are many parameters to trade-off and platform. For instance, in April 2007, my has started to move and continues to optimize in designing a coil gun, but it

38 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2806016_Sterian.qxp 6/10/2008 4:25 PM Page 39

of the two coils or as a single unified a) b) bank. Inexpensive surplus 6,800-µF snap-in electrolytic capacitors from All Electronics were perfect for the job. A high-current connector that allows for adding extra off-board capacitors in par- allel with either one of the two built-in capacitor banks is included. I built the control circuitry on a dou- ble-sided PCB (see Photo 1b). There are several surface-mount components, but none of them has a lead pitch that would make hand-soldering difficult, even without a solder mask on the PCB. Photo 1b shows the coil connections at the bottom, a DC power supply con- nection on the left, and the microcon- troller interface wires at the top. The Photo 1a—The coil gun controller is mounted to a piece of shelf board and attached to a standard bench power LM3S811 evaluation board can be seen supply. A homemade coil is attached with alligator clips. b—The coil gun launcher circuitry attaches to the coil at at the top of the picture. The connec- the bottom, to the external DC power supply on the left, and to the LM3S811 microcontroller board at the top. tors were chosen for quick connect/dis- connect, again to save time in the lab. essentially boils down to a simple circuit Components such as F4 and D14 I suggest that you use PCB traces comprising a capacitor (or a bank of enabled me to “student-proof” the proj- that are as thick as possible for the capacitors in parallel) and an inductor ect. They protect against overvoltage, high-current traces and that you also (the coil) with some series resistance. It’s undervoltage, and overcurrent at the melt solder on them to further reduce a perfect circuit for students to build in inputs the students would hook up. their resistance. There will be some one semester and for a hands-on intro- The coil currents observed across the high currents flowing in these traces. duction to the important concepts of current-sense resistors are buffered and Although they won’t get hot (due to resistance, inductance, and capacitance. amplified by rail-to-rail op-amps and the short duration of the firing pulse), then digitized by a Linear Technology their resistance will waste power, so HARDWARE LTC1861 12-bit ADC. One of the key the lower the resistance, the better. The main parts of the design are shown features of the project is the ability to in Figure 3. Note that the project sup- record and analyze real-time coil cur- SOFTWARE ports either one or two launching coils. rents to see how changes in design The LM3S811’s firmware is respon- The ability to use two coils is a bit of parameters, such as coil windings and sible for controlling the timing of the “extra credit”—the optional second coil applied voltage, affect the coil gun per- firing pulses and for receiving and storing can be used to accelerate the projectile a formance. The ADC’s SPI pins are con- samples from the current and voltage second time for higher projectile velocity. nected to the microcontroller by anoth- The heart of the coil gun launcher is er isolated interface, this time using a) the coil driver: a three-stage optoiso- an Analog Devices ADuM3401 isola- lated current amplifier (see compo- tor. Standard optical isolators are not nents IC8, T4, and Q4). The main fast enough to support the 40-µs sam- switching transistor is a 100-V MOS- pling period necessary for getting a FET with a low on resistance of only good look at the transient coil current. b) 14 mΩ. It adds as little resistance to Another lower-resolution ADC (IC7) is the coil as possible. Another 15 mΩ of used to monitor the coil voltages in real resistance is added by a current-sense time, mostly for sizing the energy storage resistor (e.g., R17), which can be used capacitors and demonstrating the expo- c) to monitor coil current in real time. nential discharge curve of the capacitors. Both the current and voltage measure- ments could have been performed with Tube Coil ICOIL an external oscilloscope, but having a Figure 2a—This shows the projectile being attracted to Projectile measurement system built into the the center of the launching tube due to the magnetic

ICOIL project saved a lot of time in the lab. field created by the coil. b—The projectile has started My project included two capacitor to move and continues to accelerate due to the mag- Figure 1—A coil gun fundamentally consists of a projectile netic field. c—Once the projectile reaches the center of within a launching tube, a coil wrapped around the tube, and banks of 13.6 mF each, which could be the coil, the is turned off and the projec- a current passing through the coil to effect projectile motion. used as either individual banks for each tile’s inertia carries it out of the launching tube.

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 39 2806016_Sterian.qxp 6/10/2008 4:25 PM Page 40

ADCs. The firmware also 16- to 60-V DC power source contains a text-based user Luminary Micro Coil gun launcher EK-LM3S811 interface that uses VT102 evaluation kit terminal screen control codes Capacitor banks Computer USB-to-serial to display the launcher’s sta- Optional external capacitor banks tus and configuration all at Optoisolation UART once. The LM3S811’s UART Figure 3—This is a block dia- Voltage/current SPI is used to communicate with gram of the coil gun launcher. ADCs The external components are a Timers an external PC, which needs Luminary Micro EK-LM3S811 only a terminal emulator LM3S811 Firing circuit evaluation kit, a PC for con- program (e.g., TeraTerm or trol, a DC power source, and optional external capacitors to HyperTerminal) for complete increase the energy storage control over the coil gun. capacity. Launching coils A screenshot of the user interface is shown in Photo 2. Single-key commands enable you to manage firing times, to control the use of separate or unified capacitor banks, and, of course, to fire the coil gun. The key to achieving maximum pro- jectile distance from a coil gun is timing. The coils must be turned on and off at precisely the right time. The LM3S811 microcontroller’s 32-bit timers are extremely useful for generating precise timing pulses for the two coils. Running at 20 MHz, the timers have no trouble generating firing pulses with a resolution of 10 µs and durations anywhere from nearly 0 (10 µs) up to 10 s. The firmware supports two recording modes: Current only, Voltage only, or both Voltage and Current. The best sam- pling rate is automatically computed to make maximum use of the LM3S811 microcontroller’s 8 KB of built-in RAM. For short firing times and single- coil operation, a maximum resolution of 40 µs sampling times is achievable.

OPERATION As you can see in Figure 4, the EK- LM3S811 evaluation board connects to the launcher circuit PCB via pins 8 through 20 of the I/O breakout pads. (Pin 18 is not used.) I soldered a 13-pin 0.1″ single-row header strip to the evaluation board for this purpose, although you could just solder wires directly into the breakout pads. Next, you will need an external DC power supply set to between 16 and 60 V. The power supply is used to charge (slowly) the capacitor banks so high-current capacity is not required. Standard banana plug jacks are provided on the PCB for direct connec- tion to a typical laboratory power supply. The last hardware hookup is the coil

40 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 41.qxp 6/5/2008 11:38 AM Page 1 42.qxp 6/5/2008 11:41 AM Page 1

TM

LEARN TODAY, DESIGN TOMORROW At the fall’s largest embedded event and technical conference

CONFERENCE OCTOBER 27-30, 2008 EXPO OCTOBER 28-29, 2008 Hynes Convention Center | Boston, MA

The Embedded Systems Conference Boston was created specifically to meet the information needs of the system architects and design engineers who create these complex systems.

The technical program at ESC is the Fall’s largest industry conference offering in-depth and unbiased content, that delivers real world solutions from leading technology experts.

FOR EXHIBITING OPPORTUNITIES PLEASE CONTACT SEAN RAMAN EVENT SALES DIRECTOR, TECHINSIGHTS FOR ATTENDEE INFORMATION, PLEASE VISIT OUR EVENT WEBSITE AT [email protected] www.embedded.com/esc/boston PHONE: 415-947-6622 2806016_Sterian.qxp 6/10/2008 4:25 PM Page 43

gun launcher itself, either one or two coils. The coils must have a resistance that limits the current to 25 A. For example, if a 60-V DC supply is used, the coils should have a resistance of at least 2.4 Ω. The launcher circuitry will probably handle more current than 25 A, but at higher currents, the built-in ADCs will saturate and provide unusable data. Use thick wire for hook- ing up your coil to minimize resistance and thus minimize power loss. Finally, connect the EK-LM3S811 evaluation board to a PC with a USB cable. The board appears as a virtual serial port on the PC. Therefore, any terminal emulator program such as HyperTerminal or TeraTerm can be used to talk to the board. The firmware Photo 2—This is a screenshot of a text-based user interface running in a terminal emulator window. VT102 control uses a data rate of 115,200 bps, 8 bits codes are used to draw a user-friendly display. per word, no parity, and 1 stop bit. The Windows Terminal font is suggested Coil 2’s firing time is controlled in a the data is displayed on your screen for the terminal emulator window similar manner, as is the inter-coil-fir- where it can be logged to a file and because it draws pseudo-graphics line- ing wait time. The full set of key imported into a numeric analysis tool, drawing characters (see Photo 2). presses used to control the timings is such as Matlab or Excel. By pressing the O key in the text- shown at the bottom of the GUI dis- It is educational to examine the coil based GUI, you can toggle between play (see Photo 2). If Coil 2’s firing current’s behavior in this second-order One-bank mode (both capacitor banks time is set to 0, then only Coil 1 fires. resistor-capacitor-inductor (RCL) sys- are ganged together) and Two-bank The two coils may be fired independ- tem. It allows for some interesting mode, where each capacitor bank is ently by pressing 1 to fire Coil 1 and by algorithms to be developed to auto- applied only to one of the coils. pressing 2 to fire Coil 2. To fire the two matically determine when to turn off A voltage input cut-off can be affect- coils in sequence with the programmed the coil current. Usually, you find the ed by pressing the V key. This pre- inter-coil-firing wait time, you must optimum launch time for each coil by vents the external DC supply from press the space bar, or the user push trial and error. In advanced coil gun reaching the capacitor banks. The button on the EK-LM3S811. designs, a feedback mechanism is used function can be used to watch the Finally, Data Recording mode is to inform the system that the projec- self-discharge property of the circuit toggled by pressing the R key. The tile has achieved maximum velocity and perform a variety of launch tests sample rate for data recording is and the coil current should be turned at different voltages if the external automatically chosen to be as high off. For example, an optical inter- power supply is not adjustable (i.e., by as possible given the amount of rupter, a mechanical switch, or a sec- letting the voltage decay before firing). available RAM in the LM3S811 and ondary pick-up coil can be used. It is The voltage input is also cut-off the length of the firing pulses. more interesting, however, to look at whenever either one of the two coils is the coil current itself for information. fired. This means that the coils are DATA RECORDING The launch coil is essentially an air- powered only from the capacitor banks, The final aspect of the system is the core inductor. But as the projectile even if the power supply is left connect- real-time recording of coil voltages and enters the core, the presence of a fer- ed. I did not want the power supply to currents. The system is designed to romagnetic material inside the core confound the observation of a “simple” accurately measure coil current during a subtly changes the inductance of the resistor-capacitor-inductor circuit. firing pulse at a sampling rate of 25 kHz. coil. Because the coil current is a The timings of the two coils are adjust- A fast dual-channel 12-bit ADC is used function of the inductance, this small ed using 12 different key presses. For for this purpose. Coil voltage also can be change in the inductance will be seen example, the duration of Coil 1’s firing sampled with a separate 10-bit ADC, in the coil current. By examining the pulse increases by 1 ms when the I key is but this is mostly for non-real-time coil current itself, you should be able to pressed. It decreases by 1 ms when the J monitoring, because an oscilloscope tell when the inductance has reached a key is pressed. The duration increases can easily perform this job just as well. maximum, indicating that the projec- by only 10 µs (the finest resolution) The acquired data is stored in the tile has reached the center of the coil. when the “i” key is pressed. It decreas- LM3S811 microcontroller’s on-chip Figure 5 shows a comparison of coil es by 10 µs when the “j” key is pressed. RAM. After the launch is complete, current during a “long” launch (about

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 43 2806016_Sterian.qxp 6/10/2008 4:25 PM Page 44

150 ms), with and without a projectile. closely, you will see that there is a is at the first maximum in Figure 6, at The launch time is about 10 times small difference in the current profile about 9 ms, when the inductance of longer than it should be for maximum depending on whether or not a projec- the coil is at a peak due to the projec- exit velocity to clearly show the cur- tile was in the launch tube. tile’s position at the center of the rent decay. With this long launch Figure 6 shows a graph of the with- launch tube. time, the projectile doesn’t exit the projectile current subtracted from the launch tube. It is pulled into the cen- no-projectile current. As you can see, DEVELOPMENT ter and stays there. the difference isn’t large, but it is The LM3S811 microcontroller and its As expected, the coil currents decay measurable. If you want to launch the evaluation kit made the development of exponentially with time as the capaci- projectile out of the launch tube, the this project easier than usual. The driv- tor banks discharge. But if you look best time to turn off the coil current er support library from Luminary Micro

Figure 4—The main parts of the coil gun controller are shown in this schematic. The two coil firing circuits are identical so only one is shown, and the same goes for the coil current sensing circuits. The isolated ADCs that transmit coil current and capacitor voltage information to the LM3S811 over a serial interface aren’t shown. Full schematics are available on the Circuit Cellar FTP site.

44 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2806016_Sterian.qxp 6/12/2008 8:59 AM Page 45

rate and the 32-bit team was able to launch a 3-cm-long, Timer2 for coil cur- 1/8″-diameter steel projectile more rent timing. Timer2 than 50′. I is used to drive state changes in a state Editor’s note: This project received machine that coordi- Honorable Mention in the Luminary nates coil current Micro Designstellaris2006 Contest turn-on and turn-off, (www.circuitcellar.com/designstellaris as well as the data 2006/). For pictures from Andrew recording process. Sterian’s circuit analysis class, go to The final compo- http://picasaweb.google.com/SterianA/ nent of the firmware GVSUW07EGR214CoilGunProject. is a VT102 interface Andrew Sterian ([email protected]) is library that translates an associate professor in the School of function calls such as Engineering at Grand Valley State vt_home() and University in Grand Rapids, MI. He Figure 5—This is a graph of coil current during a test launch, both with and vt_cursor_XY() obtained his PhD from the University without a projectile in the launching tube. The slight change in coil inductance into control codes rec- of Michigan (Ann Arbor) and has been due to the projectile is visible as a small disturbance in the current waveform. ognized by VT102 ter- teaching engineering courses for eight minal emulators. This years. Andrew owns Emsyde Design, provided all of the functions necessary for library enables you to construct a sim- an embedded systems design and con- accessing the hardware resources ple text-based graphical display with a sulting firm. In addition to embedded without having to dig into the details minimum of code (see Photo 2). systems hardware and firmware, his of the memory map or study all of the technical interests include anything bits in the control registers. The inte- WE HAVE A WINNER that gets students excited about science gration of the Keil development sys- This was a fun project to build and and engineering. tem with the evaluation kit made pro- play with. It was even more fun to see gramming and debugging simple, right my students come up with creative out of the box. It was a pleasure to not designs and implementations of their PROJECT FILES have to mess with programming own coil guns. I limited their designs To download code, go to ftp://ftp.circuit cables or convoluted debugging proce- to have no more than 100 J of energy cellar.com/pub/Circuit_Cellar/2008/216. dures. It was the first time I was able storage, so no one would be able to to single-step through code running on build a coil gun capable of propelling RESOURCES the target microcontroller with noth- projectiles through a metal can. (Refer ing more than a simple USB connec- to the video noted in the Resources B. Hansen, “Barry’s Design tion. With this kind of environment, section of this article.) The winning Site,” www.coilgun.info/home.htm. the firmware nearly J. Paul, “Coilgun Systems,” www.coil wrote itself. gun.eclipse.co.uk/index.html. In the main loop of the firmware, your YouTube, “Coilgun—Feature on Hacked key presses are Gadgets,” www.youtube.com/watch? received and translat- v=m86gK-EOEsQ. ed into actions. Every 0.5 s, readings of the SOURCES two capacitor bank ADuM3401 Digital isolator voltages are taken and Analog Devices, Inc. displayed on screen. www.analog.com The user LED on the evaluation kit is also HUF75645 MOSFET toggled as a heartbeat Fairchild Semiconductor Corp. indicator. www.fairchildsemi.com When you initiate a LTC1861 ADC firing sequence, the Linear Technology Corp. firmware enters a www.linear.com tight loop that uses Figure 6—This graph shows the difference between the two coil current wave- the 32-bit Timer1 for LM3S811 Microcontroller forms in Figure 5. The projectile in the launching tube increases the self induc- setting the data tance. When this reaches the first maximum, at about 9 ms, the projectile has Luminary Micro, Inc. recording sampling reached the center of the launch tube and the coil current should be turned off. www.luminarymicro.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 45 2806015_Tauraso.qxp 6/10/2008 4:28 PM Page 46

FEATURE ARTICLE by Carlo Tauraso Card Connection Magnetic Card Data Decoding And Transmission Almost a decade after he built his first magnetic stripe card reader, Carlo updated his design with a PIC18F2550 microcontroller. His new system is an inexpensive commercial TTL swipe card reader that reads, analyzes, decodes, and codes bitstreams.

In 1999, I built my first project with applied to an F/2F read/decode IC; and PC link will remain alive. a magnetic stripe card. The “Card the digital bitstream output from the Reader for a Parallel Port” (CRP) was a F/2F read/decode IC is decoded into a DESIGN & CONSTRUCTION small interface that connected from a human-readable format. This circuit represents a suitable TTL card reader to a PC printer port. The standard encoding scheme is “toolkit” for anyone willing to try A few years later, I developed the F/2F, which stands for “frequency- magnetic card information decoding. “Card Reader Mobile” (CRM) project, double frequency,” or “two frequency The card reader is a single-track ISO2 which used a serial port to communi- coherent phase recording.” All TTL KDR1000 distributed by CardCom cate with a cellular phone. It enabled swipe readers have an F/2F decoder Technology (www.cardcom.com). It me to send the card’s bitstream via the onboard, so if you want to extract a has a TTL interface and consumes less Short Message Service (SMS) or directly bitstream, you have to study the inter- than 10 mA. You can use practically to a PC. face with this chip. They all have the every kind of magnetic swipe card As the use of magnetic stripe cards same data interface. There are essen- reader with each TTL interface has continued to increase during the tially three communication lines: because they have the same or equiva- past eight years, I’ve been working on Card Loading Signal (CLS), Read lent F/2F read/decode chip. I tested new designs. Notebooks no longer Clock Signal (RCL), Read Data Signal the old OMRON V3A introducing have parallel and serial ports, so I’ve (RDT), plus power VCC (5 V), and only pull-up resistors. For card reader been developing my firmware/soft- GND. integration, you can identify pinouts by ware around a USB interface. My most RDT, RCL, and CLS signals are nor- reading datasheets or looking closely at recent project, which I call the “Card mally high. When the CLS goes low, the PCB. Reader USB” (CRU), serves as an inex- recording starts. When the CLS goes I disassembled my reader. Photo 2a pensive interface for a commercial high, it stops. During this time, the shows the PCB’s front side. The F/2F TTL swipe card reader (see Photo 1). It microcontroller inserts a bit into the read/decode chip is on the left. The also enables standard and proprietary stream when RCL is low. It is equal to pads on the right are for soldering a bitstream analysis. The system’s cir- 1 when RDT is low and 0 when RDT new one for other tracks. cuitry is built around a Microchip is high. For temporary buffering, it is Turning over the PCB, I discovered Technology PIC18F2550 microcon- more efficient to use an internal the pinouts. Photo 2b shows the bot- troller. I use ANACARD software to memory than an external FRAM or tom side of the PCB. The data and read, analyze, decode, and save every EEPROM. Normally, the stream clock lines are on the left. kind of coded bitstream. In this arti- length is not over 300 to 400 bits. I wired RDT, RCL, and CLS to the cle, I’ll describe the design. The PIC18F2550 has an internal PIC18F2550’s RB7, RB6, and RB5 pins RAM of 2,048 bytes, so it’s suitable (see Figure 1). All PORTB pins on the LET’S LEARN TO READ for recording all of the data from PIC18F2550 have weak pull-ups so The magnetic card reading process magnetic stripe cards. After record- you can enable them directly by involves three steps: the magnetic ing, it packs the data and then sends firmware. There is a specific register stripe passes under a read head; the it through the USB bus. During paus- called INTCON2 (bit7) to do this. analog signal from the read head is es, the PIC services the USB so the In this project, I use “Bus Power Only

46 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2806015_Tauraso.qxp 6/10/2008 4:28 PM Page 47

Enhanced Flash, USB Micro- Windows 98 SE on will recognize the a) controllers with nanoWatt device immediately. Technology.”) Capacitors C3 and C4 are FIRMWARE dimensioned according to The code is developed in microEngi- the Microchip Technology neering Labs’s PicBasic Pro Compiler “PIC18F2455/2550/4455/ 2.46, which is easy to use for PIC USB 4550: 28/40/44-Pin, High programming. The first task is to Performance, Enhanced write the descriptor tables. USB Flash, USB Microcontrollers devices have a hierarchy of data tables with nanoWatt Technology” called “descriptors,” which contain all datasheet. D1 and D2 are of the necessary information for the b) colored LEDs used to com- device identification and communica- municate the state of the tion. When you connect a device to a circuit to the user. When D2 free USB port, your PC enters a is on, the device is enumer- process called “enumeration.” It inter- ated correctly. D1 indicates rogates the device, extracting data a low-logic level on CLS, so from the descriptor tables. Without a it is on only when you successful enumeration process, your swipe a card. device will not be able to communi- Photo 1a—This is the final prototype. I swiped my European sanitary card R2 and R3 limit the cur- cate so it is useless. For example, a to test the board. All the information inside it is coded with ANSI 5 bits rent flowing through D1 and USB device has only one device standard code. b—This is the prototype board in a black box. The board is D2. RC5 and RC4 are direct- descriptor. It defines the vendor ID small, but I used a wider box than necessary. ly connected to USB data (VID) and product ID (PID). These lines. There are two alterna- numbers are an identification tag (like Mode,” so all of the power (5 V) is tive bus speeds: full (pull-up on D+) a database primary key). Without drawn from a USB. I use two small and low (pull-up on D–). I use an inter- them, your PC cannot identify the capacitors (C1 and C2) for filtering. A nal pull-up on D+ to specify Full- USB device. 20-MHz crystal is used as a reference Speed mode, so it is not necessary to If you look at the CRUDSC.asm file to generate the system clock. For full- insert another discrete component. on the Circuit Cellar FTP site, you speed USB operation, the clock source All components fit in a 60 × 25 mm will see that descriptors and other must be 48 MHz. The PIC18F2550 prototype board. I used a 3-mm LED, configurations are grouped in seven includes a phase-locked loop (PLL) mul- ceramic capacitors, and 0.25-W resis- tables. This structure is useful tiplier circuit designed to produce a tors to minimize the dimensions. I because you can reuse it with some fixed 96-MHz reference clock from a used a type-B USB connector so you minor changes to develop other HID fixed 4-MHz input. I use the prescaler can connect it with a canonical A-B devices. In short, there are seven main (PLLDIV2–PLLDIV0) to divide the USB cable. I mounted the circuit board descriptors: Device Descriptor, Con- 20-MHz primary frequency by five. The in a black plastic box (see Photo 1b). I figuration Descriptor, Interface resulting signal (4 MHz) goes to the PLL secured the card reader on the top Descriptor, HID Descriptor, Endpoint multiplier, which generates a 96-MHz with three little screws. Descriptor, Report Descriptor, and output. This signal is divided by two You can hold the box in your left String Descriptor. Unfortunately, I do using the postscaler (CPUDIV1–CPU- hand while you swipe the card. Photo 1 not have enough space to describe all DIV0). The result is the 48-MHz signal shows the final prototype with my of them. required for the microcontroller core European sanitary card. and USB module. (Refer to Table 2-3 in The device is a human interface ENDPOINT DESCRIPTOR the Microchip datasheet titled device (HID) so the installation is very The Endpoint Descriptor is one of the “PIC18F2455/2550/4455/4550: simple. Connect it to a free USB port. most important descriptors. It contains 28/40/44-Pin, High Performance, All Microsoft operating systems from key information for communication

a) b)

Photo 2a—This is the front side of the KDR1000 PCB. On the left is the F/2F chip. It is the equivalent of a 21006516 from MagTek. b—This is the bottom side of the KDR1000 PCB. The pinout sequence is on the left.

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 47 2806015_Tauraso.qxp 6/10/2008 4:28 PM Page 48

Figure 1—The circuit is simple. Be careful with the USB connector. An error can cause a short break on your PC’s USB port.

between the HID and your PC. Data is is capable of managing. CRU has 1 Report Size, and Report Count. Remem- directly moved from endpoint to end- byte for input packets and 1 byte for ber that the changes have to match the point, so here you specify the data output packets. Endpoint Descriptor specification (see transfer type and the data packet size. bInterval specifies the polling Listing 2). Regarding Listing 2, it is Every endpoint has a number and interval in frames (ms) for interrupt impossible to draw all of the concepts direction. Endpoint0 is bidirectional transfers. CRU is polled every 10 ms. around the Report Descriptor, so visit and is reserved for the enumeration the USB Implementer’s Forum process. CRU has two endpoints REPORT DESCRIPTOR (www.usb.org/developers/hidpage/) to (excluding endpoint0): EP1-IN (data The Report Descriptor is the sec- find all of the necessary documentation from HID to PC) and EP1-OUT (data ond most important descriptor. Here, about the subject matter. from PC to HID) (see Listing 1). you specify the data structure. It is a In my Report Descriptor, I specify a bLength is the size of the descriptor flexible descriptor so there is not a “Vendor-Defined” Usage Page and in bytes. I simply make the difference default scheme to follow. For Report Usage. The CRU is a generic HID between the end address label Endpoint2 Descriptor writing, you can use a free device so I cannot define a specific and the start address label Endpoint1 tool from the USB implementer’s Usage. Then I indicate a first-level divided by two. forum called “HID Descriptor Tool” Application Collection and a second- bDescriptorType identifies the (www.usb.org/developers/hidpage/dt2 level Physical Collection where I descriptor type. DSC_EP is a constant _4.zip). group my two data fields. I have 1 byte equal to 05h, declared in the file In my device, I specify an elemen- for input data and 1 byte for output USB18.INC. 05h stands for Endpoint tary structure that you can reuse by data, so I specify 255 for Logical Maxi- Descriptor. changing four fields for each I/O data: mum and 0 for Logical Minimum. My bEndpointAddress indicates the Logical Minimum, Logical Maximum, data packet length is 8 bits so Report endpoint you are describing. Bits 0 to 3 specify the endpoint number, bits 4 to 6 are reserved, set to 0. Bit 7 specifies Listing 1—This is the endpoint descriptor. The CRU is a human interface device (HID) with two endpoints. Look at bmAttributes for the endpoint type. the direction 0 = Out and 1 = In. Here, I have defined EP1-IN, so the binary Endpoint1 value is 10000001b = 81h. The second retlw (Endpoint2-Endpoint1)/2 ;bLength retlw DSC_EP ;bDescriptorType descriptor is for EP1-OUT, so I set bit 7 retlw 0x81 ;bEndpointAddress to 0. The result is 00000001b = 01h. retlw 0x03 ;bmAttributes bmAttributes indicates the trans- retlw 0x01 ;wMaxPacketSize(low-b) retlw 0x00 ;wMaxPacketSize(high-b) fer type. The USB device has four pos- retlw 0x0A ;bInterval sible values: 00h = Control, 01h = Endpoint2 isochronous, 02h = Bulk, and 03h = retlw (EndConfig1-Endpoint2)/2 ;bLength retlw DSC_EP ;bDescriptorType interrupt. The HID must have at least retlw 0x01 ;bEndpointAddress one endpoint IN with interrupt as a retlw 0x03 ;bmAttributes transfer type. Here, I specify 03h for retlw 0x01 ;wMaxPacketSize(low-b) retlw 0x00 ;wMaxPacketSize(high-b) each of the two endpoints. retlw 0x0A ;bInterval wMaxPacketSize is the maximum EndConfig1 packet size in bytes that the endpoint

48 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 49.qxp 5/27/2008 4:35 PM Page 1 50.qxp 6/5/2008 11:32 AM Page 1

ADVANCE PROGRAM HOT CHIPS 20 A Symposium on High-Performance Chips C H I P S August 24-26, 2008, Memorial Auditorium, 20 Stanford University, Palo Alto, California HOT CHIPS brings together designers and architects of high-performance chips, software, and systems. Presentations focus on up-to-the-minute real developments. This symposium is the primary forum for engineers and researchers to highlight their leading-edge designs. Three full days of tutorials and technical sessions will keep you on top of the industry. Morning Tutorial High Bandwidth Memory Technology & Systems Implications Organizing Committee Chuck Moore AMD (others TBA) Chair Craig Hampel Rambus Don Draper Rambus Vice Chair Afternoon Tutorial Scalable Parallel Programming with CUDA Keith Diefendorff Apple Ian Buck, Michael Garland, Patrick Legresley, Massimiliano Fatica NVIDIA

August 24 Finance Sunday Wen-mei Hwu Univ. of Illinois Lily Jow HP Multi-Core Technologies Publicity • MicroNetwork-Based Coherency: Extending Coherency over Standard Networks 3Leaf Sys. Kevin Krewell NVID IA • The Roofline Model: A tool for Auto-tuning Kernels on Multicore Architectures UC Berkeley Gail Sachs Telairity • Power-Performance Comparison of POWER5 &POWER6 Microprocessors IBM Advertising Keynote 1 Sebastian Thrun Allen Baum Intel • Cars that drive themselves Stanford Sponsorship Video & Media Amr Zaky Broadcom • SpursEngine - Cell Derivative High-Perf Stream Proc. for Media Acceleration Toshiba Publications • A 167-processor Array for Efficient DSP & Embedded Apps Processing UC Davis Gordon Garb Sun • PNX5100 System Arch & Apps: A High-Perf. Full HD 120Hz NXP Semi. Randall Neff • AMD mediaDSP: A Programmable Multicore Video Processor Platform AMD Registration Michael Sobelman Rambus Mobile Media Processing Local Arrangements • A 300-mW Single-Chip NTSC/PAL Television for Mobile Applications Telegent August 25

Monday Lance Hammond Apple • Voice Processor Based on Human Hearing System Audience • John Sell Microsoft NVIDIA APX2500: Enabling Stunning Handheld Graphics & HD Video NVIDIA Volunteers Supercomputing Charlie Neuhauser • PowerXCell 8i: A Cell Broadband Engine Architecture for Supercomputing IBM • Webmaster A Specialized ASIC for Molecular Dynamics D.E. Shaw Alexis Cordova Panel Ready, Fire, Aim - 20 years of hits & misses at Hot Chips Nick Tredennick CTO Nathan Brookwood John R. Mashey David Patterson Yusuf Abdulghani Spansion Dave Ditzel Howard Sachs Michael Slater Steering Committee Don Alpert Camelback Arch. Networking Allen Baum Intel • Low Cost 200Mbps Broadband Powerline Communications ChipSet DS2 Pradeep Dubey Intel • The QFP Packet Processing Chip Set Cisco Lily Jow HP PC Chips John Mashey Techviser • Howard Sachs Telairity AMD 780G, an x86 Chipset with Advanced Integrated GPU AMD Alan Jay Smith UC Berkeley • Micro-architecture of Godson-3 Multi-Core Processor Chinese Academy of Sciences • Inside Intel’s Next Generation Nehalem Microarchitecture Intel Program Committee Keynote2 Richard Swanson Program Co-Chairs • SunPower’s History and Technology SunPower Christos Kozyrakis Stanford U FPGAs Jan-Willem van de Waerdt NXP Semi Program Committee • Virtex-5 FXT, a New Field-Programmable Gate Array Platform Xilinx • Krste Asanovic UC Berkeley MAXware: acceleration in HPC Maxeler Forest Baskett NEA • New 40nm High Performance FPGA and ASIC Common Platform Altera Pradeep Dubey Intel uesday August 26 Will Eatherton Cisco

T Visual Computing • NVIDIA G100: TeraFLOPS Visual Computing NVIDIA Matt Farrens UC Davis • Larrabee: A Many-Core x86 Architecture for Visual Computing Intel Chuck Moore AMD Server Chips John Nickolls NVIDIA • Jose Renau UC Santa Cruz Tukwila: A Quad-Core Intel(R) Itanium(R) Processor Intel Mitsuo Saito Toshiba • SPARC64VII: Fujitsu’s Next Generation Quad-Core Processor Fujitsu John Sell Microsoft • Rock: A 3rd Gen 65nm, 16-Core, 32+32 Scout Threads CMT SPARC Proc. Sun Alan Jay Smith UC Berkeley Marc Tremblay Sun Please visit us on the web: http://www.hotchips.org Ralph Wittig Xilinx or drop us a line via Email: [email protected] Founder Bob Stewart SRE C H I P S 20 This is a preliminary program; changes may occur. For the most up-to- the-minute details on presentations and schedules, and for registration information, please visit our web site where you can also check out HOT Interconnects (another HOT Symposium being held following HOT CHIPS):

A Symposium of the Technical Committee on Microprocessors and Microcomputers of the IEEE Computer Society and the Solid State Circuits Society 2806015_Tauraso.qxp 6/10/2008 4:28 PM Page 51

Size is equal to 8. I use only 1 byte for absolute value. USB device. They are localized by a spe- input/output, so the Report Count is cific language ID (0409h = English). For equal to 1. For both fields, I specify a STRINGS DESCRIPTOR example, here you specify the device binary value equal to 000000010b = The Strings Descriptor indicates all of name (MAGCARD), the manufacturer 02h. It stands for Data Variable with the high-level information about your (Microchip Technology), the serial num- ber (T2A3U7), the configuration descrip- Listing 2—This is the report descriptor. Its structure is simple and you can reuse it for your own USB HID tion (CFG1), and the interface descrip- device. Remember to change the report size and report count fields. tion (EP1/INOUT). Every string has an index number reference. For example, ReportDescriptor1 the device name (String2) is referenced retlw 0x06 ;Prefix (bTag,bType,bSize) retlw 0x01 ;Usage Page (low-b)("Vendor-Defined-Page 1") from the iProduct (= 2) included in the retlw 0xFF ;Usage Page (high-b)("Vendor-Defined-Page 1") Device Descriptor. If you need more retlw 0x09 ;Prefix (bTag,bType,bSize) retlw 0x01 ;Usage ("Vendor-Defined-Usage 1") information about HID descriptor struc- retlw 0xA1 ;Prefix (bTag,bType,bSize) tures, please refer to the USB standard retlw 0x01 ;Collection ("Application") specifications (www.usb.org). retlw 0x09 ;Prefix (bTag,bType,bSize) retlw 0x02 ;Usage ("Vendor-Defined-Usage 2") retlw 0xA1 ;Prefix (bTag,bType,bSize) CODE DEVELOPMENT retlw 0x00 ;Collection ("Physical") Managing the USB interface in PicBa- retlw 0x06 ;Prefix (bTag,bType,bSize) retlw 0x02 ;Usage Page (low-b)("Vendor-Defined-Page 2") sic is simple. You must know three use- retlw 0xFF ;Usage Page (high-b)("Vendor-Defined-Page 2") ful instructions: USBInit to initialize retlw 0x09 ;Prefix (bTag,bType,bSize) the USB module of the PIC, USBIn to retlw 0x03 ;Usage ("Vendor-Defined-Usage 3") retlw 0x09 ;Prefix (bTag,bType,bSize) get any available USB data from an end- retlw 0x04 ;Usage ("Vendor-Defined-Usage 4") point, and USBOut to send bytes from a retlw 0x15 ;Prefix (bTag,bType,bSize) retlw 0x00 ;Logical Minimum (0) byte array to the USB endpoint. There is retlw 0x26 ;Prefix (bTag,bType,bSize) a particular function too: USBService. retlw 0xFF ;Logical Maximum (low-b) (255) USB code from Microchip is poll-driven retlw 0x00 ;Logical Maximum (high-b) retlw 0x75 ;Prefix (bTag,bType,bSize) not interrupt-driven, so USBService retlw 0x08 ;Report Size (8 bits) needs to be executed repeatedly to retlw 0x95 ;Prefix (bTag,bType,bSize) keep the link between the PC and the retlw 0x01 ;Report Count (1 campo dati) retlw 0x81 ;Prefix (bTag,bType,bSize) USB device alive. retlw 0x02 ;Input (Data,Var,Abs) So, let’s analyze my code. There are retlw 0x09 ;Prefix (bTag,bType,bSize) three main sections: Initialization, retlw 0x05 ;Usage ("Vendor-Defined-Usage 5") retlw 0x15 ;Prefix (bTag,bType,bSize) Reading Loop, and Sending loop. retlw 0x00 ;Logical Minimum (0) First, I disable the A/D PIC module retlw 0x26 ;Prefix (bTag,bType,bSize) retlw 0xFF ;Logical Maximum (low-b) (255) and specify that PORTA pins are all digi- retlw 0x00 ;Logical Maximum (high-b) tal I/O. You can do this with the ADCON0 retlw 0x75 ;Prefix (bTag,bType,bSize) and ADCON1 registers (see Listing 3). retlw 0x08 ;Report Size (8 bits) retlw 0x95 ;Prefix (bTag,bType,bSize) PORTA is configured as outputs to drive retlw 0x01 ;Report Count (1 campo dati) yellow and green LEDs (RA0 and RA2). retlw 0x91 ;Prefix (bTag,bType,bSize) RB7, RB6, and RB5 are configured as retlw 0x02 ;Output (Data,Var,Abs) retlw 0xC0 ;End Collection ("Physical") inputs for card reader data lines. After retlw 0xC0 ;End Collection ("Application") that, the PIC switches off both LEDs and EndReportDescriptor1 initializes the USB PIC interface by call- ing USBInit. After about 0.5 s, it clears Listing 3—This is the first firmware section: the initialization. Look at the TRISB configuration for card reader the stream buffer and switches on the output data lines. yellow LED. The device is ready for you to swipe the card into the reader. INIZIO: ADCON0=%00000000 I call USBService to keep the com- ADCON1=%00001111 munication channel between the PC TRISA=%00000000 and the device alive (see Listing 4). TRISB=%11100000 GIALLO=0 CONTA is a byte variable to count bits VERDE=0 received. CAR is a byte variable to USBInit temporarily save the 8 bits received. PAUSE 500 FOR X=0 TO 49 IND is the stream array index. Look at STREAM[X]= 0 the first while loop. The microcon- NEXT X troller executes the group of com- GIALLO=1 VERDE=0 mands while the card loading signal (CLS) is low. This signal is low when

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 51 2806015_Tauraso.qxp 6/10/2008 4:28 PM Page 52

you swipe the card, so the PIC switch- Listing 4—This is the second firmware section: the Reading loop. All bits from the card reader are packed into es on the green LED and starts bit a byte array called STREAM. recording. When RCL is low, the PIC executes a little assembly code portion RICEVI: USBService to record 1 bit into the CAR variable. It CONTA=8 saves a 0 digit when RDT = 1 (RB7) CAR=0 and a 1 digit when RDT = 0. For every IND=0 WHILE CL=0 bit, it rotates CAR left with no carry VERDE=1 and decrements the counter CONTA. IF RCL=0 THEN When CONTA is zero, the PIC has ASM btfss PORTB,7 received 8 bits, so it saves the byte bsf _CAR,0 into the stream array and updates the decfsz _CONTA,F rlncf _CAR,F index (IND). The loop continues until ENDASM the card-loading signal goes down. At the end it switches off the green LED. IF CONTA=0 THEN STREAM[IND]=CAR If the array index IND is not equal to IND=IND+1 zero, some bytes are temporarily saved CONTA=8 into the stream array (see Listing 5). CAR=0 ENDIF The PIC begins sending bytes by call- WHILE RCL=0 ing USBOUT. During the FOR loop, the USBService buffer is cleared for the next bit- WEND ENDIF stream. I prefer to send data, byte after WEND byte, and frequently call USBService. VERDE=0 After that, the program execution jumps to the label RICEVI at the head of the Reading Loop. Now, you can declarations from Microsoft Developer my code. swipe another card. Network Microsoft Driver Develop- ment Kit (DDK). When you develop BITSTREAM ANALYSIS SOFTWARE ANALYZER software for a generic HID device, you How can I decode a proprietary bit- With ANACARD v.5, you can read, work at the user level and you have stream? There are many approaches to analyze, and save a datastream from to link only your application to the this problem. I used frequency charac- magnetic cards. Decoding information HID.dll. In Kernel mode, there is one ter repeating. Normally, you can guess with nonstandard encoding is interest- supplied class driver (HIDCLASS.sys) the information encoded from the ing. The system is based on keyword with a parser (HIDPARSE.sys) to card application field. You can sup- research and frequency repetition of elaborate USB requests. At the lower pose that the stream information the same binary sequence. I developed level, there is a MiniPort driver includes your name, a serial number it in C# for .NET 2.0 using Microsoft (HIDUSB.sys) that works with the printed on the card, the tax ID printed Visual Studio. For this project, I USB hardware port. The TAUHID on your bill, and so on. Every charac- declared a new class, called TAUHID, class incorporates structures and ter has a particular binary sequence, which incorporates all of the neces- interfaces to HID.dll API functions. so if you repeat the same character in a sary interfaces to HID.dll API. When On the ’Net, you can find numerous string, the same binary sequence will be you develop firmware for the HID, HID sample codes for VB.NET, C#, VB6, repeated too. Otherwise, if a character is you do not have to develop low-level and C++ (www.lvr.com/hidpage.htm). unique, the corresponding binary drivers for it. The device uses the driv- After providing this short description sequence will be only one time. This er included in Windows. about USB developing, I want to focus function of ANACARD looks for these HID.dll is a system library that con- your attention on one key section of repetitions and no repetitions in the tains several API functions to commu- nicate with a HID. For example, call HidD_GetAttributes to retrieve the Listing 5—This is the last firmware section: the Sending loop. All of the bytes from the STREAM array are sent through the USB port. Look at the USBService call to keep the communication channel alive. HID’s vendor ID and product ID. When you want to read data, call IF IND<>0 THEN HidD_GetInputReport. It returns an FOR X=0 TO IND CAR=STREAM[X] input report from a HID collection. STREAM[X]= 0 On the other hand, if you want to write INVIA: USBService data, call HidD_SetOutputReport. It USBOUT 1,CAR,1,INVIA NEXT X sends an output report to a HID collec- ENDIF tion. You can find all of the information GOTO RICEVI about calling parameters and function

52 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2806015_Tauraso.qxp 6/10/2008 4:28 PM Page 53

powered card reader with flash memory to keep the bitstreams read. The USB port will be used only for downloading data and recharging the battery. I hope to share my next PIC experi- ence with all of you. For the time being, I hope you have fun with CRU and ANACARD. I

Carlo Tauraso ([email protected]) wrote his first assembler code in the 1980s for the Sinclair Research ZX Spectrum. Today, he is a senior soft- ware engineer. Carlo also does firmware development on network devices and various kinds of microint- erfaces for a range of European compa- nies. Several of Carlo’s articles and pro- gramming courses about PICs (USB- PIC, CAN BUS PIC, SD CARD, C18) have been published in Italy, France, and Spain. In his spare time, Carlo enjoys playing with radio scanners and his homemade metal detectors.

Photo 3—I prefer C# Visual Studio Express for application development on the .NET framework. It’s free and efficient. PROJECT FILES To download code, go to ftp://ftp.circuit cellar.com/pub/Circuit_Cellar/2008/216. stream attempting to associate the A/D external chip, transmit data by a binary sequence with the relative Bluetooth module, and so on. More- character. over, the descriptors sequence RESOURCES You can experiment with different (CRUDSC.asm) is a base for other J. Axelson, “The HID Page: Resources for character bit lengths and different ini- HID firmware development. For Developers of USB Devices in the Human tial cut bits to find your checkstring in example, I used only 1 byte for inputs Interface Device Class,” Lakeview different bitstream parts. Bitstreams and 1 byte for outputs. But if you Research, www.lvr.com/hidpage.htm. and check strings with more repeti- change the wMaxPacketSize value tions are the best for decoding. This is (endpoint descriptor) and the report Microchip Technology, “PIC18F2455/ only one approach, it may not be the count (report descriptor), you can 2550/4455/4550: 28/40/44-Pin, High best, but at the moment, I have decod- develop more complex structure Performance, Enhanced Flash, USB ed all of my wallet cards. Photo 3 packets. Microcontrollers with nanoWatt Tech- shows the “Analyze Stream” form sec- You can just read your ATM card nology,” DS39632D, 2007. tion during design. For more details, too. Swipe all of your own plastic please refer to the files posted on the cards and try to find the information in SOURCES Circuit Cellar FTP site. them. You’ll learn how systems identify ISO2 KDR1000 PCB you as a user or simply how they run CardCom Technology, Inc. FUTURE PLANS your credit. Please, don’t try to grab www.cardcom.com This project is an interesting meet- other users’ information for illegal pur- ing point between old magnetic stripe poses. I’m doing all of this for the sole PIC18F2550 Microcontroller technology and new PIC features purpose of improving my firmware/soft- Microchip Technology, Inc. such as the USB interface. It is an ware development skills. If you are www.microchip.com open project because you can reuse interested in reading more details about PicBasic Pro compiler 2.46 the schematic as a starting point for CRU software and firmware develop- microEngineering Labs, Inc. other designs that involve HID ment, you can download them from the www.microengineeringlabs.com devices. For example, if you discon- Circuit Cellar FTP site. For device nect the PORTB wires from the card installation and ANACARD, refer to HID Descriptor tool reader, you can use the four digital the program’s Help button. USB Implementer’s Forum, Inc. outputs to control a four-relay power I plan to improve the design’s mobility www.usb.org/developers/hidpage/dt2_ interface, communicate with a 16-bit in the near future. I will create a battery- 4.zip

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 53 2806018_kagan.qxp 6/10/2008 4:31 PM Page 54

FEATURE ARTICLE by Aubrey Kagan Create A Modbus Slave

Several months after creating a Modbus master, Aubrey continues his Modbus exploration by creating a Modbus slave on a Cypress PSoC microcontroller. To enable you to change configurations or speed up the CRC generation, he describes three different methods of slave creation.

Having written a two-part series slave’s design (obviously, this may it: data rate, number of stop bits, and last year about the creation of a Mod- require data manipulation to fit with parity. Confidence in the integrity of bus master (“Generic Modbus Simu- the 16-bit register format), as well as the message is provided by a 2-byte lator,” Circuit Cellar 200/201, 2007), relays and proximity sensors. The CRC that is attached to the end of the it would seem logical that I would master controller reads and writes to transmission frame. So, strictly speak- have published a loosely linked third the registers contained in the slave ing, parity is not required. The maxi- part—about a Modbus slave—shortly that are being addressed over the seri- mum length of a Modbus packet is after. Apparently, my logic is flawed al network. 256 bytes. The specification requires because it took quite a while and The register map of the slave is 3.5 transmission bytes length between another Modbus project for the also left to the slave designer. (By Modbus packets for synchronization. penny to drop. that I mean the designer of the slave The gap between two characters in a I created the Modbus slave on a module and not the salary that you frame should not exceed 1.5 charac- Cypress Semiconductor CY8C27243 receive.) I will discuss this in more ters lengths. When the data rate goes PSoC microcontroller, but it has detail later. Generally, the slave’s reg- above 19,200, the time periods been developed almost completely in isters are presented as a table to doc- become fixed values. C (see Figure 1). If you are porting it ument the address space for the net- The Modbus transaction consists of to another microcomputer, there work integrator. a master sending a packet to an should be no problem. The PSoC has The Modbus serial protocol standard addressed slave and then waiting for the ability to generate the cyclic allows for communications to be in and receiving a response. When a slave redundancy check (CRC) in hard- ASCII format or transmitted in 8-bit receives a command, it responds pro- ware, so in addition to the universal bytes (RTU format). The ASCII format vided the address matches and the software approach, I will also is optional, but all Modbus units must CRC is correct. If there is an error in describe an approach that is unique be capable of supporting the RTU for- the instruction (provided these two to the PSoC and can significantly mat. That is why I am going to con- criteria have been met), it responds speed up the CRC generation. A sider only the RTU format. with an exception message indicating third approach will demonstrate The serial port hardware interface the problem. In some cases, it may PSoC flexibility by dynamically has several parameters associated with take time for the slave to complete changing its configuration.

MODBUS OVERVIEW In its simplicity, Modbus catego- rizes I/O space as single-bit digital (coils) registers or as 16-bit registers. Interpretation of holding registers and input registers (16 bit) is left to the designer of the slave. The registers could be used for ADC values or other functions, as determined by the Figure 1—The hardware for the project needs only an external RS-485 interface.

54 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2806018_kagan.qxp 6/10/2008 4:31 PM Page 55

the instruction. In this case, the For the project, I created an imaginary compiler is extra.) Simply select the exception code is an “Acknowledge.” slave with the Modbus map (see Table 1). type of user module (UM) that you In a normal operation, if the transmis- In the additional information, you can want, place it in a digital or analog sion fails either through a lack of see the actual address that will be block (or blocks), and configure the response or an exception response, it transmitted in the “Physical Address” associated parameters and interconnec- is up to the master to act on this by column along with the associated tions to suit the application. Photo 1 reporting a problem and/or attempting commands that can be used, as well as shows the initial configuration. At the a retransmission. the function codes that will be used. outset, however, the SPIM and The Modbus message format is CRC16 modules are not used. The explained in greater detail in my Cir- USER MODULE CONFIGURATION EEPROM module is residual and is cuit Cellar 200 article (and, of course, The PSoC controller consists of a not used in this project. A timer is in the Modbus specification), but I series of logic and analog blocks that needed to generate a “tick.” The would like to remind you of the can be configured to suit your needs UART is obviously for serial commu- addressing quirk sometimes used in precisely. The configuration can be nication and the counter is used as a Modbus systems. Each one of the differ- handled with PSoC Designer, free soft- data rate generator. ent types of Modbus I/O is assigned to a ware available from Cypress. (The C One of the core concerns of the Modbus different address space. Single-bit I/O occupies 0–10,000, single-bit input is allocated 10,001–30,000, 16-bit register Item description Modbus Physical Read command Individual write Block write address address code command code command code inputs fill 30,001–40,000, and 16-bit I/O Coil1 2 1 1 5 15 fill out the rest from 40,001–65,534. Coil2 3 2 1 5 15 The quirk is that the addresses are off- Coil3 4 3 1 5 15 set so the actual address transmitted Coil4 5 4 1 5 15 over the Modbus is created from the Coil5 6 5 1 5 15 actual address minus the base of the Coil6 7 6 1 5 15 associated address space. For example, Coil7 8 7 1 5 15 address 30,194 is transmitted as Mod- Coil8 9 8 1 5 15 bus address 193 (30,194–30,001), so Coil9 10 9 1 5 15 care must be taken to not have over- Coil10 11 10 1 5 15 lapping addresses. Coil11 12 11 1 5 15 HARDWARE & SOFTWARE Coil12 13 12 1 5 15 Coil13 14 13 1 5 15 The only hardware associated with Coil14 15 14 1 5 15 this project is the interface to the seri- Coil15 16 15 1 5 15 al bus. It consists of an RS-485 inter- face IC hooked up to the PSoC (see Digital input1 10020 19 2 n/a n/a Figure 1). Digital input2 10021 20 2 n/a n/a Generating the Modbus memory map Digital input3 10022 21 2 n/a n/a is a creative exercise. Remember that if Digital input4 10023 22 2 n/a n/a you have a large number of contiguous Digital input5 10024 23 2 n/a n/a Modbus locations, the resulting mes- Digital input6 10025 24 2 n/a n/a sage can occupy many bytes of RAM Digital input7 10026 25 2 n/a n/a because the message is buffered. Con- Digital input8 10027 26 2 n/a n/a flicting with this reality, when you Digital input9 10028 27 2 n/a n/a cross-reference the PSoC resources Digital input10 10029 28 2 n/a n/a (RAM, I/O, flash memory, and peripher- als) to the Modbus addresses, it helps if ReadOnly register0 30050 49 4 n/a n/a you try to create them as contiguous ReadOnly register1 30051 50 4 n/a n/a blocks. Otherwise, you will find that ReadOnly register2 30052 51 4 n/a n/a handling the Modbus block accesses ReadOnly register3 30053 52 4 n/a n/a can prove memory consuming, as you will see in the associated project. ReadWrite register0 40060 59 3 6 16 I know my code in the project is far ReadWrite register1 40061 60 3 6 16 from optimized. It forms the most ReadWrite register2 40062 61 3 6 16 general case to allow almost any vari- ReadWrite register3 40063 62 3 6 16 able to be tied to a Modbus location, Table 1—This is a fictitious Modbus map created especially for this project. The address offset of the different regis- but it is up to you to streamline the ter spaces in the Modbus address column is translated to an address shown in the Physical address column. There approach once you understand it. are intentional gaps between the register spaces, so range access commands cannot span the different range types.

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 55 2806018_kagan.qxp 6/13/2008 11:14 AM Page 56

receives its data in a serial format and needs a serial-to-parallel module called an SPIM (the “M” is for “mas- ter”). It results in a much faster method of generating the CRC, but it is expensive in PSoC resources, using three digital blocks, as you can see in Photo 1 (DBB00, DBB01, and DBB02). I will go into more detail soon, but while I am on the subject of configu- ration, I want to introduce a third approach. The user modules on the PSoC are loaded in a register structure, so they can be dynamically changed. Because the CRC and the data communica- Photo 1—This is the user module layout. The SPIM is used to provide the serial input to the CRC generator, but tions do not occur simultaneously, it both are required only for hardware CRC generation. The data rate to the UART is derived through Counter8. The overall system timing is derived from a “tick” produced by an interrupt from Timer8. is possible to share the three digital blocks between the two functions. You can see the three individual con- is the reliability of the communica- look-up table or looping code (the figurations in Photo 2. tions. It is addressed by the use of a CRC is generated in software, bit by CRC. I have taken three approaches bit). Both are detailed in Modbus doc- SOFTWARE SPECIFICS to creating this Modbus slave in two umentation. The former is quick To allow different tasks to be exe- examples. They differ only in the while the latter needs much less cuted “simultaneously,” I use a sim- generation of the CRC. The first cre- memory. ple cooperative multitasking scheme ates the CRC using only software. One of the user modules on the where each task has an assigned There are two possible solutions: a PSoC is a CRC16 generator, which “number.” Using a counter and a switch statement in C enables each task to be executed in sequence. In each task, there are several states. The state that is to be executed is selected using the standard C switch mechanism. You will find this in the main.c module on the Circuit Cellar FTP site. In the project, where I developed this software, I was measuring the RMS value of a signal, so I wanted to minimize any time spent in inter- rupt routines not associated with the data acquisition. To this end, I allowed only a timer “tick” and an interrupt for the reception of a serial character. (Refer to the Serial_Rx interrupt procedure in serial.c.) The incoming character was simply shipped into a buffer with no further analysis in the interrupt routine. The inspection and interpretation of the incoming Modbus message, as well as the transmission of the response, was left as a series of tasks in the serial procedure. The tick is initialized to occur every 0.5 ms. This is quite a short period, but it is required for some of the Modbus timing requirements.

56 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2806018_kagan.qxp 6/10/2008 4:31 PM Page 57

b) a)

Photo 2—These are the three configurations. The configuration entitled mod2 is the base layout and continues to operate without being affected when the CRC and seri- al configurations are loaded and unloaded. Note that they use the same resources. Each configuration is selected by clicking on the associated tab at the top of the screen.

c)

The UART is configured to run at and is not implemented here. message. The CRC is generated 9,600 bps, with 1 stop bit, 8 data bits, through a 16-bit shift register. The and no parity. The Modbus specifica- CRC GENERATION value of the CRC is preset with a seed tion calls for 2 stop bits if there is no As promised, I am going to pay value. Data from an earlier stage on parity, but I know of no hardware UART some attention to the CRC that is the register can be fed straight through that actually checks for the second bit added to the end of every Modbus to the next stage or passed through an

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 57 2806018_kagan.qxp 6/10/2008 4:31 PM Page 58

exclusive-OR gate (together with the CRC Method Number of execution cycles Comment incoming data). The pattern of the Software look-up table 2,363 Fast, but needs 500 bytes of extra code exclusive-ORs is determined by the Software shift register 5,566 Slowest, but compact code CRC polynomial, where a “1” in the Hardware CRC (no overlay) 1,933 Fastest, but uses three logic blocks polynomial determines the presence of Hardware CRC (with overlay) 3,135 Quite fast, could possibly be improved by the gate. optimizing configuration change in assembler Documents of the Modbus adminis- Table 2—These are implications of different CRC approaches. Actual cycles may vary slightly depending on the actual data. tering organization detail exactly how to generate the CRC in software. The first approach uses look-up tables and is space. Both methods (CRC_TypeA for available if you prefer to use them. fast, but it requires more than 500 bytes the look-up table method and To speed up the CRC calculation, I for the look-up tables alone. The sec- CRC_TypeB for the shorter approach decided to use the CRC16 user mod- ond is slower but uses much less code in the software module Modbus.c) are ule, which I presumed would be a slam dunk. This was not to be. The CRC16 user module requires data shifted synchronously into its regis- ters. Because the UART communica- tion includes stop and start bits, it is No other PCB-design tool gives you not possible to feed the UART datas- more value per dollar tream directly to the CRC module. An Boards designed under EAGLE are developed in one-man alternate approach is to feed the businesses or in large industrial companies. Most of the top CRC16 hardware from a SPIM module companies are our customers. The crucial reason for selecting EAGLE is not usually the low price, but rather the high-end using the same data that is communi- functionality along with the ease of use. And EAGLE users cated through the UART. The data appreciate the outstanding level of support, which at rate of the SPIM shift is set to the CadSoft is always free of charge, and is available New Version without restriction to every customer. maximum of 12 MHz, so it is shifted These are the real cost killers! EAGLE 5.0 out quickly. The software must load Version 5.0 is even easier to use, especially for Schematic Capture • Board Layout each byte received or transmitted into beginners, due to an enhanced user interface. Autorouter the SPIM and then read back the ®®® resulting CRC once the entire mes- for Windows Linux Mac Version 5.0 Highlights sage has been written. This process is, >Stand-alone schematic editor available. of course, in addition to the data being >Automatic signal/contact cross read from or written to the UART. references using frame coordinates. The CRC generator on the PSoC is >Right-mouse click for more consistent Windows UI. not directly compatible with the Mod- >User-definable attributes for parts. bus CRC, but with a little massaging, >Schematic sheet management. it can be simply realized. I am indebt- >Hiding approved DRC and ERC errors. ed to Ganesh Raaja at Cypress who >PRINT preview and text-searchable patiently helped while I crunched my PDF output. way to this solution. In the end, the >Improved search engine for help. way to generate the CRC was to use >And much, much more. the polynomial 0xC002 and the seed 0xFFFF (which is normal for the Mod- Pick the level that is right for you — pay only the difference for upgrades! bus). The data was shifted out of the Light Standard Professional SPIM least significant byte first. Then, Standard and Light Editions Max. number of 1 99 999 in a final twist (pun intended), the schematic sheets have full functionality except Max. board size 4x3.2 inch 6.4x4 inch 64x64 inch for the limitations mentioned resulting bits of the CRC had to be Max. # of signal layers 24 16in the table. reflected so that bit 15 became bit 0, Layout or You can use EAGLE Light for Schematic Editor $249 $498 bit 14 interchanges with bit 1, and so evaluation and non-commercial Layout and applications without charge. forth. The code to do this reflection in Schematic Editor $498 $996 Download it from our web site. C is still in the program, but it’s com- Layout Editor and $498 $996 Autorouter mented out because it nearly doubled Layout Editor and Schematic Editor $49 $747 $1494 the execution cycles because C and Autorouter www.cadsoftusa.com 800-858-8355 ignores the fact that the carry bit is affected in a data shift. I added an CadSoft Computer, Inc., 19620 Pines Blvd., Suite 217, Pembroke Pines, FL 33029 optimized assembly procedure to Hotline (954) 237 0932, Fax (954) 237 0968, E-Mail: [email protected] speed up the process by shifting the Windows / Linux / Mac are registered trademarks of Microsoft Corp. / Linus Torvalds / Apple Computer, Inc. source register out through the carry

58 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2806018_kagan.qxp 6/10/2008 4:31 PM Page 59

bit and then shifting the carry bit unloaded and the CRC configuration project Mod2. onto the destination register. This is loaded. At the completion of the Depending on the utilization of the CRC calculation is called CRC_TypeC CRC calculation, the CRC module is processor, speed may be an issue, as well in project Mod1. unloaded and the UART configura- as code space. Table 2 provides a As discussed earlier, it is possible tion is reloaded. This loading and comparison of the different possibilities. to economize on PSoC resources by unloading has the disadvantage that overlaying the CRC generator and the change takes some time. The STATE DESCRIPTION the UART. The PSoC is configured configuration and operation of the Most of the Modbus action occurs with a UART most of the time, but modules in the initial Mod2 configu- in the serial() procedure in the when the CRC needs to be calculat- ration are unchanged. This CRC cal- serial.c module, which as the name ed, the UART configuration is culation is also called CRC_TypeC in suggests, deals with the serial com- munications of the project. The states in the procedure are summarized in Listing 1—The action taken in State 4 depends on the received command code stored in cSerBuff[1]. There are only a few valid codes; otherwise, an ILLEGAL FUNCTION exception message is returned. This listing is extremely Table 3. condensed. One of the commands is shown in more detail in Listing 2. State 4—which is shown much sim-

case 4: plified in Listing 1—is perhaps the //reaching here means we have to send a response, either the answer to most difficult to follow. Once the the message or an exception response. CRC and command issues have been //Depending on the command received/the message may be accepted or rejected resolved in earlier states, the slave switch (cSerBuff[1]) must analyze if the addressed range { received is within its address range. case 0x01: //read coil(s) (I/O space) The way the address is generated is . . command dependent, so I first had to . break; create a case (within a switch state- ment) for each command (see Listing 1). case 0x02: //read input(s) (Input only space) . Coils and discrete inputs (bits) and . . registers (16-bit words) received over break; the Modbus must be handled differ- case 0x03: //16 bit holding register(s) (I/O space) ently, because the bits are packed into . . bytes. And, of course, it is also possi- . break; ble to address a single location using different commands. So, you can see case 0x04: //read input register(s) (Input only space) . that there is not a lot of commonality . . between the processing required for break; the different commands and almost case 0x05: //Set/Reset single coil (I/O) every one needs individual code. If . . you create the slave memory map so . break; there are no bit accesses or registers, you can reduce or at least optimize case 0x06: Set value on a single 16 bit holding register (I/O) . the amount of code needed. However, . . I have tried to present the most gener- break; al case that I can, so there is a lot of case 0x0f: //Set/Reset multiple contiguous coils (I/O) code here. Because of space con- // See Listing 2 . straints and my short attention span, I . . will restrict myself to describing only break; one of the cases in detail. case 0x10: Set value to multiple 16 bit holding registers (I/O) Listing 2 shows the code associated . . with setting multiple coil outputs. The . break; 16-bit starting address of the I/O (as opposed to the module Modbus address) default: is extracted from cSerBuff[2] and //any other command received cSerBuff[3] and saved on the variable //will result in an IILEGAL FUNCTION message iI. This address is inspected to see if it ExceptionResponse(ILLEGAL_FUNCTION); is within the coil address space (00000- break; 10000), as defined by the constants } BOTTOM_00000 and TOP_00000, which are declared in a header file. The next break; step is to check if the end of the range

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 59 2806018_kagan.qxp 6/10/2008 4:31 PM Page 60

State number Description 0 Initialize hardware and software for serial reception. 1 Wait for a sync time of 3.5 characters, the time between Modbus frames, to allow detection of the first byte of frame. 2 Once the first byte and the unit address match, save every incoming byte to a buffer until the message is complete. This is a little problematic because some Modbus messages are fixed-length and others have the number of bytes embedded in them. The task is self-modifying in that when sufficient bytes have arrived, the number of expected bytes is adjusted according to the buffer contents. Once the full message is received, the next state is entered. 3 Validate the incoming CRC. If valid, then invoke the next state. Any failure in reception up to this point results in no slave response on the Modbus. Once it passes state three, there must be a response, even if it is an exception response when an error has occurred. 4 The process is split into substates based on the command that has been received (and resides in the second byte of the reception buffer). The message is validated for the memory space of the slave and a response is prepared. If there is an error or delay in execution (e.g., writing to the EEPROM), an associated exception response is prepared. Otherwise, an acknowledge/data message is prepared. 5–9 Not used 10 Initialize transmission of data, without enabling RS-485. 11 Send 3 more bytes of data, without enabling RS485. This makes for an easy way of measuring the inter-frame gap, independent of the data rate. 12 Start sending the response of RS-485 (enabled as the last step of state 11). 13 Send the complete message buffer. When the last message has been transmitted, the RS-485 must be turned around. The PSoC has an issue in that when the flag TX_COMPLETE goes true, the message has not completely cleared the microcontroller, so turning RS-485 around here would destroy the message. A timer is started based on the scan time of the tasks. 14 When the defined number of cycles is complete, the state is returned to 0. State 0 will restore the RS-485 direction. If any system update is required, such as writing to the EPROM, it can now be done because the acknowledge response has gone to the host.

Table 3—These are the states in the serial task. Each time the serial() procedure is executed only one of these states is executed. Like all state machines, the decision to change states or remain in the same state is based on evaluating certain inputs specific to that state.

of outputs also falls within the permit- can be only 1 or 0, so verification isn’t sequence has been validated, the slave ted range of the module. This is done done. can issue an “acknowledge” message by creating the number of addresses The next step is to align the actual to indicate that there are no issues on the variable iJ derived from the outputs in the slave that will be and that it will be “offline” until the received data and cSerBuff[4] and changed with the initial address in the update is complete. There is no method cSerBuff[5]. The upper address is Modbus command and then change of indicating how long this would be, then stored on the variable iK and the output value(s). The initial address but it does not preclude the slave from that is compared to the module limits, is stored on iI and the number of out- answering polls during the update peri- as above. In either event, if the address puts is stored on iJ (from earlier). od. In Listing 2, where the response is falls outside the permitted range, an This is a little complicated because immediate, it is prepared with the exception response is prepared for the actual output values are com- FinaliseTransmit() procedure. transmission in a later state. pressed into 8-bit bytes, but that can Aside from the actual length of the span many outputs, so the challenge MODBUS MASTER SIMULATION serial buffer, which could easily fill up is to extract several (up to 8) bits from Testing the slave requires a tool to a good chunk of RAM, if you have gaps a byte and then bump to the next send and receive the data. If you don’t in the register map, each address needs byte. Initially, a mask is set up on the have an existing setup, there are some to be validated, which is much more variable iK and the pointer to the first tools on the Modbus organization’s complicated. There would have to be data byte at location cSerBuff[8] is web site. Of course, there is also my code to check for illegal access to the set on variable cPoint. The truncated creation implemented on a PC (Cir- nonexisting memory in the middle of code in Listing 2—based around the cuit Cellar 200 and 201). The Modbus the range, as well as the beginning and for (cI=0;cI<(unsigned char)iJ; slave project includes a copy of the end conditions. Hence, my advice is to cI++) clause—shows how to do this. Excel worksheet for this project think long and hard about the map. The actual bit that will be modified (Slave.xls), which is an implementa- My code has not considered any gaps on the slave module is handled by tion of Table 1. within a specific range. each case in the switch statement. Despite its age, Modbus is still a Other checks the software could Each iteration through the switch viable option for data intercommuni- perform include the validity of the statement results in the mask iK cation. It is simple, well documented, data that has been received. A 12-bit being rotated every eighth time. The easy to implement, and plenty of DAC cannot accept a number greater mask is reset and the pointer to the manufacturers still support it. It even than 4,095. Any error you receive incoming message array cPoint is has undergone a makeover to become must be classified as one of the pre- incremented. Modbus/TCP, which is effectively defined error types, as I explained ear- Some operations may take time to Modbus on the Ethernet. Only the lier, although this can be limiting at execute. For instance, you may want communication medium is different, times. Because this code snippet deals to update some EEPROM settings and at the application level, the Mod- only with digital outputs, the values over the Modbus. Once the reception bus looks the same. Even though this

60 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2806018_kagan.qxp 6/10/2008 4:31 PM Page 61

Listing 2—This is an edited version of how to process the command to write to several coil outputs. The out- hints at an article on the subject, I think puts are compressed from bit form into bytes, so checking the limits and decompressing makes this one of the I will give Modbus a rest for a while. I more complicated commands to code.

case 0x0f: Aubrey Kagan ([email protected]) //write multiple coils //in this project, there is only 1 valid address is a professional engineer with a B.S.E.E. //and so the address must be 0 from the Technion—Israel Institute of //and there is only one location to read iI=((unsigned int)cSerBuff[2])<<8; Technology and an M.B.A. from the //constucting msbyte University of the Witwatersrand. He iI |=(unsigned int)cSerBuff[3]; //iI has 16 bit value works at Emphatec, a Toronto-based if ((iITOP_00000)) design house of industrial control inter- {//at this juncture the base address is invalid, so construct //IILEGAL DATA ADDRESS message faces and switch-mode power supplies. ExceptionResponse(ILLEGAL_DATA_ADDRESS); In addition to writing several articles } else { for Circuit Cellar and having ideas pub- iJ=((unsigned int)cSerBuff[4])<<8; lished in other periodicals, Aubrey //constucting msbyte iJ |=(unsigned int)cSerBuff[5]; wrote Excel by Example: A Microsoft //iJ retains the number of input registers Excel Cookbook for Electronics Engi- iK=iJ+iI-1; if ((iKTOP_00000)) neers (Newnes, 2004). {//at this juncture the top address is invalid, so construct ExceptionResponse(ILLEGAL_DATA_ADDRESS); } else { PROJECT FILES //This is a generic approach //based on a maximum of 15 bits To download code, go to ftp://ftp.circuit cellar.com/pub/Circuit_Cellar/2008/216. // iK=0x01; //set a mask cPoint=8; //and a pointer for lookup

for (cI=0;cI<(unsigned char)iJ;cI++) RESOURCES {//this is a generic (and memory expensive) way to do this //on a specific application there may be ways to simplify it. Cypress Semiconductor Corp., “16-Bit CRC Generator: CY8C29/27/24/22xxx switch (iI+cI) { Data Sheet,” 2004. case BOTTOM_00000: if (cSerBuff[cPoint] & iK) A. Kagan, “Generic Modbus Simulator {//note: LS byte transmitted second cRW_BitAddressable0 |= 0x02; (Part 1): Theory and Preparation,” Circuit } Cellar 200, 2007. else { cRW_BitAddressable0 &= ~0x02; } ———, “Generic Modbus Simulator break; (Part 2): Create a Modbus Master Using case BOTTOM_00000+1: //the response is the same as the message Visual Basic 2005,” Circuit Cellar 201, if (cSerBuff[cPoint] & iK) 2007. {//note: LS byte transmitted second cRW_BitAddressable0 |= 0x04; } Maxim Integrated Products, Inc., else { “Application Note 27: Understanding cRW_BitAddressable0 &= ~0x04; } and Using Cycle Redundancy Checks with Maxim iButton Products,” 2001. break; . . Modbus-IDA, “Modbus Application Pro- . tocol Specification,” V1.1a, 2004, www. default: break; modbus.org/docs/Modbus_Application_ } Protocol_V1_1a.pdf. if (iK==0x80) {//rollover to next byte //beware if extending this to over 16 bits ———, “Modbus over Serial Line: //since cPoint must jump ahead every 16 bits iK=1; Specification & Implementation cPoint--; Guide V1.0,” 2002, www.modbus.org/ } else { docs/Modbus_over_serial_line_V1.pdf. iK=iK<<1; } } //the first 6 bytesof the response remain the same SOURCE //the balance is truncated FinaliseTransmit(6); CY8C27243 Microcontroller and } PSoC Designer } break; Cypress Semiconductor Corp. www.cypress.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 61 2807017_paiano.qxp 6/10/2008 4:35 PM Page 62

FEATURE ARTICLE by Chris Paiano PSoC Design Techniques (Part 1) Build An Eight-Channel Mixer

Ready to learn several useful PSoC design techniques? Chris describes a switched capacitor and continuous time modules. He also walks you through an interesting PSoC project: an eight-channel mixer with adjustment knobs.

The Cypress Semiconductor PSoC can be ADCs and DACs of varying family of microcontrollers provides a resolution, fully configurable op-amps, powerful mixed-signal capability with analog buffers, filters, and more. There both analog and digital user modules. is even a “Generic SC” module avail- This allows for some rather unique able, which enables direct access to all single-chip solutions. However, a switches and capacitance values in the Photo 1—This is an example configuration for a continu- PSoC outsider might find it difficult SC micro circuitry. But these modules ous time (CT) PGA module. This is the most common to get started, especially with designs can be a bit difficult to work with. type of PGA used in PSoC projects, because it is encap- involving switched-capacitor (SC) ana- sulated in an easy-to-use module. There are only four set- tings required to define this type of PGA. log modules. BLOCKS AREN’T CREATED EQUAL SC modules are arguably the most Routing analog signals inside the versatile and unique feature of the PSoC can be a tricky process. More Some have access to only certain adja- PSoC, aside from its dynamic reconfig- often than not, the desired connec- cent blocks and their column’s analog uration capabilities. There are two tions are not directly available. An output bus. types of analog modules: SC and con- analog PSoC module’s input choices CT analog blocks are easy to use. tinuous time (CT). The latter modules are determined by its location. Cer- PGAs and comparators go here—no are for simple analog functions such tain locations have access to the Port mess, no confusion. All four CT blocks as programmable gain amplifiers 0 input multiplexers; others have have access to at least four Port 0 input (PGAs) or comparators. SC modules direct access to the Port 2 inputs. pins (the two center blocks have extra multiplexers, allowing connection to any of the eight Port 0 input pins), and the column clock has little to no effect 0 1 2 ACB00 ACB01 ACB02 ACB03 1 1 1 on operation. An example CT PGA configuration window is shown in Photo 1. Note that the AnalogBus set- ting can be enabled if direct PGA out- ASC10 ASD11 ASC12 ASD13 put is desired. All four CT blocks are the same, and

Comparator 0 Comparator 1 Comparator 2 Comparator have similar designations—“ACBxy,” where x equals the analog row (always 0) ASD20 ASC21 ASD22 ASC23 and y equals the analog column num- ber (0–3). These four blocks are all on the top row of the analog section (see Buf 0 Buf 1 Buf 2 Figure 1). SC analog blocks are the subtle bits of genius that grant the PSoC so many capa- Figure 1—PSoCs with a full complement of analog resources have their blocks arranged into four vertical columns. Along the top are the four continuous time (CT) blocks, while the two types of switched capacitor (SC) blocks (types bilities. In fact, the blocks can perform C and D) are laid out in a checkerboard pattern. such a variety of real-time functions that

62 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2807017_paiano.qxp 6/10/2008 4:35 PM Page 63

0 1 2 3 ACB00 ACB01 ACB02 ACB03 1 1 1 1 PGA_Vsub PGA_V PGA_A PGA_T Gain Gain Gain Gain

Input Input Input Input AnalogBus AnalogBus VSS VSS AnalogBus AGND AnalogBus VSS Reference Reference Reference Reference

ADC ASC10 ASD11 ASC12 ASD13 ADCINC12 SC_A Gain SCBLK ACMux Input Comparator 2 Comparator Comparator 1 Comparator Comparator 3 Comparator Comparator 0 Comparator AnalogBus BMux CompBus

ASD20 ASC21 ASD22 ASC23

Buf 0 Buf 1 Buf 2 Buf 3

Figure 2—Here is a configuration that is not achievable through conventional routing: a single ADC with access to all four CT PGAs up top. The actual input path to the ADC can be altered at runtime to read any one of the four signals going through PGAs.

they were given a completely customiz- modules for each function. This “Generic Type C and D SC blocks are arranged able user module instead of separate SC” module can be found as the only in a checkerboard pattern, beginning entry under the “Generic” category. with ASC10 (see Figure 1). a) b) SC blocks come in two varieties: Only the outer blocks (ASD20, Type C and Type D. Originally, in ASC10, ACB00, ACB01, ACB02, A or B Gain A or B Gain CAP CAP CAP CAP the CY8C25xxx and CY8C26xxx ACB03, ASD13, and ASC23) have 00 00PSoC families, they were Type A direct access to input pins. Restric- 1 0.0625 1 0.0312 and Type B. This is detailed in tions apply for specific pin connec- 2 0.125 2 0.0624 Cypress‘s application note tions, as well. The remaining SC 3 0.1875 3 0.0936 AN2041, “Understanding Switched blocks in the middle have to rely on 4 0.25 4 0.1248 Capacitor Blocks.” Most, if not all, neighbors for indirect input signals. 5 0.3125 5 0.156 of it still applies to the newer Generic SC modules, as I already 6 0.375 6 0.1872 CY8C27xxx and CY8C29xxx chips. mentioned, may be used for a variety 7 0.4375 7 0.2184 The old Type A blocks have of purposes. Providing isolated analog 80.5 8 0.2496 9 0.5625 9 0.2808 evolved into the new Type C blocks with access to just about any 10 0.625 10 0.312 blocks, and the old Type B blocks analog input is possibly one of the 11 0.6875 11 0.3432 have evolved into the new Type D handiest uses. 12 0.75 12 0.3744 blocks. Type C SC blocks are des- 13 0.8125 13 0.4056 ignated “ASCxy,” where x equals ADVANCED ANALOG ROUTING 14 0.875 14 0.4368 the analog row (1 or 2) and y Suppose you want to sample an 15 0.9375 15 0.468 equals the analog column (0–3). audio signal with an ADC. The sim- 16 1 16 0.4992 Type D SC blocks are designated plest way, with a blank project, is to 17 1.0625 17 0.5304 “ASDxy,” where x equals the ana- place the input block to the ADC 18 1.125 18 0.5616 log row (1 or 2) and y equals the module in one of the outside blocks so 19 1.1875 19 0.5928 analog column (0–3). Type D it has direct access to a pin input. This 20 1.25 20 0.624 blocks include an additional option may or may not be possible with other 21 1.3125 21 0.6552 to allow BCAP to function as a functionality in place. It also doesn’t 22 1.375 22 0.6864 regular capacitor instead of a provide control over the input signal 23 1.4375 23 0.7176 switched capacitor. Set this BSW level. It may be entirely too small or 24 1.5 24 0.7488 to “on” for normal operation. too large to read accurately. 25 1.5625 25 0.78 Passing the audio signal through a 26 1.625 26 0.8112 PGA in one of the top (CT) blocks first 27 1.6875 27 0.8424 Table 1a—This table illustrates the various gain enables more versatile placement of the 28 1.75 28 0.8736 settings available to an SC PGA’s channels when F is set to 16. This value may only be 16 or 32. ADC input. It also applies a gain to the 29 1.8125 29 0.9048 CAP b—This table illustrates the various gain settings signal, which may be adjusted at either 30 1.875 30 0.936 available to an SC PGA’s channels when F is design or run time. Unity gain (1.00×) 31 1.9375 31 0.9672 CAP set to 32. This value may only be 16 or 32. will leave the signal level unaltered.

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 63 2807017_paiano.qxp 6/10/2008 4:35 PM Page 64

As you place the ADC input block in various locations, you might notice the different choices available with each placement. An ADC placed in ASD11, for example, has access to sig- nals present in ACB00, ACB01, ASC10, ASC12, and ASC21. Changing the signal input to the ADC during run time involves altering the value in one of the control registers—specifi- cally, ASD11CR1 (bits 7, 6, and 5). For details, refer to the PSoC technical ref- erence manual. The ADC in block ASD11 has easy access to CT PGAs in blocks ACB00 a) b) and ACB01. Suppose your design had the resources available for only a sin- Photo 2a—This is an example configuration for a generic SC Type C set up to act as a two-channel audio PGA gle ADC, and you had to cycle with 1.00× gain. Note how many more settings are required to comprise the PGA function. The generic SC modules through and read signals present in all are capable of many tasks and are a bit more complicated. The two input channels are marked for clarity. The gain of channel A is determined by the ratio of F to A , and the gain of channel B is determined by the ratio of F four CT PGAs up top. There is a miss- CAP CAP CAP to B . All are equal, resulting in 1.00× gain (no amplitude change). b—This is an example configuration for a ing element. CAP generic SC Type D set up to act as a two-channel audio PGA with 1.00× gain. Note how many more settings are The block ASC12 has easy access to required to comprise the PGA function. PGAs in the other two CT blocks ACB02 and ACB03. By configuring this block as an SC PGA with unity setup’s analog configuration is shown audio signals. The SC PGA does not gain, the ADC in block ASD11 can in Figure 2. have as large a range of gains as the access all four CT PGAs with simple A generic SC module can be configured standard CT PGA module, but it is per- register changes. An example of such a to act as a PGA and cleanly amplify fect for low and unity gain applications.

64 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2807017_paiano.qxp 6/10/2008 4:36 PM Page 65

Figure 3—This is a schematic detailing the PSoC’s internal analog routing and modules used in the eight-channel mixer project. Note the minimal component count for this relatively complex circuit.

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 65 2807017_paiano.qxp 6/10/2008 4:36 PM Page 66

Figure 4—This is the matrix of independently. An SC PGA can also potentiometer/level control inputs invert its non-inverting input. The used to provide real-time control ratio between F and either A or over the various gains and settings CAP CAP available for use in the eight-chan- BCAP controls the gain applied to either nel mixer project. This setup the A or B inputs, as shown in the fol- enables a single digital timer mod- lowing equations: ule to read 16 potentiometers while A consuming only eight I/O pins (four Gain = CAP input and four output). A FCAP B = CAP GainB FCAP

Empirically, an analog column clock of 4 MHz was found to be optimum The standard CT PGA for an audio SC PGA. Faster clocks module provides gains resulted in distortion because the SC from 0.062× to 48×, blocks do not perform quite as well whereas the SC PGA I near their upper limit of 8 MHz. created has a range of The parameters necessary to create 0.062× to only 1.938× an SC PGA intended for use with AC

(with an FCAP value of signals (or audio) from a generic SC 16). This range gets module are shown for the two types of smaller and finer when SC blocks in Photos 2a and 2b. To

FCAP is set to 32 (see pass just one signal, set the unused Table 1). channel (A or B) capacitance to 0. If SC PGAs have the your signals are not referenced to ana-

unique capability of log ground (AGND = VCC/2), then a mixing two inputs and different reference setting may be controlling their gains selected for ArefMux (just like the

66 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2807017_paiano.qxp 6/10/2008 4:36 PM Page 67

Start Pead Timer interrupt pot(x) Initialize variables, modules, interrupt. Stop self Output serial titles. Drive all bank (timer module). selects low. Set flag indicating Wait a short delay current to create a Is Enable potentiomter has deadband. button been measured. pressed? Drive bank select for pot(x) high. Ye s Return Connect timer’s capture input to Read Read Read Read pot(x)’s input bus. pot(0) pot(4) pot(8) pot(12) Time Read Read Read Read pot pot(1) pot(5) pot(9) pot(13)

Return Read Read Read Read pot(2) pot(6) pot(10) pot(14)

Read Read Read Read pot(3) pot(7) pot(11) pot(15)

Have three sets of readings been taken? Ye s

No

Increase number of readings Transmit serial, reset number of readings

Figure 5—This is a flowchart representing the operation of the eight-channel mixer’s firmware logic. The mixing functions are passive and do not require user logic to operate. The logic shown handles the scanning of the poten- tiometers and real-time adjustments.

reference setting of a CT PGA). This mixer design operates passively without logic. The only code required CREATE AN 8-CHANNEL MIXER is to initialize the CT PGA modules. Now that you have the capability The SC PGA modules do not need to route analog signals anywhere at start commands when their power will, you can create a single PSoC level is set in the device editor to low, project to perform a function not typ- medium, or high. ically thought of as possible: the If you can preset all of your gains, eight-channel mixer. then you are done! However, you Using both CT and SC PGA mod- might want some sort of real-time ules, all eight simultaneously control over the gains. routable analog input signals (four CT inputs from Port 0 and four end-col- DIGITALLY TIME POT INPUTS umn SC inputs from Port 2) can be One relatively simple way to provide mixed into three outputs: Left, Right, real-time control over the mixer’s gains and Mono. The basic mixer schemat- involves three buttons and a serial dis- ic and internal routing is shown in play terminal. This does not lend itself Figure 3. to a user-friendly interface—knobs or The left output consists of a mix of sliders would make much more sense. input channels La, Lb, Lc, and Ld. The Typically, potentiometer inputs are read right output consists of a mix of input with an ADC in the analog domain; channels Ra, Rb, Rc, and Rd. The mono however, there is an interesting way to output is a mix of all eight inputs. utilize the remaining digital resources Lc, Ld, Rc, and Rd are routed through of the PSoC to implement adjustment CT PGAs before entering the mix, and potentiometers for up to 16 adjust- can therefore have a preamp gain of up ments simultaneously (see Figure 4). to 48× applied to them. These channels An 8-bit timer module captures one are ideal for use with microphones or of four input lines, which is multiplexed small-signal input sources. to four control lines in a keypad-matrix

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 67 2807017_paiano.qxp 6/10/2008 4:36 PM Page 68

result in overwriting the same line La Lb Lc Ld Ra Rb Rc Rd L R LR MLc MLd MRc MRd 1.13 0.00 0.00 0.75 1.13 0.00 0.00 0.75 1.13 0.00 0.00 01.33 48.00 00.12 00.87 repeatedly in terminal applications.) In this article, I described how to build an eight-channel mixer with Figure 6—This is an example of the optional serial terminal’s output. Each adjustable setting is shown on a single line. The program used here was HyperTerminal, which comes with most versions of Windows. adjustment knobs, using a Cypress Semiconductor CY8C27443 PSoC as the only active component. Next style. This allows timing of up to 16 sig- For this reason, the bank selects are month, I will explain how to further nals, which will be our potentiometers now strong outputs. They are driven enhance this single-chip design with (or knobs, sliders, and more). The poten- high to select a bank, and driven low DSP effects, an intercom mode, a user tiometer’s resistance controls how long otherwise. To ensure that the low drives interface, speech capability, and per- the RC circuit takes to charge up, trans- do not affect the potentiometer read- manent setting memory. I forming a voltage measurement into a ings, blocking (D1, D2, D3, and time measurement (easily measurable in D4) are now required on these lines. Author’s note: Many of the application the digital realm). The PSoC’s digital A flowchart describing the operation notes referenced in this article were High-Z inputs switch at V /2 (behaving of this adjustable eight-channel mixer CC recently submitted, so they may or may exactly as an analog comparator refer- project is shown in Figure 5. not be available on Cypress’s web site at enced to ground with the trip point at this time. For your convenience, the orig- 0.500), which works out great for this. A COUPLE OF NOTES inal, unedited versions of the relevant To measure a specific line, after the By enabling the Agnd bypass in the application notes are available on my input is connected to the timer mod- global settings and selecting external web site, along with their project and ule’s capture input, all four capacitors Agnd on P2[4], a few hundred related files. Go to www.chrispaiano.com are discharged. Then, the timer mod- microamps are available to bias the for more information. In addition, I have ule is reset and started just before the AC-coupled inputs. The two 100-µF a few homemade PSoC-based electronics capacitors are released and allowed to bypass capacitors (C14 and C15) are kits and devices for sale on my site. The begin charging. When the selected line arranged in series with the supply to project described in this article is avail- charges up above V /2, the capture facilitate a quick initial charge-up. CC able as either a kit or an assembled unit.

input triggers an interrupt—during The ACAP and BCAP settings in the which, the timed value is converted device editor have no effect because Chris Paiano has written more than into an appropriate R/C gain ratio and they are set in the software. 30 application notes for the Cypress written to the channel’s gain register. The option also exists to convert one PSoC chipset over the years, includ- If any of the eight audio input lines of the eight channels into an intercom ing such novelties as PongSoC and are left floating, the PSoC will allow line, which would make this firmware the Video RTA. You may contact some noise in from the potentiometer perfect for mixing at the individual level him at [email protected]. scanning process. At extremely high in the studio. This would enable musi- gains, some digital noise might still cians to control each relevant channel leak in even without floating inputs. level in their headphones and simultane- PROJECT FILES A simple solution to both is to use a ously maintain communication with the To download code, go to ftp://ftp.circuit pin as a “Scan Enable” line. Scanning control room. Just some simple configu- cellar.com/pub/Circuit_Cellar/2008/216. the potentiometers is performed only ration changes in the PSoC Designer, while P2[7] is high; it ceases when and this may be achieved (disconnect RESOURCES P2[7] is low. A button might be labeled PGA_Rd from SC_Rcd, and directly con- Cypress Semiconductor, “PSoC Mixed- “Hold to adjust or push to update.” A nect PGA_Rd to Analog Output 3 to iso- Signal Array: Technical Reference Man- switch might be labeled “Down to late it from the mix). Actually, don’t ual,” 001-14463, www.psocdeveloper. lock out changes and Up to adjust.” worry about doing this yourself. Next com/uploads/media/PSoC_TRM_00.pdf. There was another situation caused month, you’ll read how this is imple- by leakage in this application. The mented as a separate mode. D. Van Ess, “AN2041: Understanding bank select outputs were originally driv- The optional serial terminal dis- Switched Capacitor Blocks,” Cypress en as Open Drain High, which should play output looks like what you see Microsystems, 2004, www.future-mag. theoretically mix without diodes in the in Figure 6. At power-up, the title line com/0707/docs/analog_understanding potentiometer scanning circuitry. The is transmitted. This provides labels for _switched_capacitor_analog_blocks_an bank selects were driven high to select the data. Then, whenever the poten- 2041_12.pdf. a particular bank, and released to float tiometers are scanned, the applied gains otherwise. Unfortunately, when floating, will be looked up and displayed on the the bank outputs sharing Port 1 with the terminal. Because it all fits on a single SOURCE inputs were affected by the various charg- line, special software isn’t needed for a CY8C27443 PSoC ing capacitors. This resulted in multiple stationary, updating display. (Carriage Cypress Semiconductor Corp. gains being adjusted unintentionally. returns without linefeeds typically www.cypress.com

68 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2805017_Papp.qxp 6/10/2008 4:37 PM Page 69

FEATURE ARTICLE by Robert Papp Sound Effects Processing The StellarisGFX is a well-designed sound effects processor. The system’s keyboard is used for navigating through the user menu. You can set the volume level and select effects such as overdrive, tube overdrive, and distortion.

The clean sound of an electric gui- inexpensive device to demonstrate Listing 1 is an example of the code. tar is not often used in rock and blues some of the functions of a guitar effects Delay-based effects can be produced music. This is also the case when you processor. In this article, I’ll describe by implementing a circular buffer. examine a classic rock or blues record. my sound effects processor, which I Samples follow each other in such a Almost every beginner learning to call the “StellarisGFX” (see Photo 1). way that the newest samples will be play the electric guitar comes up in the next location in the memory. against the same problem: the song HARDWARE DESIGN When the last sample reaches the end he’s trying to play sounds different A lot of information about common location of the memory area, the next from his guitar’s original sound guitar effects is available on the Inter- one will be saved in the first location, because even the amplifiers of the past net.[1] The functions of analog circuits looping around the same memory area slightly distorted the input signal from inside simple effects usually can be again. A delay mechanism can be car- an electric guitar’s pickups. modeled to implement mathematical ried out by using a read pointer to To reproduce the recorded sound, algorithms on digital data samples. A keep track of the location that the you need a gadget (around the same simple distortion effect can be mod- samples will be read from, let’s say age as your old guitar heroes) that can eled digitally by limiting the maxi- the “past.” Listing 2 is example code generate a guitar sound similar to the mum value of the digitized sample for implementing a circular buffer. one heard on the original recording. and making it equal to a predefined The size of the memory area used and The situation just gets worse when value. The effect emulates the satura- the sampling rate will determine the you look at new music. Current gui- tion of an overdriven tube amplifier. delay time that can be implemented. tarists often play behind a With a basic knowledge of heap of tricky guitar effects guitar effects theory, I started boxes. to build my own solution. There is a solution for gui- The heart of the StellarisGFX tarists who don’t want to buy is an LM3S811 evaluation kit, gadgets for each sound: a digi- which features an LM3S811 tal guitar effects processor. ARM Cortex-M3-based micro- The expensive commercial controller equipped with a version of this device is usu- serial in-circuit debug inter- ally built with high-resolu- face for any Stellaris micro- tion audio CODECs (to condi- controller-based target board. tion the guitar’s electronic The evaluation kit’s board signal) and a fast DSP that includes the important hard- implements mathematical ware parts necessary for suc- algorithms to digitally realize cessful development work: a different effects. thumbwheel potentiometer, When I received a sample two push buttons, two LEDs, Stellaris LM3S811 evaluation and the most important part, Photo 1—The circuit was created on prototype boards connected to each kit from Luminary Micro, I other with pin headers. The LC7881 DAC circuit is under the first board with a 96 × 16 pixel OLED dis- decided to build a simple, push buttons. play.[2] The device contains a

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 69 2805017_Papp.qxp 6/10/2008 4:37 PM Page 70

relatively fast built-in ADC with four Listing 1—This code sample represents a way to produce an overdrive effect. The value of the sample channels capable of sampling signals g_ulADC_Data is limited to a preset value emulating the of an old tube amplifier by software. up to 500 ksps, which is fast enough for sound-sampling applications. How- //**************************************************************** // ever, the resolution of the ADC chan- // Overdrive nels is 10 bits. Although it is low for // high-performance sound sampling, it //**************************************************************** is still better than similar options unsigned long available on the Internet.[3] Overdrive(unsigned long g_ulADC_Data) I decided to use the LM3S811’s { unsigned long g_ulValue; internal ADC module to convert the g_ulValue = g_ulADC_Data; signal coming from the guitar pickup if (g_ulADC_Data > 600) to digital samples. Furthermore, the { g_ulValue = 4 / 3 * g_ulADC_Data; digitized samples should be stored in a } memory area. The possible types of effects can be accomplished by delay if (g_ulValue > 1023) { algorithms depending on the size of g_ulValue = 1023; the memory area. According to the } datasheet, the LM3S811 contains 8 KB return(g_ulValue ); of single-cycle SRAM. That is theoret- } ically enough memory for implement- ing a delay of about 40 ms in case of a

100-ksps sampling rate. There are filter is connected to line out. The zero, and amplifies it to 0 to 3 VPP cen- more sophisticated effects like chorus output DAC circuit implemented tered at 1.5 V to have the best resolu- and flanging, which are based on delay using the LC7881 DAC is shown in tion for the A/D conversion. mechanisms that are not implement- Figure 1a. The input amplifier circuit The amplifier circuit is shown in ed, but a simple delay feature still consists of two LM358 op-amps in a Figure 1b. Now, all of the blocks are exceeds the capabilities of many ana- single-supply operation.[4] An input composed together. The main com- log effects. Currently, Luminary Micro amplifier is also needed in the design ponents of the guitar effect are iden- is producing ARM Cortex-M3-based because the voltage level of the signal tified in Figure 2. As you can see, an microcontrollers with up to 64 KB of gained from the guitar pickup is optional PWM amplifier H-bridge SRAM, but they are not available for around 100 mV. The circuit takes the connects a speaker to the effects the LM3S800 series. analog guitar signal, which varies processor circuit, which is controlled [5] The last part is a DAC implement- between 0 V and 500 mVPP centered at by the LM3S811’s PWM Module1. ing D/A conversion. The LM3S811 does not contain a DAC. The function Listing 2—This code sample shows a delay mechanism created by a circular buffer in SRAM. Samples are requires external hardware. I used a stored one after the other. Upon reaching the end of the buffer, the next sample will be stored from the begin- Sanyo LC7881 16-bit stereo CMOS ning of the buffer again. DAC, which was removed from a bad CD-ROM unit. The LC7881 has two //***************************************************************** // D/A channels, and the maximum con- // Write sampled audio signal to memory version frequency is 176.4 kHz. Digi- // tal audio data can be transferred to the //***************************************************************** device using the flexible synchronous void serial interface (SSI) of the LM3S811. SampleQueueWrite(unsigned long g_ulADC_Data) The LC7881 datasheet recommends { using a buffer op-amp on each output if(queueCount++ < QUEUESIZE) channel in a voltage-follower configu- { ration to protect the input circuitry *nextInQueue++ = g_ulADC_Data; //load g_ulADC_Data and incr pointer from noise. } The circuit is implemented using an else op-amp from a BA10324AF quad // circle the buffer { ground-sense op-amp, which was nextInQueue = myQueue; // reset pointer removed from the same CD-ROM as queueCount = 0; // reset counter the LC7881. A second op-amp is used *nextInQueue++ = g_ulADC_Data; //load myValue and incr pointer as a low-pass filter in a Sallen-Key } topology, with a cut-off frequency of } 20 kHz.[4] The output of the low-pass

70 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2805017_Papp.qxp 6/10/2008 4:37 PM Page 71

a)

b)

Figure 1a—This is the schematic of an output circuit using a Sanyo LC7881 16-bit stereo CMOS DAC, which communicates using just three wires to the SSI module of the LM3S811. An op-amp voltage-follower and a low-pass filter in a Sallen-Key topology have been implemented according to the suggestions of the datasheet for the LC7881. b—The input amplifier circuit consists of two LM358 op-amps in a single-supply operation. This circuit is used to con- dition the low-level signal coming from the guitar to the right level for the ADC module in the LM3S811.

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 71 2805017_Papp.qxp 6/10/2008 4:37 PM Page 72

periodically by the Timer1 module LM3S811 Microcontroller on evaluation board at a 100-kHz frequency. In the ADC From Optional Speaker - 64-KB Single-cycle flash memories PWM PWM amplifier interrupt routine, the ADC module - 8-KB Single-cycle SRAM Gen1 H-bridge - Three general-purpose timers takes eight samples at every trigger - Four 10-bit channels ADC Input amplifier and then gives back control to the (LM358 Op-amps) To ADC1 - Three PWM generator blocks - I2C Bus main loop. To make this simple - Analog comparators DAC Low-pass - Two fully programmable 16C550-type UARTs From SSI (LC7881) filter algorithm work, both the peripherals - Synchronous serial interface (SSI) - 1 to 32 GPIOs in the microcontroller (GPIO ports, Guitar - OLED display ADC, SSI, PWM and Timer) and the Headphones OLED display on the evaluation Figure 2—This is the system block diagram board must be initialized. Because of the planned guitar effect. The main hard- the driver library contains the most ware parts can be found in the Luminary Keyboard Micro Stellaris LM3S811 evaluation kit. important instructions and code examples for peripheral initializa- tion, this part of the software devel- The board can be used to experiment CD-ROM that came with the evalua- opment runs quite smoothly. with the circuit as an audio pulse tion kit. The only difficulties occurred while width modulation amplifier. The best support solution file for configuring the SSI because I had to programming the LM3S811 in embed- find the right protocol from the three SOFTWARE DEVELOPMENT ded C, however, is the “Driver Library possible types in the LM3S811’s SSI For the guitar effects processor’s and Software Example Update for Keil module: Freescale SPI, Microwire, or software, I used the evaluation ver- µVision,” which you can download in Texas Instruments synchronous serial sion of the Keil µVision3 IDE develop- the “Software Updates” section of the interfaces. After some testing, the ment platform, which supports a wide web site. It contains a driver library Texas Instruments synchronous serial variety of different microcontrollers for all of the peripherals integrated in frame format transfer protocol proved from other vendors besides Cortex- Luminary Micro’s Stellaris microcon- to be the right combination for com- M3-based microcontrollers. The plat- trollers, including documentation and municating with the LC7881 DAC in form integrates all of the tools and fea- sample applications, and can be used a master operation mode. Fortunately, tures that make embedded software in the Keil µVision3 IDE. The learning the SSI module has 16-bit-wide FIFOs. development easy (in embedded C). process became an easy task from Care should be taken to transform the This scared me at first because I didn’t there. I downloaded demo applications digital format of the 10-bit-wide data have much embedded C programming tailored to the LM3S811 evaluation kit. sample sent to the DAC for sending experience. My prior experience with While testing the hardware, I learned least significant byte first. microcontroller circuit development to use the development platform and The algorithm for reversing the bit focused on writing short code snippets software development step by step. order and the way it is sent to the SSI in assembly and writing bigger applica- Providing a driver library for code module is shown in Listing 3. The tions using a BASIC compiler available developers is a good habit for other speed of the SSI was set to use a differ- with my microcontroller. Getting a microcontroller vendors as well. ent clock rate (500 kHz) from the rec- BASIC compiler for any of the ARM- The code for the guitar effects was ommendation in the LC7881 based microcontrollers is usually not an developed stepwise as well. I started datasheet, but when it was tested, the option, so I was not successful with the to make a simple main loop structure DAC provided the same sound quality Luminary LM3S811 microcontroller. I in the main part of the embedded in a wide frequency interval. didn’t even think of writing the entire software (pwm_amp.c). The input Chan- The next step was to make it possi- application in assembly, so I had no nel1 in the ADC module is triggered ble to interact with the user. You can choice but to use the development platform. Listing 3—The first part of the code sample shows the algorithm to reverse bit order. It is then sent to the SSI Fortunately, the Luminary engineers module. Texas Instruments’s synchronous serial frame format is used to communicate with the LC7881. provided useful documentation and demonstration code to support embed- // ded software development.[1] The // Send data to DAC // “Application Notes” and “Software Updates” sections of the web site con- g_ul_Data_Out = DACBaseData + g_ulTemp ; tain some useful application notes. for(ulLoop = 0; ulLoop < 10; ulLoop++) They also include source code that { demonstrates the different peripherals HWREGBITW(&g_ul_DAC_Out, ulLoop) = HWREGBITW(&g_ul_Data_Out, (9-ulLoop)); that can be found in Luminary Micro’s } products. Luminary also included SSIDataPut(SSI_BASE, g_ul_DAC_Out); some information in the evaluation

72 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2805017_Papp.qxp 6/10/2008 4:37 PM Page 73

for delay. The effects Designstellaris2006 Contest. To learn Volume include overdrive, tube more about the contest and the other IIIIIIIII overdrive, distortion, and notable projects, visit www.circuit a noise gate. This struc- cellar.com/designstellaris2006/. Effect type Effect type Effect type Effect type ture makes it easy to inte- none overdrive tube overdrive distortion grate new effects. Only Robert Papp ([email protected]) the FSM menu system has been interested in electronics Noise gate Noise gate part in the main code since he built his first one-transistor on off should be modified. Then radio at the age of 12. He graduated the new effects routine can from the Technical University of Delay Delay be inserted into the effect.c Budapest with a degree in Electrical on off file. Engineering 10 years ago. Although Robert works for a computer compa- ny, he tries to follow the news in the Figure 3—The user menu system is simple and can be easily modified EXCELLENT RESULTS according to your needs. When adding a new effect type to the StellarisGFX, electronics industry and he continues Code development and the FSM part in pwm_amp.c code should be modified, and the new code to learn about its new fields. He is portion of the effect can be inserted in the effect.c source file. circuit prototyping ran currently spending a lot of time on parallel while I was work- embedded software development for ing on this design. The hobby circuits with microcontrollers choose effect types and digitally set up entire circuit was created on a test from various vendors. the volume level of the output signal. board. I made the different modules on A menu system controlled by four different circuit boards so I could test push buttons enables you to navigate and redesign them if necessary. PROJECT FILES in the user menu. The functions As you can see in Photo 1, the To download code, go to ftp://ftp.circuit include “up,” “down,” “left,” “right,” LM3S811 evaluation kit is mounted in cellar.com/pub/Circuit_Cellar/2008/216. and “center.” Thus, the main software the middle of the board. It’s connected structure contains two other software by pin headers. The board containing routines: the keyboard button five push buttons is located in front. REFERENCES debounce routine and the finite state Jack sockets for the input and output [1] Harmony Central, Inc., “Effects machine (FSM) for navigating in the signal are on the left or right. The Explained: Articles Explaining How user system. This part of the software LC7881 DAC circuit is under the push Effects Work,” www.harmony-central. can be modified according to the types buttons. The second input op-amp and com/Effects/effects-explained.html. of effects that will be implemented. the power supply circuit are on the The main loop contains the menu sys- back of the board. [2] Luminary Micro, “LM3S811 Micro- tem update part, which checks the state Software development with the controller Data Sheet,” DS-LM3S811-00, of the keyboard buttons periodically and µVision3 IDE development platform is 2006, www.luminarymicro.com/products then changes the display contents easy. There is full support for the /lm3s811_microcontroller.html. according to which button was previous- LM3S811 evaluation kit. You can [3] Cornell University, ECE 476 Micro- ly pressed. The menu system’s structure download the firmware code into the controller Design Final Projects, http:// is shown in Figure 3. The last part of the microcontroller’s bootloader via a USB instruct1.cit.cornell.edu/courses/ee476/ main code involves signal processing. download cable. Luminary’s applica- FinalProjects. According to the menu system state, it tion notes, source code, and driver modifies sound samples and calls the library were welcome aids. [4] B. Carter, “Application Report: A effects routines in effect.c. Modified Despite the LM3S811’s low sam- Single-Supply Op-Amp Circuit Collec- sound samples are sent to the SSI and pling resolution (in comparison to the tion,” Texas Instruments, SLOA058, used to calculate the duty cycle of the DSP processors and CODECs used in 2000. PWM1 module. The H-bridge board can commercial sound effects units), my [5] R. Balog, “Audio Pulse Width Mod- be connected to the PWM1 module, StellarisGFX effects processor pro- ulation (PWM) Amplifier),” 2001, thus converting the entire circuit to a duces better sound quality than the http://energy.ece.uiuc.edu/. PWM audio amplifier. However, it do-it-yourself units available on the should be taken into consideration that Internet.[2] Because I’m a cost-con- the sound and quality of the signal will scious designer, I used recycled parts SOURCES be different from the one that can be from old electronic units (like CD- LM3S811 Microcontroller obtained from the LC7881 DAC. ROMS) for this project. As a result, I Luminary Micro, Inc. The algorithms applied on digital now have an affordable gadget that www.luminarymicro.com samples creating effect types are col- works quite well. I lected in a different section of software, LC7881 CMOS which is called effect.c. The routines Editor’s note: This project received Hon- Sanyo Electric include circular buffer read and write orable Mention in the Luminary Micro www.sanyo.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 73 27807002-Bachiochi.qxp 6/10/2008 4:38 PM Page 74

FROM THE BENCH by Jeff Bachiochi Electric Motor Technology Theory, Construction, And Requirements The principles behind electric motors have been around for almost two centuries, but the technology has come a long way during the past few years. Jeff examines electric motor theory, construction, and requirements.

Although first with a simple look at electromagnetics. have never experienced one, and we don’t showed the relationship between cur- know how it might affect life as we know rent flow and magnetic fields in 1821, ELECTROMAGNETIC FORCE it. Theories suggest that the Earth’s mov- it wasn’t until 11 years later that these At the center of our solar system, ing magnetic field may be due to the principles were used to demonstrate the sun goes through a sunspot cycle uneven flow of the outer liquid core deep the first electric motor. Actually, it every 11 years. Sunspots are areas of in the Earth’s layers. Plate tectonics show was the invention of the intense magnetic fields that poke us how irregular and continuously chang- that allowed electromagnetic forces to through the photosphere and are even- ing the surface is, so it’s easy to see that be coaxed into rotary motion. Once tually drawn toward its attracting mag- we’re not dealing with smooth surfaces electrical power could be turned into netic pole. When this collected opposi- and ideal spheres rotating in perfect bal- mechanical power, it was easy to tion overpowers the sun’s dipole state, ance on axis. However life will be affected show how the reverse was possible. In a flux reversal flips the dipole state. by this drifting magnetic field (and need of a source for his electric light, This is consistent with maximum internal currents), we can find conso- Thomas Edison proposed generating sunspot activity and the 11-year cycle. lation in the relationship between a DC power to customers in 1882. The Earth has a record of flip-flopping magnetic field and an . Meanwhile, investigated magnetic poles, but the period is much Some materials that are largely made brushless AC induction motors. By longer. The last one occurred about up of iron ore (magnetite) can be con- 1888, he was ready to oppose Edison 740,000 years ago. Needless to say, we verted into a lodestone (magnetized by proposing the use of mineral) by having the AC for power distribu- normally random mag- tion. Despite some dirty netic fields of its electrons Right-hand rule campaign tactics by Edi- Left-hand rule aligned. This can come Thumb points son, we all know how in direction of Direction from a large current (i.e., current flow of force that contest turned out. lightning) passing N

Because of the impor- S through the conductive

tance of electric motors, N material. Extreme currents

I will spend some time S bring extreme magnetic this month examining Magnetic fields that can permanent- field their construction, theo- ly affect electron spin. Fingers point ry, and what’s required in direction of When the external force magnetic field Direction to use them. What of current has subsided, the magnetic began as a real distinc- Current-carrying wire alignment can remain, giv- tion between DC and ing the material a perma- AC motors has become Figure 1—The right-hand rule helps you remember how the direction of current in a conductor nent magnetic field. The muddled due to the is related to the magnetic field it creates and how the direction of current in a coil relates to the first compass was made introduction of electron- core’s North pole. The left-hand rule shows how a conductor is affected by an external magnetic by floating this perma- field, either by creating a current as the conductor cuts through the field or creating a force as a ics to provide smart con- current passes through the conductor. (Source: National High Magnetic Field Laboratory, Florida nently magnetized trol. But let’s start off State University, www.magnet.fsu.edu/education/tutorials/java/handrules/index.html) material on water. With

74 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 27807002-Bachiochi.qxp 6/10/2008 4:38 PM Page 75

horseshoe-shaped piece of iron that was wrapped with several turns of the wire. The iron core SNSNacts as a concentrator for the mag- netic field produced by current flow in the wire. You can cause

Unlike poles attract the north/south orientation of an electromagnetic core to swap polarities if the coil is wound in the opposite direction or if the

SNN Sdirection of the current through the wires is reversed. Figure 2 shows a representation of the attrac- tion of opposing magnetic poles and Like poles repel the repulsion of like magnetic poles. Figure 3—Thomas Davenport’s 1837 patent: the use Figure 2—The attraction and repulsion of magnetic poles By controlling the direction of cur- empowers all motors. The electromagnet creates a temporary of a commutator in a DC motor. (Source: U.S. Patent magnet from a current passing through the coil wound around its rent flow in the coil of an electro- and Trademark Office, Patent 132, www.pat2pdf.org) core. The direction of current flow determines the core’s polarity. magnet, you define its pole orienta- (Source: Integrated Publishing, www.tpub.com/neets/book1/ tion. The right-hand grip rule can advances, this column will pass over chapter1/1i.htm) also show the north magnetic orien- most (i.e., the telegraph/telephone) in tation (thumb) when the fingers favor of the electric motor. But a DC the water acting as a frictionless bear- simulate the current flow direction in source and an electromagnet by them- ing, the lodestone can rotate and align the wires of a coil. selves do not make a motor. Experi- itself with the magnetic field of the ments using batteries and electromag- Earth (north/south). THE DC SOURCE nets were able to produce only partial The relationship between magnetic Not counting Leyden jar capacitors motion without the next invention. A fields and current was discovered by (circa 1745), early scientists were permanent magnet affixed to the diam- Hans Christian Ørsted in 1820 when restricted to one source of power, the eter of a turntable will demonstrate he noticed a compass needle deflect- electric pile, or battery. Alessandro rotational motion when an electromag- ing from magnetic north when he Volta’s experiments with the “artificial net oriented at the turntable’s perimeter applied electric current to a wire run- electrical organ”—named from the tor- is energized and its pole opposes the ning close to the compass. The right- pedo fish’s ability to produce an electric permanent magnet’s pole. The hand grip rule demonstrates the shock (the electric eel’s cousin)—give us repelling magnets push away, spinning direction of a magnetic field around a the basics of creating a the turntable until the opposite pole of wire when the electric current is from dissimilar metals. Without meas- the permanent magnet is attracted to the flowing in the direction of the thumb urement devices, Volta’s research was electromagnet. The opposite pole of the (see Figure 1). limited to sensory (touching a tongue or permanent magnet on the turntable is In 1825, British electrician William open wound) comparisons. How many of happy to remain attracted to the elec- Sturgeon showed how the magnetic you have tested a 9-V battery with your tromagnet and the rotation ceases. field produced from a current in a wire tongue? (Not only does the rotation cease, but could be increased without additional While the battery and the electro- the attracting poles provide a force that current by stacking the wire in paral- magnet (like the convergence of many prevents rotation.) The need here is to lel (coiling). His electromagnet was a technologies) have led to diverging be able to reverse the current flow in

Direction of rotation

N

N NSS N S N NSS

S + + +

A B C

Figure 4—This series of diagrams shows why a commutator was necessary in the development of the DC motor. When DC voltage is applied to a (a), it may remain sta- tionary because there is no starting torque produced. But with the slightest twitch, it will gain torque as it moves into position b. Torque at maximum, the rotor continues to move toward position c. Maximum attraction and zero torque now hold it firmly in position c. No further movement is possible without a change in the rotor’s polarity. The brushed commutator is the mechanical device that switches current flow in the rotor’s electromagnet core. To assure continued rotation, the commutator’s brushes must be positioned correctly to switch the current flow through the rotor, which swaps the core’s polarity as the rotor’s momentum carries it through rotor position c. (Naval Education and Training, Professional Development and Technology Center, www.tscm.com/NEETS-v05-Motors.pdf)

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 75 27807002-Bachiochi.qxp 6/10/2008 4:38 PM Page 76

Pole pieces are used in the rotor at right While the commutator is necessary angles to one another. Twice as for DC current and DC motors, at the many commutator segments are time no one knew what to do with the

N S used, which alternately powers AC that was produced by a dynamo the coils. Each coil is powered using slip rings (see Figure 6). Slip during the upper portion of its rings enable the connection of the Commutator Two-coil armature torque curve. Some electric rotor coils to the outside world with-

Generator terminal voltage motors are manufactured with out reversing the current flow (the more than two coils. More coils way a commutator does). Slip rings + B means higher overall torque. As have less arcing and wear associated A more coils are added, more with them because the current isn’t commutator segments are nec- interrupted. Finally, AC found its 0 essary. This reduces the avail- niche in the world and the AC O O O O O O O O O 0 45 90 135 180 225 270 315 360 able segment (and ) size. dynamo became known as the alterna- Coil voltages tor. By using permanent magnets Figure 5—This demonstrates how multiple rotor coils in the DYNAMO within the rotor and in dynamo produce a smoother output. (Source: Naval Education and Training, Professional Development and Technology Center, The motor and generator are the , the can produce www.tscm.com/NEETS-v05-Motors.pdf) like the chicken and the egg. AC current without the need of a Because there was no power dis- commutator or slip rings. This sim- the electromagnet every time the tribution system, while the electric plicity makes it the most cost-effec- turntable is rotated 180°. With today’s motor might have been useful, electric tive source of exchanging mechanical electronics, you can do this, but that’s motors weren’t practical without a energy for electrical energy. When the getting ahead of the story. power source. The fact that an electric rotor’s magnets are replaced with coils You can imagine that with a turntable motor could also produce power meant (and slip-rings), the alternator must of sufficient weight, if you just turn off that converting mechanical to electrical power the field windings to produce the electromagnet for 180°, momentum energy was possible. Up to this point, rotor current, as it’s used to recharge might allow the turntable to continue I’ve discussed how a magnetic field today’s automotive battery from our rotating until the electromagnet could produced by a current through a wire automobiles’ internal combustion provide another push. After all, many is used to create an electromagnet (and engine. one-cylinder used flywheel rotary motion). The reverse is also true. momentum. Before electronics, mechan- A wire (or coil) passed through a mag- AC MOTORS ics played a major role in advancing netic field will have a current induced With the fight over power transmis- technology. Thomas Davenport received in it. This is similar to the transfer of sion and distribution techniques all but the first patent (U.S. Patent No. 132) for power in a transformer (current flow to over, Americans in the late 1880s could an to use a commuta- magnetic field to current flow). not have possibly understood how their tor (mechanical means of reversing If you take a DC motor and spin the future was about to change. Labor-saving current) in 1837. Note that thousands shaft, the magnetic field of the perma- devices began to invade every household. of patents issued between 1790 and nent magnets will cut through the Synchronous AC motors became impor- 1835 were not numbered. electromagnetic coils, inducing a cur- tant because they require no slip rings or Motors (or generators) are made up of rent flow in the coils. Current flows commutators and are less expensive to two parts: a stator (the stationary part) only while the magnetic field is chang- manufacture. Because their spin was a and a rotor (the moving part). My ing. Maximum current flows as the per- function of line frequency (60 Hz), they “turntable” has a permanent magnet as manent and electromagnet’s cores could be used to keep time and stay in the rotor and an electromagnet as the become perpendicular to one stator. I could have just as easily used another, while the coil is cut- the permanent magnet as the stator ting through the maximum and an electromagnet as the rotor. In number of flux lines. Mini- fact, because of the commutator’s con- mum current flows when per- struction, this is the preferred method, manent and electromagnet’s as in Davenport’s patent (see Figure 3). cores are parallel with each Before moving on, let’s look at a prob- other, and while the coil cuts lem with a single-coil DC motor (see through the fewest lines of Figure 4). The torque on the rotor begins flux. Using multiple electro- at zero when the electromagnetic and magnetic coils and commuta- permanent magnet cores are parallel. The tor segments (as was shown to motor will not be able to self-start if the improve torque in an electric Figure 6—This is just one of many of Nikola Tesla’s patents (1888). He used slip rings to pass current to and from the rotor rotor and stator are aligned. This problem motor) will smooth out current coils. (Source: United States Patent and Trademark Office, Patent can be prevented if two electromagnets ripple (see Figure 5). 381968, www.pat2pdf.org)

76 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 27807002-Bachiochi.qxp 6/10/2008 4:38 PM Page 77

sync with the rest of the grid. will create a magnetic field. Therefore, power cannot produce the rotating mag- As previously discovered, a dynamo eddy currents produce an opposing netic fields associated with true multi- using permanent magnets in the stator field to the field responsible for its for- phase power. So, even with induction and electromagnets with slip rings in the mation. Eddy currents can be reduced motors, you’re back to needing some rotor produced (at the time) an unusable by manufacturing thinner cores, or way of adding a pole that can produce AC voltage. Once Tesla showed how AC better yet, cores using multiple thin some offset to the single-phase pulsating could be stepped up for more efficient isolated laminations. magnetic field. The shaded pole induc- transmission of power over long dis- Core is its ability to retain or tion motor uses a copper shorting bar tances (a stumping DC problem for Edi- purge itself of residual magnetization. through a portion of the stator pole, son), the usefulness and simplicity of AC Any new energy trying to magnetize the effectively dividing the pole into two motors and generators () core must null residual before poles of differing induction. The (shaded) grabbed hold. By exchanging the rotor it can perform its designed function effi- pole produces a small lag in its magnetic and stator positions of the permanent ciently. Attention to core material and field with just enough torque to enable and electromagnets, the slip rings manufacturing reduce core hysteresis. the rotor to self start (begin rotation). become unnecessary, enabling less expensive manufacturing. The stator can WHERE HAVE ALL THE PMs GONE? ELECTRONIC CONTROL be wound with a series of coils, each Multiphase power—which was easy to Prior to the advent of the semiconduc- staying in step with the AC, alternately generate and transmit—gave the multi- tor, control of the electric motor was magnetizing each pole in one direction phase AC motor the starting torque it practically nonexistent and limited to a and then the opposite, 60 times a second needed without the gimmicks associated physical switch that could turn coil cur- (60 Hz). The permanent magnet rotor is with single-phase AC motors. Tesla first rent on and off. Initially, a stack of bat- pulled toward a pole and then pushed experimented with the rotating magnetic tery cells was tapped to apply varying away once each cycle. The rotor steps (if field of a multiphase AC synchronous DC potential to a brushed DC motor. you will) between poles at the 60-Hz motor in the 1880s. That led him to Then the power rheostat (two-terminal rate, making a complete revolution once introduce theories of self-induction in a variable resistor) was used to reduce the each 60 Hz per the number of poles. Sin- rotor. Up until that point, permanent potential to motors, with great losses in gle-phase synchronous AC motors have a magnets provided synchronous rotor efficiency and heat. starting problem because the single movement. Without permanent magnets As semiconductors were developed, phase doesn’t offer any off-center torque (PMs) or powered electromagnets in the their functions were exploited by the to ensure initial rotation. Self-starting rotor core, the rotating stator magnetic electric motor industry. Diodes can be accomplished by adding a leading field induced eddy currents in the rotor enabled chopping alternating AC into or lagging component to main windings that create their own opposing magnetic pulsating DC to run DC motors. SCRs (i.e., induction, capacitive, or reactive). field. The opposing magnetic field is (and TRIACs) provided a large leap in You can see (from the earlier discus- dragged toward the stator’s rotating field. control by providing a variable delayed sion on adding an additional pole at Maximum torque is developed while the on control during each half cycle of the 90° in a DC motor) that a second rotating stator field induces its maxi- AC waveform. The devices turned off phase can provide the necessary start- mum change in field strength. As the automatically at each zero-crossing of ing torque. With a single-phase AC rotor rotation approaches the rotating the input. Because the delayed on timing source, this isn’t possible. A second pole stator field, the field strength induced on was based on each zero-crossing, each (winding) at 90° would simply be in- the rotor decreases along with the avail- half cycle was treated to the same delay. phase with the original pole. By slightly able torque. The need for this differential A transistor’s linear characteristics altering the second pole, changing the requires the rotor to run slower than the enabled it to be used as an electronic number of turns in the stator field, or by stator’s rotating field. Thus, the induc- rheostat for DC motor control. It suf- adding a capacitor, the phase characteris- tion motor is considered asynchronous. fered from the same inefficiencies and tics are altered sufficiently so that it will While multiphase AC motors heat issues as the mechanical rheostat. be slightly out of phase with the main (including multiphase induction) don’t The question became: How could the winding. This will give the rotor a bit of have the starting problems of single- electronic device be used most efficient- torque to initiate rotation. phase motors, the country’s distribution ly (outside of its inefficient linear region) system provides our homes with single- yet still provide more control than sim- CORE ISSUES phase AC power. (It’s important to note ply an on/off switch? The answer led to The changing (alternating) field of AC that 220-VAC power is mistakenly called the beginning of a new age in motor con- motors brought some unique losses to multiphase.) It is two-phase power. Each trol: phase control (PWM). Up to that the forefront in addition to the I2R loss- leg is 180° with respect to one another. A point, motor operation was based on the es in all motor windings, hysteresis, and phase offset other than 0 or 180 is nec- power delivered from the public utilities. eddy currents. Solid-core designs were essary for self-starting. However, This new electronic command of power shown to create eddy currents within three-phase power uses three legs each to a motor eventually led to our own the core as it experienced a changing 120° apart. It is true multiphase. multiphased power source. magnetic field. Any changing current As I discussed earlier, single-phase New semiconductor devices were

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 77 27807002-Bachiochi.qxp 6/18/2008 10:10 AM Page 78

Type Advantages Disadvantages Typical use Drive AC Induction Least expensive Rotation slips from frequency Fans Uni/poly-phase AC (shaded pole) Long life Low starting torque High power

AC Induction High power Rotation slips from frequency Appliances Uni/poly-phase AC (split-phase capacitor) High starting torque AC Synchronous Rotation in-sync with frequency More expensive Clocks, audio turntables, and tape Uni/poly-phase AC Long life (alternator) drives

Stepper DC Precision positioning Slow speed (requires controller) Positioning in printers and floppy Multiphase DC High holding torque drives Brushless DC Long lifespan High initial cost Hard drives, CD/DVD players, and Multiphase DC Low maintenance requires controller electric vehicles High efficiency

PM DC Low initial cost High maintenance (brushes) Treadmill exercisers, LEGO system Direct (PWM) High reliability Low lifespan motors, and automotive starters Simple speed control (Dynamo)

Table 1—We won’t be substituting newer motor designs in applications where present solutions adequately perform their designated tasks. However, we are beginning to see some of the new technologies provide solutions to problems that we never knew existed.

specifically developed to handle the motor will slow down. More on time arrangement of FET devices can be used higher current/voltages of electric (e.g., 70%) will look like an average of to steer a single-polarity input voltage motors. The FET family has extremely 70% of the input voltage and the through a load in either direction. This low on-state resistances, which means motor will speed up. arrangement of FETs associates diago- that less of the input voltage is lost The frequency of this PWM control nal devices as pairs. One diagonal pair across the device when it is conduct- signal has practical limits. At a 50% of FETs, when turned on, allows cur- ing current. Less current equals less duty cycle, a slow frequency of, say, rent to flow in one direction through heat and higher efficiencies. A single FET once per second, will cause the motor the load (motor), while the opposite will efficiently turn on and off the basic to run at full speed for 0.5 s and stop diagonal pair of FETs allows current to DC brushed motor, effectively control- for 0.5 s. Although the overall work flow through the load in the opposite ling its speed by being driven by a of the motor is 50%, the speed isn’t direction. This adds the flexibility of varying on versus off control signal constant. direction to the speed control of a (PWM). For instance, if the on-versus-off At the input of many AC-to-DC brushed DC motor. timing is 50%, then the average volt- power supplies, a full bridge network of Although the direction and PWM con- age (over time) on the motor will be diodes is used to get the alternating trol to the semiconductor power devices one-half of the input voltage. Less on polarities of an AC voltage to pass was originally provided by discrete tim- time (e.g., 30%) will look like an average through a load in one direction only (to ing circuits, the introduction of the of 30% of the input voltage and the charge up the input capacitor). A bridge microcontroller handed control of these functions to the programmer. With added internal hardware to support these con-

Flow straightener trol signals, interfacing to the power

Motor stator devices became simpler. In the previous Blood example, pairs of FETs were used to con- flow Stator housing trol the speed and direction of current through a winding (pole) of a motor, Diffuser effectively controlling the strength of a magnetic field as well as its polarity. You can begin to see how these devices can Flow tube simulate AC and DC inputs to any elec- tric motor. In fact, this flexibility leads to additional motor configurations. The advantage of the AC motor was Inducer/impeller moving the electromagnets to the sta- tor, eliminating the need for slip rings. Multiphase AC created a rotating magnetic field. The same concept Figure 7—Patients using the DeBakey VAD will have the device installed in their chests and wear an external battery pack to power the pump. (Source: The Technology Transfer and Commercialization Office at the John- could be used on DC motors. The son Space Center, www.jsc..gov/info/annualreports/ar2001/s7.pdf) commutator would not be necessary,

78 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 27807002-Bachiochi.qxp 6/10/2008 4:38 PM Page 79

common, the pole can be energized in closed-loop control. Here, you’re dealing either polarity by turning on the associ- with motion profiling, including S-curve, ated power device connected to each free trapezoidal, and velocity contouring. end. A bipolar stepper uses a single coil I am wandering a bit from my intend- per pole, providing twice the turns per ed path here. It is difficult to keep all of pole but requiring four FETs (H-bridge this structured because the development arrangement) to control the polarity. of the motor has been influenced so much by electronics. The blood lines of MOTOR CHOICES ARE EXPANDING the motor family tree are no longer pure. Although motor controllers increase Where will this lead us? It’s becoming Photo 1—The motor consists of a stator using piezo- the cost of motor applications, they obvious that there is a big future for electric strips instead of electromagnetic coils. The have encouraged the introduction of spe- small devices. The ventricular assist internal shaft rotates as the strips are phased. cialized motors designed to take advan- device pump (VAD) in Figure 7 (devel- (Source: Kenji Uchino, Pennsylvania State University, www.psu.edu/ur/heartdevices/tinymotor.htm) tage of their flexibility (see Table 1). oped in collaboration with Dr. Michael Controllers incorporate the necessary DeBakey, Dr. George Noon, and a team interfaces to control external high- of NASA engineers) was created to assist because all of the appropriately phased power devices. Based on the commuta- patients with congestive heart failure. inputs would be produced by the torless AC , the “Too big,” you say. Take a look at the microcontroller. The distinction brushless DC motor has no mainte- ultrasonic developed between AC and DC motors now nance issues associated with “brush- by researchers at Pennsylvania State becomes blurry. es” and it is quickly becoming the University’s Materials Research Insti- This new ability to control (or cre- motor of choice in many applications. tute (see Photo 1). Still too big? The ate) input to electrical motors also While most motor control applications was constructed at the provides a new control function that can be handled with microcontrollers University of California, Berkeley (see was previously nonexistent (unless and an appropriate amount of software, Photo 2). This “motor” (if you want to you consider the centrifugal governor). when it comes to high precision and think about it that way) is about 500 nm Feedback of the rotation (position or complex movement, there are alterna- across. That’s 300 times smaller than speed) is helpful (in some cases mandato- tives to rolling your own design. Perfor- the diameter of a human hair. ry) in maintaining proper control signals mance Motion Devices (PMD) has single “But this is just research stuff,” you referenced to a motor’s physical move- and multiaxis controllers that can handle say. Yes, however, the future is start- ments. There are non-sensor methods of about any motor configuration giving ing out there today on someone’s lab obtaining feedback based on monitoring table. This isn’t a case of reinventing the back EMF (output produced by the the wheel. It’s a matter of using the motor acting as a generator). The more newest technology to improve existing conventional approach is to use a sensor implementations or create entirely mounted to the motor. One of the least new ones. Meanwhile, our washing expensive approaches uses Hall effect machines, powered by AC induction sensors to sense rotor position. When motors, still get our clothes clean. I increased accuracy is needed, an optical encoder can be used. The method you Jeff Bachiochi (pronounced BAH-key-AH- choose will depend on the type of feed- key) has been writing for Circuit Cellar back information you require. since 1988. His background includes The was one of the first product design and manufacturing. He specialized brushless DC motors. The may be reached through the magazine design calls for a rotor with many ([email protected]) or his poles so a two-phase input will cog or web site (www.imaginethatnow.com). step the rotor between stator windings in either direction, depending on the order of the applied phases, one small RESOURCE step at a time. This is a micromove- T. Kuphaldt, “Lessons In Electric Circuits, ment of four steps per each tooth (PM Volume II – AC,” 2007, www.ibiblio.org/ pole) that make up the rotor. A stepper obp/electricCircuits. motor moves a precise distance and Photo 2—The almost invisible vertical thread suspending holds position without using feedback. the gold plate rotor is actually a pair of nested carbon Two types of stepper motors are nanotubes. Once cut free from top and bottom sup- SOURCE ports, the outer nanotube and plate can be electrostati- manufactured: unipolar and bipolar. A Motion control devices cally rotated relative to the inner core. (Source: Zettl lab, unipolar stepper uses a center-tapped coil The University of California, Berkeley, www.berkeley.edu/ Performance Motion Devices, Inc. on each pole. With the center tap as news/media/releases/2003/07/23_motor.shtml) www.pmdcorp.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 79 2807003-Cantrell.qxp 6/10/2008 4:40 PM Page 80

SILICON UPDATE by Tom Cantrell

MIPS For The Masses To compete with the rest of the 32-bit market, Microchip Technology designed its 32-bit offering around the MIPS architecture. The PIC32 combines Microchip’s in-house MCU know-how with MIPS Technology’s extensive IP, software, and tool library. Expect to see PIC32s for a long time to come.

Thanks to the popularity of their Filling,” Circuit Cellar 212, 2008), the engineering cost and time-to-market. venerable PIC chips and the robust headline news for the PIC32 is adop- Remember that defining and imple- 8/16-bit MCU market, Microchip tion of the MIPS architecture. Does menting the architecture is one thing, Technology remains one of the world’s that make sense? Let’s imagine the but there’s also the small matter of top MCU suppliers. There is no doubt thought process the Microchip crew coming up with gigabytes of software that the number of “sockets” filled by might have gone through. tools—“C” compiler, simulator, PIC chips is impressive. Indeed, The first fork in the architectural RTOS, TCP/IP, and on, and on (see Microchip just announced the sale of road would have been the decision of Photo 1). And once you cobble togeth- their six-billionth PIC.[1] But when I whether to “make” a new architecture er a few chips and tools, potential cus- say “popular,” I’m not just talking or “buy” an existing one. Of course, tomers will invariably start asking about the volume of chips sold. When ask a computer architect which option about an “upgrade path” or “ASIC it comes to market momentum and they’d prefer and the answer is obvi- option.” staying power, it’s the number of ous. It’s always possible (and fun!) to No single issue by itself seems “seats” (i.e., designers) that really come up with a “new and improved” insurmountable, but all of the prob- matters. With an aggressive “mass architecture. Plus, beyond any techni- lems together are pretty much a show- marketing” approach, Microchip has cal advantages, a proprietary architec- stopper for the “roll your own” idea. filled the seats on their PIC bandwag- ture offers the potential of “locking” So, let’s turn to the “buy” alterna- on with legions of true believers. customers in. This is something tive. Licensing an ARM core would be It all sounds rosy, but of late, there’s everyone in the chip business knows, an obvious solution. But perhaps been a bit of a problem. Everyone knows including Microchip judging by the that’s the problem (i.e., it’s too obvi- the 32-bit MCU market is taking off, legal slap downs they’ve dealt to ous). Major 32-bit MCU players like fueled with a powerful mix of high-per- would-be PIC cloners over the years. Atmel, NXP Semiconductors, and formance, yet practical (e.g., cost, power, “Lifetime Employment Act for STMicroelectronics are already far and size), parts from industry heavy- Computer Architects” aside, there are down that fork in the road. So, how weights with proven track records. some gotchas. In the past, creating a about making a deal with one of the It seems like the competition was new architecture was largely a matter other 32-bit MCU contenders such as giving a 32-bit MCU party and of fixing the apparent-in-hindsight Freescale Semiconductor (Coldfire) or Microchip wasn’t invited. So they mistakes of existing ones. But at this Renesas Technology (SuperH)? invited themselves. The PIC32 is point, competitive architectures are Unfortunately, history shows such what Microchip calls their 32-bit gate highly refined, so there aren’t a lot of “second-source” deals have a poor crasher. It’s a big deal, so let’s get this obvious upgrades on the table. Short track record once the honeymoon is party started (see Figure 1). of a radical departure, a “new and over. Indeed, in their former lives, improved” architecture would likely Freescale and Renesas (then Motorola ROCK AND A HARD CHIP end up looking pretty much the same and Hitachi) had a second-source deal As I reported at the time of its as all of the rest. that infamously crashed and burned announcement (“More Bits, Less And there is a bit of a problem with leaving no one (except the lawyers)

80 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2807003-Cantrell.qxp 6/10/2008 4:40 PM Page 81

better off. Even if Microchip was more willing, because the deal fills a is supported with decades worth of interested, chances are neither huge gap in their strategy (i.e., lack tools, marketing, and support. The Freescale nor Renesas would be. of a standard MCU supplier) relative architecture has plenty of IP acces- That doesn’t leave many options to ARM, their major competitor in sories (i.e., peripherals and software) does it? In fact, I can think of about the “Architectures-R-Us” biz. and headroom to support anyone’s two, namely MIPS and IBM This is a good deal for Microchip. onward and upward performance aspi- PowerPC. Without speculating fur- They get a seasoned and proven design rations. Feel like you need the flexi- ther, suffice it to say, Microchip without having to type one line of bility to ultimately move to an ASIC? chose the former. Maybe MIPS was HDL. Right out of the gate, the PIC32 Well, a custom-chip focus is MIPS

VDDCORE/VCAP OSC2/CLKO OSC/SOSC Power-up V , V OSC1/CLKI Oscillators timer DD SS FRC/LPRC ENVREG *MCLR Oscillator Oscillators Voltage regulator start-up timer

PLL Precision Power-on band gap reset reference Dividers Watchdog timer SYSCLK PBCLK Brown-out Timing reset(3) generation

Peripheral bus clocked by SYSCLK

CN1-22(1) PORTA(1,4) JTAG Interrupt BSCAN controller

PWM PORTB OC1-5 EJTAG INT DMAC(2) ICD 32 MIPS32 M4K CPU Core IC1-5 PORTC(1) IS DS 32 32 32 32 32 SPI1,2(1) PORTD(1) Bus matrix Peripheral bus clocked by PBCLK by clocked bus Peripheral 32 32 32 I2C1,2 PORTE(1) 32 Prefetch Peripheral bridge module(2) Data RAM PMP(1)

PORTF(1) 128

UART1,2 128-Bit-wide PORTG(1)

program flash memory Flash controller

Comparators Peripheral bus clocked by PBCLK

Timer1 Timer2 Timer3 Timer4 Timer5 RTCC 10-bit ADC

Notes: 1: Not all pins or features are implemented on all device pinout configurations. 2: Some features are not available on certain devices. 3: BOR functionality is provided when the on-board voltage regulator is enabled. 4: PORTA is not present on 64-pin devices.

Figure 1—Microchip may be a bit late to the 32-bit MCU party, but their MIPS-based PIC32 is making quite an entrance.

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 81 2807003-Cantrell.qxp 6/10/2008 4:40 PM Page 82

MIPS. The question is: Is it a good deal for you?

IT’S A SMALL WORLD AFTER ALL First a little history. The MIPS architecture was born in the early 1980s under the direction of John Hennessy, then a professor at Stanford University, who was in a race against a similar effort underway at cross-bay rival University of California, Berkeley, under the tutelage of Professor David Patterson. This marked the start of the RISC revolu- tion. Later, Hennessy and Patterson put aside their collegiate rivalry to author Computer Architecture: A Quantitative Approach, one of the single best tomes on the subject.[2] By the way, Hennessy is now the presi- dent of Stanford University, so who says there’s no career path for engi- Photo 1—Could Microchip have crafted their own home-grown CPU architecture? Sure. But they couldn’t have come neers beyond the lab? Things are look- up with the zillion lines of code to support it. Thanks to decades of legacy software for the MIPS architecture, a full suite ing up for us techies. See you at the of proven tools is available right out of the starting gate. “Nerd-Pride Parade.”[3] The fundamental premise of RISC bread and butter, so they’ve got you Yes, the PIC32 is a good deal for was to keep it simple, and thereby covered. Microchip. And it’s a good deal for make it faster. Instead of the baroque instruction sets found on the mini- computers (e.g., DEC and VAX) and micros (e.g., ’86 and 68K) of the time, the instruction set for a RISC was basically defined as those instructions, and only those instructions, that could be executed quickly. The origi- nal MIPS processor, known as the R2000, didn’t even have a multiply instruction! Of course, like hemlines, architec- tural fashion waxes and wanes. Today’s RISCs are hardly “reduced” by any means. But because the PIC32 is based on the simplest core MIPS offers, it’s lean and mean enough for blue-collar MCU apps (see Figure 2). You can still see vestiges of the old- timey RISCs including a classic five- stage pipeline, 32 × 32-bit register file, and a relatively terse load/store instruction set. There were a lot of gotchas with the original RISCs that MIPS and Microchip (and all the other 32-bit MCU suppliers) have fixed by now. Retro-RISCs could barely toggle a bit, something the PIC32 can handle easi- ly with atomic bit manipulation capa- bility for peripherals. In the old days,

82 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2807003-Cantrell.qxp 6/10/2008 4:40 PM Page 83

an “interrupt” was a rare event and “real

time” meant something like 60 Hz. High-performance MIPS 32-bit cores Today, the PIC32 features a shadow cores

register set and a built-in priority d de ea interrupt controller for speedy inter- thr lti- d Mid-performance u deed Next Multi-threadedM ea rupt response. The 32-bit fixed cores thr gen le- ng instruction length dogma of yore Multi-threaded with Single-threadSi DSP extensions 74K resulted in bloaty code (i.e., poor code 500 MHz in 90 nm G 34K Industry-leading performance density), but the PIC32 includes the 1+ GHz, synthesized in 65 nm GP 24KE 16-bit MIPS16e code-compression Entry-level DSP extensions scheme (a la ARM’s Thumb) to cut the cores 24K Up to 3x signal 4KSd processing performance fat. Developing RISC software (not to Fastest single-threaded 4KE performance mention debugging it) was hard, but 600+ MHz in 90 nm G Mainstream embedded after all of these years, the tools (e.g., processor M4K compilers, libraries, RTOS, etc.) have 233 MHz in 130 nm G Microcontroller replacement th been refined and optimized to the n 225 MHz in 130 nm G - 30K gates degree. And of course, there is now a multiply instruction, and a fast one at Figure 2—The MIPS line-up clearly offers a lot of headroom for the PIC32 to evolve onward and upward. Indeed, that (32 × 16 in one clock, 32 × 32 in some might wonder if the MIPS cores are overkill for blue-collar embedded apps. But Moore’s Law tells us that two). when it comes to silicon, it’s never a question of “if,” just “when.”

WHERE SILICON MEETS THE ROAD runs into the dreaded “flash bottle- from flash memory? Beyond a decent architecture, when neck.” Unfortunately, it seems as The flash memory access time for it comes time to actually build some- though flash technology is always the PIC32 is 50 ns. That means wait thing, it’s the chip implementation, playing catch up and just can’t keep states enter the picture at just 20 MHz tools, and support that matter most to pace as clock rates approach triple and become a real drag at 40 MHz and designers. “Core Wars” aside, here’s digits (up to 80 MHz for the PIC32). beyond. Microchip’s solution is a mini- the stuff I would look for when choos- A core may be able to execute an me 256-byte instruction cache (see ing a 32-bit MCU. instruction in a single clock, but Figure 3). It’s pretty simple, really lit- Faced with cries for evermore MIPS what good is that if it takes two tle more than a fancy prefetch buffer, and megahertz, a 32-bit MCU eventually clocks (or three or four…) to grab it but one with a few nifty embellish- ments. Any or all of the 16 lines (each 128 bits (i.e., four 32-bit instructions)) can be individually locked for high-speed predictable FSM CTRL response. Up to four lines can be allo- cated for read-only data (e.g., filter Tag logic Cache line coefficients) stored in flash memory. CTRL Bus Ctrl An address mask feature allows mul-

BMX/CPU tiple copies of the same code in Cache Ctrl memory (e.g., prelude common to all BMX/CPU Prefetch Ctrl Cache line interrupt handlers) to use a single address RDATA cache line. Hit LRU encode Here are a couple of possible low- Miss LRU power tweaks to keep in mind. Even if you’re running at less than 20 MHz, it Hit logic can make sense to run code from the cache (do turn off the prefetch feature) Prefetch Prefetch because accessing the cache RAM con- sumes less power than accessing the CTRL

RDATA flash memory. The PIC32 can also

PFM execute code from on-chip RAM, like- ly another path to performance and power optimization. Speaking of low power, that’s high on the shopping list for anybody mak- Figure 3—If there’s one thing holding 32-bit MCUs back, it’s the flash bottleneck. It is all the more true for RISC architectures that have a voracious appetite for instruction bandwidth. The PIC32 utilizes a small cache to keep the ing a battery-powered gadget. The last processor fed. A 128-bit-wide bus broadside loads an entire cache line with a single-flash access. thing designers need is some porky

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 83 2807003-Cantrell.qxp 6/10/2008 4:40 PM Page 84

other stuff built-in, enough to fill a 626-page datasheet. Needless to say, I Vector number can’t cover everything in detail, but here are some of the highlights.

Interrupt controller CPU Core Major drivetrain components close Priority level to the core complete the PIC32’s per- sonality shift from “computer” to Interrupt requests “controller.” Let’s start with the clock Shadow set number generator. Make that “generators” plu- ral because there are four clocks to play with. In addition to the expect- Figure 4—The original RISCs were a bit too “reduced” when it came to interrupts. Not so with the PIC32, thanks to ed connection for the high-speed a vectored interrupt controller with up to 96 sources and programmable priority. A dedicated shadow register set clock (e.g., 4- to 5-MHz crystal feed- and the ability to lock handler code into the cache accelerates interrupt response. ing the on-chip PLL), there is a sepa- rate 32-kHz input for the real-time bloat chip wasting watts like there’s the PIC32 off its low-speed on-chip clock and other keep-alive logic. On- no tomorrow (we have PCs for that). 31-kHz RC clock. Yeah, you’ll have chip, there are both fast (8 MHz) and Indeed, if you consider the billions of only KIPS, not MIPS, to play with (call slow (31 kHz) RC clocks, which can MCUs at work 24/7, saving just a few it “GROGGY Mode”), but power con- replace the external clock entirely for milliamps adds up. That’s a lot of sumption drops into the microamps applications that don’t need super- energy that we don’t have to scrounge (e.g., 125 µA typical at 25°C). accurate timing. And even if an exter- up somewhere else. Putting the chip to SLEEP is the final nal clock is used, the on-chip clocks Now I won’t try to kid you. In typi- power-saving straw. At these low lev- are useful for low-power throttle cal operation, you can figure the PIC32 els, the actual power consumption down, two-speed fast wake up (start is going to consume about 1 mA per varies greatly depending on two factors. executing using RC while crystal sta- 1 MHz, which doesn’t sound too bad. But One is which, if any, of the ancillary bilizes), and clock-fail detect with that does add up to 75 mA at 80 MHz, functions you choose to keep powered automatic switchover. or 0.25 W at 3.3 V. up, typically to provide a subsequent In the early days, MIPS chips Obviously, the PIC32 isn’t an oh-so- wake-up call. The watchdog timer or weren’t very interrupt savvy. They’d green 8/16-bit MCU, but it does have real-time clock are good choices pretty much treat every interrupt the a number of power-saving features you because they consume only a dozen same and just leave a few crumbs (e.g., should exploit. There are the usual microamps or so while the ADC is a “Cause” code) for software, which IDLE and SLEEP modes plus the abili- pricey keep-alive option at fully 1 mA. otherwise had to deal with all of the ty to individually turn off each periph- The other factor affecting power con- gory details like context switching, eral function or leave it on. That’s a sumption is temperature and its impact nesting, priority, and such. By con- nice touch because it means you can is nontrivial. For instance, SLEEPING trast, the PIC32 has a full-featured pri- power only the peripheral(s) your at room temperature (25°C) with just ority vector interrupt controller that application needs to serve as wake-up the watchdog enabled consumes does all of the juggling in hardware sources and turn off the rest. around 40 µA. Run the same setup at (see Figure 4). Dynamically reducing the CPU the maximum rated temperature (85°C) I noticed that the interrupt con- clock rate to the minimum necessary and you’re talking more than 300 µA. troller has an interesting “coalescing” to meet instantaneous performance feature I hadn’t seen before. It’s easy demand is the best solution. For MORE BITS, LESS FILLING to understand with a metaphorical instance, you can still get plenty of It takes more than a good core to get example. Let’s say you’re having a din- MIPS (and zero wait states) running at the job done. The PIC32 has a lot of ner party tonight and need to gather 20 MHz, which drops the ingredients for large power consumption to salad, a main course, and under 25 mA typical. Address/data configuration Read speed, MHz(1, 2) Write speed, MHz(1, 2) dessert. So, at 10 A.M., Similarly, you can Demultiplexed 40.0 26.6 you drive to the market dynamically divide the Partial multiplex 16.0 13.3 and buy the salad fix- peripheral bus clock Full multiplexed (8-bit data) 10.0 8.8 ings. Then, at 2 P.M., down, keeping in mind Full multiplexed (16-bit data) 16.0 13.3 you drive a second time the possible need to to buy the ingredients adjust peripheral settings Notes (1): SYSCLK = PBCLK = 80 MHz for the main course. (e.g., UART data rates) (2): Assumes zero wait states for external device Finally, at 4 P.M., you go accordingly. yet again to pick up Table 1—High-speed 32-bit MCUs can implement surprisingly fast expansion buses using a Taking clock scaling to sequence of software instructions. The PIC32 takes the concept a step further with a Parallel dessert. the extreme, you can run Master Port that does it in hardware, faster, and with zero software overhead. This is obviously a

84 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 2807003-Cantrell.qxp 6/10/2008 4:40 PM Page 85

configurable CRC genera- Today, for just a few bucks (from tion and checking. That’s $2.95 for 32-KB flash/8-KB RAM to all cool, but I was also $5.30 for 512-KB/32-KB in 10K vol- pleased to see how well ume), you get a PIC32 “controller” the DMAC handles byte- that’s equivalent to a top-of-the-line oriented stuff (i.e., “computer” from yesteryear. And it’s unaligned transfers). The a heck of a lot easier to design in (see original computer-orient- Photo 2). ed RISCs had a bit of a But you’ve heard me say it before: A “What, me worry?” atti- good chip is just necessary, not suffi- tude about lowly bytes, cient, to guarantee success. It takes a but the PIC32 DMAC lot of tools, support, and a full catalog understands that, at least of parts to stay in the game. Whatever for embedded applica- you think of the PIC32, no one can tions, bytes still matter. deny Microchip knows what it takes Photo 2—You’ve come a long way baby. As the PIC32 starter kit ($49.99) Vestiges of MIPS com- to sell MCUs. Combining their own shows, what was once a high-falutin RISC “computer” has been shrunk to a single chip, slashing the price, size, and power consumption along puter-oriented roots in-house PIC know-how with MIPS the way. remain in the form of a extensive IP, software, and tool library, User/Kernel protection no doubt we’ll see plenty of new wasteful scenario, even if it “meets model and virtual memory address PIC32s joining the line-up soon. In the schedule.” And if an unexpected translation. But in the PIC32, these fact, taking advantage of MIPS exist- delay should arise, the overhead and big-ticket software (e.g., WinCE, ing IP, Microchip has already latency could have your starving Linux, and RTOS) features are hidden announced a version of the PIC32 guests pounding the table. behind a simple fixed-memory map. with built-in USB. Larger embedded apps can face a At least for now, but I wouldn’t be When it comes to supplier competi- similar scenario. They may, for exam- surprised to see a future PIC32 with tion and choices for designers, the more ple, spend 80% of their time handling the full-featured MMU. the merrier, I say. OK Microchip, the main application and the remain- When it comes to peripherals, the bring it on! I ing 20% handling miscellaneous low- PIC32 has all of the usual suspects and priority chores. But just as with the then some. There are up to 16 channels Tom Cantrell has been working on example of driving to the market of 10-bit, 500-kHz A/D, two analog chip, board, and systems design and three times, dealing with each chore comparators with programmable on- marketing for several years. You may (i.e., interrupt) separately is wasteful. chip reference, five 16-bit timers (can reach him by e-mail at tom.cantrell@ The extra overhead (e.g., context be paired to work as 32 bits), and a circuitcellar.com. switches) burns power and, in the full complement of serial I/O includ- worst case, may even put the sched- ing I2C, SPI, and UARTs. I did notice ule at risk. one I/O extra that stands out a bit REFERENCES The PIC32 interrupt coalescing fea- from the MCU crowd. While the chip [1] Microchip Technology, “Microchip ture is a scheme that holds off back- doesn’t have an external bus interface Technology Delivers Six Billionth ground (i.e., intermittent and low-pri- per se, it does include a “Parallel Master PIC Microcontroller,” Press Release, ority) “chore” type interrupts for effi- Port” (16-bit address, 8- or 16-bit data) February 27, 2008, www.microchip. cient batch processing (i.e., like driv- that provides fast and easy connection com/stellent/idcplg?IdcService=SS_ ing to the market just once). That to external devices such as memory GET_PAGE&nodeId=2018&mcparam way, a single invocation of the handler and I/O chips, another MCU, FPGA, =en534302. can deal with all of the chores at one and more. (see Table 1). time with just a single context switch. [2] J. Hennessy and D. Patterson, This is kind of like using a timer to EASY DOES IT Computer Architecture: A generate a periodic “chore”-type inter- It must have been 20-plus years ago Quantitative Approach, Morgan rupt and then polling to see what or so that I was working on a MIPS Kaufmann, San Francisco, CA, 2006. needs to be done, but more efficient. R3000-based SBC. It was a board as [3] D. Christiansen, “Nerdiness,” IEEE- Speaking of driving, a four-channel big as this magazine that consumed USA Today’s Engineer Online, DMA controller provides the equiva- amps of power and cost thousands of December 2007/January 2008. lent of high-speed mass transit. It can dollars. I remember I had a devil of a be assigned to work with different time getting the finicky multiphase peripherals or interrupts and has lots clock generator and “double pumped” SOURCE of whizzy features like “chaining” memory interface (data transferred on PIC32 Microcontroller (multi-channel sequence of transfers), both edges of the clock) to work. Good Microchip Technology, Inc. pattern matching termination, and times. www.microchip.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 85 ib-216.qxp 6/11/2008 10:00 AM Page 86 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/vendor/ is your guide to a variety of engineering products and services.

UUSSBB Add USB to your next project—it’s easier than you might think! v USB-FIFO up to 8 mbps v USB-UART up to 3 mbps v USB/Microcontroller boards pre-programmed with firmware v 2.4GHz ZigBee™ & 802.15.4 v RFID Reader/Writer Absolutely NO driver software development required! www.dlpdesign.com

86 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com ib-216.qxp 6/11/2008 10:00 AM Page 87

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 87 ib-216.qxp 6/11/2008 10:00 AM Page 88

® ® Online Training for Microchip ARM PIC® 8051 Microcontrollers ®

8 Week Online Course COLDFIRE

Learn at your own pace with confidence! ARE Three quality tool suites Uses EasyPIC5 Development Board! q * See Webpage for Course Contents, C/C++ Schedule and what Former Students say! q Course is loaded with Flash Videos and Code Wizards Lots of Hands-on programming exercises. q Debugging 4 week grace period to finish! q Simulation q Support * Embedded C++ for ARM and ColdFire only Advanced software tools since 1984 www.crossware.com Tools for Embedded Development Tools

WWW.TOMCHRANE.COM CROSSW 360-812-2397

88 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com ib-216.qxp 6/11/2008 10:01 AM Page 89

NEW

HI-TECH C® PRO for the Cypress® PSoC® Mixed-Signal Array C Compiler FREEWARE New PRO compiler also operates in Lite mode with no time or size limits: cypress.htsoft.com/portal/CC20

Cypress and PSoC are registered trademarks of Cypress Semiconductor Corp.

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 89 ib-216.qxp 6/13/2008 11:07 AM Page 90

PCB EasyPC SW From TSI: Import Eagle libs and Designs. By Online www.pcb-sw.com Import any of the big three, using Intelligent Gerber. Download the FREE Demo from the web. PromCode D0506 Financing Available

Why fight with downloads? Access thousands of Circuit Cellar contest project files in seconds rather than minutes. Ensure that these application Abstracts libraries remain safe within your personal archive. Full Entries S CD-ROMs now available: ource Code • WIZnet iEthernet Design Diagrams Contest 2007 Photos • Microchip Technology 16-Bit Embedded Control Design and more! Contest 2007 To order, visit • Atmel AVR Design Contest 2006 www.circuitcellar.com/CD

90 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com ib-216.qxp 6/11/2008 10:01 AM Page 91

Coming Soon! A Social Networking Site for You, the Electronics Enthusiast!

We Need Beta Testers Now Sign Up At:

www.solderbynumbers.com

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 91 ib-216.qxp 6/11/2008 10:01 AM Page 92

:HFDQ·WJHWLWULJKW ZLWKRXW\RXULQSXW 3OHDVHWDNHD PRPHQWWRFRPSOHWH &LUFXLW&HOODU·V UHDGHUVKLSVXUYH\

7RSDUWLFLSDWHYLVLW ZZZFLUFXLWFHOODUFRP VXUYH\

3DUWLFLSDWLRQHQWHUV\RX LQWRDUDQGRPGUDZLQJ IRURQHRI&LUFXLW &HOODUPDJD]LQH FRPSOHWH&'520 DUFKLYHV

92 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com crossword2.qxp 6/11/2008 11:01 AM Page 93

CROSSWORD

1 2

3

45

6 7

8 9

10

11

12

13

14

15

16

Across Down 2. The robotic spacecraft that landed on Mars on May 25, 2008 1. Li 3. The “father of supercomputing” (1925–1996) 2. An area saturated with wireless networks 6. A software analysis tool used for studying the performance of a 4. U.S. president who received the results program from the “Trinity” test 8. Just in time 5. Echo effect 10. Data received incorrectly 7. A steady flow of information 11. Derived class 9. 0.1 nanometers 12. Electric current produced by the illumination of photosensitive 13. A computer that stores web documents material for clients or users 13. A box that protects network equipment 15. An object that enables portions of com- 14. A type of serial port interface on a PC puter code to share the same resource 16. A group of programs produced by the same manufacturer but not simultaneously

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

www.circuitcellar.com CIRCUIT CELLAR® Issue 216 July 2008 93 94-advertiser's index.qxp 6/13/2008 10:53 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 57 ezPCB 88 Lawicel AB 19, 57 Rabbit, A Digi International Brand

29 AP Circuits 86 FDI-Future Designs, Inc. 8, 90 Lemos International 87 Rabbit, A Digi International Brand

91 All Electronics Corp. 91 FlexiPanel Ltd. 66 Linx Technologies 89 Reach Technology, Inc.

89 Apex Embedded Systems 91 FlyPCB China Co., Ltd. 87 Loadstar Sensors, Inc. 41 Renesas Technology

88 Applied Micro Training 8 Frontpanel Express LLC 88 MCC (Micro Computer Control) 87, 95 Saelig Co.

7 Atmel 36 Grid Connect, Inc. 89 Mach Design Services, LLC 91 Schmartboard

5 Bitscope Designs 87 Hagstrom Electronics 90, 92 Micro Digital, Inc. 9 SEGGER Microcontroller Systems LLC

65 CWAV 89 HI-TECH Software LLC 11 Microchip 1 Sunstone Circuits

58, 88 CadSoft Computer, Inc. 14 HobbyLab LLC 92 microEngineering Labs, Inc. 91 Systronix

29 Calao Systems 33 Holtek Semiconductor, Inc. 21 Mouser Electronics 92 TAL Technologies

56 Comfile Technology, Inc. 50 HOT Chips 17 Symposium 89 Mylydia, Inc. C3 Tech Tools

88 Crossware Products, Inc. 89 ISP Micro C2 NetBurner 2, 3 Technologic Systems

90 Custom Computer Services, Inc. 87 IMAGEcraft 67 Nurve Networks LLC 91 Technological Arts

86 DLP Design 88 Intec Automation, Inc. 91 Ontrak Control Systems 90 Technology Sales Inc.

88 Designnotes 86 Ironwood Electronics 16 PCB-Pool 89 Tern, Inc.

36 EMAC, Inc. 64, 66 JKmicrosystems, Inc. C4 Parallax, Inc. 10 Tibbo Technology, Inc.

42 ESC Boston 91 JKmicrosystems, Inc. 87 Phytec America LLC 87 Tin Can Tools, LLC

89 Earth Computer Technologies 27 Jameco 90 PicoFab, Inc. 92 Trace Systems, Inc.

64 Elprotronic 67 Jeffrey Kerr LLC 88 Pioneer Hill Software 88 Triangle Research Int’l, Inc.

34 Embedded Developer 82 Keil Software 15 Pololu Corp. 49 Wiznet

40 ExpressPCB 67 Lakeview Research 86 Pulsar, Inc. 86 Xytronix Reasearch & Design, Inc.

Preview of August Issue 217 ATTENTION ADVERTISERS Theme: Embedded Development September Issue 218 Create A USB Virtual COM Port Deadlines RTOS Design: Customize An OS For A Powerful Embedded MCU Space Close: July 11 PSoC Design Techniques (Part 2): Add DSP Effects, A User Interface, And More Material Close: July 18 Electric Vehicle Inverter Design: Build A System For Powering AC Induction Motors Theme: A Bootloader For Blackfin The DMX Portal: Obtain DMX Control Via Ethernet Data Acquisition

BONUS DISTRIBUTIONS: PCBwest; Robo Development THE DARKER SIDE Direct Digital Synthesis 101 Call Shannon Barraclough ABOVE THE GROUND PLANE IR Proximity Sensing now to reserve your space! FROM THE BENCH Water War Prevention: An MCU-Based Monitor For A Communal Well 860.875.2199 SILICON UPDATE Icy Hot: The “Soft-Core” Concept, FPGAs, and You e-mail: [email protected]

94 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com 95.qxp 6/3/2008 3:29 PM Page 1

7KLQNLQJDERXW\RXUQH[WVFRSH" Compare the specs: Tektronix Agilent Pico Link Bitscope TiePie cleverscope Item TDS2012B MSO6012A 3206 DSO-8502 USB 310 HS3-100 CS328A r100 mV ± r r513mV ± r r100 mV ± Analog Input FSD 20 mV ± 50V 20 mV ± 50V 50 mV ± 50V 18 mV ± 80V 20V 10.8V 80V Overload Protection 300 Vrms 300 Vrms r50V r150V r100V 200V 300 Vrms Analog Channel bit resolution 8 8 8 8 8 8 or 12 10, 12 or 14 Can do hardware trigger referenced averaging Yes (10 bit) Yes (10 bit) - - - - Yes (14 bit) r3.5V Æ r2V:Æ200mV r25V:Æ200mV Analog Input Offset None r5 divisions None None 200mV then r then r50V then r100V 80V External trigger sampled, stored & displayed? No No No No No No Yes 4000k or Samples of storage, all inputs recorded 2.5k 2000k or 8000k 500k 512K 64k 128k 8000k Resolution on 2V offset signal 0.078 mV 0.078 mV 15.6 mV 15.6 mV 15.6 mV 15.6 mV 0.018 mV Tracking graph with independent time base No No No No No No Yes 60 dB or 72 Dynamic Range (raw unprocessed) 48 dB 48 dB 48 dB 48 dB 48 dB 48 dB dB or 84 dB Maximum time resolution 1ns 0.5ns 10ns 4ns 50ns 10ns 10ns Resolution at 20ms width 8 us 10 ns 40 ns 40 ns 320 ns 200 ns 10ns 1.3 ms Width at max sample rate 2.5us width 1 ms width 5 ms width 320 us width 640us width 20 or 40 ms width Peak Captured to eliminate aliasing Yes Yes Yes No No No Yes Anti-alias filter Yes ± 20 MHz Yes ± 20 MHz No No No No Yes ± 20 MHz Trigger delay Yes Yes No No Yes No Yes Period Trigger Yes Yes Yes Yes No No Yes the review continues on our website at www.cleverscope.com/review/ i 100 MHz Bandwidth i Dual mixed sig trigger i 2 analog, 8 digital inputs and ext trig

i 10,12 or 14 bit Main scope and tracking displays sampling DDE support provides dynamic i 4 or 8 MSamples/ update of excel spreadsheets Linear or logarithmic spectrum display channel storage USA master distributor i 100 MSamples/sec i Battery option i USB or ethernet i Data projector display The CS328A is an engineer’s toolbox i Regular software and Oscilloscope²Tracking Graph²Spectrum Analyzer Protocol Analyzer Multimeter Logger Result Storage firmware updates ² ² ² Maths Equation Builder and Display²Function Generator i Simple cut and paste XY Graph²Drivers for C, Dephi and Labview into documents Custom Names, Units and Scaling

www.cleverscope.com steve_edit_216_v1.qxp 6/11/2008 11:03 AM Page 96

PRIORITY INTERRUPT

by Steve Ciarcia, Founder and Editorial Director A Real Rube Goldberg Solution

Since we have a large foreign readership, let me start by explaining the title of this editorial. Rube Goldberg was an engineer in the early 1900s who became a Pulitzer Prize-winning cartoonist. He is best known for drawing cartoons depicting “Rube Goldberg Machines.” A “Rube Goldberg” is an extremely complicated apparatus or series of connected devices with the sole purpose of performing a single simple task in an extremely convoluted way.Today, whenever engineers are involved with an overly complicated piece of hardware or tortuous software, they will call it a Rube Goldberg. The bad news, of course, is when you actually need to make one of your own. After installing the photovoltaic (PV) system last fall, I decided to add a lot more energy-related sensors and controls this spring ($4.50/gal. heating oil is a lot of incentive). So, I ordered multichannel temperature sensors from two manufacturers and a PV power data logger from a third. My experience with these products is a lot like my opinion of Vista—nobody did their homework before selling it. The issue isn’t whether these sensors and loggers work—they do.They are a marvel of integration and performance.The problem is that man- ufacturers need to think beyond making just their single device work on your network. It’s a big electronic world out there and they need to think about more than just the communication needs of their product. Most webcams and IP-addressable sensors are shipped with default HTTP addresses like 192.168.1.2 and TCP port 80. If you want to access the sensor from outside, you simply address it using your outside IP address like 204.xx.xx.18 and up pops the sensor data. If you have nothing else on your system, then this default address is fine and you go merrily about your life. However, a second sensor of the same type can’t use the same default address for obvious reasons. As a user, the first thing you do is plug the second device into the network by itself and change the address to something like 192.168.1.3. For the most part, this will work fine on the LAN; but if you want to get at the sensor from outside, then you also have to use port forwarding on your router. For example, if we put the second sensor at port 8080, then the LAN address would be 192.168.1.3:8080 and the outside address would be something like 204.xx.xx.18:8080. Simple, right? Sure, until some moron designer thinks he’s making his product super easy to install by fixing the TCP address at port 80 only! Think about it. Both sensors have IP addresses we can change; but if both are fixed at TCP port 80, their port-forwarded outside address is the same—204.xx.xx.18! I’m not sure if I was the first person to question this situation, but I may have created a few ripples down in the engineering department at a couple of places. When I e-mailed one of them asking how to address two “fixed port 80” devices, here was the response:

> Inside your network, the data logger is at 192.168.1.3:80. Outside your network, you want the data logger to appear at 204.xx.xx.18:8080. To accomplish this, configure port forwarding on your router to take an incoming packet on port 8080, and map it to 192.168.1.3 on port 80.

In truth, their engineering people were absolutely correct—if you have a router that does PORT ADDRESS TRANSLATION, not just port forwarding. To my knowledge, none of the common Linksys or Netgear routers do this. Obviously, their product was designed by an engineer working in a lab behind an expensive commercial router who was unaware of the differences. But, don’t think that just tossing your Linksys router solves the problem. I recently bought a SonicWALL commercial router just so that I could add 25 more port-forwarding addresses (I presently have 26 IP addressable devices on my network) and perhaps solve the problem with “fixed Port 80” devices. Unfortunately, out of the box, my new “commercial” router doesn’t do PAT (Port Address Translation). It is another $370 software upgrade to add PAT. Over my dead body. I have 11 different kinds of devices on my network and three of them are made with TCP port 80 fixed (really stupid!). Ordinarily, the easiest kluge-technique to communicate with only one at a time is to power only one at a time. Unfortunately, data loggers and DVRs need to stay pow- ered in order to collect data. The awful solution is to attach each device to a separate Ethernet expander switch (all connected to the main router) and X-10 control the power to them via the home control system (HCS). A controlbyweb.com WebRelay-Quad is attached to a couple of HCS input bits and initiates the control routines. A simple web page flips the web relay switches and designates the communication path—a convolut- ed path for sure. Ultimately, I trust that equipment designers will get the message that fixing TCP port 80 to make their product “plug and go” is naïve. Until they do, however, at least I have another output bit on my WebRelay-Quad/Ethernet switch/X-10/HCS Rube Goldberg for their next screwed up product.

[email protected]

96 Issue 216 July 2008 CIRCUIT CELLAR® www.circuitcellar.com C3.qxp 3/30/2007 1:38 PM Page 1 C4.qxp 6/5/2008 11:52 AM Page 1