www.elektor-magazin magazine July & August 2014 100+ Pages of Electronics & Embedded Dice Clock Animal Friendly Mousetrap Smart Power Bar • Analog Discovery from Digilent Hmm hh ^bbh ^^bb ■■ bh^b hb bh ^b^b b. bb bb 10-Warrior Expansion Board • Opto-isolated PTT/CW Interfa t mmm mm m w ■ ■ bb — ■ ki ■ b ■» "■ Farmer-Goat-Wolf-Cabbage Game • Chip-8 Video Games Emulator Soldering On With the Weller Power Outlet tester with LEDs Brushed-to-Brushless Motor Conversion Acupunctural NiCd Battery Conditioner r-i £ ^3 - m. in f $ r My First Shield • WIN a Rohde & Schwarz 100MHz Digital Oscilloscope TH LED Matching & Sorting Accessory • Microcontroller BootCamp Blown Fuse Indicator • 500-ppm LCR Meter: Feedback . ==== = Hewlett Packard 71B Number Cruncher (1984) EEE J E= i m Arduino is a Tool • LM317 Turns 78xx IR Tester with Solar Cell Power Supply Stage Tuner for Guitars o 56698 24965 8 1. i. OH AH 00 .■■Lxm £46.95 *€52. AT91SAM3X8E 3.3V 7-12V 6-20V 54 (of which 12 provide PWM output) 12 12 2 (DAC) 130 mA 800 mA 800 mA 512 KB (all available for the user applications) 96 KB (two banks: 64KB and 32KB) 84 MHz US $72. £21 .95 • € 24. ATmega32u4 5V 7-12V 6-20V 20 (of which 7 provide PWM output) 7 12 40 mA 50 mA 32 KB (of which 4 KB used by bootloader) 2.5 KB 1 KB 16 MHz US $34. AR-ftimiG *.M|S S 3 *. s O iniuimi JHIUUIM ’ iinm ■««« ARDUIN0 LEONARDO Especially good for USB applications Features Microcontroller Operating Voltage Input Voltage (recommended) Input Voltage (limits) Digital 1/0 Pins PWM Channels Analog Input Pins DC Current per 1/0 Pin DC Current for 3.3V Pin Flash Memory SRAM EEPR0M Clock Speed Microcontroller Operating Voltage Input Voltage (recommended) Input Voltage (limits) Digital 1/0 Pins PWM Channels Analog Input Pins Analog Outputs Pins DC Current per 1/0 Pin DC Current for 3.3V Pin DC Current for 5V Pin Flash Memory SRAM Clock Speed Analog Input Pins DC Current per I/O Pin DC Current for 3.3V Pin Flash Memory ATmega328 5 V 7-12V 6-20V 14 (of which 4 provide PWM output) 10 to 13 used for SPI 4 used for SD card 2 W5100 interrupt (when bridged) 6 40 mA 50 mA 32 KB (of which 0.5 KB used by bootloader) Microcontroller Operating Voltage Input Voltage (recommended) Input Voltage (limits) Digital 1/0 Pins Arduino Pins reserved ARDUIN SRAM 2 KB EEPR0M 1 KB Clock Speed 16 MHz £46.95 • € 53.90 • US $73.0t ARDUINO MEGA Like the Uno but with more memory Features Microcontroller ATmega2560 Operating Voltage 5 V Input Voltage 7-12V (recommended) Input Voltage (limits) 6-20V Digital I/O Pins 54 (of which 15 provide PWM output) Analog Input Pins 16 DC Current per I/O Pin 40 mA DC Current for 3.3V Pin 50 mA Flash Memory 256 KB (of which 8 KB used by bootloader) SRAM 8 KB EEPROM 4 KB Clock Speed 16 MHz £46.95 • € 52. uarr wn«ti Features Microcontroller ATmega328 Operating Voltage 5 V Input Voltage 7-12V (recommended) Input Voltage (limits) 6-20V Digital I/O Pins 14 (of which 6 provide PWM output) PWM Channels 6 Analog Input Pins 6 DC Current per I/O Pin 40 mA DC Current for 3.3V Pin 50 mA Flash Memory 32 KB (of which 0.5 KB used by bootloader) SRAM 2 KB EEPROM 1 KB Clock Speed 16 MHz £23.95 • € 27.50 • US $38.00 J £60.95 • € 69.95 • US $95. ARDUINO UNO REV.3 The most popular board with its ATmega328 MCU Microcontroller Operating Voltage Input Voltage Digital I/O Pins PWM Channels Analog Input Channels DC Current per I/O Pin DC Current for 3.3V Pin Flash Memory SRAM EEPROM Clock Speed ATmega32u4 5V 5 V 20 7 12 40 mA 50 mA 32 KB (of which 4 KB used by bootloader) 2.5 KB 1 KB 16 MHz Features Linux microprocessor Processor Architecture Operating Voltage Ethernet WiFi USB Type-A Card Reader RAM Flash Memory Atheros AR9331 MIPS @400 MHz 3.3V IEEE 802.3 1 0/1 OOMbit/s IEEE 802.1 Ib/g/n 2.0 Host/Device Micro-SD only 64 MB DDR2 16 MB PoE compatible 802.3af card support AftCUIUC- 71 a* Technologic DESIGN YOUR SOLUTION TODAY CALL 480-837-5200 Computer-on-Modules State of the Art Embedded Design pricing starts at $139 qty 1 $99 qty 1 00 » Up to 1.2GHz ARM w/ 2GB RAM » Fanless, low power designs » All parts soldered on, no moving parts » DoubleStore SD for reliable storage » User-programmable FPGAs » -40 to +85C Industrial temperature range » Easy development w/ Android, Debian and Linux » Sub-second boot to Linux » COTS carrier boards available or design a custom solution with reduced design time and complexity Computer-on-Modules include: TS-4200: Atmel ARM9 w/ super low power TS-4600:450MHZ low cost w/ 2 Ethernets TS-471 0: Up to 1 066MHz PXA1 68 w/ video TS-471 2: like TS-471 0 + 2 Ethernets TS-4720: like TS-471 2 + 4GB eMMC Flash TS-4800: 800MHz FreeScale iMX51 5 w/ video TS-4900: 1 .2GHz QuadCore i.MX6 w/ WiFi Single Board Computers TS-7680 Industrial Computer !v»K? ScSISESl pij m pricing starts at $203 qty 1 $159 qty 1 00 Features can include: x Up to 454 MHz ARM CPU x Up to 256 MB RAM x 24V AC Power Input x WiFi and Bluetooth Radio x 2GB Flash Storage » mSD Card Socket » 2x Ethernets » 6x 30V DIO Ports * 2x CAN Ports x lx Modbus Port x 2x 3A Relays x 2x RS-485 Ports Benefits: x Converter-less power direct to 24V AC voltage x Solid screw terminals for demanding environments x Highly connected with WiFi/Bluetooth and Dual Ethernet » -40°C to 80°C, 1 00% soldered down components x Easy development w/ Debian and Linux 2.6 x Boots to Linux shell in under 5 seconds » Guaranteed availability until 2025 We've never discontinued a product in 30 years Embedded /f- > Support every Unique embedded systems that / step of the way / solutions add are built to ' with open \ value for our endure source vision customers Contents Advertorial 8 New Digital Oscilloscope from Rohde & Schwarz Oscilloscope, DVM, Function Genera- tor, FFT Analyzer in one instrument. • Project Generator 10 IO-Warrior Expansion Board By adding this universal interface card an old PC can be pressed into service as a measurement and con- trol hub. 22 Dice Clock This remarkably accurate clock is built from CD4000 ICs from thel980s, yet has an innovative display. 26 Opto-isolated PTT/CW Interface Keep the PC and your ham radio kit electrically separated with this opto- isolated interface. Also suitable for other RTS/DTR driven applications. 35 Soldering On With the Weller The famous WTCP 'ticking' solder station gets a clever update to pro- long its life on your workbench. 36 Animal Friendly Mousetrap Flow to catch a mouse alive using just a few lines of PIC code. 40 Brushed-to-Brushless Motor Conversion Let's do some chip tuning for radio- controlled models. 44 Farmer-Goat-Wolf-Cabbage Game An age old game now cast in con- temporary guise meaning it's got a microcontroller. 48 SAME: Chip-8 Video Games Emulator Cries of joy at recognizing Chip-8, now played on the Single Arcade Ma- chine Emulator, and it's PSoC based for sure. 57 TH LED Matching & Sorting Accessory A tool to finally sort those undeter- mined LEDs hiding in your compo- nent drawers. 58 Microcontroller BootCamp (4) Thanks all for participating & respon- ding to the course! We continue with User Interfaces. 66 My First Shield :-) An LED / Button / Display & More shield for the Arduino, with Bascom support. 71 Simple Transistor Tester Tests and identifies leads on NPN, PNP bipolar devices, JFETs and (V) MOSFETs. 72 Acupunctural NiCd Battery Conditioner How needle-shaped discharge pulses can help to revitalize them old NiCad's. 73 Blown Fuse Indicator LED gives Dead-Or-Alive verdict on fuse. 4 | July & August 2014 | www.elektor-magazine.com Volume 40 No. 451 & 452 July & August 2014 84 500-ppm LCR Meter: Feedback A roundup of corrections and small im- provements to our popular LCR meter. 88 Stage Tuner for Guitars Tune into: FFT implemented on an ARM Cortex ARM M4 micro on a TI Launchpad. 98 IR Tester with Solar Cell Power Supply No battery needed— sunshine valued though. 99 LM317 Turns 78xx Because we can, mainly. 100 Spirit-Level Acoustic Aid Now you can hear the spirit level reach its exact position. 101 Power Outlet Tester using Bicolor LEDs Unerringly find the Phase line on the wall outlet. 102 Current Boost for USB Lithium Charger Maxing out the current that can be sourced by the USB port. 104 RC Speed Control for DC Motors PWM speed control developed using Flowcode, with lots of user options, on a remarkably small board. 110 Experimenting with NFC Did you know your Elektor Member card is NFC ready? 112 Water Pump Regulator This circuit overcomes some of the drawbacks of water distribution pumps installed on yachts, RVs, and pleasure craft. • DesignSpark 74 Optical Theremin with myDAQ & LabView Be your own conductor —and a pro- gramming LabView user too. 78 DesignSpark Tips & Tricks Day #12: Using Buses. We delve into bused structures frequently needed on circuit boards. 80 Tunnel Diodes Weird Components— the series. • Labs 81 It's Tag Time! With a variety of clocks & things ticking on the Elektor labs website, some tagging is called for to stay organized. 82 Arduino is a Tool Got a problem Google can't solve? Arduino is your best friend. • Industry 30 Review: Analog Discovery from Digilent Analog design and its tuition make a comeback with this refreshing USB oscilloscope kit from Digilent. 116 News & New Products A selection of news items received from the electronics industry, labs and organizations • Regulars 120 Hexadoku The Original Elektorized Sudoku. 122 Retronics Flewlett Packard 71B Number Crun- cher (1984). Admit, admit! You too wanted one of these but no hope on a student budget back then. Series Editor: Jan Buiting. 125 Gerard's Columns: Stacked A column or two from our columnist Gerard Fonte. 130 Next Month in Elektor A sneak preview of articles on the Elektor publication schedule. www.elektor-magazine.com | July & August 2014 | 5 Community Volume 40, No. 451 & 452 July & August 2014 ISSN 1947-3753 (USA /Canada distribution) ISSN 1757-0875 (UK / ROW distribution) www.elektor.com Elektor Magazine is published 10 times a year including double issues in January/February and July/August, concur- rently by Elektor International Media 111 Founders Plaza, Suite 300 East Hartford, CT 06108, USA Phone: 1.860.289.0800 Fax: 1.860.461.0450 and Elektor International Media 78 York Street London W1H 1DP, UK Phone: (+44) (0)20 7692 8344 Head Office: Elektor International Media b.v. PO Box 11 NL-6114-ZG Susteren The Netherlands Phone: (+31) 46 4389444 Fax: (+31) 46 4370161 USA / Canada Memberships: Elektor USA P.O. Box 462228 Escondido, CA 92046 Phone: 800-269-6301 E-mail: elektor@pcspublink.com Internet: www.elektor.com/members UK / ROW Memberships: Please use London address E-mail: service@elektor.com Internet: www.elektor.com/member USA / Canada Advertising: Peter Wostrel Phone: 1.978.281.7708 E-mail: peter@smmarketing.us UK / ROW Advertising: Johan Dijk Phone: +31 6 15894245 E-mail: j.dijk@elektor.com www.elektor.com/advertising Advertising rates and terms available on request. Copyright Notice The circuits described in this magazine are for domestic and edu- cational use only. All drawings, photographs, printed circuit board layouts, programmed integrated circuits, disks, CD-ROMs, DVDs, software carriers, and article texts published in our books and magazines (other than third-party advertisements) are copyright Elektor International Media b.v. and may not be reproduced or transmitted in any form or by any means, including photocopy- ing, scanning and recording, in whole or in part without prior written permission from the Publisher. Such written permission must also be obtained before any part of this publication is stored in a retrieval system of any nature. Patent protection may exist in respect of circuits, devices, components etc. described in this magazine. The Publisher does not accept responsibility for fail- ing to identify such patent(s) or other protection. The Publisher disclaims any responsibility for the safe and proper function of reader-assembled projects based upon or from schematics, descriptions or information published in or in relation with Elek- tor magazine. © Elektor International Media b.v. 2014 Printed in the USA Printed in the Netherlands The Eye of the Beholder Assuming you start reading this edition right here (which frankly I have seen few engineers do), there's a true melting pot of hands-on electronics on the pages ahead. In good Project Generator Edition (PGE) tradition, the assortment of articles and projects is as diverse as I was able to make it in terms of complexity and length. This year I am again happy to respond positively to recur- rent requests from readers for Sunday afternoon projects with a fun character but still educational and with an Elektor twist. On the other hand, there are also 'mega' projects on these pages to challenge all of you ambitious programmers and fans of embedded electronics. Both types of article, and some medium-sized ones too, I am assigned to line up on— what I dream of— any number of pages. However, my colleagues from the advertising department also want their share, and the printers and accountants tell me there's an absolute limit of 132 pages bound & wrapped to arrive by mail at your home or office, not a day late. While I would agree to the limited scientific significance of modding an LM317 to look & act like a 78xx (page 99), or building a clock from CD4000 ICs (page 22) I am sure both articles contain a little something to trigger the electronics engineer in you, if only that one design aspect I have forgotten to highlight or describe in full. Although pub- lishing about electronics and reading about it may seem the two extremes of a lengthy process, they have Discovery in common. The ability to discover should be respected and remain a key element in every sense, in electronics across the entire range. In practice, one man's e-debris in brownish plastic is another man's gem (page 122), likewise one LED and a triac (page 73) as opposed to a 54-pin 10-Warrior (page 10). It's true— the articles in this PGE are best read in random order. Happy reading, Jan Buiting, Editor-in-Chief The Team Editor-in-Chief: Publisher / President: Membership Managers: Jan Buiting Don Akkermans Shannon Barraclough (USA / Canada), Raoul Morreau (UK / ROW) International Editorial Staff: Harry Baggen, Jaime Gonzalez Arintero, Denis Meyer, Jens Nickel Laboratory Staff: Thijs Beckers, Ton Giesberts, Wisse Hettinga, Luc Lemmens, Mart Schroijen, Clemens Valens, Jan Visser, Patrick Wielders Graphic Design & Prepress: Giel Dols Online Manager: Danielle Mertens Managing Director: Don Akkermans 6 July & August 2014 www.elektor-magazine.com Our Network USA Don Akkermans + 1 860-289-0800 d.akkermans@elektor.com United Kingdom Don Akkermans +44 20 7692 8344 d.akkermans@elektor.com Germany Ferdinand te Walvaart +49 241 88 909-17 f.tewalvaart@elektor.de France Denis Meyer +31 46 4389435 d.meyer@elektor.fr Netherlands Ferdinand te Walvaart +31 46 43 89 444 f.tewalvaart@elektor.nl Spain Jaime Gonzalez-Arintero +34 6 16 99 74 86 j.glez.arintero@elektor.es Italy Maurizio del Corso +39 2.66504755 m.delcorso@inware.it Sweden Carlo van Nistelrooy +31 46 43 89 418 c.vannistelrooy@elektor.com Brazil Joao Martins +31 46 4389444 j.martins@elektor.com Portugal Joao Martins +31 46 4389444 j.martins@elektor.com India Sunil D. Malekar +91 9833168815 ts@elektor.in Russia Nataliya Melnikova +7 (965) 395 33 36 Elektor. Russia@gmail.com Turkey Zeynep Koksal +90 532 277 48 26 zkoksal@beti.com.tr South Africa Johan Dijk +31 6 1589 4245 j.dijk@elektor.com China Cees Baay +86 21 6445 2811 CeesBaay@gmail.com VOICE tal COIL circuit cellar Connects You To Supporting Companies lAT^onix Batronix www.batronix.com/go/36 119 tf.jpF* Vtctdfy WjjRfc ^"IA 14 www.supermobilityweek.com 29 Cleverscope clever www.cleverscope.com 69 DLP Design Dos far. www.dlpdesign.com 33 EmAC, nc . EMAC www.emacmc.com 33 ..... Eurocircuits www.elektorpcbservice.com 87 Express PCB www.expresspcb.com 117 Front Panel Express www.frontpanelexpress.com 43 stress pc ft k u CHIPS Hot Chips www. hotchips. org 9 Labcenter www.labcenter.com 132 pi co Pico www.picotech.com/ps244 131 HPololu Pololu ijotMji'ics * iieeiKttici www.pololu.com 77 Saelig www.saelig.com 43 Schaeffer AG www.schaeffer-ag.de 69 Techno To pic a Systems. Technologic Systems www.embeddedARM.com. . . 3 Not a supporting company yet? Contact Peter Wostrel (peter@smmarketing.us, Phone 1 978 281 7708, to reserve your own space in Elektor Magazine, Elektor«POST or Elektor.com www.elektor-magazine.com July & August 2014 7 Advertorial New Digital Oscilloscope from Rohde & Schwarz High quality — Best value! Rohde & Schwarz will be giving away a top-spec R&S®HM01002 oscilloscope (with the maximum bandwidth!) to ten lucky Elektor readers! To be in with a chance just register today at www.elektor.com/hmol002 it could be your lucky day! Win a brand new R&S®HM01002, developed by Hameg Instruments and the latest member of the Scope of the Art family! its representation of the time signal, measurement window and analysis region of the FFT with on-screen results greatly simplifies spectra measurements. The new digital Oscilloscope type R&S®HM01002 from Rohde & Schwarz is available with bandwidths up to 50 MHz, 70 MHz and 100 MHz. The design stands out for its fast Waveform- Update-Rate (screen waveform capturing) and high vertical-input sensitivity. The fan-less design offers a 1 GSample/s sample rate and a memory depth of 1 MSamples. In common with all oscilloscopes in the R&S®HMO series it offers the versatility of mixed signal functionality. Its host of additional functions makes the oscilloscope an ideal diagnostic and teaching tool for a wide range of applications for students, service technicians and for developers of embedded systems. A built-in three digit DVM function simplifies the service technician's work and cuts down on work bench clutter while giving the R&S®HM01002 the ability to make simultaneous voltage measurement on two analog channels. Its function generator is particularly useful in educational environments, producing all elementary waveforms at frequencies up to 50 kHz. Trainees, graduate and undergraduate students will find it useful to solve a variety of measurement tasks. An integrated pattern generator makes it easy for developers of embedded systems to configure and generate protocol telegrams at speeds up to 50 Mbit/s. This gives developers the freedom to program customized waveforms together with the supported predefined serial communication protocols. Integrated in the R&S®HM01002 is an optional hardware- accelerated serial bus signal trigger and decoder with support for some of the most popular communication protocols (I 2 C, SPI, UART, CAN or LIN). Thanks to its 128 Kmeasurement points the HM01002 FFT- Analyzer function can hold its own against larger oscilloscopes, To make full use of its MSO capabilities a separate eight channel logic probe type R&S®HO3508 is necessary. The probe is compatible across the complete HMO-range of equipment and gives the R&S®HM01002 complete time-domain, logic, protocol and frequency analysis functionality in the same device, making it a member of the Rohde & Schwartz 'Scope of the art' family of devices. Recommended retail prices range from 798 euros for the economy model with 50 MHz bandwidth to 998 euros for the instrument with 100 MHz bandwidth. US dollar or UK pound prices are to be announced at the time of writing (Ed.). Main Features • Models available with 50 MHz, 70 MHz and 100 MHz Bandwidth • 1 GSample/s Sampling Rate, 1 MSample memory depth R&S® • High vertical sensitivity up to 1 mV/Div • Fast error signal detection rate at 10,000 Waveforms/s • Wide choice of automated measurement functions • Quickview: all important signal parameters available with one press • Mixed-Signal-functionality as standard • Targeted trigger on signal events • Versatile bus analyzer option for isolating specific data packets • FFT: the simple path to spectral analysis with 128k measurement points • Digital Voltmeter for simultaneous measurement of two analog channels • The right signal, where you need it: 50 Mbit/s pattern generator or 50 kHz function generator. 8 July & August 2014 www.elektor-magazine.com TTTTTTTTTTTTTTT CHIPS ADVANCE PROGRAM August 10-12, 2014 A Symposium on High-Performance Chips Flint Center for the Performing Arts-Cupertino,CA http://www.hotchips.org HOTCHIPS brings together designers and architects of high-performance chips, software, and systems. The tutorial and presentation sessions focus on up-to-the-minute developments in leading-edge industrial designs and research projects. (0 o tj i 1 co < <0 ■a (0 3 ui 3 < Sf Tutorial 1: Emerging Trends in Hardware support for security • Security Overview • Mobile HW Security • Secure Systems Design • Hardware assists for introspection Princeton Arm AMD Intel Tutorial 2: Internet of Things • Powering the Internet of Things Tl • Ultra Low Power Design Approaches for loT National University of Singapore • Connecting the loT Qualcomm • loT Systems Architecture: It’s not just “embedded with a radio” ARM High Performance Computing • SC-ACE Processor: NEC's Brand-New Vector Processor • SPARC64 Xlfx: Fujitsu’s Next Generation Processor for HPC • Anton2:A 2nd-Generation ASIC for molecular Dynamics Simulation NEC Fujitsu D.E. Shaw Research Keynote 1 Power Constraints: From Sensors to Servers Peter Hutton ARM Mobile Processors NVIDIA’s TegraKI System-on-Chip NVidia Aplying AMD’s “Kaveri” APU forTeterogeneous Computing AMD NVIDIA’s Denver Processor NVidia Technology HBM: Memory Solution for Bandwidth-Hungry Processors SK Hynix Inc Improved 3D chip stcking with ThruChip wireless connections Thruchip Communications Organizing Committee Chair Krste Asanovic UC Berkeley Vice Chair Fred Weber Finance Lily Jow HP Advertising Don Draper Oracle Sponsorship Amr Zaky Publications Randall Neff Press Ralph Wittig Xilinx Registration Charlie Neuhauser Neuhauser Associates CMOS Biochips for Point-of-Care Molecular Diagnostics Arm Servers The AMD Opteron “Seattle”: A 64b ARM Dense Server Processor ARM Next-Generation IP Supporting LSI’s High-End Networking X-Gene2: 28mm scale-out processor Insilixa AMD ARM, LSI Logic Applied Micro FPGAs Design of a High-Density SOC-FPGA at 20nm A Reconfigurable Fabric for Accelerating Datacenter Services Xilinx FPGAs case study: High capacity and Performance 20nm FPGAs SDA: Software-Defined Accelerator for Large-Scale DNN Systems Altera Microsoft Xilinx Baidu IBM Movidius Cointerra High PErformance ASICS Hardware Accelerated Text Analytics Myriad2 “Eye” of the Computational-Vision Storm Goldstrike 1 : A 1 st Generation Cryptocurrency Processor for Bitcoin Mining RayChip: Real-time Ray Tracing Chip for Embedded Applications Keynote 2 The Internet of Everything: What is it? What's driving it? What comes next? Rob Chandhok Qualcomm Dense Servers • SCORPIO: 36-Core Shared-Memory Processor with a Coherent Mesh MIT • Next Generation Oracle SPARC Processor Oracle • Oracle’s Next Generation SPARC Cache Hierarchy Oracle • Atom C2000 Microserver: Power Efficient Data Center Processing Intel Big Iron Server • Performance Characteristics of the POWER8 Processor IBM • Unchaining the data center with Open Power: Reengineering a server ecosystem IBM • IvyBridge Server: Delivering Performance from Workstations to Mission Critical Intel Location Services John Sell Microsoft Allen Baum Volunteer Coordinator Gary Brown Tensilica Webmasters, IT Kevin Broch Production Lance Hammond Mike Albaugh Keith Diefendorff Steering Committee Chair Alan Jay Smith Committee Members Allen Baum Don Draper Oracle Pradeep Dubey Intel Lily Jow HP John Mashey Techviser John Sell Microsoft Keith Diefendorff Program Committee Program Co-Chairs Sam Naffziger AMD Guri Sohi U . Wisconsin Committee Members Forest Baskett NEA Pradeep Dubey Intel John Davis Microsoft Alan Jay Smith UC Berkeley Steve Miller NetApp Subhasish Mitra Stanford Stefan Rusu Intel Tom McWilliams BayStorage Behnam Robatmili Qualcomm Ralph Wittig Xilinx Mike Taylor UCSD Behnam Robatmili Qualcomm Bill Dally NVIDIA Founder Bob Stewart SRE Ml Micro Magic, Inc. ac / In-Cooperation CIRCUIT CELLAR Warthman Associates Technical Writers www.warthman.com EEE computer society A Symposium of the Technical Committee on Microprocessors and Microcomputers of the IEEE Computer Society and the Solid-State Circuits Society •Projects IO-Warrior Expansion Board Measurement and control using your (old) PC By Franz-Peter Zantis (Germany) Don't throw out your old PCs and notebooks or leave them gathering dust in the basement! They can be a useful resource: by adding this universal interface card an old PC can be pressed into service as a measurement and control hub. An IO- Warrior module on the I/F board takes care of USB communication, and source code is available that works with the free version of Visual Studio. uC ADAPTER ANALOG lAZ uoauio 60 CS 60 . \ ooas^ V 1 8NS0 uoaujo .VI-8NSD uoauio DCDC AOJUai PI ACTIUE 0 0 o There are many measurement and control inter- face cards available, each with their own par- ticular advantages and disadvantages. The card described here has many positive aspects: it is simple to control using familiar program- ming languages such as Visual Basic, C# and C; sensors and actuators can be wired directly to the terminals on the board without using spe- cial connectors; and the hardware is easy to modify and adapt for a wide range of different applications. The basics First we shall look at a few basic requirements for an interface card of this type. It should be a standard Eurocard size (100x160 mm; 3.94x6.30 inch) and able to be connected to the USB port on any PC. A chip called the TO-War- rior56', from the German company Code Mer- cenaries, is used to handle the USB protocol on the board, which removes the need for complex programming. The chip is very versatile and is easy to talk to using a Visual Basic program. 10 July & August 2014 www.elektor-magazine.com 10-Warrior Expansion Board The card should have outputs that can be con- nected directly to low-voltage loads (up to 12 V) without additional hardware, and which can sup- ply power, derived from an external power sup- ply. Two of the outputs can be set to any voltage from 0 V to 12 V under program control. There are also three switching outputs of which one switches to ground. Loads can be connected to these outputs either directly or via a relay. AC line (115 V or 230 V) loads can be controlled via three further potential-free switching outputs. Two digital inputs allow switch settings to be read, and two analog input voltages can be read using an A/D converter. The interface card also has a built-in temperature sensor using a silicon tran- sistor in an old-style metal package as a sensor. Putting it into practice The upshot of the above requirements is the cir- cuit shown in Figure 1. We need a programming language to talk to the interface card, and in the following examples we will use Visual Basic. More specifically we will use Microsoft Visual Studio Express, which supports Visual Basic as well as C## and C++, and which can be downloaded for free from Microsoft's website [1]. Program- ming can equally well be done under Linux as under Windows. Introductions to programming in Visual Basic can be found on the Internet and elsewhere. The USB chip [2] comes in two variants: as an SMD in an MLFP56 package and as a ready-made module (Figure 2), which connects directly to a USB cable. In order not to have to deal with sol- dering the 56 tiny pads on the SMD, we have cho- sen to use the module, which is simply mounted upside down in a socket. The interface board is powered over its USB con- nection, with the help of an on-board DC/DC con- verter to generate the symmetrical +15 V and -15 V rails needed for the operational amplifiers from the USB's +5 V. Strictly speaking the neg- ative supply is not really necessary as the type LM324 operational amplifier used can drive its output to within a few millivolts of ground. Jump- ers JP4 and JP5 allow the supply voltages to be set at ±15 V, or at +12 V/0 V from the external supply. In the second case the maximum volt- age available on the analog outputs will only be approximately +9 V, since the output of the operational amplifier can only swing to within about 3 V of its positive supply; on the other hand, the DC/DC converter can then be omitted. Two yellow LEDs (D13 and D14) are connected to pins on the IO-Warrior and can be used to indicate the status of the system. Overall the inter- face board is clearly laid out and easy to construct. We have avoided using SMDs in the interests of making the design suitable for those who have less experience with the soldering iron. All the ICs (with the exception of the regulator) and the USB mod- ule are fitted in sockets. It is important to use high-quality header sockets for the module to avoid possible problems with unreliable connec- tions from the outset. The unpopulated board (Elektor Store no. 130006-1) is available from the Elektor Shop [3]. To simplify matters for constructors, we have also made the IO-Warrior module and the TI microcontroller, programmed to act as an A/D converter, available there (nos. 130006-91 and 130006-41 respectively). The project software (no. 130006-11) is available for download: as well as library modules the download also includes example code and a description of an experimen- tal set-up for measuring temperature. Figure 2. The IO-Warrior in module form is easy to use. Switching outputs Once the job of populating the board is com- plete there are a few more steps to take before embarking on writing a program. The library iowkit56.dll in the download ([3]) contains the driver for the IO-Warrior module: it forms the glue between the application program and the module itself. To ensure that the library can be accessed it must either be placed in a direc- tory on one of the standard system paths or be included in the Visual Basic project. The lat- ter option has the advantage that the finished program can be copied as a single directory to another computer and run there without further fuss. Figure 3 shows the arrangement of files within a Visual Basic project, here called 'Motor- steuerung' ('Motor control'). The next step is to add a Visual Basic module to the project which includes declarations of func- tions and subroutines. Doing this saves a lot of typing and searching through documentation. 3 CJIVBNet.Projektel 0 LJ [Motofsteueiung] 0 Cj [Motorsteuerung] (3CJ[binl CD [Debug] _J [Release] Figure 3. Structure of a Visual Basic project. Figure 4. Including Modulel.vb in the project. www.elektor-magazine.com | July & August 2014 11 •Projects o 12 July & August 2014 | www.elektor-magazine.com 10-Warrior Expansion Board Table 1. Parameters to the function IowKitWrite () intret An integer variable that will contain the return value from the function call after its execution, giving the number of bytes transferred. IOhandle The handle number as obtained from an earlier call to IowKi tOpenDeviceQ (see text for more information). 0 For operation in standard mode this parameter is always zero. IOdata (0) The prepared array and the starting index within it from which data are to be transferred. 8 The number of bytes to be transferred: always 8. Figure 4 shows the source code files for the project 'FanControl': note the presence of the module Modulel.vb in the project. The function IowKitOpenDevice is called to deter- mine whether the IO-Warrior is connected to the computer. The function tries to open a connection to the IO-Warrior and returns an integer 'handle'. If the handle returned is zero then no device was found: in this case an error can be reported to the user (see Listing 1). It is possible to call this function from time to time as the program is executing, to check that the hardware is still connected. If the USB con- nection is even briefly interrupted communication between the software and hardware will stop. The next call to IowKitOpenDevice will then re-open the connection and communication can continue. One possibility is to provide a button in the user interface labeled 'Connect Hardware' to trigger a call to the function. With that we have completed our preparations and can move on to the programming proper. First we will test the switching outputs. The IO-Warrior has six ports (Port 0 to Port 5) with eight I/O pins (labeled Px.O to Px.7) each, and a further port (Port 6) with two I/O pins. Pins P5.0 to P5.4 are reserved for the SPI bus. We use Port 3 for switching loads and for con- trolling LEDs D13 and D14. To begin with we will drive the two LEDs: in doing this we will show how the individual pins of the IO-Warrior can be controlled from within Visual Basic. The IO-War- rior supports standard I/O operation and a special (SPI and I 2 C) mode. We will use standard mode Figure 1. Circuit of the interface card with its multitude of inputs and outputs. to operate the I/O pins in this example. The LEDs are powered from the 5-V USB supply and driven from ports P3.3 and P3.4 via 390-ft resistors. A byte array is used to specify which pins of each port are set to a high or a low level, with the states for the eight pins of one port packed into a single byte for sending to the IO-Warrior. An additional byte at the beginning of the array is used to indicate that normal mode is to be used. The total size of the array is therefore eight bytes. Since the array is indexed from zero its declaration is as follows: Dim IOdata(7) As Byte The elements of the array can be set to whatever values are required. To light the LEDs we must set their port pins to logic high: the corresponding bit pattern is 00011000. This is 24 in decimal of 18 in hexadecimal (written &H18 in Visual Basic). Listing 2 shows how the elements of the array are set. Note that Port 1 (iOdata (2) ) is set to all ones: this is because this port is used for the chip select (CS) signals for devices connected on the SPI bus, and chip select is an active-low signal. The array can now be sent to the IO-Warrior. For this we use the function IowKitWrite: intret = IowKi tWri te (IOhandle , 0, IOdata (0) , 8) The meaning of the arguments to the function is explained in Table 1. To turn the LEDs off, we need to take pins P3.3 and P3.4 to ground. The example program in Listing 3 includes a loop that executes a fixed number of times: when the start button is clicked the LEDs should blink one hundred times at approximately 0.5 Hz. The other switching outputs are controlled in exactly the same way. To switch on a load con- www.elektor-magazine.com | July & August 2014 13 •Projects Listing 1. The function IowKitOpenDevice(). IOhandle = IowKi tOpenDevi ce ( ) If IOhandle = 0 Then MessageBox . Show( "No hardware found!", "ERROR", MessageBoxButtons . OK, MessageBoxIcon . Error , MessageBoxDefault Button . Buttonl) End Else - Code to be executed when hardware recognized - End If Listing 2. Array of port configuration settings. IOdata (0) = 0 ' Byte for parameterizi ng, in Normal- Mode always 0 IOdata (1) = 0 ' Byte for Port© IOdata (2) = 255 ' Byte for Portl ; all at 1, Port used for Chi p-Select IOdata (3) = 0 ' Byte for Port2 IOdata (4) = &H18 ' Byte for Port3 ; connectors for LEDs D13 and D14 to logic h IOdata (5) = 0 ' Byte for Port4 IOdata (6) = 0 ' Byte for Port5 IOdata (7) = 0 ' Byte for Port6 Listing 3. Pressing the button generates 100 LED flashes. Dim I0data(7) As Byte 'Array containing the port states Dim IOHandle As Integer ' vari able for the Handle Number Dim intret As Integer 'variable for Integer Return-Value Dim n As Integer 'variable for counter Private Sub BtnStart_Cli ck(sender As System . Obj ect , e As System . fventArgs) Handles BtnStart . Click IOhandle = IowKi tOpenDevi ce ( ) If IOhandle = 0 Then MessageBox . Show( "No hardware found!", "ERROR", MessageBoxButtons . OK, MessageBoxIcon . Er ror , MessageBoxDefault Button . Buttonl) End 'program termination, if the hardware is not connected Else For n = 1 to 100 ' For-Next-loop I0data(4) = &H18 'LEDs D13 and D14 on +5V: LEDs are off intret = IowKi tWri te (IOhandle , 0, IOdata(O), 8) System. Threading. Thread. Sleep(lOOO) '1000 ms to wait I0data(4) = 0 'all Pins of Port 3 on GND: LEDs are on 14 July & August 2014 www.elektor-magazine.com 10-Warrior Expansion Board ■intret = IowKi tWri te (IOhandle , 0, IOdata(O), 8) System. Threading, hread . Sleep (1000) '1000 ms to wait Next n End If End Sub Listing 4. Driving a remote-controlled mains switch. Dim I0data(7) As Byte 'Array with port states Dim IOHandle As Integer ' vari able for handle-number Dim intret As Integer 'variable for integer return-value Private Sub BtnStart_Cli ck(sender As System . Obj ect , e As System . EventArgs) Handles BtnStart . Cli ck IOhandle = IowKi tOpenDevi ce ( ) If IOhandle = 0 Then MessageBox . Show( "No hardware found!", "ERROR", MessageBoxButtons . OK, MessageBoxIcon . Er ror , MessageBoxDefault Button . Buttonl) End 'program termination, if no hardware found Else I0data(4) = &H20 'P3.5 on logical 1; Relay is active intret = IowKi tWri te (IOhandle , 0, IOdata(0), 8) System. Threading, bread . Sleep (500) '500 ms to wait I0data(4) = 0 'all Pins of Port3 to GND; Relay de-energized intret = IowKi tWri te (IOhandle , 0, IOdata(0), 8) End If End Sub nected to OUT1, OUT2 or OUT3, the correspond- ing port pin (P3.0, P3.1 or P3.2) should be taken high. OUT1 switches to ground; OUT2 and OUT3 switch to +12 V. Schottky diode D17 protects against reverse polarity connection of the +12 V supply. Logic Highs on pins P3.5, P3.6 and P3.7 cause the potential-free contacts brought out to K14, K15 and K16 to close. One interesting idea for using these is in conjunction with a radio-con- trolled mains switch, allowing mains appliances to be controlled without having to worry about high voltages. Open up the remote control and connect the potential-free contacts on the inter- face board across its pushbuttons. Using the pro- gram shown in Listing 4, the contacts will close briefly (for about 500 ms) when the Start button is pressed. Analog outputs Any voltage between 0 V and +12 V can be gen- erated at K4 and K5 (ANALOG OUT1 and ANA- LOG OUT2). The circuit uses a type MCP4822 dual D/A converter controlled over the SPI bus. When the device receives a 16-bit word over the bus, it interprets the lower twelve bits (bits 0 to 11) as the desired output level and the top four bits (bits 12 to 15) as control information: see Table 2 for details. Output VOUTA is connected to operational ampli- fier IC4.B, which multiplies the voltage by a factor of 3. Feedback resistor R12 is connected directly to the terminal of K4, and so the operational amplifier also compensates for the base-emitter voltage drop in the output transistor T6. As a result the voltage on K4 should be exactly three times the voltage at VOUTA. The maximum pos- sible voltage is 4.096 V multiplied by three, or www.elektor-magazine.com | July & August 2014 15 •Projects Table 2. Control bits for the D/A converter Bit 15 0: data are sent to DAC A, with output voltage at VOUTA 1: data are sent to DAC B, with output voltage at VOUTB Bit 14 not used Bit 13 0: voltage range at output is 0 V to 4096 mV 1: voltage range at output is 0 V to 2048 mV Bit 12 0: output buffer is disabled: output is high impedance 1: output buffer is enabled 12.288 V. To achieve this the voltage provided at K2 must be rather higher (for example +15 V) as there will be a drop of up to 2 V between the col- lector and emitter of T6 when it is in saturation. In some circumstances the transistor can dissi- pate a considerable amount of power and it is therefore fitted with a small heatsink. The smaller the output voltage and the higher the output current, the higher the power dissipation in the transistor will be. Of the voltage supplied at K2 around 400 mV is dropped across D17 and the remainder is dropped across the output tran- sistors. Note that the outputs are not protected against short circuits and so it is a good idea to use a current-limited power supply. In any case it is a good idea to proceed with care when using these outputs. LEDs D9 and D3 change in bright- ness according to the voltage on the outputs. The voltage on each output (VOUTA or VOUTB) is determined by a number, from zero to 4095, presented to the corresponding D/A converter. The number multiplied by three gives the output voltage in millivolts, and so the output resolution is 3 mV. There are five steps to carry out when using the D/A converters, as follows. Prepare a 16-bit integer value The 16-bit value that is sent to the D/A converter comprises four control bits and the twelve data bits that correspond to the desired voltage. The easiest way to construct the word is to put the voltage value in a variable and then set the top four control bits as required. SPI communications from the USB chip happen one byte at a time, and so the integer value has to be split into a high byte and a low byte. The module Bitmanipula- tion.vb in the software download includes func- tions to set, clear, toggle and extract individual bits in a byte, as well as a function for splitting a 16-bit integer into a high byte and a low byte. When the program given in Listing 5 is run, the voltage on output K4 (ANALOG OUT2) should be set to 3.6 V. The value sent to the D/A converter is 3600 mV/3 = 1200. In this example the two bytes are stored in the array msblsb. Configure the SPI bus Listing 6 shows how the SPI bus is initialized. The clock frequency and a few other parame- ters regarding the clock and data signals need to be configured: the parameters are stored in a 64-byte array and then sent to the chip. When the SPI bus is used the IO-Warrior has to be operated in its 'special' mode. In this mode the parameters to the functions iowKitWrite are different from those used when configuring normal I/O ports. lOhandle has the same mean- ing; the next parameter is 1, which enables the special mode; then follows the array with the index starting from which bytes are to be sent; and then the final parameter (64) is the count of bytes to be sent. One point to note regarding w56init(4): the USB chip is run from a 5 V supply, while the microcon- troller that acts as an A/D converter (see below) runs on 3.6 V. To ensure that excessive voltages are not presented to the microcontroller the resis- tors on the SPI lines in the IO-Warrior that pull the signals up to its supply rail must be disabled. Activate chip select Next communications with the D/A converter are enabled by activating its chip select signal (pin 2 on the converter, connected to Pl.l on the IO-Warrior): see Listing 7. Send the 16 bit integer The data to be sent must be stored in a 64-byte array as before. As Listing 8 shows, three further configuration bytes are needed, which include the number of bytes to be sent over the SPI bus. 16 July & August 2014 www.elektor-magazine.com 10-Warrior Expansion Board Listing 5. Preparing values for the D/A converter. Dim curspgch2 As UShort 'variable for desired voltage value (16-Bit Integer) Dim vmsblsb(l) As Byte 'Array for receiving high-byte and low-byte Dim curspgch2 As UShort = 1200 'desired output-voltage in mV divided by 3 vmsblsb = findHbyteLbyte(curspgch2) ' separation in high-byte and low-byte with the help of " Bi tmani pulati on . vb" 'now follows the setting of the control bits for the DAC as shown in Table 3.3 msblsb(l) = ClearBi t (msblsb (1) , 7) 'Bitl5: data are sent to DACA msblsb(l) = ClearBi t (msblsb (1) , 6) 'Bitl4: this is not relevant msblsb(l) = ClearBi t (msblsb (1) , 5) 'Bitl3: output voltage range to 0...4096 msblsb(l) = SetBit (msblsb(l) , 4) 'Bitl2: l=OutputBuf fer active Listing 6. Initializing the SPI bus for the D/A converter. Dim w56init(63) As Byte 'Byte-Array with 64 places ' SPI-Ini ti ali zati on w56init(0) = &H8 w56init(l) = &H1 w56init(2) = &H0 w56i ni t (3) = 119 w56init(4) = &H1 'for SPI-Modus 'SPI activated 'SPI parameter to conform with the DAU MCP4822 'clock frequency 24MHz / (119+1) = 200 kHz 'deactivate pull up resistors retval = IowKi tWri te (IOhandle , 1, w56init(0), 64) 'sending parameter to 10-Warrior Listing 7. Activating Chip Select for the D/A converter. 'ChipSelect of IC5 (Pl.l) from High to Low w56data(2) = ClearBi t (w56data (2) , 1) retval = IowKi tWri te (IOhandle , 0, w56data(0), 8) Listing 8. Sending data to the D/A converter. Dim w56SPIdata (63) As Byte 'Byte-Array with 64 positions 'sending the data via SPI to the DAU w56SPIdata (0) = &H9 'with SPI always &H9 w56SPIdata (1) = &H2 'number of Bytes to send; here two (high-byte and low-byte) w56SPIdata (2) = &H0 'Flags; here 0 w56SPIdata (3) = vmsblsb(l) 'loading the high-byte in the Array to send w56SPIdata (4) = vmsblsb(0) 'loading the low-byte in the Array to send retval = IowKi tWri te (IOhandle , 1, w56SPIdata (0) , 64) Listing 9. Deactivating Chip Select for the D/A converter. 'ChipSelect IC5 (Pl.l) back to logic High w56data(2) = SetBi t (w56data (2) , 1) retval = IowKi tWri te (IOhandle , 0, w56data(0), 8) www.elektor-magazine.com | July & August 2014 17 •Projects When this code is executed, 3.6 V should appear on connector K4. Deactivate chip select To complete the transaction it is necessary to deactivate the chip select signal on the D/A con- verter: see Listing 9. It would be a good idea to integrate the code described above into a single function, that simply takes the desired output voltage as a parameter. Capacitors C7 and C8 prevent any spikes that may appear on the outputs of the D/A converters from appearing on the analog outputs of the board. If it is desired to be able to change the output volt- age quickly, the values of these capacitors can be reduced, for example to 100 nF. The exam- ple code in the listings controls ANALOG OUT2; the same approach is used to control ANALOG OUT1 (on K5). The only change is that bit 15 of the word sent to the D/A converter should be set rather than cleared. Reading switch status K7 and K8 are connected via protection resistors to P2.2 and P2.3 respectively. It is possible to determine whether a high or a low level is present on each of these inputs. With its supply at 5 V the IO-Warrior is guaranteed to report a high level when the voltage on its input port pin is 3.25 V or more, although usually 2.25 V is enough. Likewise it is possible to determine via port P2.1 whether a voltage is present on K5, as long as it exceeds the necessary threshold. This can be useful when K5 is used for output voltages greater than about 4 V. Resistor R15 and diode D7 protect the P2.1 input pin of the USB chip from exces- sively high voltages. To read the state of the inputs the relevant pins are first set to their high-impedance (logic high) state. Each pin is internally pulled up to V cc (+5 V) via a resistance of between 4 kft and 8 kft and driven from the collector of a transistor whose emitter is grounded. With the transistor turned off the level on the pin can be read by the software. One function that can be used to do this is IowKi tReadNonBlocki ng. As the code in Listing 10 shows, first the required variables are declared, then all pins on port 2 are set high, and finally the read function is called. The result is placed in the array w56data. By reading values from this array and carrying out suitable comparisons the program can determine which pins are at a logic high level and which pins are low. The code always reads the state of all the pins, even though in this case we are only interested in detecting the state of pins in port 2. The code therefore only needs to inspect the value stored in w56data(3). Reading analog values In order to read analog values the interface board makes use of a microcontroller (an MSP430F2013), programmed to act as a 16-bit analog-to-digital converter. The sample rate is 488 Hz. This approach allows the characteristics of the converter to be modified by changing the firmware in the microcontroller, but we shall not discuss this possibility further here. The A/D converter has two inputs (pin 3 and pin 4). The analog input voltage can vary between 0 V and 600 mV, corresponding to digital codes of 0 to 2 16 -1 (0 to 65535). Pin 3 is connected to the output of operational amplifier IC4.C. R16, D4 and D6 protect the input of the A/D converter from voltages in excess of about 700 mV. R16 has a sufficiently low value that it does not sig- nificantly affect the results of the A/D conversions while still providing protection. IC4.C is wired as a differential amplifier with the inverting input taken to ground. If desired, the values of resis- tors R23 and R24 can be changed to provide a DC level that will be subtracted from the voltage to be measured that appears on the non-inverting input. This can be helpful, for example, to make Listing 10. Reading the state of inputs. Dim retval As Integer Dim w56data(7) As Byte w56sdata(0) = 0 'always 0 for "simple mode" w56data(3) = 255 'all Pins of Port2 at 1 (in high impedance-mode) retval = IowKi tReadNonBlocki ng(IOHandle, 0, w56data(0), 8) 18 July & August 2014 www.elektor-magazine.com 10-Warrior Expansion Board fuller use of the A/D converter's 600 mV input range. The gain of the amplifier is 0.1. The non-inverting input of the differential ampli- fier can be connected to different sources using jumpers JP2 and JP3. To measure the output current at ANALOG OUT1 (on K5), fit JP3 and leave JP2 open. Like IC4.C, IC4.A is wired as a differential amplifier, and measures the voltage across shunt resistor Rll. If a current of 500 mA flows, for example, the output of IC4.A will be 5 V; IC4.C will bring this Component List Resistors R1 = 47kft R2 = 300ft 1% R3,R10,R14,R38,R39,R40,R41,R42 = 560ft R4,R46,R47 = 390ft R5,R6,R9,R13,R18,R19,R31,R35,R37,R43,R4 5,R50,R51,R52,R54,R55,R56 = lOkft R7,R15 = 680ft R8,R12 = 20kft Rll = 0.5ft 5W R16 = 47ft R17,R20,R22,R25 = lOOkft R21,R26 = 4.7kft R23 = lOMft (not fitted) R24 = Oft (wire link) R27,R32,R36,R44 = lkft R28 = 1.3kft 1% R29 = 68ft R30,R33,R34 = 47ft 3W R48,R49,R53 = 100ft PI = 47kft trimpot Capacitors C1,C4,C5,C6,C12 = lOOpF 25V C2,C3,C9,C10,C11,C13,C14,C15 = lOOnF C7,C8 = lpF ceramic Semiconductors D1,D13,D14 = LED, yellow, 3mm D2,D4,D6,D10,D15,D18,D19,D20 = 1N4148 D3,D8,D9,D11,D12 = LED, red, 3mm D5 = 3.6V zener diode D7,D16 = 4.7V zener diode D17 = 1N5821 T1,T6 = BDX53B T2 ,T3 ,T4 ,T7 ,T9 ,T 1 0 ,T 1 1 = BC547C T5 = BC557B T8 = BC108 IC1 = IO-Warrior56-MOD (Version 1. 1.0.1 or higher) IC2 = LM1117T-ADJ IC3 = MSP430F2013IN IC4 = LM324N IC5 = MCP4822-E/P DCDC1 = AM3N-0515D or REC3-0515DR/H1 Miscellaneous JP1,JP4,JP5 = 3-pin pinheader, O.T'pitch K1 = 3-pin pinheader, 0.05"pitch K6 = USB B socket, right angled JP2, JP3, JP6 = 2-pin pinheader, O.T'pitch K2,K3,K4,K5,K7,K8,K9,K10,K11,K12,K14,K1 5,K16 = 2-way PCB terminal block DIP8 IC socket DIP14 IC socklet 26-way DIL socket strip, 0.1" pitch, for IC1, premium quality 4-way SIL socket strip, 0.1" pitch, for IC1, premium quality TO220 style heatsink, 21K/W RE1,RE2,RE3 = 5V relay, SPST-NO Jumper PCB # 130006-1 v. 1.1 www.elektor-magazine.com | July & August 2014 19 •Projects down to 0.5 V, which can then be converted to digital by the microcontroller. The measurement range can easily be adjusted by making suitable changes to the values of resistors R21 and R26. If these are changed to 10 kft then the output of IC4.A at a current of 500 mA will be just 2.5 V, and hence the output of IC4.C will be at 250 mV. To read the analog voltage at ANALOG IN2, leave JP3 open. The analog input voltage is halved by resistors R43 and R45 and then divided by ten by IC4.C. If 10 V is present on K3 the output of IC4.C will be 500 mV, suitable for the A/D con- verter. R53 protects T7 when a voltage is present on K3 and JP2 is inadvertently fitted. To measure the voltage on ANALOG OUT1 (K5) JP6 must be fitted. While R15 and D7 allow the detection of voltages above 4 V on this output, jumper JP6 allows the exact value to be read. When JP6 is fitted the voltage appears across the potential divider formed by R28 and R29, which give a division ratio of 1:20. If there is 10 V on K5, then a voltage of 500 mV will appear across R29, which is connected to the second input of the A/D converter (pin 4). This input is also pro- tected against excessive voltages by two diodes, D2 and D10. An external voltage presented on ANALOG INI (K12) can also be measured by leaving jumper Listing 11. Initializing the SPI bus for the A/D converter. ' SPI-i ni ti ali zati on w56init(0) = &H8 'configuration of SPIMode 'activating SPI 'SPI parameter for communication with the pC MSP430F2013 'clock frequency 24MHz / (119+1) = 200 kHz 'deactivating the pull-up resistors retval = IowKi tWri te (IOhandle , 1, w56init(0), 64) 'sending the initialization data to the IO-Warrior w56init(l) = &H1 w56init(2) = &H4 w56init(3) = 119 w56init(4) = &H1 Listing 12. Activating Chip Select for the A/D converter. 'activate ADU ChipSelect IOdata(2) = ClearBi t (IOdata (2) , 3) retval = IowKi tWri te (IOhandle , 0, IOdata(0), 8) Listing 13. Receiving four data bytes. ldata(0) = &H9 'indicator for using SPI (always &H9) Idata(l) = &H4 'number of Bytes to send ldata(2) = &H0 'Flags retval = IowKi tWri te (IOhandle , 1, ldata(0), 64) retval = IowKi tRead (IOhandle , 1, ldata(0), 64) valuePin4 = ldata(2) * 256 + ldata(3) 'value at Pin 4 of the ADU valuePin3 = ldata(4) * 256 + ldata(5) 'value at Pin 3 of the ADU Listing 14. Deactivating Chip Select for the A/D converter. 'resetting ChipSelect of the ADU (to logic high) IOdata(2) = SetBit (IOdata (2) , 3) retval = IowKi tWri te (IOhandle , 0, IOdata(0), 8) 20 July & August 2014 www.elektor-magazine.com 10-Warrior Expansion Board JP6 open. As in the case of ANALOG IN2 (K3) the potential divider gives a division ratio of 1:20 between the input voltage and the voltage seen by the A/D converter. There are thus many ways in which analog val- ues can be acquired. Each request to the A/D converter yields a pair of numbers: one corre- sponding to the voltage on pin 3 and the other to the voltage on pin 4. Again the readings are transferred over the SPI bus, with pin 2 of the converter acting as its chip select signal. The A/D converter internally generates samples of the analog values at 488 Hz but only reports them on receiving a suitable request. When this happens, LED D1 changes state, giving an indi- cation of A/D converter activity. R7 and D5 are required because the the USB chip and the A/D converter operate from different supply voltages. The following steps are required to fetch data from the A/D converter over the SPI bus. Configure the SPI bus This first step is similar to the configuration of the SPI bus in the case of controlling the analog outputs described above. The only difference is in w5 6 i n i t ( 2 ) , which must in this case be set to 4: see Listing 11. Activate Chip Select Again, this step is similar to the case of controlling the analog outputs. The pin that is driven in this case is PI. 3: see Listing 12. Read in two 16-bit integers Two 16-bit values, one for pin 4 and one for pin 3, must be received, making a total of four bytes. As is conventional when using the SPI bus, a write command must be issued before the read com- mand. The end result is four bytes in the array, at indices 2 to 5. The bytes must be assembled into the 16-bit integer values: see Listing 13. The received values need to be interpreted cor- rectly. The full-scale range of input voltages to the A/D converter is 600 mV, and this range corresponds to the 2 16 = 65536 possible output codes. The voltage (in millivolts) on pin 4 of the converter is thus related to the conversion result by the formula Figure 5. The USB cable is connected directly to the IO-Warrior module. V p m 4 = 600 mV x (conversion result) / 65536 and the same goes for pin 3. To calculate the actual voltage at the input terminals the calcu- lation must be modified to take account of the voltage divider and amplifier circuit. Deactivate Chip Select The final step is to deactivate Chip Select: see Listing 14. With that the process of acquiring the two samples is complete. The software download includes a document with source code that shows how to use the tempera- ture sensor in the board. ( 130006 ) Web Links [1] www. microsoft.com/en-gb/download/details.aspx?id =40787 [2] Code Mercenaries IO-Warrior56 generic universal I/O controller for USB, VI. 0.2, September 22 2011 for chip version VI. 1.0.1: www.codemercs.com/uploads/tx_sbdownloader/IOWarrior_56_Datasheet_01.pdf [3] www. elektor-magazine. com/1 30006 www.elektor-magazine.com | July & August 2014 21 •Projects Dice Clock With CD4000 ICs and an innovative display By Joost Waegebaert (Belgium) js./' t % * •*••*• • ♦ t • » • » • # • 9 t> % $ • Digital clocks are a traditional and re- warding subject for a small electronics project that can be realized in a spare moment. The trigger for this specif- ic design was a discussion in several electronics fora about the generation of an accurate 1-Hz signal. This was the provocation for the author to design an accurate clock himself, using only standard ICs (and therefore without microcontroller). Figure 1. The block diagram of the clock with a dice-like display. In the various discussions that the author was following, the solution almost invariably evolved into the direction of a microcontroller with all sorts of software tricks to obtain a sufficiently accurate timing. Although the reflex of a soft- ware solution to an electronics problem is these days usually justified, it is not necessarily the best method for a clock. This article describes a digital clock, following the classic design, but with a novel display to catch the eye. In addition, this clock is extremely frugal and, with the aid of a small battery, continues to keep time when there is a power failure. Block diagram A digital clock is not much more than a counter which is, every second, incremented by 1 (Fig- ure 1). The counter is split into several parts, with the individual sections dealing with the sec- onds, the minutes and the hours respectively. The counters each drive their part of the display. Oscillator At the heart of each clock is, of course, a stable oscillator. Any electronics engineer will automat- ically arrive at a crystal-driven implementation. The frequency is in principle an arbitrary choice— a suitable divider will then ultimately deliver 1 pulse per second. A sensible choice of this frequency will, how- ever, have to take into account the effect on the current consumption. For crystal oscillators, obtaining a low power consumption is easier at lower frequencies. A second requirement is that it should be easy to divide the frequency down to 1 Hz. A power of 2 is then always very convenient. A divider is then no more complicated than a series chain of a sufficient number of flip-flops. Since time imme- 22 July & August 2014 www.elektor-magazine.com Dice Clock morial, 32.768-kHz crystals have been available for this purpose. 32,768 equals 2 15 and it there- fore suffices to chain 15 flip-flops one after the other to generate one pulse per second. A third function that this oscillator has to fulfill is the simple generation of a higher pulse speed for the purpose of setting the clock. At low frequencies, discrete digital logic has a frugality champion in the form of the CD4000 family. Decades old, but even by modern stan- dards still extremely low power and furthermore has no special requirements when it comes to the power supply voltage. Several single-chip oscil- lator/divider combinations are available and the choice here fell for the CD4536 (see the sche- matic in Figure 2). In the CD4538 chip, the oscillator is followed by 24 flip-flops, more than enough for the applica- tion as a 2 15 divider. The binary value at inputs A through D determines which flip-flop output from the divider chain is connected to the output. In normal operation, output 15 (1110) is selected by R2 through R5 for a divider ratio of 32,768 and 1 Hz at the output. For setting the time of the clock it is easy to choose a faster output by changing the binary code on the selection inputs. Pushbutton S2 selects output 7 (256 Hz) for the slow setting speed. Pushbutton SI selects output 3 (4096 Hz) for the high setting speed. The final pushbutton (S3) stops the clock for as long as it is held down to allow the clock to be accurately synchronized to, for example, the hour beep of a radio station. When S3 is released the seconds counter will start from 0, so that the next minute will begin exactly 60 seconds after the button is released. The exact frequency of the seconds signal is adjusted with C3. This should be done only after Figure 2. The complete schematic for the clock. The complete LED driver section is only drawn for the final dice. i r +18V © +18V © i r 1 FI 50mA T © 230VAC 230VAC © 2x 15V 3VA D2 SI FAST D1 2x 1N4148 S2 n: SLOW |~R 16 T2 □ r s r@ (i 7" ( BC516 R18 ; p| TL431C | 4k7 +18V © C4 lOOn R15 BC516 4k7 R19 IC5 LM2936Z-5 BAT41 470u 35V 9V l C8 1 0u 35 V £ * CIO lOOn vcc -© C9 22u 25V Jt jk* S3 l 8 EM nr nr stop vcc © R3 |C5 MOOn 10 12 R2 16 A (d E> 8BYP B C IC1 OUT1 D CINH RES 4536D OUT2 DO > INI MOIN SET J L OINH • I ► XI = 32.768kHz 13 15 14 R8 RIO I D7 1N4148 BC516 LSEC BC516 BC516 LB2 LA2 LC2 BC516 LAI LB1 o o o ooo ooo ooo o ooo ooo ooo 1 2 3 OOOa OOOb OOOc T- CM x x k - ..J k .. X. ■«- CM Tl- — o o XXX _ J T8 2N7000 T9 2N7000 LC1 | LB3 D8 LA3 1N4148 LC3 T10 2N7000 D9 L ...... J L — — — — — _ _ _ _ J J 11 1N4148 2N7000 VCC © 7 14 1 13 1 12 6 1 5 1 4 1 3 CM T- CD CO CM T— O aaooooa© IC2 4566D CO _|_ S UJ ICO |< ICQ “ m a DC < lea B lo lo 10 2 9 7 11 1 15 VCC b? 7 14 7 13 7 12 7 7 7 m co m < < < < CM t- O CO CM t- O aaaaaaa© IC3 4566D co S UJ ICO |< ICO “ m a oc < |co B lu lo 10 2 9 7 11 1 15 RES D3 H 1N4148 D4 1N4148 VCC b? 7 77 T12 2N7000 R1 7 D5 a K 1N4148 IC4.A i- ^ CO Z — I DC LU O RES24 D6 1N4148 14 13 12 IC4.B I- CO Z — I QC LU O 15 10 R20 C6 "j VCC -© IC4 |C4 = 4518D ■ (F) 100n Y 120260 - 11 www.elektor-magazine.com | July & August 2014 23 •Projects Figure 3. This is how the numbers 0 through 9 are represented on each dice. ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo ooo 120260- 13 the clock has been assembled in its permanent enclosure. Turn the clock on for half an hour, so that it will reach thermal equilibrium before start- ing the adjustment. This is a simple job with an accurate frequency counter: The signal on pin 5 of IC1 is adjusted to 32,768.00 Hz. Without a frequency counter you need to check the time daily at a fixed time and adjust C3 accordingly. After a week of adjustments the accuracy will be very good. Counter A handy chip for use in a digital clock is the CD4566. It contains two BCD counters, the first of which counts from 0 to 9 and the second counts to 5 or 6. Here we obviously choose to divide by 6 (pin 11 of IC2 and IC3) for counters from 0 to 59. That finishes the minutes and seconds counters. Nothings else is necessary. The 24-counter for the hours is built from two BCD counters in IC4. These are reset at the counter value of 24 by generating a short pulse via D5 and D6. A nice monostable multivibrator is available in the CD4566, which will generate a clean reset signal (on pin 10 of IC3) from the short pulse at the node with Rl. For a 12-hour clock it is enough to connect diodes D5 and D6 to outputs Q1 of IC4A and Q2 of IC4B respectively. The reset pulse will then occur at a counter value of 12. Display The display for this clock comprises a number of LEDs, which are arranged in the shape of the dots of a number of dice. This has some likeness to the so-called binary clocks (which show a binary code directly), but the display pattern used here is definitely much easier to understand by less technically inclined people. A number is displayed on a 'dice' by illuminating the corresponding number of LEDs (0 through 9). This uses a variation of the patterns of dots as used on a dice (see Figure 3). The LEDs are controlled via current sources. These follow the conventional design with the combination of a transistor (for example T3) and an emitter resistor (Rll). The voltage at the base of T3 is constant with respect to the + 18 V, which is the other side of Rll. Assume that U BE is constant, therefore there is also a constant voltage across Rll. From this follows that there is a constant current in the emitter. The collector current which will flow through the LED (LSEC) is therefore this same value minus the base current. T3 is a Darlington type, which means that the base current is extremely small and its effect can be ignored. The base voltage can be set with potentiome- ter R18 and with this also the brightness of the LEDs. The additional U BE -junction (T2) in series with potentiometer R18 provides temperature compensation of the current sources. A change in the U BE -voltage of, for example, T3 will be approximately compensated by a similar change of the reference voltage at the base. VR, an integrated voltage reference type TL431, is set to 3 V with R16 and R17. V BE of the Dar- lingtons is about 1.4 V. R18 therefore adjusts the voltage across the current source resistors (Rll, etc.) between 0 and 1.6V, corresponding to LED currents up to 16 mA. Because of the current control, all the LEDs in the display segments have the same brightness, independent of the number of LEDs in series. The on/off switching of a segment is done with a MOSFET (for example T8). In addition to its switching behavior, this MOSFET is also essen- tial for isolating the clock from the display driver during a power outage. It is very important that the powered-down driver stage does not draw any current from the battery-powered clock sec- tion. The gates in the MOSFETs are ideal for this since in the steady-state there will flow only a very small leakage current (10 nA). A bipolar transistor would work just as well as a switch in this application, but will always require a base current, even in standby mode and is therefore unsuitable. The exact type of the MOSFETs is not critical: 2N7000, BSS100 and BSS123 are 24 I July & August 2014 www.elektor-magazine.com Dice Clock all suitable. The decoding of the binary value to the correct display pattern is very simple by the clever com- bination of the LEDs in the series connections. Only with bit 3 of the input code (M08) are 2 additional diodes required. Because of the current control it is also possible to give each digit its own color LEDs. The cur- rent through the LEDs remains constant after all, independent of the different voltage drops across the LEDs of different colors. The differ- ence in efficiency between the different colors can be compensated for by adjusting the current for each color. A smaller or larger current for a particular color can be obtained by changing the emitter resistors for that color. The circuit from block M01 through M08 is repeated 3 more times for the remaining digits of the clock. Hll through H12 requires only 2 current sources, since the highest number that needs to be display is '2'. A flashing seconds LED is mounted between the hours and minutes digits. This is driven directly from the 1 -Hz clock pulse. Power supply The power supply for the clock provides an unreg- ulated voltage for the display section and an uninterruptable supply for the oscillator and the counters. The required transformer voltage depends on the voltage drop across the LEDs (from 1.7 V for red LEDs to 4 V for some white LEDs). The dis- play segments with 4 LEDs in series determine the minimum voltage required. For the voltage drop across the current source (emitter resistor + ^cEsat of the Darlingtons) a value of about 3 V needs to be taken into account. Therefore, four white LEDs require 4x4+3 = 19 V. Add to that the 1.4 V for the diodes in the rectifier bridge Bl, which results in a minimum transformer voltage of approximately (19+1.4)/V2 ~ 14.5 V. The power supply voltage to the current sources does not need to be regulated since the current through the LEDs is already accurately controlled. The LM2936 (IC5) looks like an ordinary linear regulator, but is quite an exceptional chip because of its extremely low quiescent current. In the prototype, the current consumption of the counters and oscillator together amounted to 28 pA. The LM2936 delivers this current and manages to add barely 10 pA to the energy bud- get of the clock. In the absence of the line volt- Figure 4. The author built the entire circuit on two pieces of prototyping board. age the complete clock therefore consumes only 38 pA at 9 V! In addition, IC5 has a drop-out voltage of less than 0.1 V at these low currents. The backup battery will therefore be drained to the very last drop. A typical 9-V alkaline battery is specified with a capacity of 550 mAh when discharging to 5.4 V. For this clock this means 0.55/0.000038 ~ 14470 hours or more than a year and a half of standby use. A rechargeable battery is also a possibility by adding a trickle-charge resistor across Dll, but provides hardly any advantage in this circuit. Finally This little clock illustrates that using classic digital building blocks it is possible to build elegant cir- cuits in a simple way. Particularly the extremely low current consumption will be a surprise to many. Various enhancements can be conceived. For example, by making the reference voltage to the current sources dependent on ambient light, the LEDs can be dimmed when it is dark. A purely battery powered device is also possible if the transformer is replaced by a step-up volt- age regulator which powers the current sources from the battery via a 'display on' pushbutton. It is also possible to add two mode LED dice to display the seconds information from IC2. The CMOS 4000-series is still manufactured by various companies (TI, NXP, OnSemi, ...). The type names often have different prefixes. Chips with type codes like CD4566, HEF4566, HCF4566 and MC14566 are all largely compatible. ( 120260 - 1 ) www.elektor-magazine.com | July & August 2014 25 •Projects Opto-isolated PTT/CW interface Serial communication: avoid the pitfalls By Christophe Bourrier, F4EZC (France) QRV@ wanadoo.fr My opto-isolated interface allows you to transmit PTT (Push To Talk) or CW (con- tinuous wave or Morse) command signals from a computer to a transmitter, while keeping the computer circuits isolated from the radio circuits. Figure 1. An optocoupler allows us to ensure electrical separation between a PC and the radio it is controlling. The electrical isolation between radio and com- puter makes it possible to avoid interference from the computer being conducted via the serial interface to potentially cause interference in the receiver. It likewise avoids any RF from the transmitter getting fed back to irreparably destroy the computer... These sorts of dangers are mainly a threat when there is a breakdown, a fault— or sometimes a bit of finger-trouble: an incorrect setting, an antenna problem, a coax connector, defective ground or electrical wiring, can all cause serious trouble. If, for example, the transmitter goes into trans- 26 July & August 2014 www.elektor-magazine.com Opto-isolated PTT/CW Interface this ham radio interface doubles for other applications driven by RTS or DTR mit, even for only a few seconds, while it is con- nected to the computer (itself often connected to the supply line), leakage or RF feedback cur- rents would then pass down the computer and LF connexion cables, electrical circuits, and... bang! The higher the transmitter power, the great the risk is too. So protecting the computer from that sort of risk has to be the start of any protection. In the absence of appropriate precautions, despite its robustness, at best the computer's serial port will be destroyed... and at worst, the mother- board! Not only is this board simple, it also offers characteristics that I hope will convince you how useful it is: choice of RS232 command signals, LED indicator, and use of optoMOS possible. An OFF position lets you disable the circuit to avoid any unwanted commands. The basic circuit shown in Figure 1 is conven- tional, apart from the fact that it lets you choose the RTS or DTR command signals coming from the computer's RS232 socket. The OFF position prevents any commands being sent to the radio transmitter; this is handy when the transmitter is not being used, but above all while the software is initializing— whether Windows or the peripherals. Resistor Rl, the red LED and the optocoupler are fitted in series in the input circuit via selector SI which lets you choose the signals to be used. The LED lights when a command (PTT or CW) is sent by the computer. Because of its low cost, the phototransistor optocoupler in Figure 1 is perfectly suitable in the majority of cases, as long as we can put up with the fact that the emitter/collector junction is polarized and that it causes a voltage drop of sometimes over 1 volt. Resistor R2 is optional, but by biasing the base of the phototransistor, it avoids certain oscillation phenomena. Capacitor Cl makes it possible to damp certain possible output oscillations. The button lets you directly test the radio trans- mitter command. Single-pole optocoupler solid-state relays known as optoMOS™ [1] (a process patented by Clare, whose trademark it is) used in the circuit in Fig- ures 2a and 2b don't suffer from the drawback of the emitter/collector voltage drop in a pho- totransistor. They switch less fast, but still more than enough for radio applications. In either case, R2 will be left out. Using optoMOS in universal AC configuration— and hence non-polarized— (Fig- ure 2a) the voltages switched will be able to be negative or positive. Using the DC configuration (Figure 2b), pin 4 is the positive pole and the switching resistance is lower than in the AC con- figuration. Depending on the exact type, it may be under 10 ft. Watch out— in this configuration, the polarity is reversed with respect to that in Figure 1 with a phototransistor. Figure 2. Using an optoMOS, it's easy I am suggesting a small (42.5 mm x 11 mm; 1.67 to change the configuration x 0.43 inch) single-sided PCB design (Figure 3), (DC/AC). www.elektor-magazine.com | July & August 2014 27 •Projects Figure 3. PCB design and component layout. Component List Resistors R1 = lkQ 0.25W R2 = 1MQ 0.25W (optional) Capacitors Cl = lOnF Semiconductors LED = LED, red Optoelectronics (see text) version with phototransistor: 4N25, 4N26, 4N27, 4N32, 4N33, 4N37, CNY17-3, SL5500, TIL111 version with optoMOS : LCA110, OMA160 (CLARE) 6-pin DIL socket Miscellaneous S2 = pushbutton (optional) SI = 3-position slide switch K1 = mono 3.5mm jack socket (preferably isolated) K2 = 9-way sub-D socket ©0G3 S Figure 4. The prototype of my interface using a Clare optoMOS devivce. distinctly separated into two halves, along with its layout diagram. Using a conventional (pho- totransistor) optocoupler and the optional resistor R2, the jumper JP1 is fitted but JP2 stays open. Using an optoMOS in AC configuration (Figure 2a circuit), JP1 is left out, JP2 fitted, and R2 absent. Using an optoMOS in DC configuration (Figure 2b schematic), the jumper JP1 is fitted and JP2 is open, while R2 is replaced by a short wire strap. Watch out for the polarity of the mini-jack socket KIM If you fit it into a metal case, preferable use an insulated-chassis type: you will have the benefit of all the polarity options possible without having any voltage on the case. In order to be able to change the optocoupler easily, I recom- mend fitting it into a DIL IC-socket. All the types of optocouplers mentioned in the components list have been tested. Use For the first tests, don't connect up the radio transmitter. Connect the circuit's RS232 socket to one of the computer's serial ports or via a USB/ serial converter. Try your radio transmission software (PTT or CW). Select the option RTS or DTR in the software (when this is possible), as well as on the selector switch SI. Check that the LED does indeed follow the transmit commands. If you are using CW mode, it should flicker at the same rate as the Morse being handled. Connec- tor K1 must be connected to the transmitter's CW socket. In the other digital modes, it's the PTT command that is used. This lets you switch the radio trans- mitter to transmit. In this case, K1 must be con- nected to the transmitter's PTT input. Button S2 makes it possible to briefly check the transmitter action (without lighting the LED), to ensure that the wiring is correct and the trans- mitter is configured correctly. And lastly, when the circuit is not being used, do always remember to put the switch to the OFF position. ( 120328 ) Web Link [1] LCA110 datasheet: http://goo.gl/Dlgbqo 28 July & August 2014 www.elektor-magazine.com Super Mobility Week is North America’s largest forum for the mobile innovations to power your connected life — Business. Home. Health. Money. Auto. Retail. Media. M2M. Networks. Only CTIA can convene the most influential mobile marketplace, bringing together, for the first time ever, the leading authorities on the connected life. CTIRBOIH Mob i|e CON THE Mobile Marketplace Powered by CTIA MICA informa iPhone ilS jglirn telecoms*, media 11 1 'Yag/umOIw | IA I EM Xe WORLD %)ns MOBILE EQCCd ENTERPRISE l .CCA & f) CcmpTlA Expo Continua 0 NACHA CDG OINIBO NAHB IARKS National Association ASSOCIATES temia $ TOWER & SMALL CELL SUMMIT 1 tz FierceWireless iapp TWICE — WIRELESS mpi) REPAIRS EKPI“ WLSA Strive for Success. Live for Super. Super Mobility Week powered by CTIA September 9, 1 0 & 11, 2014 Sands Expo & Convention Center Las Vegas #SuperMobility •Review Analog Discovery from Digilent All the bells & whistles in one basket By You may be wondering what's so interesting about a USB oscilloscope module with Dr. Thomas Scherer several additional functions and an analog bandwidth of 5 MHz. However, this mul- (Germany) tipurpose device has a lot to offer. Its additional functions make it an all-round lab in a box' that is ideal for educational purposes or for learning about electronics on your own (the name says it all). Of course, 'real' oscilloscopes with screens and knobs are not all that expensive any more, and they have significantly higher analog bandwidths of 25 to 40 MHz. And even the low-cost models also have extra functions. So what's the advan- tage of this little plastic module from Digilent? What can it do better than a low-cost stand-alone oscilloscope? And 5 MHz bandwidth— isn't that something for the kids? The short answer is that if you're only looking for a low-cost USB oscilloscope, Digilent's offer- ing may not be your best choice. But if you're a student, a committed analog enthusiast or a hobbyist with a passion for test equipment, you should keep on reading— you may find that this little device with its bundle of leads can do a lot more than you might expect. What's in the package? This multipurpose module, which you can use to test, measure and control just about anything to do with electronics in the audio to low-RF realm, is available for US $239 from the website of Digilent, a manufacturer of all sorts of electronics acces- sories and modules. Developed in collaboration with the well-known semiconductor manufacturer Analog Devices, this little device boasts a wealth of functions (see Technical Data), which makes it an excellent hardware platform for training electronics engineering students in entry-level courses. Accordingly, this target group gets a special discount. As a bonus feature, for US $70 you can buy an accessory parts kit. It contains a number of commonly used opamps and CMOS ICs in DIL packages, as well as a bunch of mod- ern SMD ICs from Analog Devices on small PCBs which can be plugged directly into the solderless breadboard included in the kit. If you buy the package, you get a US $20 discount on the price of the parts kit. 30 July & August 2014 www.elektor-magazine.com Analog Discovery from Digilent Technical Data Oscilloscope • 14 bit DAC resolution Other functions • 2 channels with differential inputs • Sine, triangle, square wave, etc. • Voltmeter: DC, AC with True RMS • 5 MHz analog bandwidth • User-defined waveforms • Adjustable output voltage • 100 MS/s ADC sampling rate • Sweeps, envelopes, AM and FM • ±5 V / 50 mA output voltage • 14 bit ADC resolution modulation • Spectrum analyzer with many modes • 1 Mft / 20 pF input impedance • Digital I/O with all 16 pins • Vertical: 0.5 mV - 5 V per division, Logic analyzer individually controllable max. ±25 V • 16 digital channels • Digital pattern generator - up to • 16 KS buffer • 100 MS/s sampling rate 100 MS/s • Cross-triggering with other functions • 3.3 V logic level, LVCMOS compatible • Network analyzer - 1 Hz to 10 MHz • 16 K transitions buffer capacity • Data transfer and power via USB 2.0 Function generator • Trigger: pin change, bus pattern, • Waveform generator output on • 2 channels with single-ended outputs etc. 3.5 mm audio jack • 5 MHz analog bandwidth • Interpreter for SPI, I 2 C, UART, • Signal data can be exported • 100 MS/s DAC sampling rate parallel bus • MATLAB support Figure 1 shows what you get when you order the Analog Discovery & Parts Kit package. When you open the green box on the left, you see a USB cable and a fairly small black plastic module measuring 82 x 63 x 19 mm (3.22 x 2.48 x 0.75 inches) with a bunch of colored leads attached (Figure 2). A few extended six-pin headers are thrown in for free. All of the parts contained in the transparent, compartmented parts kit box are listed on the lid. For anyone who does not have a well-stocked components drawer, the kit definitely has several interesting items in store (Figure 3). Along with the usual opamps, transistors, resis- tors, trimpots, ceramic capacitors and electrolytic capacitors, there are some unusual devices such as a voltage reference IC, a voltage to frequency converter, comparators, and a variety of sensors for measuring current, magnetic fields, acceler- ation, sound, temperature, vibration, brightness and infrared radiation. Digilent has also thought about the details: along with a handy solderless breadboard, there are a bunch of jumper leads and even a small screwdriver. What's that for? Well, it's perfect for levering components free from the breadboard without damaging them. What it can do Everything comes without a single sheet of paper— obviously no trees were sacrificed for the documentation— so the first thing you have to do is visit the website listed on the back of the package [1]. That turns out to be Digilent's order page, but you can also download the necessary software there, which goes by the name "Wave- Forms". As we all know, nowadays hardware is useless without software. WaveForms is available for Windows PCs, but there is also a version that runs under Linux on i386 and AMD64 processors. W 1ANALOG Idiscovery Portable Analog Circuit Design Kit Figure 1. What you get when you order the Analog Discovery & Parts Kit package. Figure 2. The Analog Discovery package contains a USB cable and a small plastic module with a bunch of leads. www.elektor-magazine.com July & August 2014 31 •Review Figure 3. In addition to standard components, the parts kit includes some interesting sensors, a solderless breadboard and other small parts. Figure 4. The selection dialog of the WaveForms program gives you access to the main functions. Installation is a simple double-click operation. The software looks for matching hardware and then links to it. However, on my PC running Windows 7 this takes a little while; approximately 20 sec- onds each time after WaveForms is launched. When it's up and running you see the selection dialog shown in Figure 4, where you can run the basic functions as well as the other functions listed under "Technical Data". The voltage on the USB bus and the current consumption are also indicated. Figure 5 shows the window of what is probably the most important instrument: the oscilloscope. This is a full-fledged two-channel storage scope with all sorts of nice extra features. In the figure the oscilloscope is displaying the signal from the function generator, which is producing a 200-kHz sine wave with frequency and amplitude modu- lation. The spectrum of this signal is also shown in the lower part of the window. Figure 6 shows the window of the arbitrary func- tion generator, which is the source of the signal Dig i lent WaveForms 1 Analog Digital Voltage Static I/O More Instruments Connected to: Discovery s Workspace [j! Device Options (Q) Help _J Feedback (D Discovery System monitor Voltage: 4,847 V Current 387,3 mA Temp.: 30,25 C measured by the oscilloscope. As you can see, the instruments are all modular and can be oper- ated independently in separate windows, just like real stand-alone instruments. You can also see from the setting options that many features are available. The features are certainly as good as what you get with a low-cost function genera- tor, which can easily lie in the same price range as the multipurpose Digilent device even if is made in a low-wage country. The function gen- erator is called "arbitrary" because it can output user-defined waveforms in addition to the usual predefined waveforms. The only tool you need for this is MS Excel. Figure 7 shows the window of the spectrum analyzer. There you can see the typical spikes of a 100-kHz triangle waveform (first, third, ninth harmonics and so on), whose amplitudes drop with increasing frequency. The setting options here are fairly simple. A somewhat irritating fea- ture is that the frequency range settings can only be selected from predefined values, with no option for user-defined settings. This is obviously not a high-end analyzer, but its capabilities are certainly adequate for relatively simple analog tasks. In any case, it's fine for checking audio filters and the like. Now let's look at the other functions mentioned in the technical data. Checking out circuits with relative simple microcontrollers, for example, is no problem. Even if you can't measure signals at high clock frequencies, a 16-channel logic analyzer is certainly useful. The counterpart of the logic analyzer is a pattern generator, which can output parallel digital signals at a respectable 100 MS/s and can utilize the full buffer capacity for the gen- erated sequences. An especially attractive feature is that the digital I/O pins can be individually con- figured as either inputs or outputs, allowing them to be used to read or generate digital logical lev- els. Last but not least, the two analog outputs are connected to a 3.5-mm audio jack in addition to the appropriate leads on the front of the module. This means that you only need a standard audio cable to test a sound system. Selling points By itself, the multipurpose module together with the parts kit would not be of much use in a school lab or on a hobby bench for self-study. For that reason, five "getting started" videos are avail- able on the website [1], along with a complete university course in basic electronics tailored to 32 July & August 2014 www.elektor-magazine.com Analog Discovery from Digilent the device. However, the course is not recom- mended for would-be electronics specialists who don't have a mind for math. That leaves the question of why this little mul- tipurpose instrument could be a suitable bit of equipment for a small electronics lab in certain areas, even for non-students. The answer is that the Analog Discovery module has a lot of strong advantages compared to low-cost stand-alone oscilloscopes. The first, of course, is the small footprint— you already have a PC anyhow, and the device is really small and multipurpose. In the sub-professional realm it can replace a whole set of individual instruments that would collec- tively not only take up more space but also cost a good deal more. Another important consideration is that a PC has a much larger screen. Even if a low-cost stand- along oscilloscope boasts a 7-inch screen with a "massive" resolution of 800 by 600 pixels, it doesn't come anywhere close to this integrated A um 1 - Oscilloscope 1 a as File Edit Control View Settings Window Help Zoom: 5.00 X ** * jif’ 1 170HRV I I I Okllz OOkllz 1G0 kllz 240 kllz 320 kllz 400 kllz Ogtal Q. Zoom Options <0Hdp - Good Rising 2 Time 3' d Level ov - Pos E---:e 0* 200 us/drv w Measurements if X + Add |i f £ 7} Cl OV 1 V/dv | Ch Name Value □ Offset Cl AC RMS 1.59V Rang* ||C1 ADC Ms 14 I □ C2 T Samolefrec 4 MHz Heady ICs provided by ANALOG DEVICES Figure 5. The oscilloscope window of the WaveForms program. A modulated sine wave signal generated by the Analog Discovery module and its spectrum are shown here. Advertisement \ ■ ■ ^ rj Add USB to your next project, w O D It's easier than you might think! DLP-USB1232H: USB 2.0 UART/FIFO HIGH-SPEED 480Mb/s • Multipurpose: 7 interfaces • Royalty-free, robust USB drivers • No in-depth knowledge of USB required • Standard 18-pin DIP interface; 0.6x1 .26-inch footprint n, *$2 Sn 8 -9$/ DLP-I08-G 8-Channel Data Acquisition • 8 I/Os: Digital I/O Analog In Temperature • USB Port Powered • Single-Byte Commands DLP-IOR4 4-Channel Relay Cable DLP-THIb Temp/Humidity Cable DLP-RFID1 HF RFID Reader/Writer DLP-FPGA USB-to-Xilinx FPGA Module www.dlpdesign.com o •Atmel 400 Mhz Processor '128MB DDR2 RAM, 2GB eMMC '16MB Serial Data Flash, Micro SD *36 General Purpose Digital 1/0 lines *8 High Drive Digital Outputs *3x RS232, lx RS232/422/485 *2x 10/100 Ethernet, lx CAN Bus •2x I2C Ports & IxSPI •lx USB (Full-Speed) Host •lx USB 2.0 (High-Speed) 0TG Host/ DevicSJgBrt •Up to 7 channels of 10 bit A/D •Up to 4, 16-bit PWMs •Industrial Temp. -40C to +85C JPac-9x25 3.10 KERNEL Designed and manufactured in the USA, the iPac-9X25 is a web enabled microcontroller with the ability to run an embedded server and to display the current monitored or logged data. The web connection is available via two 1 0/1 00 Base T Ethernet ports or 802.11 wireless wifi networking when using the proper Linux modules and adapters. This Microcontroller has all connectors brought out as headers on a board and has the same footprint of a standard PC/104 module at 3.77" x 3.54". The iPAC-9X25 is perfectly suited for Industrial Temperature Embedded Data Acquisition and Control applications. Pricing for Qty 1 is $198 www.emacinc.com/sales/ipad 4 Since 1985 OVER 29 YEARS OF SINGLE BOARD SOLUTIONS □ , ■ J Cl □ uii men ' Monitor And Control Phone: ( 618) 529-4525 • Fax: (618) 457-0110 • Web: www.emacinc.com www.elektor-magazine.com July & August 2014 33 •Review jfii UWh 1 - Arbitrary Waveform Generator 1 File £dit Control View gettings Window Help I Stop All ] - Select Channels - Mode: | Independent -] ^ Options t^i I lelp Channel 1 (AWG 1) Enabled ■ Slup AWG 1 • Preview Basic ] Sweep Advanced Ing: None * Wait none - Kun: contnuous - Repeat rtinte w 1 [§] Carrier 0FM [g] AM Standard Standard Standard Type [ Sine ▼ Square ▼ Sine ▼ w || | --| ■'III Frequency 200 kHz * 2 kHz - 1kHz - Amplitude.-' Index 2 V * 20% - 80% Offset OV 0% * 0% * Symmetry 50% * 50% - 50% - Phase 0 deg 0 deg - 0 deg * AWG 1 : Running Components * Manual scale - Show: 200 us/drv Modulation 10 Vdrv » 0 % "I V/dnr 0 ms i • i 1 .6 ms 2 i )}| UWh 2 - Spectrum Analyzer File Edit Control View Settings Window Help Export Measurements ^ Markers Add Zoom Options P| Single ^ Stop Till T2 Maximum 1 00 MHx RRW 244 14 Fb Center: 500 kllz 100.00 Id Iz/dW V r requeue) Range 1 MHz to 2.442 kHz / Frequency Center 500 kHz Span 1 MHz Track Disabled J Level Units dRV Ref MdRV Range 150 dBV i^Add Trace gj Trace 1 Channel 1 Trace 2 Driver Input divider and gain selection IE Scope reference and offset TV Buffer -> v Driver Clock generator T i! T Analog Outputs (AWG) ADC DAC IE l/V ■> ~T~ Out 2E Audio -> Left AWG1 AWG ref and offset TV Out A_ i/v ■> AWG2 Audio Right FPGA ft O TV Prog Data PC USB , USB clrl v+, v- Figure 6. The arbitrary waveform generator produces the 200-kHz sine wave signal measured in Figure 5, which is both frequency modulated and amplitude modulated. solution. That's because low-cost oscilloscopes usually have ADCs with a resolution of just eight bits. As a result, the vertical amplitude of a sig- nal is limited to 256 pixels unless pixel repli- cation is used, which does nothing to improve the waveform presentation. With a resolution of 14 bits, the Analog Discovery is clearly playing in a different league. What's more, the window of the WaveForms program can be expanded or contracted as desired. Finally, the software for low-cost stand-alone scopes is often rather rudimentary, even when a USB port or Ether- net port is available, and not especially user- friendly. Here as well, WaveForms comes out on top. Another thing: even if a stand-along scope has more bandwidth, with the Analog Discovery module you get an arbitrary function generator and much more as a bonus. Another plus point is that you can download a PDF document with a detailed description of the inner workings of the Analog Discovery module [1]. Where else can you find something like that? Of course, there are two sides to every coin. The most serious shortcoming is doubtless that the Analog Discovery module is not galvanically isolated. This is not important for analog signals with potential differences of a few volts, since differential inputs are available. However, the digital I/Os are referenced to a ground level that is directly connected to the PC ground via the USB cable. This means you need to know what you're doing when you work with digital signals. ( 120585 - 1 ) This interesting kit is now available from the Elek- tor Store, www.elektor.com. Web Link [1] More information, user guides and software: www.digilentinc.com/AnalogDiscovery Figure 8. Internal block diagram of the Analog Discovery module. All of the circuit details are described in a PDF document. 34 July & August 2014 www.elektor-magazine.com Animal Friendly Mousetrap Weller's (Cooper Tools') legend- ary Magnastat soldering stations have performed valuable service in labs and elsewhere over many years. Gradually, however, they get long in the tooth and develop one minor ailment or another. Old flames never die, they just burn out! But are those grounds for pensioning off faithful old servants? Soldering On With The Weller Don't discard old technology! By Ingo Burret (Germany) Nowadays even the most basic soldering sta- tion contains elaborate control electronics. But in Weller's revered turquoise-colored WTCP 51-LT, WTCP-S, WTCP 50, WTCP 51 [1] (and previous) soldering stations, the matter of temperature reg- ulation was managed mechanically. In a number of countries Weller products are sold under the brand name Cooper Tools. Figure 1 shows the internal construction of the soldering iron. Reading upwards, the tip (1) is linked mechanically to a metal cap (2), which forms the temperature sensor in this system. The cap is ferromagnetic and in its cold state attracts a permanent magnet (3). A push rod transfers the movement arising from this action to a contact bridge (4), which enables the heater current supply (5) to switch in. The numeral on the ferromagnetic cap is a code for the regulated temperature (from 260°C to 480°C). As the iron heats up and the temperature rises towards the required value, the Magnastat loses its ferromagnetic characteristics abruptly, thanks to the Curie Effect [2]. It can then no lon- ger retain the permanent magnet. The magnet drops off and operates the switch, cutting off the power supply to the heating element. When the tip cools, the temperature sensor attracts the permanent magnet once more and the whole sequence begins afresh. This snap action of the Magnastat is very consis- tent and reliable, with no wear and tear caused by ageing or fatigue of the materials. In addi- tion, the Curie Values of the soldering tips display very little variance. A further advantage of this arrangement is that changing the tip switches off the iron, meaning that the heating element does not burn out because the tip is missing. Hot contacts All the same, it frequently occurs that the mag- netic switch seizes up. Then you have to knock or shake the iron in the hope of dislodging the switch. The soldering station itself is still OK oth- erwise and you probably have numerous soldering tips of different shapes and temperature values in the drawer. Over the years you must surely have become fond of the device, meaning you should not throw it out on account of such a minor flaw. Of course you can replace the magnetic switch (the replacement part comes as a single item with the push road and permanent magnet), but it's expensive. And if you then establish that the heater winding is burnt out as well, it's doubly annoying. So how can you unburden the magnetic switch without undue effort? As the two-conductor wir- ing delivers 24 VAC to the heater (a third wire Figure 1. Cutaway drawing of the Magnastat soldering iron (Weller illustration). www.elektor-magazine.com | July & August 2014 35 •Projects r A Figure 2. A triac and a resistor ensure only meager current flow though the magnetic switch. 24V ac IN © — i TRI1 TIC236^ R1 SI I I I -*-! Magnet 7 I HI 260F 50W HEATING ELEMENT Figure 3. The triac and resistor can easily be mounted inside the soldering iron handle on a small piece of PCB. is provided for potential equalization) a mosfet or bipolar transistor will not offer a simple solu- tion. Relays would be too large to fit inside the soldering iron. The solution is a triac, which is conveniently small and wired almost like a tran- sistor (Figure 2). The "electronics" comprise just a resistor for reducing the trigger current for the triac and hence the current through the switch to a tolerable value. The triac fits nicely onto a wedge-shaped scrap of PCB material fixed inside the handle of the sol- dering iron (Figure 3). So the magnetic switch soldiers on forever, even unto grim death... ( 130008 ) Web Links [1] www.weller.de/products/product. php?pid=431 (set language to English) [2] https://en.wikipedia.org/wiki/ Curie_temperature Animal Friendly Mousetrap Non-lethal pest control By Manfred Haemmerle (Austria) Mice are really cute little creatures— except when they enter your home, where they can cause considerable damage and leave droppings that can jeopardize our health. This leaves us with no option: if there's a mouse in the house, we've got to catch it and take it outside. Dead or alive! A couple of years ago we had a crisis: a mouse we had caught in a snap trap was still twitch- ing. Somehow the truly lethal blow had not dis- patched the creature to the afterlife. This left me no other option than to grab an axe and deal with the poor mouse. No, let's drop the subject 36 July & August 2014 www.elektor-magazine.com Animal Friendly Mousetrap there. But afterwards I had to promise faithfully to my animal-lover wife that I would never, ever again murder mice using such beastly, blood- thirsty methods. There had to be another solution and not one of those so-called live-catch traps, which seldom catch anything (people claim to have seen whole families of mice dancing round them, laughing their little heads off). Some of the most outlandish solutions devised by mankind are to be found in the Mousetrap Museum in my country [1]. As a seasoned electronics enthusiast I realized imme- diately that outsmarting the mouse demanded an ingenious combination of sophisticated hard and software. And that's something you definitely won't find at any Mousetrap Museum! Trap shut, mouse alive At the supermarket I discovered some storage baskets made of expanded metal lattice. These come in various sizes and one of them (measur- ing 20x12x12 cm) would serve as my mouse- trap, fastened to a wooden base with hinges and inverted with the base of the basket on top. The small hand-grip hole on one end would serve as the entry point (the other handle opening was blocked afterwards with the printed circuit board). A trap door was fixed over the way into the cage. You can use a small piece of thin wood or circuit board material, suspended on some stiff wire or rings and kept open by a pin passing through a metal loop (Figure 1). As soon as a mouse looking for food breaks the infrared (IR) beam, a magnet pulls the pin out of the loop, the trap- door falls and closes the escape route. No way out for the mouse! Figure 2 shows the electronics of the mousetrap. Power comes from four (rechargeable) batteries. The voltage of NiMH batteries is just right for Figure 1. This is how we fix the trapdoor to the cage. _ R1 [r2 ~ Tr 8 J3 ©> BC547C K4 6 O K3 O Q T1 2P

ELEKTOR 140011-1 U1.0 CL LD ry •'H L - 1 -— • 140011-3 140011-2 #4 LED1 IR TX www.elektor-magazine.com | July & August 2014 39 •Projects Brushed-to-Brushless Motor Con Chip tuning for RC by jorg Prim Exchanging a standard motor in an RC model for a brushless equivalent involves (Germany) some alterations. But the circuit described makes the task simply child's play. Plenty of manufacturers of RC airplanes offer keenly priced 'ready to fly' (RTF) models. RTF means that no tinkering is required; the models can be flown straight out of the box (sort of). The only preparation necessary before your new model makes its maiden flight is to pop some batteries in the RC transmitter and charge up the plane's battery. These models are a great fun and ideally suited for beginners too. All the same, people often feel a desire for a more powerful engine after a few trial flights. That's because most RTF models are equipped, for cost reasons, with standard, brush-type, motors. They are also fitted with a combined 'nerve center' PCB that incorporates a 2.4 GHz or other LPR band receiver, the drive controller and frequently also the servos. An upgrade should not pose problems; surely all that's necessary is to exchange the weak- ling motor for a more powerful one? Frequently, however, anything that sounds simple is con- demned to failure. Here it's because the new, more powerful motor is heavier and takes more current, making a bulkier battery necessary. As a rule even this is no help, because the sturdier motor is unable to defeat the excess weight of the model. Lighter, stronger, further Here's an ideal application for a brushless motor. With no extra weight overhead these motors offer higher performance along with lower wear and tear, because they have no commutator. Stan- dard (brush) motors are controlled by pulses (a few kilohertz in frequency) produced by a drive controller, so as to generate motor control pulses with a repletion rate of around 3 kHz. When the input pulse width is 1 ms the motor does not move, whilst at 2 ms the motor runs at full tilt. 40 ' July & August 2014 | www.elektor-magazine.com Brushed-2-Brushless Conversion A brushless (BL) motor on the other hand is driven with three-phase alternating current, for which the previous drive controller is not designed. In a BL motor the rotational speed is proportional to the three-phase frequency. The brushless drive controller is much more complex in its construction, since it is tasked not only with generating the desired frequency but also with keeping count of the motor revolutions, in order to keep the motor and power source in step. Fortunately the trade offers plenty of suitable BL-type drive controllers at modest prices, so no problem here. Only one minor problem remains to be addressed: the BL drive controller expects to see a servo sig- nal on its input (Figure 1). This involves pulses of 0.9 to 2.1 ms length repeated every 20 ms. In this case 0.9 ms corresponds to 'motor off' and 2.1 ms to Tull throttle'. The receiver mod- ule of the model provides no servo output for the motor, however, since the main PCB already provides a drive controller suitable for standard motors. The output of the receiver unit looks in principle as shown in Figure 2. A power MOSFET is provided with a PWM signal. An N-channel MOSFET is used mostly, driven by a signal that is referenced to ground, in other words switching the motor with positive-going pulses. The PWM signal is a square wave of several kilo- hertz. In this way the pulse width is varied from 0 to 100 % (often only from 20 to 90 %). In the motor the pulsed drive is transformed into kinetic energy: the greater the pulse width, the higher the rotational speed of the motor. At 100 % the MOSFET is conductive all the time and the motor runs at maximum power. Servo signal from the microcontroller The circuit described here now transforms the PWM signal from the receiver module into a servo signal for the drive controller (Figure 3). Input K2 is connected to the receiver unit in place of the standard motor. Here only Pin 1 is assigned, deriving its ground connection through the MOS- FET of the receiver module. R3 is a relatively low- value pull-up resistor, to ensure that the PWM signal reaches the microcontroller input PB4 with its pulse edges as steep ('fast') as possible. With D1 we can monitor whether the controller is working. A three-wire servo cable is connected V+ Figure 1. Here's how a servo signal looks. Figure 2. Typical drive controller configuration for standard motors. +5V Figure 3. A small circuit with a small microcontroller! www.elektor-magazine.com | July & August 2014 41 •Projects Figure 4. And a particularly compact PCB... to the BL drive controller at K3. Pin 3 is ground and Pin 2 the positive operating voltage (5 V) for the drive controller. Pin 1 carries the servo signal from the microcontroller to the drive controller. The software in the microcontroller evaluates the signal at PB4 and is tolerant of PWM frequencies from around 500 Hz up to 10 kHz. The servo signal generated on output PB1 is proportion- ate to the pulse width of the PWM signal. If no suitable PWM signal is detected, the software always delivers a 0.9 ms 'motor stop' servo sig- nal at the output. The software is self-calibrating, requiring the user to give a single short burst of full throttle at switch-on for the software to 'learn' the maximum PWM pulse length. Naturally you need to hang on like the grim death to the model during this calibration process. The LED flashes twice briefly after power-on— indicating operational readiness. When the motor is idle the LED is dark but it is illuminated as soon as the 'engine' is turning. Construction of the small, single-sided PCB in Figure 4 is child's play. If you provide the 8-pin ATtiny controller from Atmel with a socket, this must hold the IC firmly during even the most intrepid flight maneuvers. The controller is the- oretically programmable in-circuit, although for space reasons we had to omit the necessary interface connector on the PCB. If you have no facility (or desire) to program the controller your- self, you can acquire it ready-made, just as you can the PCB [1]. The software (source code and hex code) is also available of course. Please note that the circuit is designed only for receivers using motors switched to ground and for PWM frequencies between 500 Hz and 10 kHz. ( 120527 ) Internet Link [1] www.elektor-magazine.com/120527 Component List Resistors IC1 = ATtiny45-20PU, programmed, Elektor Store # R1 = 330ft 120527-41 R2 = 1 kft R3 = 47 kft Miscellaneous Capacitors 8-pin IC socket K1,K2 = 2-pin pinheader, 0.1" pitch Cl = lOOnF K3 = 2-pin pinheader, 0.1" pitch Semiconductors D1 = LED, 3mm, red PCB # 120527-1 42 ' July & August 2014 | www.elektor-magazine.com PASSPORT-SIZE PC SCOPES Great scopes for field ^e wItMaPtop^ ssssSS !G sa/s AWG/ wf m gen . - PSHa $2 ^ ^^"^ISSSSSSS SS 5 SS^^«»-» *w q Hign-end «0«Hza ^ FR£E ^ope carry * 5qq I ’^25222 JESSKs with e- v,vg a j LCD integrated generator, WMpt memory, very i^notse floor. - DS2000A series $83 c l + 7 % T '7 J J a 4 •i - * % * . The Convenient All-in-One Solution for Custom-Designed Front Panels & Enclosures m ONLY $90.24 with custom i logo engraving You design it to your specifications using our FREE CAD software, Front Panel Designer We machine it and ship to you a professionally finished product, no minimum quantity required • Cost effective prototypes and production runs with no setup charges • Powder-coated and anodized finishes in various colors • Select from aluminum, acrylic or provide your own material • Standard lead time in 5 days or express manufacturing in 3 or 1 days B 'FRONT PANEL EXPRESS FrontPanelExpress.com 1 (800)FPE-9060 Electric Guitar Sound Secrets and technology BEST- SELLER ! 1 w !i! M % #defi ne F_CPU 8000000UL #include #define LGoat PD4 #define LCabb PD6 #define LWolf PB5 #define RGoat PB3 #define RCabb PB4 #define RWolf PB6 #define BuzzerPD5 #define statLGoat 0b00000001 #define statLCabb 0b00000010 #define statLWolf 0b00000100 #define statRGoat 0b00001000 #define statRCabb 0b00010000 #define statRWolf 0b00100000 #define statLBoat 0b01000000 #define statRBoat 0bl0000000 /* Inputs are as follows: PIND&7 ( 0b00000111 ) 7 = SI (Boat) 6 = S2 ( LGoat) 5 = S3 ( LWolf) 4 = S4 ( LCabb) 3 = S5 (RGoat) 2 = S6 (RWolf) 1 = S7 (RCabb) 0 = not connected */ void setLeds (void) ; uint8_t readlnput (void) ; void boatStart (void) ; void boatContinue(void) ; void playSound (ui nt8_t Sequence); buzzer BZ1. Also the farmer gets very excited and starts racing across the river in celebration. We surmise a slight problem there arising from his activity but no matter— the game will start again. The program running inside the ATtiny micro is available for free downloading from Elektor's Mag- azine website [1]. It's supplied for you to feast on the C code and optionally program your own ATtiny2313 chip. An extract appears in Listing 1. ( 130354 ) Web Link [1] www.elektor-magazine.com/130354 Figure 3. Suggested front panel layout designed for the Serpac H75 9 V case. www.elektor-magazine.com | July & August 2014 47 •Projects SAME: Chip-8 Video Games Emulator Single Arcade Machine Emulator: a virtual machine on a PSoC By Camille Jourdan Gay (Japan) (ccamyy@gmail.conn) and Luc Lemmens (Elektor Labs) You're not going to believe me, but despite appearances, the aim of this article is not to get you playing, neither Pong nor Tetris, but rather to encourage you to have a go at programming. Happily the one doesn't rule out the other. current, of virtual machines, like Java or others: the software imitates or simulates, or as we say emulates, the functions of an item of equipment that doesn't actually exist. In this way, the Chip-8 video games, written for a virtual platform, are able to run on a real platform with which they have not the slightest affinity. By programming a virtual machine there, we will transform any embedded system into a video games console: a touch-screen mobile phone, a computer, a refrig- erator or a washing machine— it doesn't much matter, as long as their microcontroller is capa- ble of emulating a (simple) virtual machine. We just need a microcontroller, a display, a few but- tons, and an interpreter for running the Chip-8 video games code that is easy to find on the web. Ideal for students, the exercise is highly educational and very instructive for anyone who wants to gain experience in system architecture programming: registers, stack, memory space, program counter, etc. This lets you get a proper Where have all the listings gone? We'd bet- ter start by explaining why there's hardly a single line of code in this article. This absence, apparently in contradiction with the subject, is deliberate: rather than approach it through an examination that would necessar- ily have to be superficial in an article of just a few pages, the full description of the software has been brought together in a very compre- hensive and clearly-structured document that Elektor members can download free of charge. Obviously the full source code is available too. Chip-8 in 2014? The Chip-8 language originally designed by Joseph Weisbecker for RCA's 1802 micropro- cessor will soon be 40 years old! [1] In the late '70s and early '80s, it made it possible to cre- ate video games without having to worry about their hardware context. This is the idea, still very 48 July & August 2014 | www.elektor-magazine.com Chip-8 Video Games Emulator grasp of how a basic computer operates, in an entertaining way. The heart of the Chip-8 virtual machine resem- bles that of a real microcontroller, with its pro- cessor, its registers, its stack, its memory, and its two timers. It is capable of executing 35 16-bit instructions (called opcodes) with which the video games are programmed, without requiring any other resource. Everything happens between a few buttons for entering data, and a display for the eyes and possibly a sounder for the ears. The interpreter is a program that, on an embed- ded system, executes the code for the Chip-8 video games, recovered ready-made (e.g. Tetris. ch8). It is written in the language of the embedded microcontroller. It translates the 35 virtual opcodes into a code that is execut- able by the real microcontroller. In the code for a game, the opcode 0OEO for example gives a clear screen command in a single line, while in the embedded system code it will be several lines, the number and exact nature of which will depend on the hardware used. The part of the embedded system memory used by the interpreter is divided in two: it has its own workspace for its own variables, for the interfac- ing with the hardware, etc.; and then a space for the virtual variables of the Chip-8 architec- ture, for example, the program counter or stack pointer. The code for the game itself is stored in an array of bytes that the interpreter reads in order to translate each of the opcodes into an equivalent function executable by the micro- controller to which it is addressed. In C, for handling these opcodes, we use quite simply a switch/case structure for layered switching. For example like this one: whi le (1) { opcode = gameMemory [programCounter] ; switch (opcode) { case 0001: ExecuteOpcode0001 () ; break; case 0002: ExecuteOpcode0002 () ; break; //... } programCounter++ ; } Undefined space The workspace size is undefined and depends on the hardware and the programmer's choices. For example, the opcode currently being executed (16 bits) does not have a memory space defined by the Chip- 8 architecture; it's a combination of the program counter and the virtual memory space (8 bits). The programmer can choose either to make it into a macro #defi ne OPCODE ( (READ_PROGRAM_MEMORY (PC) << 8) | READ_PROGRAM_MEMORY (PC+1) ) or to use a variable in the workspace short OPCODE = ( (READ_PROGRAM_MEMORY (PC) << 8) | READ_PROGRAM_MEMORY (PC+1) ) The first case will limit the use of the microcontroller's memory, the second case, the use of the CPU in case of frequent calling. Certain of the 35 virtual codes are easy (e.g. ADD or SUB), others can cause quite a head- ache, particularly those that allow us to draw on the display or the one that produces a random number— a very useful function in games. It's not possible to go into detail here, but nothing of this interpreter will be hidden from you; everything is carefully described in a 31-page downloadable document which we can't recommend too highly to read [2]. There you will find all the detail for programming each code. It seemed to us pointless and frustrating to show here only certain aspects, which would still be incomprehensible because of the lack of an over- all view. On the other hand, this article describes the construction of a real embedded circuit that lets you play Chip-8 video games. This principle is applicable to any other microcontroller circuit with the necessary inputs/outputs. When, thanks to the downloadable documentation, you have seen how I've configured my system (timers, inputs, etc.) and programmed the interpreter, it may be that my approach and my dodges will be useful and will inspire you. Even if you take a different route to arrive at the same result, you will undoubtedly encounter the same difficulties as I did, like for example the lack of memory or the too few inputs available. Virtuality materialized We've talked enough about the virtual, now let's take a look at the hardware. Flere's what we're going to need: www.elektor-magazine.com | July & August 2014 49 •Projects VDD N Figure 1. The simplicity of the emulator circuit is deceptive: within the PSoC IC1 hides a programmable arsenal that runs the Chip-8 virtual machine. • a matrix display of 64x32 dots or more • 16 buttons (in practice, 3 or 4 are enough for most games) • a sounder (unless you prefer silent games) • a microcontroller capable of emulating the Chip-8 virtual machine, with these specifica- tions: - 35 16-bit instructions (opcodes) - 4 kB of memory - 16-level 16-bit stack, used for the return addresses - 16 8-bit general-purpose registers and 3 special registers (memory pointer, program counter, stack pointer). - 2 60 Hz 8-bit counters: Delay Timer and Sound Timer. It's not a lot. I've also made provision for my system to be compatible with a more recent ver- sion of Chip-8, called Super Chip (SCHIP), which allows a 128x64 dot display and handles a few additional codes and registers. If you were expecting a complicated circuit, you're going to be disappointed by Figure 1 . Apart from the buttons, the liquid crystal display, and the voltage regulator (IC3), there are only two integrated circuits: a 29466 PSoC, which has the status of microcontroller (IC1), and an I 2 C EEPROM. Oh, and I was forgetting Bzl. I'd initially conceived this circuit for a single game, resident in the microcontroller memory. While on the way, I had such fun that the idea expanded 50 July & August 2014 www.elektor-magazine.com Chip-8 Video Games Emulator An entertaining and educational exercise for gaining experience in system architecture: registers, stack, memory space, program counter, etc. to house eight games in a separate EEPROM. All that it took was to add a selection menu so the player can choose from the games available. This is, moreover, how the reset button S9 appeared, which is not needed in the monogame version. A PSoC (Programmable System on Chip) com- bines on the same chip a microcontroller and miscellaneous digital (counters, convertors, etc.) or analog (amplifiers, filters, etc.) accessories which can be freely combined with the help of the software. My choice of the 29466 PSoC is based on the one hand on its price (€ 30 for the essential programmer and € 5 for the actual PSoC itself) and on the other, on the presence of several digital sub-assemblies that enable us to have two timers, a PWM signal generator (for the sounder) and a built-in random generator. For the buttons S1-S8, there's not even any need for biasing resistors on the corresponding PSoC inputs, as these are internal and configurable. To create the two 8-bit timers mentioned above, I used several of the PSoC's modules. These can be configured either by laboriously writing the values given into the registers provided for the purpose, or by using a special configuration tool, which is much more convenient: the PSoC Designer, provided for the purpose with a graphical inter- face, using which all you have to do is arrange the modules as you see fit before establishing the desired connections between modules and between ports using logical operators. This con- figurator also lets you define global variables like the microprocessor frequency, port configura- tion, etc. just by clicking. PSoC Designer auto- matically creates functions for direct interaction between the microcontroller and the modules (e.g. Timerl_Start() , Timerl_Stop () , etc.) The ports connected to the buttons are configured as inputs, fitted with internal pull-up resistors. The other ports are configured as outputs. Fig- ure 2 illustrates the module configuration. The names of the DELAY_TMR and SND_TMR timers leave us in no doubt as to their function; the second auto-decrements and makes the sounder sound when its value is other then 0. Thanks to an AND gate and SND_PWM, this is the generator for the 4 kHz PWM signal made audible by Bzl. PRS8 delivers the random numbers for the Chip-8 RND opcode. Here are a few of the PSoC's specific features. Buttons: The state of S1-S8 is read by a func- tion that returns a variable in which each bit corresponds to one of the buttons. It's simple, but when you examine the software and my doc- umentation, you'll see that I did have to cheat because of the internal resistors, whose high bias has to be established each time before reading the port. Otherwise the input stays low even once the button has been released. Display: There's a huge choice and the display drive techniques vary. Here we use a KS0108 driver chip which uses parallel bit-banging. The DI pin distinguishes the instructions from the data, the RW line read from write, the two CS1/ CS2 pins the right side of the screen from the left (128x64 = 2x64x64), and lastly the EN signal Figure 2. for synchronization. The 8 pins on port 2 are used Configuration of the PSoC for the data being read or written. In my doc- modules. www.elektor-magazine.com | July & August 2014 51 •Projects Page o ii x 55 Dl ra cl "S Lines Line □ ' Line 1 — Line 2^ Line 3— Line 7 Column AddressfO -63} 0 :a: ■ ■ ■ i; ii > -\ Q Q 0 -I- A® J"- 0 d Sit o o 0 1 I 1 D D 0 =1 0 0 0 0 ; Q 1:5 Q 1 : Q . :s: - o ffflff IIT " ' ' ! 0 , :y .\ o o D 'd ^ ; o 0 ■ a Q Q Q '"0 o' o Sit o ! i . o ;:t o'Ti ! o : 0 f "o' so" ■i ■ S ,yr i l 1 f ■; “ ■> 0 : 0 ! 0 0 D D D 1 lsL®. 1 o' o' o' o' 0 0 0 o' o' o' o' o' Data DBOiLSB) -DB1 -DB2 DB3 DB4 DBS DBS DE7rMSB) x 55 □n ra Cl ■a C OJ Line 6 Line 9 ' Line 10 1 ■ ■ ■ :a: ■ ■ ■ ■j' ■ r ■ ■S' I i ! 1 ! 1 0 0 * 0 0 . Line IS— 0 0 0 0 * t >, >p 0 0 Hi o ::v "“d d ::j: o o ■rri-' o 0 ; 0 "i'T'o' ■ ■ ■ r 1 : 0 [O : 0 95 Q 3 i 0 0 d 0 d I %i ! :i ;|0 ■ 1 ■ 0 : i f f ■ i - ■ h' — M: Q : a. : 0 mV4 j i 0 ■ 0 i=i: D 0 D D 0 0 r- ■. 0 O' 0 0 0 0 o' o' DBOiLSBj. DB1 DB2 -DB3 -DB4 DBS DBG -bB7(MSB] r- ii x. ¥ CTp ra □_ eg Line 56 Line 62- Line 63— 0 0 0 ■ ■ ■ p m m , j: a: 0 D 0 D 0 0 1> • 1 • t 1 - . . -|_ > >. * >Al t JL i: :r. o , r 1 : 0 : 0 0 , ■ 0 0 0 0 0 5- 0 ■ ■ $ 3 a 3 i Q ■ ■ I, *;; r Q 1 : 0 V To . . — 3 : o o ; o ; o o o ; o o o o .. 1 . 1! f ' i It. 0 0 0 ! 1 0 0 0 V G G 5 G i? ■! a : 0 : ■i r Mill A IP A I ! D D D D D 1 ■ ■ ■ i o. i o -- — '■ o :i: o o o o o o' o' DBOtLSB) DB1 DB2 DB3 -DB4 DBS -DB6 -bB7> 12 )& 0xl)//we decode the opcode by groups of 4 bits { /^OPCODE DECODING AND EXECUTION*/ } if (ERROR) { /*ERROR HANDLING*/ } if ( ! ( (OS_FLAGS >> PC_NOT_INCREMENT_FLAG) &1) ) { PC += 2; // Increment the PC except if told not to } } Here we are now arrived at the 35 opcodes, among which we'll be able to spot: • the arithmetic operators like add and SUB which most microcontrollers know • the branch operators like jmp and call - apparently simple, but which, because they affect the virtual architecture, need to be handled with care • the operators that affect the memory, which are no problem for microcontrollers with plenty of memory, but which oblige us to use dodges if the microcontroller's mem- ory space is tighter than that of the Chip-8 architecture. • the operators that affect the hardware and depend directly on the hardware configuration All this is described through the menu in the on-line documentation, as are the opcodes spe- cific to the timers, buttons, and random numbers. We'll conclude here with one special category, www.elektor-magazine.com | July & August 2014 53 •Projects Figure 4. The PCB designed as double- sided is easy to make single-sided. the Chip-8 graphics opcodes. We've seen that the standard display format is a 64x32 matrix. As we have a 128x64 dot screen, one Chip-8 pixel corresponds to 4 actual pixels. The origin (0,0) is the top left corner. The graphics codes are by far the most difficult to transpose - among other things, because the logic of our display is totally different from that of the Chip-8 architecture, which writes in "lines" of 8 pixels, while the LCD display writes in "columns" of 8 pixels. Chip-8 draws the pixels from co-ordinates in fixed-width groups (8-bits) and variable height. The 128x64 display is divided into two 64x64 screens, in turn divided into 8 pages, themselves divided into 64 columns (Figure 3). Hence we are obliged to write our pixels in column of 8 within one of the 2*8*64 boxes, which implies a fixed height for these pixel groups. We're only going to be able to use the fixed Y co-ordinates (lines 0, 8, 16, 24, 32, 40, 48, and 56) and each write operation will also affect certain of the neighboring pixels, which requires a certain degree of gymnastics. The on-line document explains how to set about this and gives other valuable explanations about managing the display. Construction After all that virtual stuff, here we come now to the concrete bits. The suggested PCB layout (Figure 4) is dou- ble-sided, but for the sake of a few straps, you can easily produce your own single-sided one— especially as only through-hole components are used. The 128x64 pixel display with its KS0108 chip won't be any problem to source, but do watch out for its pinout. We ordered a TG12864B-02 (Vatronix), but received a TG12864B-03, on which pins 19 and 20 for the anode and cathode of the backlight panel are reversed. So watch out for that suffix! Whence the presence of the very Component List Resistors R1 = 270ft 0.25W 5% R2 = 820ft 0.25W 5% R3,R4 = 2.7kft 0.25W 5% R5 = lkft 0.25W 5% R6 = 100ft .25W 5 % R7 = wire link (see text) PI = 47kft trimpot C1,C2,C3,C4,C5,C6,C7 = lOOnF 50V 20% Semiconductors LED1 = LED, red, 3mm IC1 = CY8C29466, Cypress PSoC, pro- grammed, Elektor Store # 130469-41 IC2 = 24LC256 EEPROM IC3 = LM317 6x6 mm S10,S11 = on/off switch 8-way DIL IC socket for IC2 (see text) LCD1 = 128x64 pixels, e.g. Vatro- nix TG12864B-03 or Midas MC128064A6W (see text) Bzl = 5 V buzzer Capacitors Miscellaneous C1,C4,C5 = lOpF 50V radial S1-S9 = pushbutton, PCB mount, 24V 50mA, 54 ' July & August 2014 www.elektor-magazine.com Chip-8 Video Games Emulator philosophical 0 ft resistor R7 (in fact a simple wire strap) for changing the configuration of these two pins according to which model of display you have. Where necessary, cross over R6 and the wire strap (R7) so that pin 19 is grounded via R7 and pin 20 connected to V DD via R6. Farnel/Newark offer the MC128064A6W (Midas), but if you want to find cheaper, you can take a look on eBay. Although it's not obligatory, the backlight is unde- niably convenient for the player. It only uses 20 mA. The EEPROM is fitted underneath the PCB (sol- der side) to make access easier; if you want to add or change games, it's easier to remove the EEPROM from its socket to plug it into the pro- grammer than if it was under the display! Note in Figure 5 the special type of socket to make up yourself in order to be able to solder it on the copper side of the PCB! The regulator IC3 is fitted flat to the PCB. If you make a double-sided PCB like the one in the pho- tos, the metal surface of the LM317, which is at V dd (+5 V), must not come into contact with the copper of the surface, even if this has no volt- age on it. As a precaution, it's best to arrange sufficient spacing and fix the regulator using a nylon nut and bolt (Figure 6). The PSoC is programmed using a PSoC MiniProg interface connected to Kl, directly from the PSoC Designer programming environment (we used version 5.4). During programming, the whole circuit can be powered via this interface and the normal supply is not needed. Firmware Elektor supplies the (source) code for program- ming the games into the EEPROM and the code for the PSoC emulator, but not for the actual games themselves! The programmed PSoC avail- able from the Elektor Store [8] (# 130469-41) contains only the firmware. You won't have any trouble downloading Chip-8 games code [3]. Some are in the public domain, others not. Be sure to respect any copyright; this remains in force even after decades. If you want to program the firmware in the PSoC flash memory yourself, connect a MiniProg (Cypress) programmer to Kl. Figure 5. IC2 must be fitted into a socket that you'll have to make up yourself from socket headers, in order to be able to solder the pins to the PCB tracks. Figure 6. We can see the regulator fitted a small distance from the copper surface. Here are the three ways to load a game: • insert the game into the EEPROM using a third-party tool that lets you copy a file to an EEPROM; • insert the game in the EEPROM using the tool [9] that I've made available; in this case, the emulator board (Figure 4) is used for flashing the EEPROM; • insert the game directly into the PSoC flash memory. In this case, you'll need to modify the default values of the interpreter vari- Figure 7. Menu for selecting the games the PSoC finds in the EEPROM. www.elektor-magazine.com | July & August 2014 55 •Projects About the author Following his Electrical Engineering studies at the INSA in Lyon (France) and an exchange year at the University of Tokyo, Camille Jourdan is currently in Japan under an international business volunteer scheme with Ichikoh Industries, who manufacture automotive lighting. Fie has worked in electronics, image processing, and in software development in Tokyo and Paris. This Chip-8 project was designed and built on a personal initiative during his free time, in Japan, using equipment from Akihabara, Tokyo's electronics district— a place of pilgrimage he recommends to Elektor readers! Camille is grateful to Matthieu Denoual for advising him to publish this project, together with his Laboratory Director Yoshio Mita, and of course Luc Lemmens at Elektor Labs! ables in order to be able to insert the game there. Flence the code must be located in the PR0GRAM_M EMORY array just after the typefaces (global . c). • EEPROM present with headers: selection menu runs, then the game selected using the settings indicated. (130469) To close, here are the three scenarios handled by the interpreter: • EEPROM missing: the game present in the PSoC mem- ory will be run (whether it was copied from an EEPROM that had pre- viously been con- nected or from the PSoC programmer) • EEPROM present, header miss- ing: the game in the EEPROM runs using the default settings Web Links [1] General description of instructions, http://en.wikipedia.org/wiki/CFIIP-8 [2] Full documentation for the SAME Chip-8 emulator, www.elektor-magazine. com/130469 [3] Commented games code and documentation by David Winter, www.pong-story.com/chip8/ [4] Details of the Chip-8 instructions, http://devernay.free.fr/hacks/chip8/C8TECFI10.FITM [5] Information about Super-Chip and a good example of an interpreter (in French) http://blogs.wefrag.com/mrhelmut/2012/01/14/recette-creer-son-premier-emulateur/ [6] Useful libraries (fonts) for programming LCD display screens, http://en.radzio.dxp.pl [7] Tool for converting game code into hex arrays, www.fourmilab.ch/xd/ [8] the PSoC in the Elektor Store, www.elektor.com/psoc_chip8 [9] Instructions for programming the EEPROM, www.elektor-magazine. com/130469 56 July & August 2014 www.elektor-magazine.com Led Sorting & Matching Accessory TH LED Matching & Sorting Accessory This project is a spinoff from, and an accessory to, the magnificent Precision Adjustable Current Source published earlier this year [1]. The sim- ple tool shown here can help to sort or select through-hole LEDs by visually comparing their color, brightness and/or radiation angle. Though they may all look identical in your stor- age box, LEDs can look completely different when lit, especially when mounted close to each other (like in an LED bar or panel). In the "early LED days" color and brightness dif- ferences occurred with LEDs from the same man- ufacturer, and sometimes even from the same type and production run. Production processes may have improved, but K2 Component List K1 = 2-way connector (pads and clearance at PCB edge) K2 = 20-way SIL socket, 0.1" pitch K3 = 20-pin SIL pinheader, 0.1" pitch JP = Jumper, 0.1" pitch PCB # 140067 (C)Elektor 140067-1 VI .0 1 K1 1 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9|10 most of you should own up to having at least one By Henry Morizot box marked "LEDs" containing devices of unde- (France) termined brand and type numbers. With this accessory LEDs can easily be con- nected in series by inserting their pins into a socket strip. Next, the precision current source can be set to different values to see what the light bar looks like. Even small differences in color, bright- ness and radiation angle can be spotted with confidence. With our Precision Adjustable Cur- rent Source the maximum clamping voltage is about 20 V, meaning we can power roughly up to 10 'normal' LEDs in series. This number depends on the type and color; a red one will typically have a forward voltage of some 1.8 volts whereas blue may be in the 3-volts region. Set the clamping voltage of the DC current source to maximum value (fully clockwise), and the current to the 1 mA - 20mA range. Start with the reference LED in the left-most socket position, with the cathode pointing to the left, and insert the other ones in neighboring positions to the right. A jumper must be set on the two pins in the same position in front of the rightmost LED. All LEDs should be lit then, the reading on the LCD of the current source show- ing the total forward voltage of all the LEDs in series. You can switch off one or more LEDs by moving the jumper, that way you can also deter- mine the forward voltage of each individual LED. If the clamping indicator on the front panel of the DC current source lights, the forward volt- age of the LED chain exceeds the range of our DC current source (you did set that clamping to max— right?). ( 140067 ) Reference and Web Link [1] Precision Adjustable Current Source: Elektor April 2014, www.elektor-magazine.com/130287 www.elektor-magazine.com | July & August 2014 57 •Projects Microcontroller BootCamp (4) User interfaces BASCOM-AVR IDE [2.0.7.6] - [C:\Arbeit_neu\Elektor\Uno\Uno4\Bascom4\UNO_LCD2.bas] u 5 0J £3 , ! * Ife e W ✓ , ! & B % X 1 - <2) H ft „ I • ? , m | File Edit View £rogram Tools Options Window Help ^ iJMA_TSA_V2.bas ^ LINO_LCD2.bas S3 ▼ Label ' UNO_ICD2 . BAS Voltage AO, A3 Sregfile = "m328pdef.dat" Scrystal = 16000000 Sbaud = 9600 Dim D As ford Dim U As Single Config ADC = Single , Prescaler = 64 , Reference = Avcc Config Lcdpin = Pin , Db4 = P0RTD.4 , Db5 = PORTD 5 , Db6 Config Led = 16 * 2 Cls Cursor Off Do Locate 1 , 1 Led "A0 " D = Getadc(l) U = D * 5. 0 U = U / 1023 Led U Led “ Locate 2 , 1 Led "A3 “ D = Getadc(3) * I m By Burkhard Kainka (Germany) Serious microcontroller applications usually have some sort of interface between humans and the machine. You can do a lot with a just a small display, a few but- tons, a potentiometer and a couple of LEDs. What's more, you can hit the ground running with the Arduino shield developed by Elektor, which is described elsewhere in this edition. First let's see what it takes to drive a display. Various types are available, including graphic and text displays. Text displays range from tiny with a single line of 8 characters, to large with four lines of 20 characters. As the saying goes, small is beautiful, and in many cases you don't have to display a lot of characters. That's why the new Elektor shield has a small two-line text display with eight characters per line. In any case, that's enough room for messages such as " V=3.3V " or "1=8. 2mA". What more do you need on your electronics bench? LCD connection Figure 1 shows how the display module on the shield is connected to the ATmega328 on the Arduino board. You can also see the other periph- eral components there: two LEDs, two pushbut- tons and a potentiometer. If you wish, you can build all this yourself on a piece of prototyping board. You don't even have to use exactly the same type of display module. One with two lines of 16 characters would work just as well. If you like to keep things simple, you can order the new shield on the web page for this article [1], where as usual you can also download a file containing the code for the programs described here. The display occupies six pins on port D: D2 to D7. That's handy, because it leaves exactly two spare for the serial interface: DO (RXD) and D1 (TXD). Ports B and C remain free for whatever strikes your fancy. All standard display modules 58 July & August 2014 www.elektor-magazine.com Microcontroller Bootcamp of this sort can optionally be operated in 8-bit mode, which means that the data is sent to the display over eight lines in parallel. However, 4-bit mode has become customary to reduce the num- ber of port pins used on the microcontroller. In this mode each data byte is sent to the display in two steps. For example, if you want to write an upper-case A you have to send the hex value &H41 (binary &B01000001, or 65 in decimal nota- tion), as specified in the ASCII code table. In fact you first send &B0001 and then &B0100. How- ever, you don't actually need to know all these details or how to go about initializing the display, since Bascom does all the hard work for you. If you simply write Led “A” in your program, the letter A will appear on the display. Our first example program (Listing 1) shows how it all works. First you need a Config instruc- tion to tell the compiler how the display pins are connected to the port pins. Next you have to initialize the display with the Config Led = 16 * 2 instruction. You can choose from several formats here. The format 8 * 2 is not supported because the display controller in the LCD module is designed for two lines of 16 characters (16 * 2), even with this small display. That's not a problem in practice because the program keeps on running without an error if you accidentally write up to 16 characters in a line. However, when you see the truncated output on the display you will have to consider how you can shave a few more characters off the message. After you initialize the display, you should clear everything with the Cls (Clear Screen) command. Everything written after this lands on the first line, starting at the left end. Here it is the word "Elektor" - seven characters, short and sweet. If you send another character to the LCD now, it will be written to position 8 on the first line, but what you actually want is to start with the sec- ond line. For this you use the Locate command. Here Locate 2 , l causes the next character to be written to the leftmost position of the sec- ond line. The program outputs an incrementing number at this position. The count variable N is incremented once per second, so you can use the program to measure time. For example, it's Listing 1: Text and number output. i ' UNO_LCDl . BAS Text Output i $regfile = "m328pdef.dat" ' ATmega328p $crystal = 16000000 '16 MHz $baud = 9600 Dim N As Word Config Lcdpin = Pin , Db4 = Portd.4 , Db5 = Portd.5 , Db6 = Portd.6 , Db7 = Portd.7 , E = Portd.3 , Rs = Portd.2 Config Led = 16 * 2 Cls Led "Elektor" 'Cursor Off Do Locate 2 , 1 Led N N = N + 1 Wai tms 1000 Loop Figure 1. Basic diagram: how the LEDs, buttons and display on the Elektor shield are connected to the ATmega328 on the Arduino Uno board. www.elektor-magazine.com | July & August 2014 59 •Projects taken me 1200 seconds to write these lines since I started the program. That's 20 minutes, which means I'm pretty slow today. There are two Led instructions in this example program, and it's important to understand that they do two completely different things. The pure text output instruction simply copies the charac- ters set in quotation marks by the programmer. By contrast, the instruction Led N converts the numerical value in the variable N into text and then sends this text to the display. In this case N is an integer, but in other cases it could be a real number with decimal places. Bascom decides on its own what has to be done, which is very convenient for the user. In other languages the programmer has to do more in these situations. On the display you will see an underscore after the number that was output, which represents a cursor. The cursor shows where the next char- acter will be written if and when it comes. This may be very helpful when you're busy typing something in, but in our case the cursor is irri- tating. Fortunately, we can do something about this with the Cursor Off command, which is ini- tially commented out in the code. If you delete the comment character, recompile the program and download it to the microcontroller, you will Liquid Crystal Displays Liquid crystal displays (LCDs) are very popular because they are easy to read and don't need much power. They can be operated without a backlight, although the backlight on the Elektor shield is always on. This still results in much less power consumption than an LED display with the same number of characters. The reason LCDs are so energy efficient is that they do not have to generate light. Instead, they control whether ambient light is transmitted or blocked. The liquid crystal material, which is located between two sheets of glass, rotates the polarization plane of the incident light depending on the applied voltage. A polarization film is always located on one of the glass sheets. (Incidentally, if you have a defective LCD module you should sometime pull off this film, because you can use it to perform interesting experiments with light [2] [3] .) The display element of an LCD module is driven by square-wave voltages with no DC component, which are applied across the individual segments. There are dedicated CMOS ICs for this purpose, but some microcontrollers can also drive LCDs directly. However, standard LCD modules have special built- in controllers that handle the actual drive tasks. The great-grandfather of all LCD controllers was the HD44780. Even today, most controllers are HD44780 compatible. This involves several standardized control commands as well as the connections to the display module. There are usually 14 lines, and in some cases two more for the backlight. The display on the Elektor shield need only 14 lines because the backlight is hardwired. About the individual lines: GND and Vcc are obviously ground and +5 V. Vee is connected to a contrast trimpot. With many LCD modules the optimal setting is approximately 4.5 V between Vee and Vcc. It is therefore often sufficient to connect a fixed resistor with a value of 470 ft to 1 kft between Vee and ground, which saves the cost of a trimpot. RS is an input that allows the display be set to receive either data commands (RS = 1) or control commands (RS = 0). Data is necessary to display text, while control commands are necessary for initialization and positioning the cursor. R/W switches between reading and writing. Reading is actually only necessary to determine whether the display is ready to receive the next data. This can also be ensured by a short wait time, so the read direction is often not used and R/W is tied to ground. E is the Enable input. It is used to indicate to the display controller that valid data is present on the data bus (lines DO to D7) and should be read in by the controller. The controller always reads in the current data after a falling edge. In 8-bit mode all eight data bits are put on the bus and then a falling edge is generated on the E input. In 4-bit mode this process occurs twice, with only the upper four data lines (D4 to D7) being used for data transfer. The lower nibble (least significant bits) is sent first, followed by the upper nibble. The display must be initialized to operate in either 4-bit mode or 8-bit mode before it is used. 60 July & August 2014 www.elektor-magazine.com Microcontroller Bootcamp see that the cursor has vanished. This is a good place to remind you how easy it is to display more information by using the Bascom help function. Simply move the cursor (here we mean the one on your PC monitor) to the key- word concerned and press the FI key, and you're already a lot wiser. For instance, you can learn how to make the cursor blink. A two-channel voltmeter Happen to need a two-channel voltmeter? List- ing 2 shows one of many possible solutions. In the previous instalment we told you how to convert the data provided by the A/D converter into a voltage reading. Now let's see how you can show it on the display. First we write a string at the start of each line that identifies the input. The is followed by a space character to separate it from the reading. We also tack on a couple of spaces after the reading (in this case a real num- ber) has been output. Without them, the follow- ing situation could occur: Your last reading was 4.859 V, and the new reading is 5.0 V. Bascom outputs "5.0" just as it should, but the rest of the previous output is still there on the display, so you see "5.059 V" and wonder what's going on. To prevent this from happening, we always delete anything that might be present after the current output. Here we accept the risk that this may involve characters intended for a larger dis- play that are not visible on the actual display. Incidentally, this program uses the ADCO and ADC3 channels for its measurements. You can connect a signal source to ADCO, preferably with a protective series resistor as shown in Figure 2. There's already something connected to ADC3: the potentiometer on the Elektor shield. You can adjust it to provide a voltage from 0 to 5 V. All of the Arduino pins are also fed out to socket headers on the shield. If you connect a hefty electrolytic capacitor (you surely have an elec- trolytic somewhere on your bench - but don't exceed 470 pF) between the GND and ADC3 pins, which puts it in parallel with the potentiometer, you have a low-pass filter and you can see on the display how the voltage gradually adjusts after you change the potentiometer setting. The rea- son for the 470 pF limit is that you might allow the capacitor to charge slowly to 5 V and then quickly turn the potentiometer towards zero. If the capacitor is too large, the resulting discharge current could fry the potentiometer. Measuring brightness Now let's edit the program so that the ADC2 channel is displayed instead of ADCO (see List- ing 3). On the shield board, LED1 is connected to this channel through a jumper and a 1 kft series resistor, since this port pin can also be configured as an output. However, in this case we leave it in the high-impedance state. Now you can see Listing 2: Displaying voltages. i 1 UN0_LCD2 . BAS Voltage A0, A3 f $regfile = "m328pdef.dat" ' ATmega328p $crystal = 16000000 '16 MHz $baud = 9600 Dim D As Word Dim U As Single Config Adc = Single , Prescaler = 64 , Reference = Avcc '5 V Config Lcdpin = Pin , Db4 = Portd.4 , Db5 = Portd.5 , Db6 = Portd.6 , Db7 = Portd.7 , E = Portd.3 , Rs = Portd.2 Config Led = 16 * 2 Cls Cursor Off Do Locate 1 , 1 Led "AO " D = Getadc(l) 'AO U = D * 5.0 U = U / 1023 Led U Led " Locate 2,1 ' Pot Led "A3 " D = Getadc(3) U = D * 5.0 U = U / 1023 Led U Led " Waitms 1000 Loop www.elektor-magazine.com | July & August 2014 61 •Projects Figure 2. Using the analog inputs. that a perfectly ordinary LED can also act as a photodiode - in this case as a light sensor. If you shine a bright light on the LED, it can deliver a voltage as high as 1.5 V— three times as much as a silicon photodiode. That's because a larger band gap means a greater voltage, which applies equally well to the forward voltage of a diode and voltage it generates. Another thing you might notice is that at low light levels the voltage measured on ADC2 is affected Listing 3: Measuring the LED voltage and the potentiometer voltage. Do Locate 1 , 1 Led "A2 " D = Getadc (2) ' LED1 U = D * 5.0 U = U / 1023 Led U Led " Locate 2 , 1 Led "A3 " D = Getadc(3) 'Pot U = D * 5.0 U = U / 1023 Led U Led " Wai tms 1000 Loop to a certain extent by the potentiometer voltage on ADC3. This is due to the sample-and-hold capacitor at the input of the A/D converter. This capacitor is first charged to the voltage present on the measurement input, and then its charge is measured. If the capacitor last saw 3 V from the potentiometer during the previous measure- ment, some of its charge will still be left because it cannot discharge quickly enough through the extremely high impedance of the LED. For this reason, the microcontroller data sheet recom- mends that the internal resistance of the signal source should not exceed 10 kft. Here we are dealing with many megohms instead, so it's bet- ter to set the potentiometer to zero. Then you will see that there is still a measurable voltage at low light levels. This circuit shows that the A/D converter has very high input impedance. A typical digital voltmeter with an input impedance of 10 Mft would not be able to measure the LED voltage, but the ATmega can do so. With very high impedance signal sources, you can connect a 10 nF bypass capacitor in parallel as shown in Figure 3. This makes the measure- ments much more reliable. Even with very dim light, you can now measure a voltage of roughly 1 V. For all PN junctions with their exponential characteristic curves, the rule of thumb is that the voltage rises by approximately 70 mV when the current is increased by a factor of 10. This means that the span between 1.0 V and 1.5 V cor- responds to seven decades of current range, and thus seven decades of brightness. That should be more than enough for measuring from 10 lux to 100,000 lux, and we can see the makings of a light meter here. Maybe that's an attractive job for an enthusiastic reader? There's nothing wrong with a nice collection of Bascom programs with contributions from many people. PWM outputs When precise timing matters, timers come to the fore. Most microcontrollers have several timers. Timerl of the ATmega328 has a resolution of 16 bits. You can regarded it as a sixteen-stage counter, similar to the well-known CD4040 (which has only twelve stages). A clock signal (or other pulse signal) entering at one end comes out at the other end with a lower frequency. You can use the CD4040 to build a clock generator or a frequency divider, or as the basis for a binary pulse counter. Timerl can also handle all of these 62 July & August 2014 www.elektor-magazine.com Microcontroller Bootcamp functions; you just have to initialize it properly. There are also two 8-bit tinners on board (TimerO and Timer2). One of the many operating modes of Timerl is PWM mode. It can generate two pulse width mod- ulated signals, which means rectangular pulse signals with adjustable mark/space (on/off) ratio. Among other things, they can be used to con- trol the brightness of a lamp, much in the same way as a dimmer on the AC line which simply switches the voltage on and off at a high rate. Here we want to do the same thing by using the PWM output to control the brightness of an LED. The PWM output has a maximum adjustment range of 10 bits, but it can also be configured in 8-bit mode. Here 10 bits is an attractive choice because it matches the resolution of the A/D con- verter. In both cases the counter runs from 0 to Figure 3. Using an LED as a light sensor. Listing 4: PWM control. i Porte. 0 = 1 ' Pullup ' UN0_LCD3 . BAS PWM Porte. 1 = 1 ' Pullup i Config Portb = Output $regfile = "m328pdef.dat" Cls ' ATmega328p Cursor Off $crystal = 16000000 '16 MHz Do $baud = 9600 Locate 1 , 1 SI Alias Pinc.O Led "PWMA=" A = Getadc(3) Pwmla = A S2 Alias Pinc.l Led A Dim D As Word Dim U As Single Led " If SI = 0 Then Config Adc = Single , Prescaler = 64 , If B > 0 Then B - B - 1 End If Reference = Avcc '5 V If S2 = 0 Then Config Timerl = Pwm , Prescale = 1 , If B < 1023 Then B = B + 1 End If Pwm = 10 , Pwmlb = B Compare A Pwm = Clear Up , Compare B Pwm = Clear Up Locate 2 , 1 Config Lcdpin = Pin , Db4 = Portd.4 , Led " PWMB=" Led B Db5 = Portd.5 , Db6 = Portd.6 , Db7 = Led " Portd.7 , E = Portd.3 , Rs = Portd.2 Waitms 100 Config Led = 16 * 2 Loop www.elektor-magazine.com | July & August 2014 63 •Projects Figure 4. A pair of LEDs connected to the PWM outputs. PWMA PWMB 1023. You could for example program the out- put to switch off when the counter reaches 511, which results in a PWM signal with a 50% duty factor. This is achieved by repeatedly comparing the counter value with the programmed value in a compare unit. There are two compare units in the microcontroller, so you can generate two independent PWM signals with the same timer. PWM1A is output on port pin PB1, while PWM1B is output on pin PB2. That reminds us of some- thing. You guessed it: LED 2 is connected to PB2 through a 1 kft series resistor. Coincidence? Not at all, because now you can use the PWM signal to control the brightness of the LED. The program in Listing 4 uses the PWM1A out- put together with the A/D converter input ADC3, which is connected to the potentiometer. The measured value of the potentiometer setting is used as the comparison value for the PWM sig- nal. If you set the potentiometer to mid-range, the PWM output is a symmetrical square wave. Everything from 0 to 1023 is possible. The actual output value is shown on the LCD. If you want to look at the signal, you can connect a scope probe to PB1 (Arduino pin 9). What is the frequency of the PWM signal? That depends on the frequency of the clock input to the timer. It can be the clock signal from the Arduino board (16 MHz), but it can also be a lower-fre- quency signal derived from the clock signal by passing it through a prescaler. Here the initializa- tion instruction Prescale = 1 means that the full clock frequency is used. You might think that this yields a PWM frequency of 15.625 kHz (16 MHz divided by 1024), but in fact it is only half of this (approximately 7.8 kHz). This come from the fact that Bascom uses the "Phase Correct PWM" mode instead of the "Fast PWM" mode. You can learn more about this from the microcontroller data sheet, but that's more like a book than a data sheet. Here Bascom saves developers time and effort by always choosing a reasonable option for each setting. This means you can obtain work- ing results with Bascom even if you don't fully understand all the details. LED 2 is connected to the second PWM output (PB2). In our program this output is controlled by the two pushbuttons SI and S2. To make the program easy to read, the Alias instruc- tion is used to assign the button names to the port inputs. This means that when you write If Si = 0 Then in your code, Bascom knows that what you actually mean is If Pinc.l = 0, so the state of port pin PCI has to be polled. Another important consideration is that the buttons are connected to ground and therefore require pullup resistors. As a result, the program normally sees the quiescent state SI = 1. This only changes to SI = 0 when someone presses the button. That makes things very simple. When you press SI you reduce the PWM output level (assuming it is greater than 0), and when you press S2 you raise the PWM output level (assuming it is less than 1023). This proceeds in single steps if you press the button briefly, but if you press and hold the button it changes continuously at ten steps per second. The current output value is always shown on the LCD. Button polling The program shows a very simple example of how to use buttons and corresponding program branching. Of course, there are lots of other ways to obtain the desired result. Developing the ideal user interface for a given task is a fascinating job. You can configure a wide variety of things with two buttons and a potentiometer. A lot can be achieved with just a few buttons. The program uses everything that the Elektor shield has to offer. The LCD shows the two cur- rent PWM values, the potentiometer controls the PWMA output, and the two buttons control the PWMB output and thereby LED 2. Is that really everything? Well, not quite— LED 1 isn't doing 64 j July & August 2014 www.elektor-magazine.com Microcontroller Bootcamp anything. So let's plug a wire into PB1 (Arduino pin 9) and ADC2 (Arduino A2) to connect PWMA to LED 1 through a 1 kQ resistor and a jumper (Figure 4). Now you can control the brightness of the LED with the potentiometer. With two LEDs whose brightness can be set independently, you have the makings of a little skill-testing game. The first player sets the bright- ness of LED 2 to some arbitrary value using the buttons. Then this LED is covered, and the sec- ond player tries to set LED 1 to the same bright- ness using the potentiometer. The LCD reveals how well this went. Then the two players swap roles. All differences between the two values are recorded. The player with the lowest score at the end is the winner and is designated "Hawkeye". ( 140064 - 1 ) Web Links [1] www.elektor-magazine.com/140064 [2] http://b-kainka.de/bastel49.htm (in German) [3] http://en.wikipedia.org/wiki/Polarizer MCS Boot Loader Up to now we have described two options for programming the Arduino: using the Arduino boot loader or using the ISP interface, which is also brought out on the Elektor shield. With an external programmer, you can also use the ISP interface to load a different boot loader. Bascom has the MCS boot loader, which can be adapted to various microcontrollers. That's attractive because it allows you to equip different microcontroller boards with the same boot loader. The source code is included with the Bascom example programs. All that is necessary for adaptation is to configure the microcontroller type, the clock frequency and the desired baud rate. The configuration for the ATmega328P was not yet there, but the adaptation was easy. The fully adapted boot loader, including the source code and hex file, can be downloaded from the Elektor website [1]. The files are called BootLoaderUno_16.bas (16 stands for 16 MHz) and BootLoaderUno_16. hex. Note that the fuse settings must be slightly different (see the first AVR Studio screenshot) than for the Arduino boot loader because more memory space is needed. The boot area is 1024 words with the MSC boot loader and starts at &H3C00. If you intend to use the BASfOM-AVR Option? £orrf4er Communication Environment Simulator Programmer Monitor PrWet Proqtammer Ploy suutnj MCS Etuulludifci Fr as* warning PI Auto Flash PH AunVenfa PI I Iplnari fmle arirl Data Program after connote O Set locus to termhal ermiator alter programming Serial MCS LuaiJet Buutao: |H£4 (*£] V Close programmer modem when ready Ask to tend ttP it it emote Defeat ✓ ok X CdriLcI Reset NONE 6 UIH © RTS Snft MSC boot loader, you must configure Bascom accordingly. Here again it is important to set the right COM port and the right baud rate, in this case 19,200 (see the second screenshot). There is another important setting on the MCS Loader tab. As you may recall, data is transmitted to the Arduino board over the USB bus, but it arrives through a simulated RS232 port. All Arduino systems use the RS232 DTR line as a Reset line; a falling edge on this line triggers a reset. That's what starts the boot loader, because the microcontroller runs the program code stored at the boot address (&H3C00) when it starts up. This code waits for a specific action from the PC. Either new program comes down the pipe or it doesn't, and then execution branches to the start of program memory at address zero. This process occurs with every reset, which is what allows Bascom to force a jump to the boot loader by changing the level on the DTR line. Users have it easy because they don't have to press the reset button themselves. www.elektor-magazine.com | July & August 2014 65 •Projects My First Shield :-) LEDs, buttons, display and more In the microcontroller world as elsewhere, learning by doing is a good approach. The Arduino Uno, which features especially low cost and a low entry threshold, has a significant shortcoming: almost no on-board peripherals. We have therefore developed a compact shield that gives starters a text display, LEDs and pushbuttons to provide a good basis for their first projects. There are also two extension connectors for users who already have a bit of experience. They can be used to connect relay modules, wireless modules and many other devices. By Jens Nickel (Elektor Germany) Like it or not, very low-cost, mass-produced microcontroller boards have changed the electron- ics landscape. If you want to or have to develop a working project or demo that does not need very much computing power, you can simply grab an Arduino Uno - and there's bound to be one lying around somewhere, just waiting to be used. Beginners in particular benefit from the free Arduino development environment, and all you need to download programs is a USB cable. If you prefer to program in Basic, you can also work with Bascom and the boot loader. Complex programs in C or C++ are also possible with the free AVR Studio environment and a small pro- grammer, such as the AVR ISP mk2. Intelligent shields There aren't many peripheral devices on the Arduino Uno; a single LED is all you get from the board designers. You can also use the USB interface to access the microcontroller on the Uno board (an Atmel ATmega328P) over its UART port. However, most of the microcontroller pins are fed out to two rows of socket headers which provide the basis for the shield concept. If you equip another PCB with a matching set of pin headers, you can plug it directly into the micro- controller board. A shield can hold a wide variety of peripheral devices, including displays, sensors, or interfaces such as Bluetooth or WLAN. Thanks to the widespread use of the small Arduino Uno board, there are now hundreds of commercially available shields. Getting started Many of our readers are interested in learning how to work with microcontrollers and program in Bascom and/or C. For them, the Arduino Uno is a natural choice. To become truly familiar with programming a microcontroller, you need to come to grips with the key interfaces of the IC yourself at least once. The best way to do this, of course, is to work with peripheral devices that use these interfaces. Unfortunately, there is hardly any shield available that provides all the necessary peripherals in a small, low-cost package, so we 66 July & August 2014 www.elektor-magazine.com Arduino Extension Shield decided to develop our own shield. It contains a display module, two user LEDs, two pushbuttons and a potentiometer (Figure 1). That means you can get started right away after you plug in the shield. For larger projects the shield also has a pair of connectors which allow other extension boards to be connected over ribbon cables. A relay board and a wireless module are already available, for example. The shield can be ordered from the Elektor Store [1] as item no. 140009-91. if you are a nov- ice programmer and you want to try out or use this small board primarily for demo and exam- ple applications, you actually don't need to read any further in this article. Elsewhere in this issue we describe some initial small applications for our shield, written in Bascom Basic. They are also excellent for test purposes. For the C users (including would-be users) among our readers, we promise that C software will be coming soon, since we plan to use shield fairly often in future Elektor projects. Figure 1. The shield is shown here on an Arduino Uno board, but it can also be used with other 5-V Arduino boards. (see the "Voltages" inset). On our shield we con- nected a power indicator LED to the 3.3 V pin, so that you can see whether the Arduino board is powered up when the shield is plugged in. There are also two user LEDs on the shield, which can be driven by Arduino pins IO10 and AD2. Socket headers The socket headers of the Arduino Uno are dupli- cated on the shield. There is an Arduino standard for the signals available on these headers, which must be adhered to regardless of the microcon- troller fitted on the Arduino board concerned. The individual sockets are also called "Arduino pins". The Arduino pins and the corresponding pins of the ATmega328 microcontroller are listed in Table 1. Due to the display and the buttons, it is not possible to plug another shield piggy-back onto the Elektor shield. However, all of the Arduino pins remain accessible when the Elektor shield is plugged in, and in most cases their operation is not affected by the connected shield, as you can see from the circuit diagram in Figure 2. Among other things, this applies to the analog inputs ADO and ADI, the serial interface pins RX and TX, and the digital 10 pins 108 and 109. Additional I/O pins can be freed up by pulling the jumpers (JP1 and JP2) and unplugging the display module. LEDs, buttons and potentiometer Two supply voltages are always generated on Arduino boards: 5 V and 3.3 V. They are available on a socket header and can be used by shields Table 1. Arduino pins, microcontroller pins and shield functions Arduino Pin ATmega328 Function SCL PC5 EEC-SCL (*) SDA PC4 EEC-SDA (*) I013/SCK PB5 ISP-SCK I012/MIS0 PB4 ISP-MISO I011/PWM/M0SI PB3 ISP-MOSI IOIO/PWM PB2 LED2 I09/PWM PB1 ECC-GPIOB 108 PBO ECC-GPIOA 107 PD7 LCD-D7 106 PD6 LCD-D6 105 PD5 LCD-D5 104 PD4 LCD-D4 103 PD3 LCD-E 102 PD2 LCD-RS I01/TX PD1 ECC-TX IOO/RX PDO ECC-RX ADO PCO SI ADI PCI S2 AD2 PC2 LED1 AD3 PC3 PI AD4 PC4 EEC-SDA AD5 PC5 EEC-SCL (*) Connected to AD4 and AD5 on the Arduino Uno www.elektor-magazine.com | July & August 2014 67 •Projects I 1 Figure 2. Circuit diagram of the shield. The Arduino signal lines are also available on socket headers on the shield. Figure 3. A wide variety of extension modules can be connected to the two extension connectors. 433-MHz RS485 WIFI (PLANNED) m BLUETOOTH (PLANNED) EXPANDER ARDUINO ADC GNUBLIN T-SENSOR (PLANNED) 140009-12 AD2 is actually intended to be used as an ana- log input, but on the Arduino Uno board it is connected to the microcontroller port pin PC2, which can easily be configured in software as a digital output. LED1 is connected to AD2 and can also be used as a photosensor, as described in the Microcontroller BootCamp article in this issue. According to the Arduino standard, pin IOIO must be able to output a PWM signal. This gives us the option of using LED2 to visualize the duty factor of that signal. Two pushbuttons and a potentiometer are avail- able for user input. They are connected to the ADO, ADI and AD3 inputs. To allow ADO and ADI to still be used as analog inputs, we omitted pull-up resistors and debounce circuitry. However, it's very easy to connect internal pull-up resis- tors in the ATmega328, both in C and in Bascom. The potentiometer is connected to analog input AD3. If you configure the A/D converter of the ATmega328 with a 5 V reference voltage, which is common practice, the setting range is 1 to 1023 (10 bits). Display The alphanumeric display module from Electronic Assembly [2] is removable. It provides two rows of eight characters, which is sufficient for simple indications. Two buttons are located next to the display to enable simple menu control. We chose a display module with a 4-bit parallel interface, which means that four lines in addition to the E and RS signal lines must be routed to the display. This is a slight disadvantage compared to an SPI interface, but software support for the parallel interface is better. For instance, Bascom provides specific instructions for writing character strings to the display. The display controller is of course HD44780 com- patible, which allows popular C libraries to be used. The address offset for the second line is 40 hex [3]. UART connector K1 is a fully wired Embedded Communication Connector (ECC), which has been described in detail in a previous article [4]. In accordance with the specification, the UART signals TX and RX as well as two digital I/O lines are available here, with a logic high level of 5 V. There is also 5 V constantly available on one pin for powering connected peripheral devices. In this case the 68 July & August 2014 www.elektor-magazine.com Arduino Extension Shield Component List Resistors R1,R2,R3,R4,R5 = lkfi R6,R7 = 100ft R8,R9 = 330ft PI = lOkft trimpot with adjuster P2 = lOkft trimpot, SMD, Vishay TS53YJ103MR10 Semiconductors LED1,LED2 = LED, low-current, red (SMD 0805) LED3 = LED, low-current, green (SMD 0805) Miscellaneous S1,S2 = pushbutton K1 = 10-pin boxheader, 0.1" pitch K2 = 14-pin boxheader, 0.1" pitch K3,K4,K5,K6 = Arduino Shield stacking header, Adafruit ID 85 K7 = 6-pin (2x3) pinheader, 0.1" pitch JP1,JP2 = 2-pin pinheader with jumper, 0.1" pitch LCD1 = LCD 2x8 characters with back- ground lighting, Electronic Assembly DIPS082-HNLED 2 pcs. 7-way precision socket strip for LCD1, TE Connectivity 1814655-7 PCB # 140009-1 [1] or Assembled board # 140009-91 [1] peripheral device is a small module that gives user projects access to various interfaces to the outside world (see Figure 3). An RS485 module [4] and a wireless communication module have already been developed in the Elektor labs. The latter allows the Arduino board to transmit and receive data wirelessly at an ISM frequency like 433 MHz [5]. Advertisement LCR + Stability Use the Cleverscope FRA panel to easily auto plot Gain/Phase, Impedance, Capacitance or Inductance vs Frequency. Display the Gain and Phase Margin. Check for instability. Easy As, with Cleverscope. Measurement See our FRA tutorial video to show you how to verify your operating power supply or amplifier design. Check the impedance of your DC buses. Verify magnetics you have wound. 80 dB dynamic range! 0 - 65 MHz isolated Sig Gen. (u | ;n [lEwa *1 A I itfLrtl taut d i ■ 1-W Oh- '‘ire: JfeUfiX Streaming 100 G samples to disk ♦ ♦ Protocol Analysis • Symbolic Math • Matlab Interface • 80 dB dynamic range *100 MHz Bandwidth • Tracking Zoom • 0-65MHz isolated sig gen • Video Tutorials CS328A-FRA 1 4 Bit MSO www.cleverscope.com o ~o 6 ) Figure 2. VI Front Panel with frequency and amplitude readouts. www.elektor-magazine.com | July & August 2014 | 75 DESIGNSPARK PCB optical t her min firwl.vi (Mock Km ‘fc'x n» eat Prcjtc* oprm too* w*noo» * ♦ t. - » is then fed to the Graph module as well as the Frequency Meter which is connected to the VI Front Panel. Figure 3. VI Back Panel showing signal scaling block. Figure 4. Component layout of the extremely simple board to hook up to the myDAQ unit. ILL receive voltage signals varied by LDR1 and LDR2. In the VI Back Panel, DAQ Assistant 2 is used to introduce these two LDR-var- ied voltage signal into the VI. The ana- log signals vary between 0 to 5V. The tone is generated by the predefined MyDAQ library. One of the analog inputs is used to manipulate the frequency of the tone to ^ be generated. The maximum tone frequency that can be generated by myDAQ is 20 KHz and hence to scale the analog input value up to 20 kHz the signal value is multiplied by 4000. This signal BM Component List Resistors R1,R2 = lOkft P1,P2 = lOkft preset Capacitors 01,03 = InF C2, 04 = lOOnF C5, C6 = lOOpF 25V radial Semiconductors IC1 = LM358N Miscellaneous K1 = 2-way terminal block header, right angled, 3.81mm pitch K2,K3 = 2-way PCB terminal block PCB # 130550 As the tone generator's maximum signal strength is 2 V pp the analog input signal is matched and multiplied by 0.4. This signal is then fed to the Graph module and the bar meter which is con- nected to VI Front Panel. The VI signal scaling block is shown in Figure 3. Start Theremin-in' Assuming you have successfully built the board shown in Figure 4, and downloaded the project software from the Elektor Magazine website [5], you proceed as follows: • connect the Elektor Optical Theremin add-on board to myDAQ; • connect the speaker or Elektor Optical Ther- emin Play Box to myDAQ; • connect the myDAQ unit to your PC via the USB data cable; • run the VI file from the software folder; 76 | July & August 2014 | www.elektor-magazine.com CD E CD m CD > ~TD ut loot) yyndow Help gOM Quote PCB Quote IQI3U0 $iltf ©.l&llif J * _ □ - S * IV om ,§j DSP12_LargeProjects2.prj [Del Schematic Design: Design 1 ; x * J D A a 3 □ 0 3V3 S-U . . . . I SD2360 DA 1 AS lfc ' DATA* 1* ' DAT A3 L2 ' DAT A2 l 'DATA! i 'DAIAH 4- f ■ * 0PIQ5/XCLk! VDD CPI04/RDX/eSYB VCC-PWM 0OU13/X.NTB. VC.C_PWM 0PIQ2/HI30. GH1U1 /BULK 0PIQ9/M0SI . SHKK SPKN vae.puN SSR NC VS.5-.PW 11 V5J3 Ah<; 25101.17 70061.05 thou An open bus doesn't keep track of connections— it's just a line in the schematic. Open bus net connectivity is specified using the net names that automatically appear when you connect it. Figure 2 shows an example of an open bus. When I drew the connections from the resistors to the bus, DesignSpark automatically put the small 45-degree angle at the end of the connection and displayed the net name. If you delete the bus, all of the resistor connections will be deleted as well. You can change the net name by right clicking on the net and selecting "Change Net". A closed bus is more intelligent because it acts like a container for all of the bus nets and only those nets are allowed to connect to it. You change an open bus (the default) to a closed bus by right clicking on it and opening its properties window. There you can click on the Add Net button to open the Add Net to Bus window shown in Figure 3. A list of all of the nets in the design will be presented (N0001 to N0004 in this case) that you can then choose to add to the bus. If you want to add a new group of net names that end in a number like an address bus you can use the New Nets option. For example, if you wanted a 16-bit address bus you could set the name to AO to A15 which are created when you click the "Add To List" button. Open vs. Closed Buses So which kind of bus should you use? It's a hard question to answer because 78 | July & August 2014 | www.elektor-magazine.com Tips & Tricks I think both types have their merits. I generally prefer to use closed buses for large buses like a data bus and open buses for short small buses like a SPI bus. But how DesignSpark treats them might also affect your decision. Closed buses can be copied and they will keep all of the net associations which can be useful for large buses. But be careful when copying between different schematic pages because the nets in a bus follow the same rules as regular schematic nets so make sure you name them something different than the default Nxxxx. Also, when you paste the bus DesignSpark will ask you if you want to merge the nets because it will detect that the net names already exist in the design. Normally you would let DesignSpark merge the nets together. Another advantage of closed buses in DesignSpark is that they can be probed using the new cross probe tool. When you probe a closed bus the cross probe tool will cycle through all of closed buses in the design that have the same nets associated with them. This is a great way to see where a bus is used in a design. Open buses can also be copied but when you paste them all you get is their shape. You can also probe an open bus too, except that you're limited to probing each net individually instead of the entire bus. Working with Buses When you add a bus to a schematic it draws a solid line that you can then make connections to. DesignSpark automatically creates a 45-degree bus connection point to the bus when you add bus connections and you can control the size of the connection point line by using the Bus Defaults window in the Settings menu. It's also possible to change the direction of the connection line by clicking on it and using the F key (flip command). One downside of buses is that it's very easy to miss a connection and make single node nets. DesignSpark doesn't have a schematic net check tool and the PCB design rule check (DRC) tool can't check for single node nets but it is possible to manually check your design. The easiest way to do this is to open the DesignSpark project file and run the "Generic Netlist" report from the Output -► Reports menu. It's important to do this from the project file because if you run it from a schematic page the report will only include the nets from that page. Figure 4 shows a report for a design with a closed bus with nets DO to D3 and an open bus with AO to A1 which are connected to several resistors R1 to R7. The report makes it easy to see that nets D2, D3 and A1 only have 1 connection. It's also easy to see that net DO has 3 connections which may also indicate an error depending on the design. Conclusion DesignSpark's open and closed buses are easy to add to schematics and each as their strong points. The DesignSpark online help has even more details about how it implements buses and how to use them. Next time we'll look at some of the more advanced DesignSpark PCB features. ( 140058 ) Figure 3. Add net to bus window. □ DSP12_LargeProjects2 - Notepad n x File Edit Format View Help Figure 4. Netlist report. www.elektor-magazine.com | July & August 2014 | 79 DESIGNSPARK PCB U Tunnel Diodes Weird Component #7 By Neil Gruending (Canada) I was looking for some inspiration around my lab this month and my Tektronix oscilloscopes caught my eye. I've always admired the older models and how they achieved such high per- formance with discrete components. One part that's always intrigued me was how Tektronix used tunnel diodes in some of their oscilloscope trigger circuits. They aren't common anymore but some new parts are still available if you look hard enough. maximize the tunnel effect. This means that the diode will start to conduct forward current with very little bias voltage. The forward current will increase and eventually peak (i\) and then reach a minimum (/ 2 ) as the bias voltage is increased like in Figure 2. This behavior gives the tunnel diode its negative resistance characteristic and lets it be used for an amplifier or oscillator. The peak current value is one the key characteristics when specifying them. Figure 1. Simplified tunnel diode bias circuit. Figure 2. Tunnel diode current characteristic. So why did Tektronix use tunnel diodes in oscil- loscope trigger circuits? Probably because tunnel diodes switch quickly and can also act as a flip flop. For example a Tektronix 465 oscilloscope uses a couple of tunnel diodes to create a trigger pulse for the oscilloscope logic circuitry. One diode is used to arm the trigger pulse and the other is used to fire it [1]. The diodes are necessary to allow the circuit to have defined operating states for the trigger logic. Figure 1 shows a tunnel diode in a simplified bias circuit. Tunnel diodes are made from a PN silicon junction with a very narrow depletion zone to Let's look Figure 1 again. The 10-mA diode is biased with 9.9 mA of current which is right at the peak diode current when trigger is high impen- dence. The diode is triggered into its minimum current state when trigger injects enough current into it to push it past the peak current. This triggering characteristic is also how you can test a tunnel diode. If you measure the resis- tance with a DMM and it reads a high value then the diode is defective. A low resistance reading means that it could be ok but to know for sure you need to verify that the diode will switch between its peak and minimum current values. In some critical circuits you may also have to verify that the values haven't drifted over time which is a common issue. If the values have changed, some circuit adjustment and calibration might be necessary. Tunnel diodes are pretty interesting devices that met a real need in the 1960s and were heralded as the next big semiconductor discovery after the transistor. They're pretty hard to find now unless you are repairing vintage electronics but if you're interested in learning more about tunnel diodes and their uses, check out some of the Tektronix oscilloscope enthusiast websites [2]. ( 140057 ) Web Links [1] http://wl40.com/mmm/tek-465-late.pdf [2] http://wl40.com/tekwiki/wiki/Tunnel_diodes 80 | July & August 2014 | www.elektor-magazine.com Elektor Labs It's Tag Time! Man has always wondered about the nature of time and how to measure it. Elektor.Labs too has its share of time-measuring projects. We tagged them all to save you time lookin' 'em up. ardjjino - e . battery ilji i ijuitar LED Linux LFcauti msmuu seismograph U5b whesHe By Clemens Valens (Elektor.Labs) The problem of measuring time was solved in 1967 when the General Conference on Weights and Measures (CGPM; the acronym is French derived) redefined the second as being equal to 9,192,631,770 oscillations of a photon emit- ted by the transition of an electron between the two hyperfine levels of the ground state exci- tation of the cesium-133 atom— please excuse me if I made a mistake in the reproduction of this definition. The CGPM could just as well have chosen 9 GHz or 10 GHz or another round value as the defini- tion of the second, but it did not. The definition of the CGPM was chosen to be as close as possible to the historic value of the second. However, the last word on the second has not yet been said. Indeed, in 2012, physicists David Wineland and Serge Haroche were awarded the Nobel Prize fortrapping individual ions, a feat that— experts say— is expected to change once again the defi- nition of the second. Clocks have always been a popular subject in Elektor, and at Elektor.Labs too several people have posted projects for measuring time. These projects can be subdivided into a few categories: Pretty Objects: in this category we find clocks that were built to look good. Here we find Nixie tube designs, the Propeller Clock and other cre- ative time display circuits. Precision Instruments: some people want to have a clock with millisecond accuracy or with long-term accuracy. These are the GPS- and radio-based (DCF77, France Inter; WWF; MSF) clocks but also the designs using real-time clock (RTC) chips. Programming Projects: in case you want to study how to program an FPGA or microcontrol- ler, or even a PC, you need a subject to grind your teeth on. Time is such a subject because it ranges from easy (counting seconds) to compli- cated (perpetual calendars). Add-on Modules: small projects that mostly show how to use an RTC chip allowing you to inte- grate it into another project that needs to know the time. So now that you know that all these projects are out there wait- ing for you, how do you find them? This is where tags come in. Of course you can do a site search, but you can also use the tag cloud at Elektor.Labs. Click on the link " more tags " to view them all. Then click a tag that interests you and get rewarded with a list of projects related to the tag. As an example, find all the clock projects at [1]. (140060) Web Link [1] www.elektor-labs.com/tags/time www.elektor-magazine.com July & August 2014 81 •Labs Arduino is a Tool By Clemens Valens Barring you just woke up from a 10-year long coma you will have heard about (Eiektor.Labs) Arduino. Everybody is talking about Arduino and all & sundry are developing programs ("sketches") and extension boards ("shields") for Arduino. We have filled scores of pages in Elektor about, or on using Arduino. Here is another one. With the tester ready all we had to do was power up everything, lean back and watch everything work just fine. This to me shows the real power of Arduino: an easy-to-use multi-purpose tool that can help you out in many prototyping and test situations. So, if you are still wondering what all this Arduino fuzz is about, try to remember this article the next time you can't figure out how to test your almost-completed-but-not-working yet super- duper ultra gadget. ( 140059 ) Web Link [1] www. elektor-labs. com/node/3380 This article however is slightly different because it is not about an Arduino project but about using Arduino as a tool. I use Arduino quite often because it is so easy to program and use. I sometimes even use it as a calculator because it is quicker to write an Arduino program (called a 'sketch') than a PC application. To give you an example, the other day at Elektor. Labs we had to test our prototype of the MIDI Channel Analyzer [1]. Hedwig our secretary had brought a nice keyboard with MIDI capabilities from home, but, for some reason, it wouldn't allow us to test the analyzer properly. We had run into the chicken-and-egg paradox where we needed a MIDI analyzer to figure out the MIDI behavior of this keyboard to test the MIDI analyzer. So we called Arduino to the rescue. It took me less than five minutes to write a sketch that sent a Note-On and Note-Off message every second on a different, incrementing, MIDI channel. Elektor. Labs veteran Ton Giesberts added a transistor to the Arduino board to make the serial port MIDI compatible (the Data signal has to be inverted) and connected it to the device-under-test (DUT). We could have done without the transistor if we had used a software serial port on the Arduino, but it would have meant more testing. 82 July & August 2014 www.elektor-magazine.com Connect with us! facebook.com/elektorim www.twitter.com/elektor Register for our FREE Elektor.POST newsletter to receive our weekly Summer Deals www.elektor.com/newsletter, || *lf you already receive Elektor.POST you don’t have to act. You’ll automatically receive our Summer Deals. V U 1 1 mi i PI 1 A ] * H ■ • •Projects 500-ppm LCR Meter: Feedback By Jean-Jacques Aubry (France) The interest Elektor readers have shown in the 500-ppm LCR Meter published in March, April, and May 2013 [1], with a follow-up in November of that same year, was a pleasant surprise, taken as encouragement by the whole team— it's an unmistakable sign when such an advanced project generates so much enthusiasm. This publication won the confidence of hundreds of you who have successfully built the instrument. Let's just remind everyone that the LCR Meter is still available in the form of an assembled, tested module [3]. We'll never be able to praise highly enough the benefits of the direct interaction in the Elektor forum [2] between the author of this project and his readers, whether they have built the circuit themselves or are still thinking about doing so. These fruitful, multilingual exchanges have been the occasion for the author to complete the infor- mation given in the article and to correct it where necessary, and even to improve his software. We can't recommend too highly reading these exchanges, especially in the Test & Measurement sub forum, all topics containing "LCR Meter" or similar in the title. The aim of this article is to bring together the key information from there. Port selection The port chosen in the Port/Select port... menu is saved in the preferences file (AU2011 X.Y.Z.ini). With the original version of the AU2011 soft- ware (version 2.1.2), once the port had been selected and was open, the Port/Select port... menu is disabled. If you choose the wrong port (which can hap- pen if several devices are connected to the same computer), the program opens the port OK but then won't be able to communicate with a device that is not the LCR meter— for a very good rea- son. But you are then not able to select another port. The only way to do so was to destroy this preferences file. A radical solution— but not ideal! 84 | July & August 2014 | www.elektor-magazine.com 500-ppm LCR Meter: Feedback As from version 3.0.0, the addition of a Port/ Close the port... menu lets you close the wrong port so as to select another. No connection to port COMx The rather unfriendly "No connection to port COMx" message can appear even though the connection is good and the port number is cor- rect, if a second instance of the AU2011 program is run without closing the first one! It is impos- sible to connect to a port that is already busy. Operation with USB supply A few people have had a problem with the LCR meter in 'stand-alone' mode, powered using a USB supply. The majority of these supplies have the D+ and D- lines either biased at a voltage of around 2-3 V, or else simply connected together. For the LCR Meter's FT232R IC (U19) to be able to enable the regulator U15, its SLEEP output must be at logic 1. This is not the case if these two lines are floating. In this (rare) case, they need to be connected together (to the power rail)— or change the type of power supply! Stand-alone and PC mode To use the LCR Meter in stand-alone mode but powered via a USB cable connected to a PC, don't forget to press and hold one of the display mod- ule keys before powering up using SW1. Other- wise the LCR meter starts up in PC mode; it will briefly display the message "Bootloader v2.1" and then nothing! ESR (Equivalent Series Resistance) The LCR meter measures the in-phase and quadrature components of the DUT, i.e. the series resistance Rs and the series reactance X s . The other parameters (Z, phi, R pf X p , Q, D, etc.) are then all deduced by calculation. In the case of a high-value capacitor (from a few tens to thousands of pF), the series resistance Rs does indeed correspond to its ESR— just so long as the measurement is carried out at a fre- quency very much lower than its resonant fre- quency (because the series inductance of such a capacitor is not negligible). For these very high values, the measurement needs to be made at 1 khlz or even 100/120 Hz. Inconsistency of the measurement in the extreme ranges A very few readers have told us about a strange, non-reproducible phenomenon when measuring high value resistances (50 M Q. and above) with a value practically doubled @ 10 kHz, or low value capacitors (like 100 pF) with severe instability of this value @ 100 Hz. This is caused by a slight instability in the U16 (LT1611) regulation loop, and depends solely on the particular specimen of LT1611 used. The normal signal at output 1 of U16 (frequency around 1.8 MHz) appears in Figure la. Fig- ure lb shows the same signal with the insta- bility present. When this occurs, the oscilloscope will show a high level of noise at U6 output (TP6), which interferes with the measurement. One solution is simply to replace the LT1611, in the hopes of coming across a less lively specimen! The real solution is to insert an RC network (39 kft / 1 pF) into the link between U16 pins 5 (V jn ) and 4 (SHDN) (Figure 2a) so that U16 performs a soft start. Figure 1. The spread in certain parameters of the LT1611 (gain of built-in error amplifier, temperature, etc.) can cause instability (lb) that interferes with the measurements. www.elektor-magazine.com | July & August 2014 85 •Projects It's easy to modify the board (Figure 2b) as follows: • cut the track between U16 pins 4 and 5, as well as the track between pin 4 and V jn ; • reconnect pin 5 to V jn/ at C67; Figure 2a. The most reliable solution is to delay the starting of LT1611 using an RC network (soft start). LI 3 4 — — +5VA <±>- X 2 1 CTX20-1-R R103 co C67 J^91 U16 VIN SW LT1611 SHDN NFB GND 4u7 1u C64 1u R81 X Figure 2b. The modification to the board to add the RC network in Figure 2a is only needed if you observe the noise seen in Figure lb. • solder a 39-kft resistor (0603 or 0805) between pin 4 and V jn ; • solder a 1-pF capacitor (0805) to pin 4 and connect its other terminal to the ground side of C67. Measuring RF inductors A few readers have been disappointed by the results when measuring inductors with values below 200 nH (SMD RF inductors). At the frequency of 10 kHz, an ideal 100 nH inductor has a reactance of 6.28 mQ. A real inductor also has a series resistance of sev- eral tens of milli-ohms. So the quality factor Q of this inductor is very much lower than 1 and the series resistance becomes the main parameter, the reactance being only the secondary param- eter with a much greater inaccuracy! What's more, using measuring cables, even short ones, does not allow you to perform an effective SHORT/TRIM; you only have to move one cable ever so slightly to see the measured value change by several (tens of) nanohenries. ( 140069 ) Web Links [1] 500 ppm LCR Meter Part 1, Elektor March 2013: www.elektor-magazine. com/110758 Part 2: Elektor April 2013, www.elektor-magazine. com/130022 Part 3: Elektor, Elektor May 2013, www.elektor-magazine. com/130093 Important Update: Elektor November 2013, www.elektor-magazine. com/130307 [2] Elektor Forum: http://forum. elektor.com/viewforum. php?f= 1543743 [3] Assembled LCR Meter module: www.elektor.com/500-ppm-lcr-meter-main-board LCR Meter modules in stand-alone version (with display): www.elektor.com/500-ppm-lcr-meter-kit-with-main-board-and-lcd-board 86 July & August 2014 | www.elektor-magazine.com Professional Quality Trusted Service Secure Ordering pee i - . Elektor PCB Service at a glance: O 4 Targeted pooling services and 1 non-pooling service o Free online PCB data verification service o Online price calculator available O No minimum order value o No film charges or start-up charges !“ - V i mCHtME, "••-' S'.'! Ji-W ‘ I *« "t f 4< M KWH * i Delivery from 2 workina days •Projects Stage Tc(nec Fast and accurate 4 H, r Guitars lr By Emile van de Logt (Netherlands) Although you can buy a professional stage tuner for your guitar, designing and building your own device is a lot more satisfying. At first I thought it would be fairly easy to determine the fundamental frequency of a guitar signal by using a fast Fourier transform (FFT), but in practice things turned to be a lot more difficult. This project uses a fast Cortex ARM M4 processor and a special frequency analysis algorithm based on autocorrelation. The final PCB differs from the prototype shown here in several places. For some time, the author of this article had been looking for a fast and accurate way to tune his guitars. Although there are 'stomp box' pedal devices for this purpose, the good ones are expensive and not always easy to read. After purchasing a professional guitar stage tuner, the author quickly started thinking about building his own. After all, he thought, determining the fun- damental frequency of a guitar note shouldn't be all that difficult, and displaying the deviation from the desired frequency with a few LEDs should be pretty straightforward. 88 July & August 2014 | www.elektor-magazine.com Guitar Tuner The ideal started to take on concrete form when the author received a TM4C123GXL Launchpad Evaluation Board (Figure 1) from a colleague. It contains an ARM Cortex M4 microcontroller, which has DSP capabilities and a lot of I/O pins on board. That makes it a powerful board at a very reasonable price— just $13 from TI, plus shipping charges. Ideal for reading in a guitar signal and processing it. In this article we first have a look at the TM4C- 123GXL board to give you a good idea of what it can do. As with every design, the design approaches and design choices are important— in particular the approaches that lead to something that doesn't work, because they provide insight into what you should do to arrive at something that does work. That's why we want to briefly examine the first design using an FFT, before moving on to the ultimate implementation. TM4C123G Launchpad Evaluation Kit The manufacturer of this board, Texas Instru- ments, is known for their good documentation and support material that helps you get started quickly. The support resources for this board con- sist of a wiki with a workbook [2], presentations and even video clips. The integrated develop- ment environment (IDE) is Code Composer Studio (CCS), which truly includes everything you might want. All you have to do is follow the instruc- tions in the workbook, connect the TM4C123GXL board to your PC through a USB port, and start designing. Following the presentations is a real pleasure. They give clear explanations and are supported by videos and example projects. The board even comes with a complete application programming interface (API) called Tiva, which you can use to control all of the I/O pins. For a student, engineer or hobbyist, this is the ideal way to start working with this advanced family of microcontrollers. The evaluation board is populated with a TM4C- 123GH6PM ARM Cortex M4 microcontroller with a maximum clock frequency of 80 MHz, a floating point unit (FPU) with DSP capabili- ties, 256 KB flash memory, 32 KB SRAM, 2 KB EEPROM, eight UARTs, four versatile serial inter- faces, four I 2 C modules, CAN, USB, two 12-bit A/D-converters and a whole lot of I/O ports. In particular the 12-bit A/D converters, the gener- ous I/O and the DSP capabilities make this board very suitable for the objective of implementing a professional guitar tuner. First approach: fast Fourier transform (FFT) Rendered overconfident by the impressive specs of the evaluation board, the author started work- ing on an FFT implementation. A variety of ready- ARM" Cortex ™-M4F SO MHz JTAG MPU NVIC ETM 5WD/T FPU TM4C123X Series MCUs 256 KB Flash 32 KB SRAM RDM 2KB EEPROM Analog ldO vortage Regulator 3 Analog Comparators 2k 12-tjrt ADC Up to 24-channe! 1 MSFS Temp Sensor Serial Interfaces Motion Control System Figure 1. The TM4C123GXL board from Texas Instruments, which is fitted with an ARM Cortex M4 processor, (photo: TI) Figure 2. High-level block diagram of all functions and connections on the TM4C123G board, (illustration: TI) www.elektor-magazine.com | July & August 2014 89 •Projects How Yin works: autocorrelation and parabolic interpretation Instead of the fast Fourier transform, the Yin algorithm is based on another method that is often used in digital signal processing: autocorrelation (see http://en.wikipedia.org/wiki/Autocorrelation). An autocorrelation is the sum of the point-by-point multiplication of all samples of a signal with the samples of an offset version of the same signal. Suppose the input signal is white noise with sample values in the range of -1 to +1. When these values are multiplied by other sample values offset in time, the products will also lie in the range of -1 to +1. If all these products are added up (and assuming the number of values is sufficiently large), the sum will be close to zero because the individual values tend to cancel each other out. The situation is different with a non-random signal, such as a guitar signal. If the same operation is performed on a guitar signal, the resulting value will typically be greater than zero and will depend on the offset. The interesting point is that the maximum value is obtained precisely at the point where the offset signal is exactly aligned with the original signal, which means that it has been shifted by one period. The Yin algorithm utilizes this effect. The signal is shifted in increments of the sampling period (here 1/6000 second) and correlated with itself. Then the algorithm looks for the offset value that yields the largest correlation result. This is a measure for the most significant frequency in the signal. The Yin algorithm also applies several refinements to increase the accuracy, such as parabolic interpolation. Suppose the Yin algorithm finds that the autocorrelation is greatest with a signal that has been shifted by 16 samples. This corresponds to a signal of 6000/16 = 375 Hz. The next frequency that also yields this result is 6000/15 = 400 Hz (these frequencies always correspond to multiples of the sample period). The desired frequency therefore lies somewhere between these two values. The optimal frequency is found by parabolic interpolation between these two points, which dramatically improves the accuracy. made routines for this can be found. In the course of implementing these routines, the author soon ran into difficulties. Let's do some simple calcu- lations: The spectrum of guitar signals is roughly 2 kHz. According to Shannon [3], this means that you have to use a sampling frequency of at least 4 kHz. If you then want to implement an FFT with a resolution of 0.5 Hz, you need an 8192-point FFT. Although the TM4C123G should be fast enough to handle this, the necessary amount of memory would quickly approach the limit of 32 MB available on the board. With a bit of cutting and trying, it ultimately proved pos- sible to achieve a sampling rate of 1 kHz (for a usable spectrum 500 Hz) and fit a 2048-point FFT into the available memory. However, the rest of the software still had to be written. It was clear that this approach would not lead to the desired result. The second approach: autocorrelation and pitch detection While searching the literature for a suitable way to determine the frequency components of a sig- nal, the author quickly found a scientific article [4] describing how a autocorrelation function [5] could be used to accurately determine the funda- mental frequency of a signal. The authors of this article underpinned their method for determin- ing the fundamental frequency of a signal, which they called the Yin algorithm, with suitable math- ematics. That was exactly what we needed. For more details about this algorithm, see the inset. Based on this article, Joren Six wrote an C+ + library [6], which Ashok Fernandez converted into an excellent C library [7]. This is a nice example of how a scientific article can lead to a specific practical application. The C library (Yin.h and Yin.c) was imported into this project virtu- ally unchanged and worked immediately, which further testifies to the high quality of the library. Notes and frequencies In order to properly understand the design of the guitar tuner, you need some basic knowledge of musical notes, intervals and frequencies. The starting point for tuning musical instruments is often the A note with a frequency of 440 Hz. The other notes are called B, C, D, E, F and G. The intervals between these seven notes are either halftones or full tones. The interval between the B and C notes and between the E and F notes is a halftone. The interval between all other pairs of notes is a full tone. An octave consists of a series of twelve halftones. They are called C, C#, D, D#, E, F, F#, G, G#, A, A# and B, where the sharp sign (#) indicates a note that is a half tone higher than the note without the sharp. The B note of each octave is followed by the C note of the next octave. The octaves are num- bered in sequence. The A note with a frequency of 440 Hz is in octave 4, which is indicated by the notation "A4". A note that is an octave higher than another note with the same name has twice the frequency of the latter note. For example, 90 July & August 2014 | www.elektor-magazine.com Guitar Tuner the A5 note has a frequency of 880 Hz. The six strings of a guitar are tuned to E2, A2, D3, G3, B3 and E4. The low open E string (E2) has a frequency of 82.407 Hz, while the high open E string (E4) has a frequency of 329.628 Hz. The twelfth fret of the high E string (E5) yields a frequency of 659.255 Hz. If you finger the high E string at the 24th fret (E6 note), the resulting frequency is 1318.51 Hz. This determines the upper limit of the spectrum for the guitar tuner. At the other end of the spectrum, you have the bass guitar (with four strings), which is tuned an octave lower than a regular guitar: El, Al, D2, G2 (El is 41.203 Hz). A five-string bass guitar also has a B string (BO; frequency 30.868 Hz). This determines the lower limit of the spectrum for the guitar tuner. The frequencies of the notes within an octave do not increase linearly, but instead exponentially by a factor of 2 X . For example, if the A4 note is 440 Hz then the A#4 note is 440 x 2 1 / 12 = 440 x 1.059463 = 466.164 Hz. This forms the basis for the values in Table 1, which are represented directly in the C code. Key requirements for the guitar tuner Before we describe the actual design, let's sum- marize the key requirements for the guitar tuner: • Fast: Updated ten times a second. • Accurate: The error margin for determin- ing the fundamental frequency must be less than 5%. • Display: Indication of the note with the octave number and whether it is natural or About the author Emile van de Logt is employed at Rotterdam University of Applied Sciences as an Education Manager for the Electrical Engineering and Health Care Technology faculties. He studied Electrical Engineering at Eindhoven University of Applied Sciences, and Management Science at the Open University. Emile is an electronics enthusiast. He conducted the Embedded C Programming and FPGA/VHDL workshops for Elektor, builds tube amplifiers and guitar effect equipment, and is an amateur beer brewer with a completely automated brewing system for which he personally designed all the hardware and software. sharp. • Deviation: Indication of the relative devia- tion from -50% to +50% using 21 LEDs (5% per LED). • Light show: Animated display moving toward the central lamp when the note is in tune. • Flat tuning: It must be possible to set the tuner for flat tuning (all strings tuned one or more tones lower) from 0 to minus 6 so that the display can be read in the normal manner. • Range: The lowest string of a bass gui- tar (B0 with a five-string bass) up to and including the highest note on a regular gui- tar (E6) must be detectable. This makes the tuner usable for a wide variety of musical instruments. const float note fraqLMAJC NOTES] = { 20.602 , 21.827 32,70 3, 34-643, 36,708, 38,891, 41.203, 43.654 SB. 40 6,, 69 . 2 96 r 73.416, 77.7B2, 82 . 407 r 87 . 307 130,013.. 136.591, 145,332. 155.563, 164.314 r 174.614 261 . 62 S, 277.183, 293,665, 311.127, 329.626, 349.223 5.2 3 , 2 5-1 r 554.355, 587,330, 622.254, 659 . 255 , 698.456 1046.502, 1108.731, 1174,659, 1244.506, 1313.510, 1396.913 e*n s t CJlAS no [MAX_MGTE £ ] 1 4 ] = ( "E Q " r ” FD " r ,P F# D%"M" "Cl 1 ', "C#!" r "Dl" /'Dtl" /'El’ 1 r "FI r lr F#l" , ta GJL" "C2'% "CttS'V'DZ" , p "E2'' , "F2' - , ,p F# 2" r n G2" "CS'", " C#3" . "D3" , ''D#3" /'E3P P ,, F3 ,, P ,p F# 3" r "G3" h C4 ir ,, ^#4” , "D4" , 1, Dtf 4" , '‘Efl’ 1 , ”F4 111 , |r F#4 n r n G4 "■ ,r C5 , lr C# 5 U , "'D 5 "■ , 11 B# 5” , "E 5” , " F5 " , ,, F#5 n , " G5 ,r » C6 " , lf e# 6 11 r "D 6 " , T1 Dt 6" , "E 6 " , " F6 18 1 ; 23.125, 24.500, 25. 957 , 27.500, 29.135, 30.868 46,249, 48.999, 51. 913, 55.000, 58.270, 61.735 92. 499 , 97 . 999, 1D3.S2G, 110.000, 116 . 541, 123.471 184.997, 195.998, 207. 652, 220.000, 233.082, 246.942 369.994, 391.995, 415.305, 440.000, 466.164, 493.383 739.989, 783.991, 830. 609, 800.000, 932.328, 987.767 " G#0 " , " AO " r "AtO t " B0 " "Gitl 11 1 "Al” , ''Atfl” , pl Bl” " G#2 11 r " A2 " r " A# 2 ” , n B2 ” "G#3 " , "A3 " , "A#!” , ” B3' 1 "Gtt4 11 j. "A4 11 , "A# 4” j "B4’ 1 " G#5 11 , ,r A5 " , "A#5 ” j " B5 ” Table 1. www.elektor-magazine.com | July & August 2014 91 •Projects Figure 3. The complete circuit diagram does not contain a lot of components, since most of the functionality is located on the TM4C123GXL board. Design description The hardware of the guitar tuner (see Figure 3) and the software work closely together, which is why they are described as a unit here. By the way, it's helpful to download the software for this article [8] to help you follow the description. The design is basically structured as follows: • The guitar signal is applied to the input of a sixth-order low-pass filter with a corner fre- quency of 1700 Hz. This filter was designed using TI's WebBench Filter Designer tool. The manufacturer specified their own opamp for this (ADA4096), but a standard opamp such as the LM833 is perfectly ade- quate here. • The output of the low-pass filter is read in by -50 -45 -40 -35 -30 -25 -20 -15 -10 -5 0% +5 +10 +15 +20 +25 +30 +35 +40 +45 +50 0000000000*0000000000 CM50 CM05 COOO CP05 - - 3V3 VCC © © CON CP50 CP45 CP40 CP35 CP30 CP25 CP20 CP15 CP10 CP05 LDSH 6 12 CP50 3.05 11 CP45 3.04 10 CP40 3.03 9 CP35 1.10 8 CP30 1.02 7 CP25 1.07 6 CP20 1.09 5 CPI 5 1.08 4 CP10 1.04 3 CP05 1.03 2 LDSH 1.05 F 7S 3.06 2.05 2.03 SW1 a 1 FLAT TUNING / G_7S 3.07 ^DP_7S 3.08 ^PE3„AIN0 3.09 ^SW FT 1.06 1.01 3.01 3.3 V VBUS PD2 PD1 PDO PA7 PB5 PB4 PA6 PA5 PB1 PBO PE4 CONI PC7 PC6 PC5 PC4 PB6 PB3 PB2 PA4 PA3 PA2 PB7 CON 4.07 CM50 12 Ok 4.06 CM45 11 p 4.05 CM40 10 Pi 4.04 CM35 9 p 2.07 CM30 8 p 4.03 CM25 7 p 2.02 CM20 6 p 2.08 CM15 5 p 2.09 CM10 4 p 2.10 CM05 3 p 2.06 COOO 2 -o TM4C123GXL PD3 RST PEO PEI PE2 PE3 PE5 PD6 PD7 PFO PF1 PF2 PF3 PF4 GND GND 2.01 X 4.08 MPX1 7S 4.09 MPX2 7s' 2.04 V A_7S 3.10 B 7S ' 4.01 C 7S ' 4.02 D 7S ' 4.10 E 7S ' \ \ 3.02 DIS1 DIS2 CA CA 0 O' o 1 b c d e f i HDSP-H101 5 10 o 10 CA CA 0 O' O 1 b c d e f o 8 HDSP-A101 7 o X. C0N2 0 R1 R2 C2 II 3n3 R3 R4 -| 33k |T 22k 1M |-| 47k~|- R25 CP50 DBDB101G C0N4 CM50 CM45 CM40 CM35 CM30 CM25 CM20 CM15 CM10 CM05 COOO -"u IC3 VCC © lOOOu X 35 V C12 □ lOOOu 35 V 7805 ■> ♦ 0 ^* 7905 C13 □ lOu 35V i C14 □ © IC1 © lOu 35 V IC4 C7 lOOn "X C9 C8 lOOn CIO © IC2 © lOOn lOOn © -5 V IC1, IC2 = ADA4096-2 3V3 © T9 s \ \ O Uil ]R9 R13 | R17 J T1 R21 T3 T5 T7 z rCEKjO r l ~ ! ° r ^2 fS® r^KjD BC557 < o z h- <' BC547 CO r*» O X BC547 z BC547 BC547 o CD 3V3 © T10 Q LI- CLH o R11 R15 R19 R23 T2 T4 T6 T8 z ■OD^T) rOoC) r l ~ !;r KO rOD^T) BC557 < o, z CO h- 00 X BC547 CO I s - Q X BC547 z BC547 Q_ O X BC547 Lowpass Filter F c = 1700Hz C4 C6 3V3 (+) HI R5 1k2 390n R6 MjEJ HI R7 HI 33k JC 33k \ 39n R8 LLJ R47 °- C15 I 2u2 100 V I 330 p 30n 220p R48 140076 - 11 92 | July & August 2014 | www.elektor-magazine.com Guitar Tuner AINO (ADC input 0) of the microcontroller. • The ADC clock frequency is 125 kHz, and there is 16-fold hardware averaging. This means that each sample value is determined by taking the average of 16 input samples. The time needed for this is 128 ps. The set- tings for this are configured in the routine i ni t_ti merO_for_adc ( ) . • The Yin algorithm needs at least two com- plete cycles of the guitar signal in order to determine the fundamental frequency. With the lowest note (BO at 30.868 Hz), this cor- responds to approximately 65 milliseconds. The update rate is 10 Hz, or in other words every 100 milliseconds. This means that the Yin algorithm should be able to detect fre- quencies as low as 20 Hz (E0). • The sample rate FS is set to 6 kHz. This means that 600 samples are read in every 100 milliseconds. This takes place in the interrupt routine ADC0_SS3_IntHandler ( ) . The input samples are written to a ring buf- fer, which is a special type of buffer that can be written by one process and read by another process. • After 600 samples have been read in, a sign (variable sampled_new) is sent to the While loop in the main() routine. The While loop reads the 600 samples from the ring buffer and writes them to the input buffer for the Yin algorithm, when is then called. The Yin algo- rithm in turn determines the fundamental fre- quency (variable pi tch) of the guitar signal. • Next the routine fi nd_nearest_note ( ) is called. This routine determined which note in the previously mentioned table is closest to the measured value (variable nnote). It also determine the relative deviation in percent (variable cents). + 3V3 VBUS + 5V CP30 PB5 GND GND CP05 PBO PDO CP40 CP10 PB1 PD1 CP45 LED-sharp PE4 PD2 CP50 Flat-tuning PE5 PD3 CP25 PB4 PEI G_7seg CP15 PA5 PE2 DP_7seg CP20 PA6 PE3 AINO CP35 PA7 PFO B_7seg • Both variables are passed on to another interrupt routine, TimerllntHandler ( ) , which runs at 200 Hz. It outputs the name of the note and the octave number to the 7-segment displays, which are driven in mul- tiplex mode (this takes place in the routine display_note()). The relative deviation with respect to this note is also indicated by the 21 LEDs. This is handled by the routine di splay_cents ( ) . The larger the devia- tion, the more LEDs are lit. This function is provided by a state machine that also gen- erates the animated display when the string is in tune. The only thing left to describe is how the various I/O signals of the TM4C123G board are used. Vir- tually all connector pins on the board are used, and thanks to the large number of pins there is no need for supplementary hardware. The pin assignments are shown in Table 2, and in the actual code. The names shown in red in the table are the stan- dard names of the connector pins, while the other names describe their functions in the guitar tuner. • CP05 to CP50: connections for the 10 LEDs that indicate positive deviations. • CM05 to CM50: Connections for the 10 LEDs that indicate negative deviations. • C000: connection for the LED that lights up when the string is in tune. • Flat tuning: input for the pushbutton switch used to set the degree of flat tuning. When it is first pressed the current flat tuning set- ting is shown; each subsequent press lowers the flat tuning by one step, down to a limit of minus 6. After this the flat tuning setting C_7seg PF2 GND D_7seg PF3 PB2 CM20 CM25 PB3 PEO F_7seg CM35 PC4 PFO A_7seg CM40 PC5 RESET CM45 PC6 PB7 COOO CM50 PC7 PB6 CM30 mpxl_7seg PD6 PA4 CM15 mpx2_7seg PD7 PA3 CM10 E_7seg PF4 PA2 CM05 Table 2. www.elektor-magazine.com | July & August 2014 93 •Projects Figure 4. The PCB for the guitar tuner. The TM4C123GXL board is plugged onto the corresponding connectors on the rear of the PCB. returns to zero. Example: When flat tuning is set to -1, the E string is tuned to D#. How- ever, when this string is plucked the display shows "E". If flat tuning is set to 0 in this sit- uation, the display will show "D#". • LED-sharp: Connection for the LED that lights up when a halftone (#) is detected. • mpxl_7seg and mpx2_7 seg: Used to drive the 7-segment displays in multiplex mode. • The xx_7seg signals supply the drive levels for the 7-segment displays. Putting it all together You have a choice of two different ways to install the software: Extended: Download and install Code Composer Studio (CCS) version 6 and the Tivaware API [10]. This should not create any problems if you use the previously mentioned Getting Started work- book. Installation is described in detail in the first section. Then you can download the guitar tuner project from the Elektor website [8] and place it in the CCS workspace. This gives you the option of Component List Resistors (SMD1206) R1,R7,R8 = 33kO R2 = 22kO R3,R25 = 1MO R4 = 47 kO R5,R6 = 1.2kO R9,R11,R13,R15 / R17,R19,R21,R23 = 470 R10,R12,R14,R16,R18,R20,R22,R24,R47,R48 ,R49,R50 = lOkO Capacitors (C1-C10: SMD1206) Cl = 330pF C2 = 3.3nF C3 = 30nF (e.g. Mouser 581- 1206 1C303JAT2A) C4 = 390nF 16V C5 = 220pF 16V C6 = 39nF 50V C7,C8,C9,C10 = lOOnF C11,C12 = lOOOpF 35V radial (0.2" pitch; 0.5" diam.) C13,C14 = lOpF 35V radial (0.1" pitch, 0.2" diam.) C15 = 2.2pF 100V radial Semiconductors B1 = DB101 bridge rectifier T1-T8 = BC547 T9,T10 = BC557 IC1,IC2 = ADA4096-2 or LM833 dual opamp (SOIC-8) IC3 = 7805 IC4 = 7905 21 pcs. LED. high-efficiency, red, 3mm (for CP05-CP50, C000, CM05-CM50) 1 pc. LED, high-efficiency, red, 5mm (for LDSH) Miscellaneous TM4C123GXL evaluation board DIS1 = 7-segment-display, red, common anode, 0.56", 13 mcd@10 mA (e.g. Avago HDSP-H101) DIS2 = 7-segment-display, red, common anode, 0.3", 10 mcd@10 mA (e.g. Avago HDSP-A101) CON2 = 2-pin pinheader, 0.1" pitch CON4 = 3- pin pinheader, 0.1" pitch CON5,CON6 = 12-way PCB terminal block, 0.1 "pitch SW1 = pushbutton with make contact 2 pcs. 20-way (2x10) receptacles for evalua- tion board, 0.1"pitch 3 pcs. jack sockets, panel mount, 0.25" diam. PCB artwork, # 140076, download at [1] 94 | July & August 2014 | www.elektor-magazine.com Guitar Tuner modifying the code if you so wish and generating a new .bin file. Next, connect the TM4C123GXL board to the PC with a USB cable and click the Debug button. The new firmware will be loaded directly to the TM4C123GXL board. Minimal: This is intended for people who only want to program the TM4C123GXL board with the guitar tuner firmware and do not want to install the complete CCS development environ- ment. In this case, only install the LM Flash Pro- grammer software [11] and use it to upload the Guitar_Tuner_Yin.bin file from the Debug direc- tory for the project to the TM4C123GXL board. The procedure for this is also described in the Workbook file. You can order the TM4C123GXL board directly from the manufacturer, which is fast and the least expensive, or you can order it from a distributor such as Farnell. A small modification to be board is necessary before it can be used with the guitar tuner firmware. For compatibility with other TI boards, some port pins on the board are con- nected together. For instance, PB7 is connected to PD1 via resistor RIO (0 ft) and PB6 is connected to PDO by resistor R9 (0 ft). These two resistors are located just below the microcontroller the connections for all of the LEDs and the 7-seg- ment displays. Several SMD components are used, but they can be soldered relatively easily with a fine-tip soldering iron. Flowever, a hot-air soldering station is a better choice. Start by assembling the power supply compo- nents on the shield board. The transformer (not shown on the schematic) can be a 2x6 V or 2x9 V type, and it does not have to supply much power. After assembling the power supply, first check whether it provides regulated +5 V and -5 V voltages. Disconnect power to the board and then solder the rest of the components on the PCB. The 7-segment displays may be soldered directly to the PCB or fitted in sockets to raise them off the board. Mount the 2xl0-pin female headers on the rear of the shield board so that it can be plugged into the TM4C123GXL board. Wire the LEDs to connectors CON5 and CON6. There are 21 in total. The central LED connects to pin 2 of CON5 (C000), with the LEDs CP05 to CP50 (deviation +5% to +50%) to the right and the LEDs CM05 to CM50 (deviation -5% to -50%) to the left. There is also the Sharp LED for indicating half tones, which connects to pin 2 of CON6. LED between the cor- responding output on the connector and the ground pen (1) of the connector. After assembling the board, check the low-pass filter for correct operation by connecting a sine-wave Figure 5. The rear of the PCB with the TM4C123GXL board attached. This is also an early prototype with a number of changes made on the board. manufacturer's name, and they are labelled R9 and RIO. Using a sol- dering iron, carefully remove these two resistors. The PCB designed for the guitar tuner (Figure 4) is intended to be mounted on top of the TM4C- 123GXL board as a sort of 'shield'. The shield holds the low-pass filter, the power supply, and www.elektor-magazine.com | July & August 2014 95 •Projects Figure 6. Photo of the author's prototype, which he regularly uses on stage. signal (500 mV pp ) to CON2. The output signal from the filter can be seen at test point TP1 (LPF_OUT). The filter should allow signals up to 1700 Hz to pass through and block signals at higher frequencies. If the filter works properly, you can connect the TM4C123GXL board (evaluation board on the bot- tom, shield on top, USB connector facing Cll/ C12/IC3/IC4). Now check that the decimal point of the small display blinks once per second. Then press the Flat Tuning button and check whether 0, -1, -2, ..., -6 appear on the display. Set Flat Tuning back to 0, connect a guitar, and pluck a string. The note and the octave number should appear on the display, and the LEDs should light up. Tune the guitar so that the central LED (C000) lights up. With the author's prototype, notes as high as D5 (22nd fret on the high E string) were detected properly. The low E string (E2) also works well. The tuner has not yet been tested with a bass guitar, but it was tested with a function generator. That showed that frequencies down to 20 Hz were detected without problems. If you wish, you can fit the project in an enclo- sure. The author used a Hammond chassis (515- 0950) for this, equipped with a front panel. That is also the reason why the LEDs are not mounted directly on the PCB, but instead fed out over CON5 and CON6. Happy Tuning! ( 140076 - 1 ) Web Links [1] www.ti.com/tool/EK-TM4C123GXL [2] http://processors.wiki.ti.com/index.php/Getting_Started_with_the_TIVA%E2%84%A2_C-Series_TM4C123G_LaunchPad [3] http://en.wikipedia.org/wiki/Nyquist%E2%80%93Shannon_sampling_theorem [4] YIN, a fundamental frequency estimator for speech and music, 2002, Alain de Cheveigne & Hideki Kawahara [5] http://en.wikipedia.org/wiki/Autocorrelation [6] https://github.com/JorenSix/Pidato [7] https://github.com/ashokfernandez/Yin-Pitch-Tracking [8] www. elektor-magazine. com/140076 [9] http://www.ti.com/lsds/ti/analog/webench/webench-filters.page [10] www.ti.com/tool/ccstudio [11] www.ti.com/tool/lmflashprogrammer 96 July & August 2014 | www.elektor-magazine.com 25% OFF CIRCUIT CELLAR Whether it’s programming advice or design applications, you can rely on Circuit Cellar for solutions to all your electronics challenges. Raspberry Pi, embedded Linux, low-power design, memory footprint reduction and more! Become a member, and see how the hottest new technologies are put to the test. RiwtwT-r t\ I/O hert [Pwl 3 ) !*■ MffW i n " i IMiTi: tlltw Mu ll B circuit cellar MCU-BASED COLOR DATA ACQUISITION MfL fjfrjrM , rif artiwin .^nsi.r » ms mar ■ Wertt* Clide | 04* Pm tHstrnnlcj: fn^reiXTPeur m wn Cdbe-SoMoO RokUt H-f* I/O kund | Robot* «urJH trtrtrft 0*Sk* for [ IE0 CbJirWWriKJlofi | CWfoG Se^pi-rs ^ Tl((5. tut th-nfl fIM? ri*5 is DtfWl SNft* JOIN TODAY! www.circuitcellar.com/sepN1 3 •Projects IR Tester with Solar Cell Power Supply By Wouter Eisema (Netherlands) capacitor with small dimensions and a very large capacitance, in this case it is 1 farad! There is no need to limit the charging current into this type of super-capacitor. D1 prevents the electrolytic capacitor from discharging via the solar cell. In order to keep the voltage drop across the diode as small as possible, a Schottky type was used (BAT85) for this. An IR LED is used to detect the IR signals. Such an LED does not only work as a gener- ator of IR light, but also generates a voltage when exposed to IR light. For this purpose the LED needs to be connected the 'wrong way' via a resistor to the power supply voltage. When modulated IR-light from a remote con- trol reaches the LS274, the voltage on IC1 pin 13 will change in sync with the detected IR pulses. The first inverter will convert these variations into digital pulses which then con- tinue to a highpass filter, consisting of C2 and R2. This filter blocks the low frequency signals and ensures that the indicator LED is only driven by short-duration pulses. After the filter there are two more inverters connected in series. The final one drives the red LED directly, the inverter output will self-limit the LED current. As you can see from the schematic, not all the gates in the IC have been used. As is custom- ary, the unused inputs have been connected to ground. The author designed this tester for IR-remote controls as an excuse to experiment with a GoldCap. Of course there are simpler ways to test a remote control, but the version described is of singu- lar design. The energy consumption of this circuit is so small that it can easily be powered from the combi- nation of a solar cell and a GoldCap. An on/off switch is not necessary. A small solar cell charges a GoldCap (Cl) via diode Dl. This is a special type of electrolytic You can test many different types of IR remote controls with this circuit. Press any arbitrary but- ton on a remote control and the LED will light up as long as you keep the button pressed. The distance between the IR-source and the IR LED should not be too large, about 20 cm (8 inches). The circuit itself can also be tested in the absence of a remote control: Point the LED of the tester towards bright daylight, briefly cover the IR LED and the indicator LED will light up briefly. A small circuit board has been designed for the tester, but you can also easily build it on a small piece of prototyping board. The solar cell and the 98 July & August 2014 | www.elektor-magazine.com Build-Your-Own-780X GoldCap are connected to the circuit board with a few short pieces of wire. The circuit can be made very compact of you use SMD components. This would allow it to be implemented as a key chain, for example, with a transparent window in the enclosure for the solar panel. ( 140117 - 1 ) Web Link www. elektor-magazine. com/1401 17 Component List Resistors R1,R2 = 10MQ Capacitors Cl = GoldCap IF 5.5V C2 = lOnF Semiconductors LED1 = LED, high-efficiency, red, 5mm D1 = BAT85 D2 = IR-LED LD274 IC1 = 4069 Miscellaneous Solar cell, size approx. 22x7mm, e.g. Conrad Electronics # 160839 PCB artwork, # 140117-1, free down- load at [1] LM317 Turns 78xx The author of this tip was recently able to get his hands on a bunch of LM317 voltage regulators. Now he has little need for an adjustable regula- tor in the circuits that he builds. Fixed voltage regulators of the type 78xx he uses frequently however, but he didn't want to modify his exist- ing circuit board layouts to accommodate the LM317 regulator. To prevent the bunch of LM317s from being neglected in a corner he thought of the following. With the aid of a small piece of prototyping board, two (or three) resistors, an electrolytic capacitor and a PCB header he turned an LM317 into a 78xx (see schematic). The sche- By Johnny Verhoeven matic is the standard application for the LM317. (Netherlands) The output voltage amounts to: Table 1. Resistance values for various standard output voltages. The table lists the resistor values for various output voltages. The theoretical value is shown for resistor R2. You can use the nearest E96 value for this or approximate this value by connecting two resistors in series. The significant part is the construction of the entire assembly, as can be seen in the photo. It is important that the PCB header has the same pinout as a 78xx. If you would like to save some space then it is possible to omit the electrolytic capacitor. ( 140174 - 1 ) V out = 1.25 x (1 + R2/R1) Vout (78xx model) R1 R2 5 V (7805) 1410 6 V (7806) 1786 9 V (7809) 470 Q 2914 12 V (7812) 4042 15 V (7815) 5170 www.elektor-magazine.com | July & August 2014 99 •Projects Spirit-Level Acoustic Aid By Wouter Eisema (Netherlands) This aid for a spirit-level gives an acoustic and optical indication when the air bubble in the vial of the level is exactly in the middle. In comparison with existing optical and acoustical levels, this aid is much cheaper. This circuit is very handy for people with hearing or vision impairments, but also for those who would like to hang a pic- ture frame or shelf on their own and can't keep an eye on the level while they're occupied with other details. The circuit design is exceedingly simple. The main component in the schematic is ici Component List Resistors R1 = 220Q. (SMD 1206) R2 = 390ft (SMD 1206) R3 = lkft (SMD 1206) Capacitors Cl = lOOnF (SMD 1206) C2 = 330nF (SMD 1206) Semiconductors LED1 = LED, white, 5mm LED2 = LED, red, 5mm T1 = BC848B (SOT-23) ICI = 78L05 (SOT-89) IC2 = IR optocoupler with wide gap, e.g. Optek OPB815L Miscellaneous BZ1 = active piezo buzzer, small model Small vial to fit in optocoupler 9V battery and clip-on connector PCB layout # 140121-1, download at [1] k a R1 • • □ (C)Elektor 140121-1 VI .0 3s*? O ML c2 a \ an optocoupler which has an air gap that is quite wide and will accommodate, with a bit of effort, a small bubble level vial of about 30 x 10 x 10 mm. The LED in the optocoupler transmits infrared light, which goes through the vial and then arrives at the opto-transistor. In parallel with this transistor are an LED and a transistor with a self-oscillation buzzer. When the IR light passes through the liquid, the transistor receives enough light so that it will conduct. The LED and buzzer are then not active. When the air bubble is in the middle, the IR-light becomes sufficiently scattered, with the result that the opto-transistor will turn off and as a consequence the LED turns on and the buzzer sounds. The power supply for the circuit is provided by a 5-V voltage regulator. Since the circuit will only be used intermittently and draws only a few tens of milliamps, it can easily be powered from a 9-V battery. LED2 serves as power supply indicator, so that you will not for- get to turn the circuit off after use. The author designed a small circuit board for the circuit, but it contains so few parts that it would also be very easy to build it on a small piece of prototyping board. Note that the circuit board shown uses some SMD parts. After mounting all the parts, the spirit-level vial can be clamped in the optocoupler and, if necessary, be held in place with a little glue once the correct position has been found for proper operation. It is best to build the circuit into a small enclo- sure. The enclosure will house the circuit, an on/ 100 July & August 2014 www.elektor-magazine.com Power Outlet Tester off switch and a 9-V battery. The circuit board is mounted in the enclosure in such a way that is can be moved slightly in order for the indication to match that of an external vial which is glued to the outside of the enclosure as an additional aid. The little enclosure can be used on its own to level objects, but can also be attached with a spring clamp to a normal spirit level and be used as an additional indicator. ( 140121 - 1 ) Web Link www.elektor-magazine.nl/140121 Power Outlet Tester using Bicolor LEDs Editorial note: this circuit may not work, or not as described, in all countries depending on the way the Neutral (N) and Earth/Ground lines are con- nected in accordance with the national electricity code and relevant guidelines for electrical safety. Most simple phase testers indicate whether an AC powerline voltage is available; at the wall outlet they identifies the Live (L) connection. This handy tester can do more. It uses just four resistors (two times two resistors in series to halve the voltage stress on each resistor), two bi-color LEDs and a pushbutton. The complete circuit can be fitted inside a stan- dard 3-pin plug-top with an Earth connector. Make sure that the circuit is completely enclosed in the plug housing and that the pushbutton is rated at AC line voltage. With the socket tester plugged into an AC power outlet both LEDs should light to indicate a flow of current between the live (L) and neutral (N). The LED color is not important; both bicolor LEDs will be lit so the overall color will be orange. Bicolor LEDs have been specified to avoid the need for an additional diode which would be connected in anti-parallel if a single LED were used. When the pushbutton is pressed only one of the LEDs will light, indicating that the power outlet Earth connection is correctly wired. The lit LED indicates the Live (phase) connection. ( 140172 ) By Hans-Norbert Gerbig (Germany) www.elektor-magazine.com July & August 2014 101 •Projects Current Boost for USB Lithium Charger By Ian Field (UK) A TL431 shunt regulator can be used to ensure that a lithium cell cannot be charged to more than 4.2 V, meaning: when the cell has reached its maximum voltage, the TL431 must shunt all of the current flowing through the limiting re- sistor. A resistor with a value of around 10 ohms then limits the current to within what the TL431 can safely shunt. by the gain of the PNP transistor. As the TL431's maximum current rating is no lon- ger the limiting factor, the only constraint is the maximum current that a correctly spec- ified USB charger can supply (500 mA). When the battery is at its lowest voltage, the current limiting resistor works out at 4.5 ft, with 4.7 ft being the most suitable actual value. The transistor used here is a 2SB857 (T2), this was the junkbox part that came readily to hand while rounding up the parts. There's noth- ing particularly special about this device, it is rated 50 V, 4 A and a /7 fe(min) of 60, meaning just about any TO220 PNP with similar ratings will do the job. The one in the prototype was not fitted with any heatsink. With no load (maximum shunt current) it did get moderately warm, but not in the least uncomfortable. Another approach shown here is to add a PNP out- put transistor to the TL431 in much the same manner as a Sziklai pair. Now the maximum shunt current is the 100 mA that the TL431 can handle multiplied As the PNP transistor now does most of the heavy lifting and its collector is returned to the nega- tive rail, a current sensing resistor, R4, can be inserted in the collector lead to switch a second transistor, Tl, which operates the 'cell full' indi- cator, LED1. This would have been more com- plicated with only the TL431 as inserting the current sensing resistor in the anode lead would create a variable offset voltage working against its reference point. The current sensing resistor in the collector lead is included in the feedback loop and has very little effect on regulation. The 'battery full' voltage is accurately set with PI. ( 140122 ) 102 July & August 2014 www.elektor-magazine.com ALSO AVAILABLE: The all-paperless GREEN Membership, which delivers all products and services, including Elektor magazine, online only. 0lektor membership Your GOLD Membership Contains: • 8 Regular editions of Elektor magazine in print and digital • 2 Jumbo editions of Elektor magazine in print and digital (January/February and July/August double issues) • Elektor annual DVD-ROM •A minimum of 10% DISCOUNT on all products in Elektor.STORE • Direct access to Elektor.LABS; our virtual, online laboratory • Direct access to Elektor.MAGAZINE; our online archive for members • Elektor.POST sent to your email account (incl. 25 extra projects per year) • An Elektor Binder to store these projects • Exclusive GOLD Membership card cr^-- — - ©ektor membership Connect with us! www.facebook.com/elektorim www.twitter.com/elektor Join the Elektor Community Take Out a GOLD Membership Now! •Projects RC Speed Control for DC Motors Small and versatile By Jan Lichtenbelt (Netherlands) This article describes how to DYI a PWM-based speed control for RC models on a small board with nothing but discrete components (well al- most). The software for the project was entirely developed in Flowcode. Remote control (RC) is used for model aircraft, race cars, boats and trains to mention but a few examples. The principle is sim- ple: an RC transmitter sends code repre- senting the position of one or more control levers ("sticks") to the receiver in the model. Depend- ing on the position of the levers a pulse of 1 to 2 ms with a repetition rate of 50 Hz will become available in the model. This pulse can be used directly for controlling servo motors, but must be Translated' for DC motors into a forwards- (air- craft and race car models), or forwards/ reverse- (model train, boat) speed control. There are commercial RC receivers available with pulsewidth modulation (PWM) outputs to con- trol the speed of a DC electromotor. This article describes how you can build a PWM-based speed control yourself on a remarkably small PCB still yet using discrete components for the most part. A microcontroller can translate the RC dutycy- cle (5-10%) into a 0-100% PWM signal both in a forward or reverse direction by means of two PWM signals and a MOSFET bridge, see Figure 1. When one bridge input is kept Low and the other input receives a PWM signal, then the motor speed will be regulated in 'forward' direc- tion. Swapping the two inputs reverses the motor direction. There are small differences in requirements for different types of models. Aircraft and race cars need a very fast response, while model trains and vessels have a more natural, slow response. When a receiver failure occurs it is desirable for a model train to keep running, while a race car should stop as soon as possible. Another failure situation to consider is what to do after an over- load current or an overtemperature of the bridge driver or motor? The original purpose of this design was an elec- tronic bridge driver for the motor with through- hole parts only. The only exception in this cir- cuit is a small bridge driver IC which fortunately can be soldered by hand. In experiments by the author a version of the circuit with four MOS- FETs sometimes failed and therefore got rejected. The best choice was found in a MOSFET bridge ADP3624ARDZ, good for 4 amps peak current. This is enough for the model train motor used (gauge I) with typical currents of 0.3 A, and 1 A maximum. This bridge driver can be used with a supply voltage of 4.5-18 V; it has two non-in- verting inputs and includes an over-tempera- ture warning output. The IC is available in a SOIC package with 0.05" pin distance. This pin distance allows it to be soldered in a traditional 104 July & August 2014 www.elektor-magazine.com RC Speed Control way with the aid of de-soldering wick to remove solder between the pins. Hardware The diagram in Figure 2 shows the simple setup of the circuit. The Microchip PIC12F1840 receives the RC pulses of 1-2 ms and translates them into PWM signals. These signals are used to con- trol the ADP3624 MOSFET bridge with the motor connected to the output. Resistor R6 (10 kft) in parallel with the bridge output is added to ensure that the design still works if no motor is connected. Capacitors Cl and C3 (100 nF) have to be as close as possible to the bridge driver and the motor. To use the MOSFETs as switches the gate voltages should be at least 4.5 V. With high current surges during switching, a supply voltage of 5 V can easily drop below this value. Therefore a ceramic capacitor (C7) with its high capacitance should be fitted as close as possible across the bridge driver. A 10-pF ceramic SMD capacitor is commercially available to hobbyists and can easily be soldered. The bridge driver, IC2, gives a temperature warn- ing by changing pin 8 from Low to High. This signal is used in the PIC microcontroller in an interrupt procedure. Resistor R1 (1 kft) and zener diode D1 (5.1 V) are included for safety reasons. The bridge shutdown pin (1; SD) of IC2 is not used, because shutdown is already implemented in the firmware executed by the microcontroller. When the RC transmitter is placed close to this Figure 1. Full bridge control of motor speed and direction. The shunt is optional. K4 o- r\. 2 2 -o \^r A. 3 3 _r\ A. 4 4 r\_ 5 5 K2 i A 2 RC-Receiver r\. 3 K2 O- O- Tr2 R3 -| 100R D2 1N4148 IC4 JtsI IR TSOP31236 +5V © K4.B K4.A 1 -O O- -O O- -O O -O O- -O O- 1 +7V...+18V © RC5-Rx Receiver GND K6 X 1 C4 lOOn VDD RA3/VPP RA2 RM | C1 PIC12F1840 RAO/DATA RA1/CLK RA5 VSS 5 PWM1 2 R1 ( rGZF- 2 PWM2 4 8 ZD1 Jci Cl VDD INA OUTA IC2 OTW SD ADP3624 INB OUTB GND ^^V1 TlOOn X C7 lOu K3 < ' 1 @ 1 C3 ^ ■ ( M lOOn V— © < H— 1 Motor 130259 - 12 Figure 2. Full schematic of the speed control circuit. www.elektor-magazine.com July & August 2014 105 •Projects board some high frequency components (like 40 MHz in the author's country) can be present at the input of the microcontroller. A capacitor of l-10nF (C5) at the input of the RC signal (K2a) will reduce these high frequency signals. The power supply (7-18 Vdc) is straightforward comprising voltage regulator IC3 (L7805) and capacitors C6 (10 pF) and C8 (100 nF). C4 is an RF decoupling capacitor for the microcontroller. In principle this 1-amp voltage regulator can supply the RC receiver with 5 V and power additional servos connected to the same receiver. However, if the RC signal is lost, it is found that some RC receivers generate random pulses. Some ser- vos will start to oscillate with likely high power peaks which can easily result loss of control by the microcontroller. If this happens, decouple the servos for a while and test if the speed con- trol works correctly. Try to change to a different radio channel to improve the functioning. Connect the servos and test again. When the problems persist, it is strongly advised to use a separate voltage regulator for the servos or perhaps use additional capacitors. To avoid these surges when RC signals are lost, it is strongly advised to turn the RC transmitter on before the microcontrol- ler is powered up, and to turn not only the RC transmitter off, but the microcontroller also. Use the best radio channel available. The PIC 18F1840 microcontroller uses its internal oscillator of 16 MHz. The Master Clear is given by the microcontroller itself. A 2-ps software timer is used to sample the RC pulses of 1-2 ms, resulting in a higher accuracy than strictly needed for the byte (8 bits) to control the PWM output. Essential data are permanently stored in EEPROM and will be available when needed in the pro- gram. The RC signal's pulses on pin 4 (port A3 of IC1) are recorded by means of interrupts on change. The RC receiver is powered at 5 V, but the RC pulses were found to be about 3 V. PIC input port A3 is TTL compliant and will just detect these 3-V RC pulses. The OverTemperature sig- nal of the bridge driver is detected on pin 6 (port Al), which is part of a comparator with the ref- erence voltage set internally to 2.5 V. The PWM frequency is produced by internal timer2 set here to about 40 kHz, which is within the requirements of 20-100 kHz for this type of bridge driver. In-Circuit Serial Programming (ICSP™) via three pins of the microchip controller is possible using connector K4a. The data, clock and programming voltage of 13.8 V and the power supply volt- age of 5V are connected to the microcontroller. During normal operation of the microcontroller a 5-pin header between the connectors K4a and K4b is used. Instead of RC pulses on pin 3 of the microcon- troller, the IR pulses of an IR remote control with RC5 protocol can also be connected to this port. This makes it possible to change input parame- ters of the microcontroller. A 36-kHz IR receiver TSOP31236 can be used for this. The output should be default high by means of resistor R2 (1 kft). Diode D2 (1N4148) will make this level Low by the IR receiver. Resistor R3 (100 ft) pro- tects the input of the microcontroller. At connector K5 two LEDs can be connected to show the direction, 'Forward' and 'Reverse'. The maximum output current is 25 mA each. This allows using a double set of LEDs. The LEDs will used during the start-up procedure. If RC is lost (flickering) and during over temperature inter- rupts (both off). 'LED 1' connected to pin 7 of the microcontroller is also used to show data by means of RC5 communication with another micro. This RC5-Tx signal will be sent to another micro with an LCD screen to read start parameters used and to show various data during operation. Consider using the PIC16F628A or equivalent PIC 16F1847 as described in Elektor [1], without the RF transmitter. However, if you want to see the PIC data during operation, they can be sent and received with the RF modules described in that article. The software for this RC5_Rx Microchip PIC 16F1847 is part of this article. To activate the RC5-Tx output on pin K5a-1, the other pin K5a-2 must be High at startup by means of a 1-kft resistor connected to +5 V. Attention: for normal use with two LEDs, K5a-2 must be Low at startup, for example, through a LED and current limiting resistor connected to GND. Software The software for this circuit is suitable for speed control suiting many applications. The two possible start procedures take at least three seconds: • Set the control stick to the maximum posi- tion. The 'Forward' LED will turn on. As soon as it turns off, put the control lever in the minimum position. The 'Reverse' LED will then turn on. As soon as it turns off return the control stick to its neutral position. This can be any position like the center position or the minimum position. It is important that 106 July & August 2014 www.elektor-magazine.com RC Speed Control you can see both LEDs at the same time. If not, fit an additional pair of LEDs in a posi- tion where you can see them both. Minimum and maximum position will be stored in the EEPROM. • Set the control stick to the neutral position. Turn the power for the microcontroller on and leave the handle in the neutral position for at least 3 seconds. The minimum and maximum handle position will be read from the EEPROM. The center position can also be a little above the minimum, allowing braking with reversed motor direction in case of race cars. When using this for the first time, always test the correct rotation direction of the motor(s). In general, when the RC receiver gets out of range of the RC transmitter the motor will con- tinue with the last setting received. Using the RC5 communication as described below, this can be changed into halting the motor when RC signals are lost (with both LEDs blinking). Only when the center position equals the mini- mum position, the motor will be controlled in the 'Forwards' direction only. The motor will only be able to go 'forward'. This can be used with race cars and airplanes. In that case the program stops the PWM if the car or plane is out of range of the transmitter for longer than 140 ms (or 7 RC pulses). It is strongly recommended to test this behavior regularly. A PWM of 0% of 500 ms duration will prevent (too) high currents due to a sudden change of the motor direction. Each motor has to overcome its start friction and needs a minimum PWM percent- age to start the motor. The program uses a typical PWM minimum value of 30%. Over-temperature warning of the bridge driver will stop the motor and it will start again after cooling down. Both LEDs will be off. The bridge driver does have an internal hysteresis for this control signal. Some filtering of the RC signals was found to be necessary, especially if several transmitters are in the area. A moving average is used with a small filtering with an RC time (50%) of 60 ms (three RC pulses). Twelve RC pulses are used in the moving average, which takes about 12 x 20 = 240 ms. Theoretically for a step function, 93% will be achieved in this time. This all will result in a small degree of filtering in combination with a fast response, necessary for airplane applications in particular. For details, updates and Flowcode source code files, see [2]. Component List Resistors R1 = lkft R2 = lkft (for IR receiver) R3 = 100ft (for IR receiver) R6 = lOkft Capacitors C1,C4,C8 = lOOnF C3 = lOOnF (on motor terminals) C5 = l-10nF C6 = 100pF 25V C7 = 10|jF 25V, ceramic, SMD, e.g. AVX-18123D106KAT2A (Farnell # 1327761) Semiconductors ZD1 = 5.1V zener diode D2 = 1N4148 (for IR receiver) IC1 = PIC12F1840 IC2 = ADP3624ARDZ or ADP3624ARDZ-RL (SOIC) IC3 = L7805CV TSOP31236 (36kHz version) connected to K2 Miscellaneous K1,K3 = 2-way screw terminal block, 0.2"pitch K2 = 3-pin pinheader, 0.1" pitch K4 = 10-pin (2x5) pinheader, 0.1"pitch K5 = 3-way screw terminal, 0.2" pitch K6 = 1-pin pinheader PCB # 130259-1 Communication Changing the microcontroller parameters given above requires communicating with the micro- controller. An RS232 interface was rejected due to bad synchronization properties with only the start bit available if just the RS232-Rx is used. Instead, IR communication with RC5 protocol is used with much better synchronization half way each bit. RC5 IR-transmitters can be found in many households. The RC5 application addresses are not used. Consequently any RC5 transmitter, independent of its purpose, can be used. Only the button commands (6 bits) are read. The RC5-Rx signal ends up at the same pin 4 (port A3 of IC1) as the RC pulses. Remove the RC input and connect the IR receiver IC to this pin. The RC5 input will be recognized due to the fact that its level is default high, while the RC pulse Figure 3. PCB layout with ADP3624 bridge sitting between motor pins and Cl. The dimensions of the board are 38.1 x 26.4 mm. RC-in doubles as the RC5-Rx input. www.elektor-magazine.com July & August 2014 107 •Projects are default Low. The software is very flexible and not only the official RC5 bit-time of 2 x 889 ps is detected, but also much faster pulses. The RC5-Tx output will be available on the LED at pin 7 (port RAO of IC1) if the other 'LED' at pin 3 (port A4 of IC1) is High by means of a 1-k Q. resistor to 5 V at startup (5 V is available on pin 2 of K4a/b for example). RC5-Tx differs from the official protocol in two ways: • The protocol is close to the RC6 protocol, which enables transmission of bytes (8 bits) or even integers (16 bits). The RC6' proto- col used here, i.e. 2 start bits, 1 byte and 3 integers. • We use a bit time period of 2 x 255 ps, which is the maximum frequency that can be used with the RF transmitter described at [1]. Each transmission will take (2+8+3x16 = 58 bits) 58 x 0.5 = 29 ms. This requires a special RC5-Rx program for the PIC 16F1839 with LCD screen, which can be found in the free download offered with this article [4]. PCB All components (through-hole and SMD) are mounted at the top side of the small PCB (Fig- ure 3). Fix the bridge driver by soldering one pin, and then the other pins. Wick away any excess solder. Pin 1 of the ADP3624 bridge driver is indi- cated by the gray point on the package. At the bottom side of the IC there is an area intended to make thermal contact with the PCB. Remove the protection layer on the board at that particu- lar place. Next, fit C7, the 10-pF ceramic capac- itor. Pin 1 of the PIC microcontroller is at the upper left side. At the right side of the PIC the components are, top to bottom: Rl, ZD1 (GND right side), C5 and C6. Right beside these are K3 (3-pin RC input) and C8. At the right side of the PCB you find 10-pin (2x5) ICSP™ connector K4. LED connector K5 has three additional fix- ing holes right at the edge of the PCB. Ground pin K6 at the upper right side is optional, this is convenient during testing the PCB. See the video on YouTube [3] where the PCB gets tested— note that RS232 is still used for the communication, and the EB006 board for the ICSP™ programming. ( 130259 ) The firmware for this project was completely developed in Flowcode 6 for PIC (available from Elektor, www.elektor.com) Web Links [1] Modular RF Link using Manchester code, Elektor September 2013: www.elektor-magazine.com/120049 and www.elektor-magazine.com/120187 Note: PIC16F628A replaced by the equivalent PIC16F1847. Programming of this microcon- troller using Vpp on pin A5, Vdd, GND, Clock pin B6 and Data pin B7. Pin BO is the RC5/RC6 input(Rx) or output(Tx) pin. LCD Data DB4...DB7 connected to IC pins A0-A3, RS to B4 and E to B5. Normally a resistor of lkft is connected between VDD and MCRL. [2] Jan Lichtenbelt: Remote Speed Control of DC Motors, Matrix Multimedia article MX040: http ://www. matrixmultimedia.com/article.php7a =677 and updates http://www.matrixmultimedia.com/mmforums/viewtopic.php?f=36&t=11613 [3] YouTube pre-testing the PCB (version with RS232, now replaced by RC5): http ://youtu . be/TSJCCADYKsE [4] Extra documentation and software: www.elektor-magazine. com/130259 108 July & August 2014 www.elektor-magazine.com Create Complex Electronic Systems in Minutes Using Flowcode 6 Design -► Simulate Download New in Version 6: • Component Library Expansion; • Improved Simulation; • New Test Features; • 3D Design Environment; • Third Party Instrument Support; • Dashboard HMI Components; • And More! Flowcode is one of the World’s most advanced graphical programming languages for micro- controllers (PIC, AVR, ARM and dsPIC/PIC24). The great advantage of Flowcode is that it allows those with little experience to create complex elec- tronic systems in minutes. Flowcode’s graphical development interface allows users to construct a complete electronic system on-screen, develop a program based on standard flow charts, simulate the system and then produce hex code for PIC AVR, ARM and dsPIC/PIC24 microcontrollers. Further Information and Ordering at www.elektor.com/flowcode ogGfiplte The latest on electronics and information technology Videos, hints, tips, offers and more Exclusive bi-weekly project for GREEN and GOLD members only Elektor behind the scenes In your email inbox each Friday slektor post Th& feeg.nning of * teauiifol friendship L~.» »* Silicon bawd life forms of the World Wh * n w rtfiwv* f l6 Dtfcfer.PDS? m EMfchfr mat ftri 4 imuBcn^nu wy to *Mt) rS , ftw unite! W 1 - iwrw:^ &f*aor Elektw.TV goes Linux tfcfctor rttim JH Bubq Intentm n* IT ON ELEtfTOft.TV »>;> St @ektor Register today at www.elektor.com/newsletter. i n ■ ■■ •Projects Experimenting with NFC Near field communication with the Elektor Member Card By Burkhard Kainka (Germany) Like other members of the Elektor community, last year I received an Elektor Gold Member Card. It has an embedded Mifare chip for near-field com- munication (NFC). I tried to figure out how to use this capability, but I didn't get very far. My prob- lem was that I didn't have any device that sup- ported NFC. Things are different now, because I have become the proud owner of a Nexus 7 tab- let. According to the data sheet, the Nexus 7 has a built-in NFC reader. Catch IF© Sea ito/iiU Hrota TfSl'X! •Xeaut.it* in ♦ ♦ ♦ C * - * • H ... £ * patch the ballooning arro« the globe by Han Nabben I*#»w*Vi/tr*fO«©* m*I» NFC AnM CATCH IMS pvudK * toot r.t© th« Kct©r f , [©«<<«, prx«« jni t«autv ©f ba<©«nrtg. Th© M tt'©gr«bon Of tfC <*ilp% in tKa book <« a oniqtw innovatio© wfoch Km not boon good bOfXO Wt>*n a pnjrtpKona or tafctot with WC * h#M agar** a paga with a tag • May* cip« m automatic a*v start#© • ftaodon eon conroct to toc>M modn • Fr*# nun: can to (Jcwr*oa4#d • O^ckgroor© rfcmjtion on NFC can 0# acco:c©d « Ciptal contort can bo oodod to rho boo« by th# ra«d©r Uammon about ho# to *31 «ojf own ron'ontl Tha trtta song at tha bcc* . “Catch tKa 8ui* by Tim Akkanmon. is rcoiporatod n trto covar of th© boo* ■Caleb r * o ftai rawot eft© * w© nr*r©c f »»rft bock* r» rft© ^jftra? Snapng tha pfysctf snd opfaf wertrfi, Catcb fh© Sir? damcroerabof ho* con m^ant ond add v*A* to tha lr*©fun© tad Farm afow ;«r«bnart to ntarac* «wt*i ©varyday etyaeft r> tvcilyg *©w w©v* ' Min Ooviin o4 AAI Rovoorth. ’K© Nr» YO't-btt©* m©rt©« ntafcgane© company tpoenkhng n g*s&at tacfr.»:.j > martais The first question was: does it actually work? To answer that question, I decided to build a sim- ple resonant circuit for a quick test. NFC works at the allocated ISM fre- quency of 13.56 MFIz, so I wound a coil with 15 turns and a diameter of 40 mm (about 1.6 inch) and soldered an LED to the leads. The reso- nant frequency of this arrangement is roughly correct. When I held the coil next to the rear of the Nexus, the LED blinked cheerfully, from which I concluded that the tablet was constantly transmitting signals to try to contact NFC tags. Following this encouraging start, the next step was to hold my Elektor Member Card next to the Nexus to see what would happen. Guess what? The browser started up and opened the Elektor website at www.elektor.com. So it really works! Generally speaking, NFC technology has not made large inroads al least in Europe, so I had no idea at all of what to expect. Actually I should have known better, because I have a copy of the Elek- tor book Catch the Sun , which incorporates NFC technology. In particular, it contains several NFC tags, including two that are user-writable. So I decided to see what I could do with them. It turns out that these NFC tags open or play quite a few things on the tablet, including web- sites, videos, and tunes. Among other things, I managed to find information about how to write my own data to NFC tags. I got hold of a suitable app: TagWriter from NXP, the manufacturer of the Mifare tags [1]. The app also told me which kind of information I could write to the tags. First I tried writing a link to my own website. Loading the data into the tag was easy - I only had to hold it next to the tablet. I used one of the tags on the last page of the book. In practi- cally no time the link was stored in the tag, and it automatically launched the browser on the tab- let. The next question was whether or not I could overwrite that data. I tried writing a message to the tag, and it worked. The tag opened a text window and the stored message was displayed. Next I decided to experiment with the Elektor Gold Member Card again. I wanted to see if I could reprogram it and write my website address to the tag. What I discovered is that the tag in the Elektor Gold card has less room for user data. However, it worked OK when I omitted the description of my website and only stored the Internet address (URL). Now I have a good idea of what NFC is all about. Hopefully some other readers will find this short article useful. ( 130216 - 1 ) Web link [1] https://play.google.com/store/apps/de- tails?id=com.nxp.nfc.tagwriter 110 July & August 2014 | www.elektor-magazine.com DVD ed: The Full Range of 2000-2009 Vo I umes of Elektor Magazine! I'L-LiLA' through] a ISBN 978-1-907920-28-8 £77.95 *€89.00* US $121.00 Ediifioti l ] CtlMATi lektor :KTOR on DVD ■ O YEARS OF ELEKTOR ON DVD O ^ e ='ronit Archive, Article PDFs Quick Search Function ' ° 1} 0 E ’ e . kto " Editions, Over 2500 Articles Easy Print Function c,es ' O Ideas, Circuits and Projects for fi„,* ot Work, in College, at' Home E ' eCtrOI,,ci ... 3“ C«I|e3s' a+ HOiiJe !“"!** aut l hi-olect? t oi. nuctiou R Q AH •Projects Water Pump Regulator for yachts, mobile homes, etc. going swimmingly! Except the price, that is. These new pumps with their encapsulated regu- lation circuit work out almost twice as expensive as the ones they replace. By Paul Cordonnier (Belgium) If you spend a lot of time at sea, or in and around har- bors, surely you've been confronted at some point with the drawbacks of water distribution pumps on yachts, or pleasure craft in general. In principle, a water system comprises a distri- bution network pressurized by a 12-V pump typ- ically drawing 5-10 A, and usually operating in an on/off fashion, and an expansion vessel. The latter eliminates sudden changes in the flow and ram effects. It is a source of comfort, but also of problems: space taken up, maintenance, etc. New models of electric pumps make it possible to dis- pense with the expansion vessel. Instead, a little electronic circuit takes care of running the pump according to the flow. No expansion vessel, the pump makes less noise, its consumption drops, and the flow is modulated gently. Everything's The author is not an electronics engineer by train- ing, but rather by conviction: so he started look- ing for— and found— a simple, cheaper solution, which is shared with the Elektor audience here. Let's first focus on SI on the schematic dia- gram in Figure 1 . Although shown as an ordi- nary switch, it's actually a pressure switch, con- trolled— as its name indicates— by the pressure of a fluid when it exceeds a certain threshold. So its job here is to power the circuit when the pres- sure in the water distribution circuit is too low, and to cut it off again once it has come back up. The (existing) pump Ml is controlled by IC1, 112 July & August 2014 www.elektor-magazine.com Water Pump Regulator which modulates the width of a 1-kHz signal (PWM) driving the gate of the power MOSFET Tl. The latter, in series with the pump's nega- tive power line, is designed to be driven directly by a microcontroller. The PIC16F684 compares the voltage across the FET's drain/source resis- tance and a reference voltage (set by the user with preset R3) on its pins 10 and 9 respectively, and aims to bring them together according to the difference measured. When the motor volt- age is higher than the reference, the pulsewidth reduces; in the reverse situation, it increases. The PWM range is limited to between 55% (140/255) and 98% (250/255). For debugging purposes, the PIC sends the instan- taneous value of this ratio to the serial output (@ 2,400 baud). If there is no flow in the water distribution cir- cuit, the pressure rises to reach the actuatioon threshold of the pressure switch that opens SI and the pump control circuit is disconnected. Diode D2 clips the voltage peaks in order to (crudely) protect the comparator. LED D3 is driven by the output of the analog comparator built in to the PIC, pins 9 and 10 of which are the inverting and non-inverting inputs, while LED D4 is controlled by the software. The connector K3 is associated with debugging; it can be left out. The regulation program in PICBasic Pro is as simple as can be, since the PIC has nothing else to do. The source code can be downloaded from the website [1]. The programmed PIC is avail- Figure 1. The pulse width modulation control of the pump consists primarily of a PIC and a MOSFET. Figure 2. The gate and drain signals of Tl (yellowish and green respectively). www.elektor-magazine.com July & August 2014 113 •Projects Figure 3. The specific layout of the PCB is explained by the choice of a watertight case. COMPONENT LIST Resistors (0.25W) R1 = lkft R2 = lOkft R3 = 2.5kft preset R4,R5 = 470ft Capacitors Cl, C2 = lOOnF, 2.5mm C5 = lOOnF, 5mm C4 = 33pF 10V, radial, 2mm C3 = 470pF 25V, radial, 5mm Semiconductors D1 = 1N5408 D2 = 1N4001 D3, D4 = LED, red, 5mm T1 = RFP70N06, N-MOSFET 70A 60V IC1 = PIC16F684-I/P, programmed IC2 = 7805 Miscellaneous K1 = 3-pin PCB screw terminal block, 0.2" pitch K2 = 5-pin pinheader, 0.1" pitch K3 = not connected 14-way DIL IC socket Pump used: Jabsco PAR-MAX 1.9 gal/min (7.2 l/min) 12 V 3 A able from Elektor, as is a printed circuit board. Inserting the regulator in a pump's negative supply line in an existing installation ought not to cause any problems, but you do need to take special care with the installation, as it is going to be fitted in a potentially damp environment. This explains the specific design of the PCB, designed for one particular case (the PICCOLO ABS B 65 from Fibox), chosen for its ingress protection rating (IP 66/67); its contents are protected from powerful jets of water and even submersion down to about 3 ft. (1 m). The pump used by the author is a 1.9 US gal- lon/min. 12-V, 3-A type. For Kl, sailors will pre- fer a spring terminal block rather than a screw type, which risks coming loose in the presence of vibration. Happy Sailing! ( 110188 ) Internet Link [1] www.elektor.com/110188 114 July & August 2014 www.elektor-magazine.com SS;s VOl electronics senga . networ data „ ai medial information ' | ■m product news ( embedded design tips tutorial software Q) neering tools system au d i o business n inq media ° COMMUNITY .. ^Jat\4'4x) -Uk4r> iAouy ir\4tiy^s4s opirtiorts! Ov&cjv. omtI" ovy Nje^i Social stadia 0«He4s f or J&Yick- ertgage*vei4j CIRCUIT CELLAR / AUDIOXPRESS / ELEKTOR •Industry New USB Counter / Timer DAQ Devices Measurement Computing Corporation's two high-speed USB Counter /Timer DAQ devices are available with four or eight counter I/O. The USB-CTR Series feature high-speed pulse counting with a 48 MHz maximum input frequency. Resolution is programmable up to 64 bits, with an aggregate scan rate of 8 MB/s. These new devices offer some of the most advanced counter / timer functionality available in USB DAQ today. Supported high-level input modes include totalize, period measurement, pulsewidth measurement, and timing measurement. Four independent PWM timer out- puts and 8 digital I/O are also provided. Timer output channels can operate continuously or for a specified pulse count, with duty cycle and period changeable on the fly. Counter and digital channels can also be scanned synchronously. Flexible edge, level, direction, and debounce settings allow the counters to better adapt to user signals. The new USB-CTR Series features 4 or 8 counter I/O; 48 MHz maximum input frequency; programmable resolution up to 64-bits per counter; aggregate scan rate of 8 MB/s. It supports the following counter input modes: Totalize; Period measurements; Pulsewidth measurements; Timing measurements. The devices also feature debounce filter circuitry; 4 PWM timers; 8 digital I/O; Synchronous high-speed reads of digital and counter inputs. Software options include comprehensive support for Visual Studio® and Visual Studio® .NET, DASYLab®, and NI LabVIEW™. The four channel USB-CTR04 is priced at US$359, and the eight channel USB-CTR08 is priced at only $429. www.mccdaq.com (140323-11) Microchip's GestIC® Technology Wins 11 Global Awards Microchip Technology Inc., has been recognized by 11 global electronics industry publications for the product innovation and technology leadership of its patented GestIC® technology, which enables the next dimension in intuitive, gesture-based, non-contact user interfaces for a broad range of end products. The MGC3130 is the world's first electrical-field (E-field)-based 3D gesture controller, and it utilizes GestIC technology to provide low- power, precise, fast and robust hand position tracking with free-space gesture recognition. In the Americas, the MGC3130 won five awards. It was handpicked by the editors of Electronic Design Magazine for their "Best of Electronic Design Awards," in the Digital category. EDN named the MGC3130 to their annual "Hot 100 List," in the Microcontrollers & Processors cat- egory. EE Times chose this product as a finalist in the ULTIMATE PROD- UCTS: Sensors category of their "Annual Creativity in Electronics (ACE) Awards." Electronic Products Magazine bestowed a "Product of the Year Award" on Microchip's GestIC technology, while Design News awarded its coveted "Golden Mousetrap," in the Electronics & Test: Embedded Computing/Processing category. In Asia, the MGC3130 received three prestigious honors. EE Times China Magazine selected it as a Product of the Year in the Microcontroller/ Memory/Interface category of their "ACE Awards." EDN China bestowed an "Innovation Award" in the Embedded System: Microcontrollers cat- egory. Electronic Engineering & Product World China Magazine selected GestIC technology for an "Editors' Choice Award" in their Best Sensor Solutions category. In Europe, the MGC3130 was recognized by three organizations. These included Europe's most prestigious elec- tronics-industry honors, the annual "Elektra Awards," who named the MGC3130 as their Semiconductor Product of the Year in the Analog category. It also won France's "Electron d'Or Award," in the Sensors category. From Italy's "Innovation Awards" came a win for the MGC3130 in the Best Innovation Award category. http://www.microchip.com/get/38XW (140232-III) 116 | July & August 2014 | www.elektor-magazine.com Shuntless Current Sensing from mA to kA ams AG (has introduced a reference design board which measures current to an accuracy of ±1% by monitoring the voltage drop across a copper track on a PCB. The development of the new technique, which uses the ams AS8510 data-acquisition front end, enables designers of Battery Management Systems (BMS) to reduce bill-of-materials cost by eliminating the precision shunt resistor normally used in current- sensing applications. A precision resistor with low temperature drift can typically cost as much as $1.50 in volume. Accurate current measurement is an essen- tial function in a BMS, which provides functions including monitoring of a battery's state of charge and state of health. The new reference design board from ams provides a blueprint for the cur- rent measurement function in a BMS, and can be applied in e-bikes, pedelecs and other applications drawing current of up to 40A. The same design can also readily be adapted to measure currents of up to 100A using only the resistance of a PCB's copper track. The new ams reference design takes advantage of the very high sensitivity and precision of the AS8510, an integrated data acquisition front end which provides two measurement channels. One channel is used to measure current by sens- ing the voltage drop over a 10-mm section of a PCB track with a known resistance value and tempera- ture coefficient. The other, matched channel mea- CU E CU c n CD > “O 4 M Shuntless Battery Management - 1% accuracy - No shunt needed www.ams.com/ASB5 10/CopperShunt L e^DresspSb.corn sures the temperature of the copper track. This tem- perature measurement can be performed either inter- nally by the AS8510, or by an external temperature sensor. By applying a compensation algorithm developed by ams, the AS8510 can eliminate the effect of the varia- tion in the resistance of the copper track over tempera- ture. This means that it can produce current measure- ments accurate to ±1% over its entire operating tem- perature range (-40°C to +125°C) without the normal requirement for a precision shunt resistor with a low temperature coefficient. www.ams.com/AS8510/CopperShunt (140116-V) www.elektor-magazine.com | July & August 2014 | 117 Dual 20 A/single 40 A Step-down Power Module Intersil Corporation's ISL8240M is a dual 20A/single 40A step-down power mod- ule that sets a new standard for efficiency and power density in infrastructure and embedded computing applications. Capable of delivering up to 100 W of output power in a 2.9 cm 2 footprint, greater than 90 percent power efficiency, and industry-leading thermal performance, the ISL8240M provides designers with a turnkey DC/DC con- verter solution for high current applications. Today's power systems for communications and computing infrastructure support high current loads from increasingly power hungry FPGAs, ASICs, and microproces- sors. To supply these high current circuits, equipment makers often rely on discrete power solutions that are complicated, take up valuable real-estate and may have significant power output limitations. Intersil's power module family reduces design complexity and creates headroom in the power system, increasing flexibility while improving efficiency and thermal performance. The latest addition to Intersil's complete family of power modules, the ISL8240M is pin-to-pin compatible with the company's popular ISL8225M 30A power module, expanding the output current to 40 A and delivering up to 100 W output power. This offers designers a high level of flexibility, enabling a single PCB design across platforms. The ISL8240M is also capable of delivering up to 240 A output when six modules in parallel operation are current shared, enabling the industry's highest total output current. Key Features and Specifications: • Wide input voltage range: 4.5 V to 20 V; • Adjustable output range: 0.6 V to 2.5 V; • Capable of providing two separate outputs up to 20 A per channel or a single 40 A output with current shar- ing up to 6 modules in parallel operation for 240 A; • Achieves >90% efficiency (12 V jn , 2.5 V out ) at 40 A; • Full suite of protection features: over-current, over-/under-voltage, and over-temperature monitoring. The ISL8240M leverages Intersil's patented technology and advanced packaging techniques to deliver greater than 90 percent power efficiency and the best thermal de-rating performance in the industry, enabling the ISL8240M to operate at full power over a wide temperature range. The module also provides over-temperature, over-current and over-voltage protection, further enhancing the robustness and reliability of the solution. www.intersil.com/products/ISL8240m (140231-VII) JSL8240MjDual 20A/$ingle Step-Down Power Module inteisil SMT Test Points and Ball and Socket Connectors Vero Technologies has announced the introduction of a complementary range of SMT devices suitable for use with high-speed placement machines. Four industry-standard sized loop terminals, the 0603 (1.6 x 0.80 x 1.15 mm), the 0805 (2.0 x 1.25 x 1.45 mm) and the 1206 (3.2 x 1.60 x 2.0 mm) are initially available; all are compatible with industry-standard probes, clips and hooks. Additional designs and sizes will follow during the coming months. All sizes are available in a nickel-plated stainless steel construction; the largest size is also available in a copper alloy, allowing customers to choose the material that best fits their production process. Also introduced is a 2 mm high, 1 mm diameter, ball and socket terminal. It requires a minimum pad size of only 0.080", 2.0 mm, enabling it to be placed by any pick and place machine in even the most congested board designs. The socket has less than 2 mQ contact resistance, is rated at 3 A and offers gentle detachment. The matching 3.2-mm diameter socket has a ±30° angular movement before disconnection, giving good reten- tion during use. All the new products are available ex-stock in units of 2000 or 2500 on standard 7" tape and reels for automated pick and place; they are also available in mini- mum quantities of 100 for smaller volume requirements. Vero Technologies now offers a complete range of products suitable for all manufacturing processes, and all available from stock. http://www.verotl.com/en/category/Surface+Mount+Technology (140231-VI) 118 | July & August 2014 | www.elektor-magazine.com PCB-POOL®: free 3D data for EAGLE PCB layout software UNBEATABLE at price-performance ratio. The PCB manufacturer Beta LAYOUT LTD is now introducing a virtual 3D EAGLE viewer in its PCB-POOL®. The unique tool is called "brd-to-3D" and works with a proprietary library. By uploading the EAGLE layout file ("with more formats com- ing soon/ the customer receives a 'free' comprehensive 3D package consisting of: • Photo-realistic images of your printed circuit board and SMD stencil; • a STEP file of the virtually assembled PCB; • a PDF formatted 3D view that rotates freely allowing all angles of viewing The brd-to-3D tool is a complement to Cad- Soft's EAGLE software that currently does not have a direct STEP-export. Customers can also obtain a free laser-sintered 3D model of the assembled printed circuit board with the purchase of a PCB-POOL® prototype order. For users not familiar with the 3D world the PCB-POOL® website provides pre- pared video tutorials that explain handling and processing of 3D files to the photo-realistic renderings. www.pcb-pool.com/brd-to-3d www.pcb-pool.com/ppus/info_video_3d_freecad.html www.pcbpool.com/ppus/info_video_3d_simlab.html (140231-1)