www.elektor-magazine.com FT311D-based Android User Interface Builder •magazine June 2014 Android User Interface Builder Lathe Tachometer Touch-2-Switch Seismic Detector Microcontroller BootCamp XXL LED VU Meter DIY I 2 C for RPi Hack-Your-Own Reflow Oven Dimensioning Photovoltaic Cell Arrays The MAS6510 • 3-D Print Your Own Ink Multi-switch Lights Control A Jumbo PCB US$9.00 - Canada $10.00 06 Elektor ComputerScope (1986) 25274 24965 7 7 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- Join the Elektor Community Take Out a GOLD Membership Now! Let Jr " ^KvO* ^Te ^^r^tnewte 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 ALSO AVAILABLE: The all-paperless GREEN Membership, which delivers all products and services, including Elektor magazine, online only. (2|ektor Take Out Your Membership Now at www.elektor.com/member m Connect with us! www.facebook.com/elektorim www.twitter.com/elektor Contents Projects 8 Android User Interface Builder The FTDI FT311D is a flexible bridge that can interface your circuit to an Android smartphone or tablet. It offers options for seven digital outputs, four PWM outputs, asynchronous serial and I 2 C and SPI interfaces. To make things sim- ple we have designed a small board to carry the chip: introducing the 'Elektor Android breakout board'. 14 Lathe Tachometer Flere's a non-invasive, all electron- ic add-on to display the running speed (rpm) of your lathe or milling machine, be it CNC or vintage. It's state of the art— witness the use of an Arduino Micro board and a .96 inch OLED display for instan- taneous readout. The little instru- ment also has a clock displaying the equipment running time. 18 Touch-2-Switch This capacitive-detection dual wall touch-switch, designed to fit into domestic electric wall-boxes, uses analog technology throughout. A single multi-purpose version that you can configure as you wish to function as a simple on/off switch, a 2-way switch, or momentary but- ton, on two independent channels. 26 Seismic Detector This simple circuit generates acoustic and visual alarms when it detects a shock, vibration or earth- quake. It also has a relay that can be used to energize other devices or external indicators. 30 Microcontroller BootCamp (3) This month we focus on the analog to digital converter, which is ef- fectively a voltmeter built into the microcontroller. The A/D converter simply supplies data., which has to be transmitted. That's where the serial interface comes into play. 40 XXL LED VU Meter The circuit described here has an exceptionally wide input range of 60 dB and a step size of 1 dB thanks to the use of 6 LM3915 driver ICs, which control a total of 60 LEDs. An interesting aspect of this design is that it is entirely analog (there is no microcontroller to be found) and that has a didactic purpose. 46 DIY I 2 C for Raspberry Pi What do you need for this? Actu- ally not that much: a Raspberry Pi board, an SC card with the Raspberry Pi operating system and I 2 C drivers, a PIC 16F88 microcon- troller, a PIC programmer, and a breadboard with an LED, an LDR and a few bits of wire. 50 Dimensioning Photovoltaic Panel Arrays What's the promise of monocrystal- line silicon, polycrystalline silicon, amorphous silicon, and CIS cells 4 | June 2014 | www.elektor-magazine.com Volume 40 - No. 450 June 2014 when arranged in a solar panel and charging a battery? 56 Hack-Your-Own Reflow Oven Thanks to SMDs, printed circuits are getting smaller— and thus the cost of projects. The fact remains that for soldering these miniature compo- nents, you need little fairy fingers... or a reflow oven! You're hesitating? 74 Multi-switch Lights Control Complex electrical wiring is required if a single load like hallway or corri- dor lighting is to be switched on and off by any one of a large number of switches. Here we propose a work- around using a DIY thyristor. • Industry 76 News & New Products A selection of news items received from the electronics industry, labs and organizations • DesignSpark 64 DesignSpark Tips & Tricks Day #11: Working with Large Designs This month we learn how to deal with multiple-schematic sheets in DesignSpark PCB. 66 Varactor Diodes Weird Components— the series. Labs 68 3D-print Your Own Ink Our 3D printers really should be put to good use, like printing stuff that's useful to electronics engi- neers. 70 Jumbo PCB To Escape From Labs The Elektor lab PSU design incor- porating the PCB transformer we wrote about is one step closer to prototyping and testing. 72 Chip Tips: The MAS6510 Highlights of a new capacitance-to- digital converter. • Regulars 80 Retronics Elektor ComputerScope (1986). Almost 30 years ago a trainee at Elektor Labs designed an ambitious test instrument like an oscilloscope with PC support. Series Editor: Jan Buiting. 84 Hexadoku The Original Elektorized Sudoku. 85 Gerard's Columns: Lazy Days A column or two from our colum- nist Gerard Fonte. 90 Next Month in Elektor A sneak preview of articles on the Elektor publication schedule. www.elektor-magazine.com | June 2014 | 5 •Community Volume 40, No. 450 June 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 A www Guide to Elektor This space being remarkable for intensive read- ing (even by my CEO) but drawing little response overall, I will venture to present a condensed what-where-why (www) guide to Elektor magazine within the constellation called Elektor International Media. You may have noticed that Elektor is no longer at a single .com website but divided across Magazine, Store, Labs and Forum. All are intensely online driven to serve our 300 K audience around the globe. • Elektor Magazine at www.elektor-magazine.com is a service website where our valued Green and Gold Members find their digital copies and the archive of past editions, and are able to renew or change their membership. It is also home to the famous free software downloads with published articles, as well as all "Project" edi- tions of Elektor.POST. Status: Okay; Up For Revision 2015. • Elektor Store at www.elektor.com is our online retail activity as well as the portal to all of EIM's websites and publications. Use it to shop around for books, PCBs, semi- kits, DVDs, and PCB fabrication equipment. Create and manage your Store account, track orders, find special offers, get in touch with Customer Services, view legal stuff. Status: Under Construction. • Elektor Labs at www.elektor-labs.com showcases Elektor's wide open kitchen, where the editors taste and select the dishes to refine and serve out in the printed maga- zine, with the help of authors, graphics people and the Elektor lab crew. Status: Okay; Lively. • Elektor Forum at http://forum.elektor.com was relocated and restyled recently. It's amazing what help you can find there, like for the recent 500 ppm LCR Meter. Good for older projects. Status: Okay; login procedure provisionally shared with Elektor Labs. A grand operation is currently underway as our web staffers are harmonizing all login data. After all, Magazine, Store, Labs can be browsed freely to an extent, but logging on is required at some point to place an order or reach content. Or, in case of the forum, reply to, create and write topics. When lost aim for www.elektor.com as our portal site. Bookmark it. When utterly lost aim for www.eimworld.com. When interested in hands-on electronics, start on page 8. Enjoy this edition of Elector (page 17), Jan Buiting, Editor-in-Chief The Team Editor-in-Chief: Publisher / President: Membership Managers: International Editorial Staff: Laboratory Staff: Graphic Design & Prepress: Online Manager: Managing Director: Jan Buiting Carlo van Nistelrooy Shannon Barraclough (USA / Canada), Raoul Morreau (UK / ROW) Flarry Baggen, Jaime Gonzalez Arintero, Denis Meyer, Jens Nickel Thijs Beckers, Ton Giesberts, Wisse Flettinga, Luc Lemmens, Mart Schroijen, Clemens Valens, Jan Visser, Patrick Wielders Giel Dols Danielle Mertens Don Akkermans 6 June 2014 www.elektor-magazine.com Our Network USA Carlo van Nistelrooy + 1 860-289-0800 c.vannistelrooy@elektor.com United Kingdom Carlo van Nistelrooy +44 20 7692 8344 c.vannistelrooy@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 Batronix www. ba tronix. com/go/34 ctsvntC Cleverscope www. cleverscope. com {dlr Hss rpr: DLP Design www.dlpdeslgn.com Eurocircuits www. elektorpcbservlce. com stress pc b Express PCB www. expresspcb. com 78 45 29 67 77 Labcenter www. labcenter. com. | -1 i (CO Pico www.plcotech. com/ps243 nPoioiu Pololu EoboCtci * ei&sIkmIgi, www.pololu.com Saelig www.saelig.com 92 91 39 29 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 June 2014 7 •Projects Android User Interface Builder By Jens Nickel (Elektor Germany) A user interface is almost always needed when controlling and testing a piece of hardware. Ideally the interface would show data on a display and provide a keyboard for entering commands. Surely it should be possible to use a smartphone for the job? The FTDI FT311D is a flexible bridge that can interface your circuit to an Android smartphone or tablet. It offers options for seven digital outputs, four PWM outputs, asynchronous serial and I 2 C and SPI interfaces. To make things simple we have designed a small board to carry the chip: introducing the 'Elektor Android breakout board'. Explore the FT311D Android Bridge A large proportion of electronics projects, includ- ing those published in Elektor magazine, includes a serial interface over which readings are trans- mitted and commands are received, typically in the form of ASCII strings. A terminal program, running on a PC, is normally used fortesting and sometimes even in normal operation. However, even in laptop form such a computer can be cum- bersome to use as well as noisy and expensive. Smartphones and tablets offer a more conve- 8 June 2014 www.elektor-magazine.com FT311d Android Bridge nient alternative, and their touchscreen displays allow a pleasant control interface to be provided for the user. On the technical side the main obstacle to this idea is that the only usable interface to the out- side world offered by smartphones and tablets is a USB slave port. This means that our circuit must include a microcontroller implementing a USB host interface and we have to get involved in writing the firmware to handle the interface protocol. We also have to make sure that the operating system running on the mobile device is capable of sending and receiving bytes over USB under the control of a user-written application. Open accessory Fortunately the last problem at least has been solved for all modern Android smartphones and tablets. Google, the company responsible for developing the majority of Android, already has its finger on the pulse: recognizing the demand for an interface to RGB LED light shows, ser- vo-controlled robots and other such 'maker' projects, it introduced in version 3.1 of Android the so-called 'Android Open Accessory', or AOA, mode. This offers the possibility of simple com- munications with external hardware over USB [1], with no need to write or install special USB drivers in the operating system. Internally two USB bulk endpoints are provided (for input and output), allowing data to be transmitted and received at up to 12 Mbit/s (USB Full Speed). For more infor- mation on how USB works see the Elektor article 'Inside USB' [2]. The external hardware must pro- vide USB host functionality and the mobile device can also be charged over the USB port. When a board with suitable hardware (called an 'acces- sory') is plugged in, an AOA-enabled Android device will recognize it from its USB descrip- tors [3]. If the developer so wishes, an specified application can be launched automatically when the hardware is connected. Support is of course available to Android developers working on such hardware and software [4]. Nev- ertheless, designing hardware to provide USB host functionality and writing the corresponding firm- ware will be a daunting prospect for many, as the USB standard is rather complex, particularly when it comes to making 'plug-and-play' work reliably. A neat device Taking the complexity out of designing USB inter- faces is something that Scottish chip designer FTDI has been working on for many years. Its best-known product is perhaps the FT232, an easy-to-use USB-to-serial converter. More recently the company introduced a programmable device with USB host functionality (the 'Vincu- lum'), which makes it easy to design hardware that, for example, is capable of accepting USB memory sticks. Around two years ago FTDI brought the FT311D [5] on to the market. Like the Vincu- lum, this device provides a USB host port and a number (seven, in this case) of spare pins for controlling other hardware. To make it easier to use the chip FTDI supplies it ready-programmed with firmware to implement the whole USB com- munications stack including the AOA protocol: see the block diagram in Figure 1 . The bridge chip has a range of different interface modes. In the simplest case the seven pins of the FT311D can be used as digital inputs and outputs (GPIOs). Other modes provide for the output of PWM sig- nals, asynchronous serial communications, and I 2 C and SPI bus interfaces (both as master and slave). The I 2 C option alone opens up the possibil- ity of connecting a huge range of special purpose devices to the FT311D, from port expansion chips and A/D converters to real-time clocks. Practi- cally any project, therefore, can be connected to an Android device using the FT311D bridge. The interface mode is simply selected by the Figure 1. Block diagram of the Android breakout board. The FT311D and the FTDI library in the Android app handle the USB communications protocol: external hardware can be controlled (for example over an I 2 C bus) by calling simple functions such as 'WriteDataQ'. www.elektor-magazine.com June 2014 9 •Projects Figure 2. FTDI provides demonstration Android apps: this example allows control of digital inputs and outputs. Compatibility All Android devices running version 3.1 (Honeycomb) or above support Android Open Accessory mode. Your device can tell you which Android version it is running: on our Samsung Galaxy Tab it is under 'Settings', 'About device'. Some devices running version 2.3.4 and above of Android also support AOA mode: devices vary depending on whether the manufacturer happened to include AOA support when customizing the operating system. For older Android devices an alternative possibility for connecting to external hardware is the Elektor Andropod module, which uses a pre- programmed Vinculum device to communicate using the Android Debug Bridge (ADB). The module is available from Elektor [10]. level on three digital input pins. For flexibility these can be connected to jumpers or switches (see the text box 'Interface modes'). It is not possible to configure the device using a PC pro- gram or similar. The simple route to an app The manufacturer has designed a simple protocol for each of the interface modes. Packets contain- ing a couple of bytes of payload data flit back and forth over the USB connection to instruct the FT311D how to set its outputs and read back its inputs. In each case the first byte in a packet from the smartphone or tablet to the device rep- resents the command: in GPIO mode there are three different commands to configure the pins as inputs or outputs, to set or clear the outputs, and to read back the inputs. In PWM mode a dif- ferent command sets the mark-space ratio from 5 % to 95 %, the byte immediately after the command specifying the PWM channel (from 0 to 3). Further commands configure the I 2 C, UART and SPI interfaces and read and write data over them. The commands are fully documented in the 'FT31XD Programmer's Guide', which can be downloaded from FTDI's website [5]. This protocol is of course handled inside the FT311D by its pre-programmed firmware. On the Android device side the main jobs are to assemble the command packets and to handle the protocol requirements of AOA mode on the USB interface. When an app is launched it can determine whether an FT311D-based accessory is in fact connected. Fortunately FTDI supplies a suite of Java library files, one corresponding to each mode of the chip, to handle these tasks, and given a basic knowledge of Android programming it is easy to integrate these libraries into your own pro- gram. In the case of GPIO mode, for example, the library file FT311GPIOInterface.java provides the functions ResetPort, ConfigPort, WritePort and ReadPort. The library files are also embedded in small Android demonstration programs, each of which provides a graphical user interface on the smartphone or tablet. The GPIODemo app (see Figure 2), for example, displays seven buttons to control the outputs and seven 'LEDs' to indi- cate the status of the inputs. These demonstra- tion projects, eight in all, not only provide a way to test the chip and its connections, but can also 10 June 2014 www.elektor-magazine.com FT311d Android Bridge Figure 3. The board (not including the screws) can be purchased from Elektor ready-built and tested. form a basis for further app development. The demonstration projects and the libraries are in the Android.zip archive: this can be downloaded from FTDI's website. Breakout board To make it easier for our readers to try out this neat device, Elektor Labs staffer Ton Gies- berts has designed the 'Elektor Android break- out board', a small board available ready-built from Elektor (Figure 3). The circuit diagram is shown in Figure 4. Ton was (in part) inspired in his design by an article on the FT311D by Jeff Bachiochi published in our sister magazine Cir- cuit Cellar in December 2013. The Android tablet or smartphone is connected to Kl, a USB A socket, on which a charging volt- age VUSB (nominally 5 V) is also provided. The Android device, the FT311D and any other con- nected hardware are powered over K3, a micro USB socket. This choice has the advantage that the power adapter supplied with the smartphone or tablet, which normally uses the corresponding type of plug, can be repurposed. Low drop-out regulator IC2 produces the 3.3 V supply required by IC1, the FTDI chip. External hardware is connected to K2, which carries the relevant signals from the FT311D as well as power at 5 V and 3.3 V. It is also possible to power the board and the Android device over the 5 V pin on this header. Pins CFGO to CFG2, which set the interface mode of the device, can be pulled to ground using jump- ers. If a jumper is omitted, an internal pull-up in the device pulls the input high. FTDI suggests connecting an LED to the /USB_ ERR output, which it calls the 'Error LED'. How- ever, this is misleading: the LED will light con- tinuously when the FT311D has successfully established a connection with an AOA-compati- Figure 4. The circuit is built around the FT311D. The 5 V supply is provided over micro USB socket K3. Component List Resistors R1,R2 = 27ft, 0.1W, 1%, 0603 R3,R4 = lOkft, 0.1W, 1%, 0603 R5 = 620ft, 0.1W, 1%, 0603 R6 = lkft, 0.1W, 5%, 0603 Capacitors: C1,C2 = 47 pF, 50V, 5%, COG/NPO 0603 C3,C6-C9,C11,C13 = lOOnF, 25V, 10%, X7R 0603 C4,C5 = 27pF, 50V CIO = 4.7pF, 6.3V, 10%, X5R 0603 C12 = lOpF, 10V, 20%, X5R 0603 Inductors LI = 600ft @100MHz, 0.38ft/0.5A, 0603, Murata BLM18AG601SN1D Semiconductors D1 = PRTR5V0U2X TVS diode LED1,LED2 = LED, 0805 IC1 = FT311D-32L1C-R IC2 = KF33BDT-TR, LDO Miscellaneous Kl = USB-A socket, PCB mount K2 = 10-pin pinheader, 0.1" pitch; round pins for plugging onto a breadboard (e.g. Harwin D01-9923246) K3 = Micro-USB-B socket, SMD JP1 = 6-pin (3x2) pinheader, 0.1" pitch, incl. 3 jumpers XI = 12MHz quartz crystal, 20ppm, 18pF, 5x3. 2mm PCB # 130516-1 vl.l [6] or Elektor Android Breakout Board, ready assembled and tested, Elektor Store # 130516-91 [6] +3V3 O C6 | C7 | C8 lOOn lOOn lOOn C9 lOOn Kl USB A VUSB O D1 _L PRTR5V0U2X VUSB Q T R6 < i I Ik | j LED2 ^ ^ i- Tc r 600ohm POWER r@iooMHz _L ■@100MHz |Q2 +5V KF33BDT-TR IOBUS6 IOBUS5 IOBUS4 IOBUS3 IOBUS2 IOBUS1 IOBUSO CJ T- CM O O O o o o m 11 12 m ]h CO in C5 c 5 C j> c p "M CO JP1 CD T- CM 0 0(3 o o o Micro USB B +5V O K2 31 "'J 30 ■VJ 29 ■'J 26 ■VJ 25 ■VJ 24 ■VJ 23 ■VJ ■cj +5V +3V3 106 105 104 103 102 101 IOO 130516 - 11 www.elektor-magazine.com June 2014 11 •Projects Interface modes ble Android device, and so Ton felt it was more appropriate to label it simply 'USB LED' in the circuit diagram. The LED flashes when an error occurs; if an Android device that does not support accessory mode is connected, it remains dark. The Elektor Android breakout board can be pur- chased ready-built and tested [6]. A header is soldered at K2, making it easy to plug the unit into a breadboard. It is a good idea to fit two spacers or bolts to the holes on the opposite side, as shown in Figure 5. Test and demonstration For initial testing download the demonstration projects from the FTDI website [5]. In each case inside the /bin directory there is a .apk file: this is roughly the Android equivalent of what would be a .exe in the Windows world. Connect the smart- phone or tablet to the PC and copy the .apk file into the Android device's file system, for example into the Download directory. The smartphone or tablet now has to be configured to allow such downloaded applications to be installed. In the case of our Samsung Galaxy Tab this involved ticking the 'Unknown sources' box (under 'Set- tings', 'Security'). Now navigate to the .apk file in the device's file system (under 'My Files', 'Down- load') and tap on it. Normally the Android device will ask if you wish to install the appli- cation. If this does not work, one of the installer apps avail- able for free download from the Google Play Store may be able to help. The best example to try first is the GPIODemo app. Install the app and configure the breakout board for GPIO mode by fitting all three con- figuration jumpers. Next apply power to the board, either from a PC using a micro USB cable or using a suitable micro USB power adapter, and the power LED should light. Now connect the tablet or smartphone to the board. LED1 should now light, 12 June 2014 www.elektor-magazine.com JP1 allows one of the six available interface modes to be selected: GPIO (digital inputs and outputs), PWM (mark-space ratio from 5 % to 95 %), I 2 C master, asynchronous serial, SPI master and SPI slave. Pins IOO to 106 on K2 change behavior depending on the interface mode selected: the table also shows the pin numbers for the FT311D chip. Modue GPIO PWM I 2 C Serial SPI Master SPI Slave CFG2 15 GND GND GND GND open open CFG1 14 GND open open GND GND GND CFGO 12 GND GND open open open GND IOO 23 IOO PWMO SCL TXD IOl 24 IOl PWM1 SDA RXD 102 25 102 PWM2 RTS 103 26 103 PWM3 CTS CS CS 104 29 104 TXEN* CLK CLK 105 30 105 MOSI MOSI 106 31 106 MISO MISO TXEN = transmit enable for RS-485 line driver FT311d Android Bridge and simultaneously a dialog box should appear on the Android device asking whether the GPI- ODemo app should be launched automatically in the future whenever the hardware is connected. When the app is running the user interface appears as shown in Figure 2. The upper area allows you to select whether each GPIO pin is an input or an output: on touching the 'Config' button the appropriate command is sent to the breakout board to put the settings into effect. The levels on the outputs can be toggled by touching the white buttons and then touching 'Write'. You can verify the results using a multimeter or more conveniently by plugging the FT311D board into a breadboard and wiring the outputs to ground or the 3.3 V supply via LEDs with series cur- rent-limiting resistors, as shown in the picture at the beginning of this article. More information on all the demonstration apps and corresponding test circuits can be found in the 'FT311/FT312D Demo APK User Guide', which can be downloaded from the FTDI website [5]. In the Elektor Labs we tried out the I 2 C mode of the device by connecting the I 2 C communications pins to a Gnublin relay board [7] [8] : see Fig- ure 6. Note that in the demonstration app the field labeled 'Device Address' must be filled in with the address of the target I 2 C device omit- ting the least-significant bit (which is used to distinguish between read and write commands on the bus). We also carried out some interesting experiments with two FT311D boards, one configured as an SPI bus master and the other as an SPI bus slave. We connected the two boards and then found we could send bytes from one Android device to another: data sent from the master app when 'Write' is touched are immediately displayed by the slave app. And conversely, data entered in the slave app with 'Write' will be read into the master app when it is given the 'Read' command. We hope that the above has given you a glimpse of the possibilities that this board opens up and we are sure you will think up lots of exciting new projects using it. ( 130516 ) Figure 5. A breadboard is the ideal foundation for experimenting. Figure 6. The Gnublin relay board can be controlled over its I 2 C bus. Web Links [1] http://source.android.com/accessories/custom.html [2] www. elektor-magazine. com/090992 [3] http://source.android.com/accessories/aoa.html [4] http://developer.android.eom/tools/adk/adk2.html#src-download [5] www.ftdichip.com/Products/ICs/FT311D.html [6] www. elektor-magazine. com/1305 16 [7] www. elektor-magazine. com/130 157 [8] www. elektor.com/gnublin-relay-module- 130212-91 [9] www. elektor-magazine. com/1 10405 [10] www.elektor.com/110405-91-andropod www.eIektor-magazine.com June 2014 13 DESIGNSPARK PCB Lathe Tachometer Feat. Arduino Micro & OLED By Andre Jordaan (Switzerland) Here's a non-invasive, all electronic add-on to display the running speed (rpm) of your lathe or milling machine, be it CNC or vintage. It's state of the art— witness the use of an Arduino Micro board and a .96 inch OLED display for instantaneous readout. The little instrument also has a clock displaying the equipment running time. Attention Bridgeport lathe and milling machine users; get in touch with an electronics geek and have him build this circuit for you. Attention Arduino users: build this circuit for a nearby Bridgeport lathe owner and get access to his prize machinery. In this project a reflective IRED / phototransistor device is used as a sensor to produce a retrofit readout of the number of revolutions of a spin- dle (or "shaft") on a lathe, a milling machine or a similar piece of equipment in the metalwork- ing toolshop. Without even scratching the surface of elemen- tary metalworking and finishing, electronicz peo- ple should know that the turning speed is crucial for anything that cuts, drills, mills, finishes or polishes metal, wood, glass, and recently, hard plastics, Teflon® and rubber too. In the case of a round steel bar being milled to end size, the turning speed used to do the first couple of rough passes using toolbit TV at angle x may differ considerably from that applied much later for an ultra-smooth surface finish using toolbit 'B' at angle y. In both cases, the shaft speeds have to be set and verified by the operator using 14 | June 2014 | www.elektor-magazine.com Lathe Tachometer whatever gears or reduction drives are available on the machine. To the metalworker, the turning speed his prized machine is running at equals the supply volts and amps to the electronics engineer. Get the turning speed (=voltage) wrong and you risk destroying your precious stock material (=64-bit ARM MPU), object being created (=Linux dev system) and/ or $50K Bridgeport lathe (=128-bit LeCroy logic analyzer). =You don't want that to happen. Where we write spindle or shaft in the remainder of this article of course we mean chuck, 3-claw head, 4-claw head, boring head, end mill, polish pad, drill, tap, etcetera , since all of these tools are fitted eventually to the powered shaft or spindle of the lathe or milling machine. How it works As with most applications of embedded technol- ogy the schematic in Figure 1 does not reveal a lot about the workings or aim of the circuit. In fact, you could be looking at NASA's latest alliga- tor counter for use at Cape Canaveral. One of the reasons for the happy scarcity of components in the schematic is the use of an Arduino Micro board in position MOD(ule)l, resulting in all manner of things being controlled and decided by software rather than discrete parts. The Arduino Micro is first programmed with the project firmware of course via its micro USB connector. The unregulated supply voltage from a 9-V 6LR22 alkaline battery (or a 7 V to 9 V power adapter) enters the circuit on Kl, and gets reduced to 5 volts by stabilizer IC1. LED1 acts as a Power On indicator. The Adafruit OLED (organic light emitting diode) display module [1] is connected straight onto 8-pin connector SV1. The OLED module with its monochrome, 128 x 64 graphic display gets its 5-volts supply voltage from the same regulator as the Arduino Micro. Other OLED modules may be used but be sure you match their pinout to the board. The only input device to the circuit, a reflective IRED / phototransistor ("reflective optical sen- sor" device) like the one at Yourduino [2], is connected on K2. The LED inside the device is again powered from the +5 volts rail via R3. It is on as long as the 5-V supply voltage is pres- ent. The phototransistor's SENS+ pin is pulled to +5 volts by R4, and the signal fed to the INT/D3 line of the Arduino Micro board. A piece of matt black adhesive tape or similar is secured around the lathe's shaft, leaving a narrow gap (of about 3 mm). Whenever the light emitted by the LED reflects off the shaft at the position of the gap, it illuminates the internal phototransistor, caus- ing the SENS+ line to drop logic Low, and High again when the LED light is not reflected. Hence the speed of the rising edges of SENS+ signal indicates the shaft speed. Note that due to reduc- tion gears being present in the lathe or milling machine the shaft speed is not the motor speed. The Arduino Micro can be reset to force it to start executing its firmware from scratch by press- ing SI. Finally, the function of LED2 on Arduino Micro line D7 is free to assign by the programmer— like OVER REV or CALL KEITH [4]. Figure 1. Schematic of the precision rev counter for CNC lathes and milling machines. All measurement and control functions are handled by an Arduino Micro plug-on board. IC1 www.elektor-magazine.com | June 2014 | 15 DESIGNSPARK PCB Figure 2. Printed circuit board layout designed by Elektor Labs for the project. Component List Resistors R1,R5 = 390ft 5%, 0.25W R2 = lOkft 5%, 0.25W R3 = 100ft 5%, 0.25W R4 = 22kft 5%, 0.25W Capacitors C1,C2 = lOOnF 10%, 100V, 5mm pitch C3 = lOnF 10%, 100V, 5mm pitch Semiconductors IC1 = 78L05Z LED1 = LED, yellow, 3mm LED2 = LED, 3mm, color t.b.d., optional, see text Miscellaneous MODI = Arduino Micro, Farnell/Newark # 2285194 SI = pushbutton, PCB mount, 6x6x9. 5mm SV1 = 8-way pinheader receptacle K2 = 4-way pinheader receptacle K1 = 9V battery connector clip + wires Reflective Optical Sensor, like TCRT5000 Monochrome 0.96" 128x64 OLED graphic display, Adafruit # 326 (UG-2864HSWEG01) 34-pin DIP socket for Arduino Micro (DIY from SIL pinheader receptacles) PCB # 130470-1 Listing 1. Excerpt from Firmware. ino //to be done when when sensor is interrupted: void i nter rupt_rpm_time ( ) { // current_i nter rupt_time = microsQ; // if (microsQ - previous_i nterrupt_time > (1/fMax)) { current_i nterrupt_ti me = (microsQ - previ ous_i nterrupt_ti me) ; previous_i nterrupt_time = microsQ; // Serial. print("+") ; // Serial . pri ntln (current_i nter rupt_time) ; // di gi talWri te (ledPi n , HIGH); } void calc_run_Time() { //calculating running time unsigned long elapsed; unsigned long over; elapsed=millis() ; h=int (elapsed/3600000) ; over=elapsed?63 6 0 0 0 0 0 ; m=int (over/60000) ; over=over?660000 ; s=int (over/1000) ; ms=over?61000 ; } Software The program "Firmware. ino" is recommended educational reading if you want to understand all the ins and outs of the control program, and how it got developed and tweaked. The program is richly commended by the author. Arduino users will know how to transfer the file to their Arduino Micro board, starting from file 130470-1. zip, which can be downloaded free of charge at [3]. The Arduino program waits for a rising edge at its INTI input and uses five rising edges to com- pute the average time between them. Using some math the rpm (revolutions per minute) is calcu- lated and sent to the OLED display. A snippet of the program code is printed in List- ing 1. Here we see how the interrupt produced by the sensor gets handled, and the Tachometer's internal clock is ticking to display the "up" time. Build it, use it The printed circuit board designed by Elektor Labs has through-hole parts only and its component overlay is given in Figure 2. Let the electronics people handle the programming, board stuffing, soldering and wiring, and the mech people do the mounting of the board in a case, and the 16 | June 2014 | www.elektor-magazine.com Lathe Tachometer Figure 3. The Arduino Micro board secured on to the solder side of the tachometer board (early prototype). Figure 4. The Lathe Tacho board has boards fitted at either side: an Arduino Micro at the solder side, and a .96" OLED display at the front. Note the use of SIL pin strip receptacles to ensure the correct mounting distance. mounting of the reflective sensor close to the powered shaft of their lathe or milling machine. If you are a mechatronics fan you do both jobs with ease, in the proper sequence. A slotted optocoupler and a vane fitted at a suit- able place on the machine shaft may also be suitable but the assembly is more intricate to mount— if not invasive. If your machine shaft is not reflective, stick a small piece of paper on it to do the light reflection. The Arduino Micro is plugged on to the rear (sol- der) side of the Tachometer board (Figure 3); the OLED unit, on to the front (component) side (Figure 4). After switching on, the Arduino Micro initializes, then displays the Elektor logo and "Elector Elec- tronics" (s/c), then "Tachometer by A. Jordaan" and the firmware version number (Figures 5a; 5b). Next, the current rpm value is displayed, and the 'up' time of the tachometer (so you can bill your customers and come across serious). Figure 5. The Lathe Tachometer startup screens. The OLED readout should blend in beautifully with all manner of tech info and lights that can be seen in a 21 st century metalworker's toolshop. should also be easy to add more channels and other controls like relays etc. One wish of the author is send the count pulse on to Mach 3— the control software for his CNC machine. ( 130470 ) Over to you The project being open in terms of hardware and software, there should be nothing in your way to do custom adaptations like getting that k right. It will be insightful for sure. The hardware for exam- ple may be adapted to support different types of sensor types like Hall effect. Other possible applications include a step counter, a rev counter for model planes, a PWM percentage meter, or a simple event driven animation on the display. It Web Links [1] OLED display: www.adafruit.com/product/326 [2] Reflective Infrared Sensor: http://yourduino.com/sunshop2/index.php?l = product_detail&p=217 [3] Arduino Micro firmware: www.elektor-magazine. com/130470 [4] Keith Fenner's Turn Wright Machine Works on Youtube: www.youtube.com/user/KEF791 www.elektor-magazine.com | June 2014 | 17 •Projects Touch-2-Switch Versatile capacitive switch in a wall box By David Ardouin (France) [2] This capacitive-detection dual wall touch-switch, designed to fit into domestic elec- tric wall-boxes, uses analog technology throughout. A single multi-purpose version that you can configure as you wish to function as a simple on/off switch, a 2-way switch, or momentary button, on two independent channels. At low cost, modern- izing your home electrics has never been so tempting. Specifications • changeover, 2-way, or momentary switch • replaces a standard mechanical switch in a wall box • choice of controlling one or two separate lighting circuits • configurable illuminated indicator • modern appearance, easy to reproduce, 230 V/50 Hz or 120 V/60 Hz • no programmed devices • configurable using just a soldering iron In these times of home automation and smart electrical installations, the big manufacturers are vying with each other in ingenuity. It seems to be a ferocious fight, judging by the proliferation of models of wall switch on offer, from the simple white changeover switch to automatic systems of controlling lighting for any home by phone or touch tablet— and not forgetting the silent, round, square versions you can customize to your heart's content. I'd always dreamt of bringing my home electrical installation up to date using 18 June 2014 www.elektor-magazine.com touch switches, but couldn't quite bring myself to spend a fortune on this sort of accessory. So that's why I decided to design one that would exactly meet my requirements. The new touch switch will: • replace a mechanical switch and fit into a standard flush-mounting wall-box, attrac- tive and modern in appearance, yet easy to reproduce; • give the choice of controlling one or two sep- arate lighting circuits and operate as a sim- ple changeover switch, a 2-way switch, or as a momentary push-button; • have an indicator configurable as either a constantly-illuminated pilot light or as an output state indicator. Look as hard as you like, even with the major names in this field, but you won't find any prod- uct with these specifications. I must admit, however, that changing to an elec- tronic version inevitably implies the switch is going to consume some power all the time— but I've kept this to the strict minimum. It does also require the presence of a Neutral (cold) wire— which may not be present in lighting circuit boxes. Tips I suggest exploring the circuit diagram (Fig- ures la and lb) by following the line of think- ing that led me to this solution. The first crucial choice was picking a technique for switching a power of a hundred or so watts. Exit the triac because of instability at low loads and a mon- strous consumption of several tens of milliamps. Using a MOSFET transistor and diode bridge promised minimal losses, but though it worked fine for a single channel, it caused me unaccept- able problems running two channels in parallel. What's more, the diode bridge would mean the low-voltage supply could no longer be achieved using a classic capacitive dropper; it would have been necessary to revert to a power resistor with deplorable efficiency. No question either of using a relay, because of its holding current. A con- ventional relay, no— but maybe a bistable relay? Much less common than their monostable coun- terparts, latching relays use power only at the moment of changing state. A pulse of just a few SAFETY As there's no transformer, this sort of power supply has the advantage of being very compact— but it does not provide voltage isolation. As the internal ground of the circuit is directly connected to the Live (hot), it is strictly forbidden to handle the circuits, including the capacitive part and the electrodes, when the supply voltage is present. User safety is only ensured once the switch is enclosed within its back box. For testing and for any handling in the presence of hazardous voltage, get into the good habit of disconnecting the circuit to be tested before connecting your measuring instruments to it, then powering it back up to read the measured value, and lastly, disconnecting the power again before moving on to the next step. TR1 TR2 Example of isolation transformer created by hooking up two 12-V power transformers back-to-back. For the testing, I recommend making up an isolating transformer from two 230 V/12 V (US: 115V/ 12 V) transformers rated at a few VA wired back-to-back. A dangerous voltage will still be present on the output, but only across the two end terminals. This accessory will make it easier and safer for you to check the circuit is working properly. You will be able to switch the relays, but not connect up an actual load. www.elektor-magazine.com June 2014 19 •Projects Figure la & lb: Circuit diagram in two sections: right, the high- voltage circuit; left, the low-voltage circuit. Unless electrically isolated from the power line supply, all the conducting parts of this circuit are live! Despite their high values, C2 and C3 are non-polarized capacitors. I 1 Guaranteed microcontroller-free! tens of milliseconds is enough to make them switch over; then they don't consume anything at all until the next time they switch. Perfect! In the 12-V version, relays K1 and K2 (Fig- ure 1 b) draw a current of 18 mA for 20 ms when switching. A "luxury" solution would have been to drive the coil via an H-bridge. But I pre- ferred to store the energy needed for switch- ing in capacitors C6 and C14, which provide the polarity inversion depending on the sense of the edge applied by U5 and U6. These latter, helped by Q1 and Q2, form lev- el-shifters to amplify the drive signal voltage and supply the current needed by the relays. These devices are normally used to drive MOSFET gates, but they fulfill their role marvelously here for a derisory cost. The AC powerline supply (J 1) makes use of the impedance of a capacitor (C5) to drop the volt- age to the required value, with minimal losses. The choice of this component depends on what powerline voltage you have; choose the 150 nF for 115-120 V/60 Hz or 100 nF if your domes- tic grid is 230 V/50 Hz. A rectifying diode (Dl) and zener (D2) then provide regulation to 12 V. Unfortunately, this kind of circuit always draws 20 June 2014 www.elektor-magazine.com Touch-2-Switch / R6 R7 VCC +12V \ Chi Set Chi Reset Ch2 Reset Ch2 Set \ some power, whether the rest of the circuit is powered or in stand-by. Now it was clearly out of the question that, to supply the 20 or so mil- liamps needed to operate a relay for very short periods of time, I would let such a circuit dissipate some 240 mW in heat all the rest of the time. Since the relays only consume power when they are being driven, I deliberately under-rated their supply by a factor of six. It charges at its own speed the large reservoir capacitor Cl, which is used as a buffer when power is drawn; in prac- tice, this reserve is enough to withstand even the most frenetic pressing! When the circuit is powered down, R6 and R7 discharge C5 rapidly, so as to avoid this capaci- tor holding a potentially lethal charge. For work- ing voltage reasons, two resistors have delib- erately been used in series; under no circumstances must they be replaced by a single resistor! This remark applies equally to R1 and R2, which limit the current surge when the circuit is powered up. Varistor R8 protects the circuit from any spikes. Fuse FI is a 5-A type that will protect against possible overloads or wiring errors; it corresponds to the maxi- mum current relays K1 and K2 can take. Go for a slow- blow type (T), which will be more robust against the surge current from high- power filament lamps. The input and output connec- tors are spring terminals— much more reliable than traditional screw terminal blocks. Always remember that any work involving the mains supply must be done with the power off. Details Now let's take a look at the control circuit (Figure la). Surprise: there's no micro- controller here! It's my delib- erate policy, a bit of nostal- gia... The capacitive detection is provided by two half-moon-shaped electrodes, positioned behind the switch front panel and con- nected to J7-1 and J8-1. U2 and U3 are special- ized ICs for capacitive detection. Although at first sight deceptively simple, in fact they include sev- eral sophisticated algorithms that are essential for guaranteeing faultless detection overtime. Their outputs have one specific feature that gave me a bit of a headache: in order to confirm the device is working correctly, regardless of its logic state, the output regularly goes briefly high-impedance, which produces pulses of erratic logic levels. In order to filter these out, I've added Cll and C15, the values for which are not arbitrary; they are just enough to filter the pulses without degrading the rise-time too much, as that would be hinder proper switching of the flip-flops in U4. Capacitors C9 and C13 directly define the reactivity of the capacitive / www.elektor-magazine.com June 2014 21 •Projects Figure 2. The dual switch assembled. button. To make the detection more sensitive, you can increase their value up to 10 nF; on the other hand, if you experience unwanted triggering, you can reduce the value down to 1 nF. Diodes D5 and D6 form a logic OR which, depending on the configuration of solder bridge S4, will allow the outputs from both capacitive detectors to be combined so as to form a single electrode driv- ing just the first output. A solder bridge between its pads 2 and 3 will activate the "single switch" mode, while bridging 1 and 2 give you two inde- pendent channels. In the same way, SI and S3 The behavior is configured using just a soldering iron by applying (or not) blobs of solder on bridges S1-S10. Channel 1: S3 1-2 momentary mode S3 2-3 two-position switch mode S5 bridged; S6 & S7 open indicator 1 always lit (pilot light) S6 bridged; S5 & S7 open indicator 1 lit while pressing S7 bridged; S5 & S6 open indicator 1 follows output state S5, S6, & S7 open indicator 1 disabled Channel 2: SI 1-2 two-position switch mode SI 2-3 momentary mode S4 1-2 Channels 1 & 2 independent S4 2-3 Channel 1 only S8 bridged; S9 & S10 open indicator 2 always lit (standby light) S9 bridged; S8 & S10 open indicator 2 lit while pressing S10 bridged; S8 & S9 open indicator 2 follows output state S8, S9, & S10 open indicator 2 disabled let you choose between the momentary contact operating mode (bridge across 1 and 2 for SI and across 2 and 3 for S3) or latching contact mode at the flip-flop output (bridge across 2 and 3 for SI and 1 and 2 for S3). The first mode is useful for an installation where there are a number of buttons all operating a remote-controlled switch or timer in the electrical distribution board. The drive signals then go on to the power board via connectors J3 and J5. Touch switches no longer give the mechanical feedback of their predecessors, which is why it's worth using illuminated indicators to confirm the action requested. For a single switch, D7 only will be fitted in the middle position, while with two separate channels D8 and D9 will be used. Capacitors C17 and C18 are recommended [1] in the event that the electrodes detect impedance changes (of the MOSFET transistors Q5 and Q7, as it happens) that might disrupt their operation. Bridges S5-S10 define the behavior of the LEDs with a choice of permanent pilot light, touch con- firm, or copying the output status (see Table). To drop the 12 V voltage present on J4, 1 chose a step-down regulator (Ul) specially designed for low powers. With its associated components, it supplies a maximum current of 10 mA @ 3 V — plenty to power this little world. Soldering iron in hand... There's a downside to the miniaturization of surface-mount components: they're jolly small between our big fingers. So I used 1206 format passive components, a little easier to solder. The three PCBs are supplied as one board (Figure 2) 22 June 2014 www.elektor-magazine.com Touch-2-Switch 100% soldering iron configurable - a dodge to reduce manufacturing costs (at the expense of a few hours of extra work on routing). It'll be easier if you keep them together during the soldering stages. Start by soldering all the surface-mount components on the top side, then continue with the SMDs on the underside. If you choose to use only a single way of your switch, fit only LED D7. For two separate channels, fit D8 and D9, and not D7. On the assembly drawing, the rectangle in the corner of the LED symbols indicates the position of their cathodes. Then fit the through-hole components on the power circuit (130272-3). The male and female headers that form J3-J6 will be soldered later, during assembly. The capacitive detection circuit doesn't require any soldering for the moment, as the two copper electrodes are the sole components. Checking Temporarily link across J7-1 and J7-2 using a short length of flexible hook-up wire. Do the same with J8-1 and J8-2. Using a 9 V battery or a bench supply set to this voltage, power the logic sec- tion via connector J4-2, taking care to respect the polarity shown on the copper. If everything is OK, you ought to measure a voltage of 3 V across C3. Place your finger on the insulating side of one of the electrodes, the LED for the relevant channel should light at once; the capac- itive detection here always takes place through an insulating surface - do not touch the copper electrodes directly, operation will be erratic. On the "power" side, connect a voltmeter to the pins of J4-1 then power the circuit by applying the AC power supply line voltage to terminal block Jl. Never forget that the whole of the cir- cuit is now at a lethal voltage, and from now on you must not touch it. Check you have a voltage close to 12 V on J4-1. Now separate the three circuits using cutters, using a small, flat file to smooth the cut edges. Insert J3 to J6 in the positions provided, but for the moment solder only one pin on each of the headers. Stack the two "driver" and "power" cir- cuits together and check the connectors line up properly. Touch up your soldering if necessary, then finalize it all by soldering the remaining pins. Final assembly In order to give a professional finish and inte- grate perfectly into an existing electrical system, the electronics are preferably built in to wall box normally used to hide an electrical junction. In order to match my own installation at home in France, I chose the Odace range from Schneider Electrics. The fitting consists of three parts: the light grey mount that fixes to the wall-box, the white circular blanking plate, and the trim, which comes in different colors. To mount the electron- ics, the first step is to cut off the two lugs at the rear of the mount (Figure 3). A junior hacksaw or mini cutting disk will be perfect for this job. The first PCB, the electrode one, is going to be glued into the circular blanking plate (Figure 4). Apply a thin, even layer of epoxy adhesive all over the copper side of this board. I must emphasize it's vital that the entire surface must be evenly covered to avoid any air pockets that might disrupt the capacitive detection. You can then insert the glued-up PCB into the blanking plate, taking care to align the two parts as accurately as possible. Depending on the number of indi- cators installed (D7, D8, D9), drill holes in the blanking plate using a 3 mm drill and fit one or two light-guides (Figure 4). To finish this part, finally solder two 15 mm long rigid wires (e.g. resistor lead offcuts) to the pads J7-2 and J8-2. The detection board is assembled behind the grey mounting plate using four spots of epoxy adhesive in the corners (Figure 5), after having carefully inserted the two electrode connection leads into the corresponding pads. Before com- pleting the gluing, check that the LEDs are in line with the blanking plate light-guides— it's all too easy to get it the wrong way round. Lastly, solder pads J7-1 and J8-1. All that remains to complete the assembly is to plug the power part (Figure 6) onto the connectors provided. The cross-section view (Figure 7) shows the details of the stacked boards. The connections to be made for configuring as 2-way switches or momentary buttons are given in Figure 8a. Very often with most mechanical switches, you will find in your back box only a Figure 3. Modifying the mounting plate. www.elektor-magazine.com June 2014 23 •Projects Figure 4. Assembling the electrodes. Live (hot) wire (check the color used in your country) so you'll also have to run a Neutral (cold) wire (check color in your country) which you'll be able to pick up from the nearest socket outlet, for example. If you should inadvertently reverse the Phase and Neutral connections on Jl, the touch part, the LEDs, and the relays would all work normally, but the loads being controlled wouldn't light up. Check the wiring again carefully before closing up your installation. The markings R and O refer to the French identi- fication of the relay contacts translating to Rest Capacitors (miscellaneous) Cl = 470 |jF 25V, Panasonic EEEFK1E471AP, (1244419) C5 = lOOnF 305V, X2 Class, 15mm pitch, Epcos B32922C3104M (1112840) C6,C14 = lOOpF 25V, Panasonic EEEFK1E101AP (1244416) Inductors LI = 22pH 0.11A, Multicomp MCFT000190 (1711917) Diodes D1,D5,D6 = BAT54 (9526480) D2 = BZX84C12 (1902445) D7,D8,D9 = LED, yellow, Kingbright KPT-32 16SYCK (2099249) Semiconductors Q1,Q2,Q5,Q7 = 2N7002ET1G (2317616) U1 = TPS62120DCNT (1864820) U2,U3 = AT42QT1010-TSHR (1841593) U4 = SN74HC74D (9591680) U5,U6 = ZXGD3005E6TA (1904033) Miscellaneous Fl-1 = fuse holder, Littelfuse 64900001039 (1271673) Fl-2 = fuse, 5A slow, 5x20mm, Schurter 0034.3124 (1360818) Jl = 2-way PCB spring terminal block, 5.0mm pitch, Wurth 691414720002 (1841365) J2 = 4-way PCB spring terminal block, 5.0mm pitch, Wurth 691414720004 (1841367) J3-1,J4-1,J5-1,J6-1 = 10-pin pinheader, low profile, 0.1" pitch (1668506) J3-2,J4-2,J5-2,J6-2 = 10-way receptacle, low profile, 0.1" pitch (1668102) K1,K2 = relay, bistable, 12V, TE PE014F12 (9913459) R8 = varistor, 300V, Epcos B72205S0271K101 (1004358) GL1,GL2,GL3 = LED light pipe, Bivar PLP2-375, (2293497) PCBs 130272-1, 130272-2, 130272-3 (elektorPCBservice) (numbers in round brackets are Farnell/Newark order codes) Component List Resistors (SMD 1206, 5%) R1,R2 = 470 0.25W R3,R9,R11,R12,R29,R30 = 470kft R4,R19,R24 = 120kft R5 = 330kO R6,R7 = 2.2MO R10,R13,R27,R28 = lOkO R20,R22,R23,R25,R26,R31,R32,R33 = IkO Capacitors (ceramic, SMD1206, 20%) C2,C3 = 4.7pF 16V C4 = 22pF 50V C7,C8,C10,C12,C16,C17,C18 = lOOnF 50V C9,C13 = 4.7nF 50V X7R C11,C15 = InF 50V 24 | June 2014 www.elektor-magazine.com Touch-2-Switch Figure 5. Assembling the "small signals" circuit. Figure 6. Fitting the "power" section. Figure 7. Cross-sectional view of the assembly. and Operate. If the state of the LED indicator is reversed with respect to the load connected, all you have to do is swap the connection over between these R and O terminals. Figure 8b shows how to wire it up as a 2-way switch with other mechanical switches or IMPACT switches. As the configuration of each of the two chan- nels is independent of the other, you can even mix the two types of wiring on the same switch. Lastly, in the case of a configuration as a single channel, the connection will be made only to the terminals 01 and R2. If you're feeling adventur- ous, don't hesitate to send me photos of your own projects [2]! ( 130272 ) Web Links [1] Atmel - QTAN0079 "Sensor design guide": www.atmel.com/Images/docl0752.pdf [2] ardouin.david.projects@gmail.com Figure 8. Wiring as switch or momentary button (a) or as a 2-way switch (b). b Lm AC Fewer 2m 115V j^rijUaL. — www.elektor-magazine.com June 2014 25 •Projects Seismic Detector,, Using a piezoelectric sensor This simple circuit generates acoustic and visual alarms when it detects a shock, vibration or earthquake. It also has a relay that can be used to energize other devices or external indicators. By Wouter Eisema (Netherlands) Figure 1. This piezoelectric sensor from Measurement Specialties generates a voltage when it is moved back and forth. The author developed this circuit in response to the many earthquakes that have occurred in the Groningen area in the Netherlands in recent years as a result of 50 years of gas extraction in this province. It can also be used to detect passing trucks or other sources of vibration. The sensitivity is adjustable to allow the detector to be used under various conditions. Along with an LED and a buzzer for the visible and audible indications, there is a relay that can be used to energize other circuits or devices. A small 433-MHz (or 868-MHz) LPR (transmitter) could also be connected to the relay output for wireless transmission of the detector signal to a remote location. A simple transmitter/receiver combina- tion suitable for this purpose is also described in the article 'Wireless Signaling' in this edition of Elektor. Among other things, this arrangement allows the detector and transmitter to be mounted in a location that is not easily accessible. Operation The key component of this compact circuit is the vibration sensor (Figure 1). The LDTM-028K sensor from Measurement Specialties used here consists of a thin piezoelectric plastic film sealed in plastic, which has two solder pins at one end for fitting to a PCB and a threaded bush at the other end for attaching a pendulum or a weight. When the sensor is moved back and forth, for example by vibrations, the piezoelectric film generates a voltage that depends on the degree of bending and can be as high as 70 V or so. With very small motions (e.g. light vibrations) the signal level from the sensor is only a few millivolts, so a lot of amplification is necessary if you want to use it to switch something. For this purpose, the sensor is connected to the input of IC1, a type MCP601 opamp from Microchip (see the schematic diagram in Figure 2). This single-supply opamp with rail-to-rail output can operate with a supply voltage as low as 2.7 V. The gain of this opamp stage can be adjusted over a 26 June 2014 www.elektor-magazine.com Seismic Detector Figure 2. The circuit design is very simple, consisting of an amplifier stage (IC1), a pulse stretcher (IC2) and an indicator stage with a relay. wide range with trimpot PI. Diodes D1 and D2 on the non-inverting input of IC1 protect it against excessive voltage from the sensor. The opamp output is low under quiescent condi- tions. The output is connected to a pulse stretcher built around IC2a-IC2d. The output of the pulse stretcher is low when the opamp output is low; Cl is discharged and the outputs of IC2a, IC2b and IC2d are high. When the vibration sensor generates a pulse, the output of IC2c goes high, and it is kept high by IC2b until Cl has charged enough to cause the output of IC2a to go low. When the voltage on Cl reaches the necessary level, pin 12 of IC2d is pulled low by R3 and the output of IC2d goes high. The output of IC2b also goes high, and the pulse stretcher returns to its initial state. The next pulse from the vibra- tion sensor can be processed after Cl has dis- charged again. Diode D3 and resistor R3 ensure that on pin 12 of IC2d, a high level at the output of IC2a over- rides the signal level at the output of the pulse stretcher (pin 8 of IC2c). The pulse length of the pulse stretcher is approximately 20 seconds Component List Resistors R1 = 82kQ R2 = 470kft R3 = lOOkft Semiconductors D1,D2,D3,D4 = 1N4148 LED1 = LED, low-current, red, 3mm T1 = BC547 IC1 = MCP601 (Microchip) IC2 = 74HC132 Miscellaneous BZ1 = active piezo buzzer, e.g. Multicomp MCKPT-G1210-3916 SI = pushbutton with break contact RE1 = PCB relay, 3V (e.g. Omron G5V2H13DC) Sensor = LDTM-028K (Measurement Specialties) PCB # 130517-1 [1] Figure 3. All of the components (including the sensor) can be mounted on this small PCB. Depending on the actual application, the sensor can also be mounted on the underside of the board. www.elektor-magazine.com j June 2014 27 •Projects Figure 4. The sensitivity can be increased by attaching a metal strip to the sensor to act as a pendulum. The length and weight of the metal strip can be varied as desired. with the stated component values. It can be adjusted by changing the value of Cl (a larger value results in a longer time). The pulse stretcher output drives an LED via series resistor R5 and a transistor. The transistor in turn drives a mini buzzer and a relay connected in parallel. A larger alarm indicator or the mini transmitter described elsewhere in this edition (see "Wireless Sig- naling") can be connected to the normal- ly-open relay contact. Although the output stage may appear somewhat overendowed, with an LED indi- cator (R5/LED1), a buzzer (BZ1) and a relay (RE1), you can easily omit one or two of these options by simply not fitting the com- ponents concerned on the board. The entire circuit operates from a supply voltage of just 3 V and the quiescent cur- rent consumption is only 50 pA, so a pair of AA alkaline cells is sufficient to power the circuit for many years. A pushbutton switch with a normally closed contact is included in the supply voltage line. This can be used to cancel the alarm indication before the end of the stretched pulse period— a simple but effective solution. Assembly and use Although the circuit only consists of a few components, a PCB layout (Figure 3) has been designed for it to make assembly eas- ier. As usual, the layout can be downloaded free of charge [1]. Two pads for the relay contacts are joined together on the PCB. This may appear a bit strange, but it pro- vides more freedom in the choice of relay. Usually the pin for the common contact is in the middle (which is true for the type in the components list) and the pin closer to the relay coil is for the NC contact, but some relays (such as the AZ822 from American Zettler) have these pins reversed. There's not much that needs to be said about fitting the leaded components, which shouldn't cause any problems. If desired, you can use sockets for IC1 and IC2. The sensor is sol- dered directly to the PCB, and a metal strip acting as a pendulum can be attached later. It's a good idea to place the two AA cells for the power source in a battery holder, which can be fitted together with the PCB in a plastic case. When fitting the board in the case, bear in mind that it will be mounted upside down in use and the metal strip needs to be able to pass through the case and move freely. The unit can be mounted on the ceiling of the room you want to monitor, or on a wall using an angle bracket. The sensor can also be fitted on the under- side of the board if this is more convenient. Adjustment: After mounting the unit at the location to be monitored, adjust the sensitivity by turning trimpot PI to the point where the buzzer just stops sounding. It's a good idea to experiment with this a bit so that the alarm does not go off every time a truck drives by. You can also adjust the length of the metal strip attached to the sensor as necessary. The sensor and metal strip can also be housed in a plastic pipe (with a diameter of 10 cm [4 inches] or so) for protection, mounted so that the strip is free to move. This reduces the effects of wind and air currents on the sensor. ( 130517 - 1 ) Web Link [1] www. elektor-magazine. com/1 305 17 28 June 2014 www.elektor-magazine.com X ■ ■ ^ 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 DLP-I08-G 8-Channel Data Acquisition Only $29.95/ • 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 passport-size pc scopes er^at scopes for md use vvlt, laptop rate aslope. e-in color TFT-LCO and JO M H z SCOPE ^ ^ tri 500M5a/s Jest selling tPT-lcd. 30MHz SCOPE tencnscope witn ign-enaioOMHz 2-cf ' ' , fffEE ^ope carry * a integrated generator, «M(ft memory, very - DS2000A senes $833+ BS, FREE T !VIC£ SA NEW! 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 @ektor elektor post Tte thinning of a teau||fu[ Wen9s „ based life forms of the World unite! EJeto-.WJSr v nVK* £nj- J n-tfiiaami flve )■ to MMb ft*, bs , fa — J ‘i £ ^ "™"hr Bfo si P» mu™ T „.ju , v Tww n * ril, n wt C»et*r ' n "** n» ■«**, lnm w ri(w trujctl 1 . ijrv| picducS M-rJ Wt> hope (1 -j! "jw you ■ yv^i we recef ra J icc-, t- ctv ' W WV 1 ’ mo to «* pramr^ ** rwrt , lw , ^ fffti ei*Mo-rrwi ***** Hflnwpj - k-rwYTWrtMj Elektoj.TV goes Linux »entir Am fiuOg htMhHn t* W^TCH IT ON ELEKT&ft.TV ti Register today at www.elektor.eom/newsletter.L •Projects Microcontroller BootCamp (3) Serial interface and A/D converter BASCOM-AVR Options Compiler Communication Environment Simulator Programmer Monitor Printer COM port Baudrate Parity Databits Stopbits Keep T erminal emulator open O Use Existing COM ports COM2 ▼ 9600 ▼ None ▼ 8 ▼ 1 ▼ Default \y Ok Handshake None Emulation Font Backcolor NONE It I ^ 4, DIGITAL (PWM~) £ a. This instalment focuses on the analog to digital converter, which is effectively a voltmeter built into the microcontrol- ler. However, it does not have a pointer or a display, so you have to do a bit of work to be able to read the mea- surements. The A/D converter simply supplies data. In order to be displayed somewhere, this data has to be trans- mitted. That's where the serial interface comes into play. By Burkhard Kainka (Germany) Although most PCs nowadays have dispensed with the traditional serial interface, it is still widely used in the microcontroller world. This interface was originally developed to transfer serial data over a conductor. The individual bits obediently travel down the wire one after the other. The bit timing is precisely defined so that the receiver can make sense of the serial bit stream. A com- monly used data rate is 9600 bits per second, which is also called 9600 baud. In addition to the eight data bits of each byte, there is a start bit and one or two stop bits. Each data bit is pres- ent on the wire for an interval of approximately 100 ps (at 9600 baud). Print output Every ATmega microcontroller has a serial inter- face (UART) with RXD (PD0) and TXD (PD1) lines. These signals are TTL compatible, which means that the signal level is 5 V in the quiescent state and 0 V in the active state. By contrast, a COM port on a PC operates with RS232 signal levels. They are -12 V in the quiescent state and +12 V in the active state. For this reason, a periph- eral interface IC such as the MAX232 is often necessary to invert and adapt the signal levels. Instead of this, the Arduino board has a serial to USB converter that sends the data over USB. This means that you need a driver for a virtual serial port (such as COM2) on the PC. For pro- grams running on the PC, that makes the data transported over USB look like it entered the PC through a conventional serial port. This data can therefore be displayed using a standard terminal emulator program. We recommend that you use the terminal emu- lator program integrated into Bascom. You can open it under Tools > Terminal Emulator or with the key combination Ctrl-T, but you have to con- figure the right settings to make it work prop- erly. In particular this means selecting the right COM port (the same one you configured for the boot loader) and setting the right baud rate (in this case 9600). For the rest you can use the default settings: 8 data bits, 1 stop bit and no parity (Figure 1). Now you have to persuade the Arduino Uno to transmit something. That's easy in Bascom, thanks to the Print command. See Listing 1 for an exam- ple of how to use the Print command (note that all code files can be downloaded at [1]). This com- mand can be used to send output to a printer, 30 June 2014 www.elektor-magazine.com Microcontroller Bootcamp which explains its name. However, to avoid wast- ing paper it's better to send text and data to the monitor. The result is shown in Figure 2. There are two Print commands in the program. The second one sends a message in quotation marks: "Uno". But first a number is sent - more particularly, the number N. If it's been a while since you had anything to do with math, you may still have a vague memory that unknown quan- tities in algebra are often designated as x. You could do the same in Bascom, but in situations where numbers are simply incremented (1, 2, 3 and so on), the symbols N, M, I and J are com- monly used in source code. However, you are free to choose your own symbols for variables of this sort. The only thing that really matters is that you first tell Bascom what type of number each variable represents. This is because Bas- com has to know how many bytes of memory the number needs and how computations should be performed with the number in the code. For this reason, the variables must be declared (dimen- sioned) before they are used. That's the purpose of the following instruction: Dim N as Byte. This means that N is a number of type Byte, which clearly indicates that this number consists of eight bits (recall the previous instalment) and has a number range from 0 to 255. Assignments Now you can perform calculations with the num- ber variable N. The variable is assigned the value 0 at the start of program execution. Although you might think this is only logical, it is actually a particular feature of Basic. In other languages you have to write 'N = O', but in Bascom this is done automatically. The value of N is subse- quently incremented by 1 each time the loop is executed. My old math teacher would have boxed my ears if I wrote 'N = N + 1', because it is not valid mathematical equation. However, in many programming languages the equal sign is used as an assignment operator. The intention here is that the variable N is assigned a new value by adding 1 to the existing value. You can see the results of this ongoing incre- menting in the terminal window: the value of N increases by 1 after each output. You can also see something else: the value stops rising after it reaches 255, since we defined N as a single-byte number. This means that 255 + 1 is not 256, but instead 0. This is called number overflow. Here this is not a problem, but in other places it can be a problem - namely when you have inadver- tently chosen a number type that is too small and the overflow is not detected. There's another detail that should be noted here: why does the display always go to a new line after "Uno", but not after the number? The answer is BASCOM-AVR Options Figure 1. Terminal emulator settings. Listing 1. Print output t ‘ UNO_Pri nt . BAS c $regfile = “m328pdef.dat” $crystal = $baud = 9600 Dim N As Byte Do Print N; Print “ Uno” Waitms 200 N = N + 1 Loop Figure 2. Print output transmitted over a serial line. www.elektor-magazine.com j June 2014 31 •Projects Figure 3. Using the A/D converter. simple: by default, Bascom sends the control character CR (which stands for 'carriage return', like an old-fashioned typewriter) and LF (line feed) at the end of each Print command. If this is not what you want, you have to put a semicolon at the end of the instruction (Print N;). That's why the text is on the same line as the number. A space is also inserted to separate the num- ber from the text. As you can see, it's all very simple and straightforward; you could use the same approach to display '200 mV' on the mon- Listing 2. Using the A/D converter ? ' UNO_ADl . BAS ADC ! $regfile = "m328pdef.dat" $crystal = 16000000 $baud = 9600 Dim D As Word Config Adc = Single , Prescaler = 64 , Reference = Avcc '5 V Do D = Getadc(0) Print D Waitms 200 Loop itor. After all, our original intention here was to display measurements from the A/D converter, and now we're ready to do so. The serial bits output by the Atmega328, which are sent to the serial to USB converter on the Uno board, can easily be seen with an oscillo- scope. Simply touch the scope probe to the TX pin of the microcontroller, which is routed to the socket header at the top right on the Arduino board. Then you can see the data stream. The RX pin is next to the TX pin, and if you type some characters on the terminal you can see them on the RX line. This shows that the PC can also send data to the microcontroller. At this point the received data does not do anything because the program ignores it. The A/D converter The analog to digital converter (ADC) in the microcontroller is a sort of measuring device. As we all know, measuring involves comparing. First you need some sort of unit to serve as a reference quantity. Before you can measure a distance in meters, you have to know how long a meter is. Likewise, you have to know how big a volt is before you can say how many volts are lurking in your wall outlet. The situation here is similar. The microcontroller needs a reference voltage so that it can compare the voltage on a selected analog input (AO to A5 on the Uno board) to the reference voltage. The reference voltage is connected to the AREF pin. Flowever, you can also use a register to select the reference voltage. For example, you could apply an external refer- ence voltage of 1 V or connect a 5 V reference voltage from inside the microcontroller, but of course you shouldn't do both at the same time. Now try measuring the voltage between AREF and GND (see Figure 3). Since the A/D con- verter hasn't been configured yet, the voltage is zero. If you load the program in Listing 2 into the microcontroller and make this measurement again, you will see a voltage of 5 V. This is due to the following configuration statement: Config Adc = Single , Prescaler = 64 , Reference = Avcc This initializes the ADC, which means it enables the ADC with specific attributes. Flere Single mode means that only one measurement is made for each request. The other option is Free (short for free-running mode), in which measurements 32 June 2014 www.elektor-magazine.com Microcontroller Bootcamp are made repeatedly without interruption. The prescaler generates a clock signal for the A/D converter by dividing the processor clock sig- nal, which is 16 MHz on the Uno board. In this case the A/D converter runs at 250 kHz (16 MHz divided by 64). It can also run faster, but then it is not quite as accurate. The setting 'Reference = Avcc' connects the Aref pin to Avcc, which the supply voltage of approximately 5 V. Incidentally, it's worthwhile taking a look at the data sheet for the microcontroller - the section on the A/D con- verter is practically a data sheet in its own right. If after that you still don't have any idea of what settings you can or should use, the Bascom Help is a good source of information. Simply point the mouse to 'Config' and press the FI key, and you will be rewarded with all sorts of useful informa- tion and a bit of sample source code. The 'instruction D = Getadc(O)' initiates a mea- surement of the voltage on AO and copies the result to the variable D. The A/D converter pro- vides readings with a resolution of 10 bits, which corresponds to a number range of 0 to 1023. The variable D must therefore never be dimen- sioned as a byte variable. You should use either the type Word (range 0 to 65535) or the type Integer (range -32768 to +32767) to ensure that the readings will fit. The measurements are made using a successive approximation algorithm with ten steps. First the converter compares the input voltage to half the reference voltage. If it is higher than the reference voltage, the next comparison is to three-quarters of the reference voltage. If it is still higher, the next comparison is seven-eighths, and so on. The resolution doubles with each step. At the end you have number that indicates which step on a ladder with 1024 steps between zero and the reference voltage corresponds to the measured voltage. Each step is approximately 5 mV (5 V divided by 1023) if you use a reference voltage of 5 V. For comparison, the resolution of a digital voltmeter with a 3-V2 digit display is roughly twice as good (2000 steps). This makes the microcon- troller a fairly good measuring device, although you shouldn't confuse resolution with accuracy - the accuracy can be seriously compromised by an inaccurate reference voltage. The analog inputs are subject to the same con- siderations as the digital inputs: an input voltage well below zero or well above the supply voltage can lead to undesirable side effects, extending as far as latchup (as described in the previous part of this series). However, here again a 10-kft resistor in series with the analog input can prevent serious problems. With that precaution in place, it's even okay to touch the input with your finger. If you do so, you will see varying readings in the terminal window (Figure 4), including many limit values (0 and 1023) because the hum voltage exceeds the measuring range. The overall effect is similar to the waveform from a half-wave rectifier as seen on a oscilloscope. If you compare the measurement cycle time, consisting of the programmed wait interval of 200 ms plus the actual measurement time, with the AC line voltage period of 20 ms (at 50 Hz), you can see that here again there is a stro- boscope effect. This is called undersampling, and it produces a low-frequency alias signal because the measurement samples do not all lie within the same period of the measured signal. In fact, there are several periods of the input signal between each pair of samples. A bit of math Our first simple measurement program only gen- erates raw data, so you have to calculate the signal voltage yourself. Consider the following example: You connect analog input A0 to the 3.3 V output of the Arduino board. Now you see a reading of 676, or something close to that. You grab your pocket calculator and calculate: 676 + 1023 x 5 V = 3.305 V (okay). Another option is to modify the program and have the microcontroller do the math (Listing 3). For this you need a variable that can hold more than just integer values. You can use a variable U of type Single (which means a single-precision floating point / real number variable), which is fully suf- Figure 4. Measurement data from a 50 Hz signal. www.elektor-magazine.com | June 2014 33 •Projects Figure 5. Measuring the microcontroller's own supply voltage. ficient. Now you can convert the raw data in two steps. You can only perform one calculation in each instruction (that's a Bascom rule). The long chained equations you see in C or Pascal are not possible here. U = D * 5.0 U = U / 1023 Now you can see the result in the terminal win- dow. Of course, you should treat the large num- ber of decimal places with caution, since they give a false impression of the actual resolution. Later we will show you how to properly round Listing 3. Conversion to volts i ' UN0_AD2 . BAS 0. . .5 V i $regfile = "m328pdef.dat" $crystal = 16000000 $baud = 9600 Dim D As Word Dim U As Single Config Adc = Single , Prescaler = 64 , Reference = Avcc '5 V Do D = Getadc(0) U = D * 5.0 U = U / 1023 Print U ; " V" Waitms 200 Loop off readings of this sort, but for the time being it's nothing to worry about. At this point you can see that it makes a dif- ference whether you power the Uno board over USB or from an external power supply. The sup- ply voltage on the USB port can easily differ from 5 V by 10% or more (see Figure 5), and the accuracy of the measurement results will vary accordingly. By contrast, the 5 V regulator on the Uno board has a relatively narrow toler- ance, typically around 1%. Try both options for yourself. Also measure the actual voltage on the 3.3 V terminal and the voltage on the AREF pin in each case. Armed with that information, you can significantly improve the accuracy. Suppose you measure a reference voltage of 5.03 V with an external power supply (using a high-precision DVM). Enter this value in the program in place of the nominal value of 5.0 V, and your readings will be nearly spot on. You should also try other reference settings. If you configure 'Reference = Aref', at first you do not have any reference voltage at all. You have to provide your own reference voltage, with a free choice anywhere in the range of 0 to 5 V. For example, you can connect the Aref pin to the 3.3 V terminal of the Uno board. In this case the measuring range extends to 3.3 V. Another option is 'Reference = Internal'. In that case the A/D converter uses an internal 1.1 V reference voltage, and you can measure this voltage on the Aref pin. The data sheet very modestly states a tolerance of approximately 10%, which means 1.0 V to 1.2 V. In our case we measured 1.08 V, which is only 2% away from the nominal value. However, you should measure the actual value yourself. There are two things worth noting about this relatively low reference voltage. The first is that the accuracy is independent of the supply voltage; and the other is that it gives you a rel- atively high resolution of approximately 1 mV. Measuring the microcontroller's own supply voltage You might wonder whether the microcontroller can measure its own supply voltage At first the answer appears to be no, since you would need a sufficiently large reference voltage that is inde- pendent of the supply voltage. However, it turns out that this is indeed possible because the data sheet reveals several interesting details about the A/D converter. The input multiplexer (an ana- log switch similar to the well-known 4051) has 34 j June 2014 www.elektor-magazine.com Microcontroller Bootcamp External programmer When you want to use a microcontroller, you usually need some sort of programming device. This is not necessary with the Arduino because it has a built-in boot loader, as described in the first part of this series. However, you do not have a boot loader when you buy a new AVR microcontroller and fit it on your own PCB, so you have to use a programmer. One low-cost option is the Atmel ISP mkll. It can be used with the free AVR Studio 6 development environment. However, there are lots of other programmers that can do the same job. A six-pin ISP connector is normally used for in-system programming (ISP) of AVR microcontrollers. Many microcontroller boards, including the Arduino, have a suitable 6-pin header for this. The SPI interface, which consists of serial data streams (MOSI to the microcontroller and MISO back to the programmer) and a clock signal (SCK), is often used to transmit the programming data. This interface will be described in more detail in a later instalment. The pinout of the ATmega328 is: AVWSP midi (OOOOAOOOS229) Dcvkc Programming Tool avpjsp mkn lr.trrf.rr tfftingt Tool information information Mtmoiio Fum Lock bits Production file Device ATm«,« 328 P Interface BP — Device Erase Chip w | | Erase now Flash (32KI) C:\Arbeit.neu\E leMortUno\Uno3\B*scom3\UNO_AD2ne)r v Erase device before programming V Verify Flash alter programming EEPROM(IKB) Verify EEPROM after programming can always restore everything to the original state if you do something really wrong, such as accidentally deleting the boot loader. You can also use the programmer to read out the content of the flash memory, for example in order to make a backup copy (including the boot loader) that you can use to restore the Arduino if necessary. A backup copy (UnoBoot.hex) [1] is also available in the Elektor archive in case you need it. In order to load your own program into the microcontroller, you first have to load the hex file. In this case you must tick the option 'Erase chip before programming' to ensure that the boot loader is deleted. This means you have to decide whether or not you want to use the boot loader. You can also opt to use another boot loader, such as the MCS boot loader. We'll describe how that works in one of the upcoming instalments. Device signature Target Voltage 0JE950F Reed 5,1 V Reed 0 Program Verify Read.. - B Retd- Erasing device... OK Programming Flash. ..OK Verifying Hash. ..OK [»] Verifying HastuOK 1 2 3 4 5 6 MISO, PB4 Vcc SCK, PB5 MOSI, PB3 Reset GND AVWSP mlcD (OOOOAOOQ6229) Device Programming Tool Device AVWSP mkn • ATm«,. 328 P Interfere settings Tool information Device information Memorial Finer Lock bite Production file Interface BP Device signature Target Voltage 0JE950F Read | 5,1V |Ftead| 0 The Arduino Uno board has two ISP ports for external programmers. The one close to the USB connector is best ignored, since it is used to program the USB to serial converter described in the body of this article. The ISP port for the ATmega328 is located at the edge of the board. It's nice to know that it's possible to connect an external programmer, because it means you Starting operation read registers Reading legate. EXTENDED. -OK Reading register HIGH— OK Reading register LOW. ..Ok Read registers . .OK p] Read registers._OK Fuve Name Value ® WDTON ® EESAVE S3 ® BOOTS! 256W.3FOO - BOOTRST 59 (/) CKDIVS £ ® CKOUT ®SUT.CKSU EXTXOSC.8MHZ.XX.16KCK.14CK.6iMS - fu*e Register Value EXTENDED OiFD m HIGH 0*06 1 i nw OvCC 1 Copy to clipboard 1 V Auto re«o Vi Verify aft er programming 1 PfOflWni | Verify | | Read You can also view the microcontroller fuse settings with Bascom or in Atmel Studio 6. By the way, the term 'fuse' comes from the early days of microcontroller technology when there was program memory in which links were literally burnt through to program the memory once and for all. The modern fuses in ATmega microcontrollers are actually flash memory cells that must be configured to define specific basic settings. Among other things, they allow you to switch back and forth between the internal clock and an external clock source. The screenshot shows the factory default fuse settings of the Arduino Uno board. You can see that the boot loader is enabled (BOOTRST) and how much memory is reserved for it. www.elektor-magazine.com j June 2014 35 •Projects Figure 6. Temperature measurement under load. a total of eight channels, of which six are con- nected to pins AO to A5. The other two are only fed out in the SMD version of the ATmega328. However, there are also several 'hidden' internal channels, and one of these (channel 14) allows the microcontroller to measure its internal 1.1 V Listing 4. Measuring V cc . 1 UN0_AD3 . BAS Vcc / 1.1 V < $regfile = “m328pdef.dat” $crystal = 16000000 $baud = 9600 Dim D As Word Dim U As Single Config Adc = Single , Prescaler = 64 , Reference = Avcc Do D = Getadc(14) U = 1023 / D U = U * 1.1 Print “Vcc = Print U ; “ V” Waitms 1000 Loop ‘ Ref 1.1 V reference voltage. The trick here is to use the imprecise supply voltage as the reference volt- age and measure the precise internal reference voltage. In this case the program must calculate in the opposite direction to determine the actual supply voltage (see Listing 4). The first mea- surement (Figure 5) shows the supply voltage with USB power, which in this case is about 4.5 V. Then an external power supply is connected while the program is running, so the supply voltage is provided by the distinctly more precise 5 V volt- age regulator. The corresponding measurement is accordingly close to 5.0 V. Measuring the temperature In addition to measuring its own supply voltage, the ATmega328 can measure its own tempera- ture thanks to an internal temperature sensor connected to channel 8 of the A/D converter. The output voltage of this sensor is proportional to the temperature, with a factor of approximately 1 mV per degree. The accuracy is not especially high - the specified tolerance is ten degrees. However, you can always calibrate it yourself. According to the data sheet, the sensor output is 242 mV at -45 °C, 314 mV at 25 °C and 380 mV at 85 °C. To obtain meaningful readings with volt- ages in this range, you have to use the relatively low internal reference voltage (1.1 V). However, the same program is supposed to measure higher voltages as well, so it automatically switches to the higher reference voltage (Avcc) as necessary. For internal temperature measurement the A/D converter operates with the internal 1.1 V ref- erence voltage and a resolution of about 1 mV, which roughly corresponds to 1 degree at the temperature sensor output. At 25 degrees C the sensor output is approximately 314 mV. We decided to take a quick-and-dirty empirical approach, and we determined that the tempera- ture in degrees C could be found by subtracting 338 from the measured value (see Listing 5). However, even better results could be obtained with a bit more computation effort. In any case, you should adjust the results according to your actual situation to obtain the best possible match with the temperature shown by an ordinary ther- mometer. Next we held a finger on the micro- controller to see whether the temperature rose. Then we wanted to see whether the tempera- ture of the microcontroller increases when it is driving a load. Figure 6 shows a 220 Q. resistor connected between two port pins. If one output 36 June 2014 www.elektor-magazine.com Microcontroller Bootcamp is set high and the other is set low, the voltage on the load resistor is close to 5 V. This results in a load current of roughly 20 mA. We wanted to see whether this causes the microcontroller to warm up. The program also measures the volt- age drops on the port pins. For this purpose, the reference voltage must be briefly switched to 5 V. Although it is somewhat unusual for a program to work with two different reference voltages, switching voltages while the program was run- ning does not cause any problems. The results: with an output current of 20 mA, the voltage drops are just 0.4 V at the lower output and 0.5 V at the upper output. This leaves 4.1 V Figure 7. Temperatures and voltage drop Listing 5. Temperature and voltage drops c ‘ UN0_AD4 . BAS Temp t $regfile = “m328pdef.dat” $crystal = 16000000 $baud = 9600 Dim D As Word Dim N As Word Dim U As Single Config Portb = Output Portb.5 = 1 Portb. 4 = 0 Do Config Adc = Single , Prescaler = Auto , Reference = Internal ‘1,1 V Waitms 200 D = Getadc(8) ‘Temperature D = D - 338 Print D ; “ deg” Waitms 500 Config Adc = Single , Prescaler = Auto , Reference = Avcc ‘5 V Waitms 200 D = Getadc(0) U = D * 5.0 U = U / 1023 Print U ; “ V” D = Getadc(l) U = D * 5.0 U = U / 1023 Print U ; “ V” Loop www.elektor-magazine.com j June 2014 37 •Projects across the load resistor, yielding a current of 19 mA. The additional power dissipation in the microcontroller is 17 mW (0.9 V x 19 mA). Sig- nificant warming cannot be expected from this amount of power, and that's exactly what we saw from the temperature measurement (Figure 7). According to the data sheet, the maximum cur- rent at any port pin should not exceed 40 mA and the total current should not exceed 200 mA. In our experiments we found that the ports could handle currents up to 100 mA without damage, which means that even small DC motors could be operated directly from the ports without driver ICs. However, if you want to be on the safe side the rule is to never exceed 40 mA. Listing 6. Measuring the input hysteresis t ‘ UN0_AD5 . BAS Hi/Lo Input Threshold c $regfile = “m328pdef.dat” $crystal = 16000000 $baud = 9600 Dim D As Word Dim Dmin As Word Dim Dmax As Word Dim N As Word Dim U As Single Config Portb = Output Config Adc = Single , Prescaler = 64 , Reference = Avcc ‘5 V For N = 1 To 10000 Portb. 5 = Not Pine. 5 Next N Dmin = 1023 Dmax = 0 Do For N = 1 To 10000 Portb. 5 = Not Pine. 5 D = Getadc(5) If D < Dmin Then Dmin = D If D > Dmax Then Dmax = D Next N U = Dmi n * 5 . 0 U = U / 1023 Print “Min = Print U , “ V” U = Dmax * 5.0 U = U / 1023 Print “Max = “; Print U , “ V” Loop ‘ 13 100k A5 ‘ A5 100pF GND Figure 8. Measuring the input hysteresis. Figure 9. The upper and lower switching thresholds of an input. 38 June 2014 www.elektor-magazine.com CD l n -i — > L_ CD > “O < Measuring the input hysteresis In the previous instalment of this series we used external test equipment to determine the switching thresholds of a digital input. Now we want to the same thing entirely auto- matically with the built-in A/D converter (see Figure 8). For this we use two new variables (Dmin and Dmax) to hold the values of the lower and upper switching thresholds (see Listing 6). The measurement loop is preceded by a control loop which ensures that the input voltage is already within the desired range before the actual measurement starts. At first the maximum possible value is stored in the Dmin variable and zero is stored in the Dmax variable. The pro- gram then looks for the actual limit values. This is done using a random-sample approach. The longer the mea- surement session lasts, the more accurate the determined limit values are. This program shows how to use loop counters. The For-Next loop counts down from N = 1000 to 0 and executes the instructions inside the loop exactly 1000 times. Although one thousand iterations may sound like a lot, the entire process takes only a fraction of a second. The large number of mea- surements increases the probability that the measurement results include the true limit values. This means that you have a good chance of finding the correct values after just one round. This can be seen from the fact that the subsequent rounds do not yield any significant changes. For N = 1 To 1000 ... instructions ... Next N Figure 9 shows the result of this experiment. The switching thresholds are 2.23 V and 2.62 V. These are approximately the same as the values determined using the external test equipment. ( 130568 - 1 ) Web Link [1] www.elektor-magazine.com/130568 npoioiu Robotics & Electronics Addressable RGB 30-LED Strip, 5 V, 1 m (WS2812B) ITEM #2546 $ 16 95 Waterproof, individually addressable LED strip that runs on 5 V. Can be chained to form longer strips or cut for shorter sections. Other lengths and LED densities available. 37D mm Metal Gearmotors • Several gear ratios stocked • Versions with integrated encoders also available Step-Up/Step-Down Voltage Regulator S18V20ALV ITEM #2572 • 3 V to 30 V input • Adjustable 4-1 2 V output can be above or below input voltage • 2 A typical max output current • 1" x 0.6" programmable module with native USB • ATmega32U4 with Arduino-compatible bootloader A-Star32U4 Micro ITEM #3101 Mini Maestro 12-Channel USB Servo Controller • USB, serial, and internal scripting control • 6-, 1 8-, and 24-channel versions also available Sub-Micro Servo ITEM #1053 Specs at 6 V: • 6oz*in • 0.07 sec/60 Zumo Robot (Assembled with 1 ITEM #2506 $9995 Arduino-controllable tracked robot small enough for mini-sumo (less than 1 0 cm x 1 0 cm) and flexible enough for you to make it your own. Individual parts and kit version also available — build your own configuration! Finding the right parts for your design can be difficult, but you also don't want to spend all your time reinventing the wheel (or motor controller). That's where we come in: Pololu has the unique products — from actuators to wireless modules — that can help you take your design from idea to reality. Find out more at: www.pololu.com www.elektor-magazine.com j June 2014 39 •Projects XXL LED VU Meter With a wide range and high resolution I f* WV « . * * c i « « 5* -V ,* By Emile van de Logt An LED VU meter is an excellent tool for keeping a close eye on the magnitude of (Netherlands) audio voltages and so help prevent an input from being overloaded, for example when used with a mixing desk or a guitar amp. The circuit described here has an exceptionally wide input range of 60 dB and a step size of 1 dB thanks to the use of 6 LM3915 driver ICs, which control a total of 60 LEDs. The author was looking for an LED VU meter for his DIY guitar tube amplifier. After some research an old veteran soon presented itself: the LM3915 dot/bar display driver. This IC spans 30 dB with a step size of 3 dB. It can be used to drive a total of 10 LEDs. Various LED VU kits using this IC are available and are usually satisfactory. Further research resulted (of course) in an Elek- tor article by Rikard Lalic. This article from the 2002 Summer Circuits edition [1] describes an LED VU meter, again using the LM3915, but now with a range of 60 dB, which is achieved by using 2 LM3915 ICs, where the second IC receives a voltage that is 30 dB smaller. Rising to the challenge to make an LED VU meter that has this wide range, as well as a step size of 1 dB, this article describes the design, con- struction and test of such an XXL LED VU meter, with a range of 60 dB and a resolution of 1 dB, meaning there's a grand total of 60 LEDs to be controlled! An interesting aspect of this design is that it is entirely analog (there is no microcontroller to be found) and that is has a didactic purpose. The author uses it to explain to his students that mathematics and the design of electronics go hand in hand. This article also contains a few sidebars where readers can refresh their own theoretical knowledge somewhat! Design and calculations Lalic, in his original design, assumed a fixed set- point of 5 V for the first LM3915. To allow this design to measure higher powers as well, he 40 June 2014 www.elektor-magazine.com LED VU Meter supplied a table where the input signal to the LM3915 could be adjusted using a voltage divider. Because the LM3915 has a default step size of 3 dB, having a step size of 1 dB has to be solved by using multiple LM3915 ICs. In the original design the second LM3915 was adjusted 30 dB lower than the first LM3915. This can be fur- ther refined by adding two more ICs, which are adjusted to be 1 dB and 2 dB lower respec- tively, relative to both of the existing ICs. All this together will now create a total range of 60 dB in steps of 1 dB. Therefore we have a total of six LM3915 ICs which are adjusted according to Table 1. As an example we will assume that full power drive is reached at an RMS power of 100 watts into 8 ft. This corresponds to an 28.28 V rms and 40 V peak (see sidebar 'Power and voltage: RMS and peak?'). Since the LM3915 responds to the peak value (because it is, in fact, a comparator), the voltage divider has to be scaled such that this 40 V corresponds to the reference voltage of 5 V at the input of the LM3915. Supposing that R2 has a fixed value (10 kft), then the correct voltage divider ratio can be set with the aid of R1 for various (RMS) powers and loudspeaker impedances R L . In the sidebar we already observed that P = rms u 2 R L Rearranging this becomes U = -\l 2 P rms R l This peak voltage 0 is reduced by the voltage divider R1/R2 to 5 V, so that we obtain the following: Figure 1. Because six ICs type LM3915 have been used, a total of 60 LEDs can be controlled, which results in a range of 60 dB and a step size of 1 dB. 10 k Rl + lOk U x 10& = 5 x (Rl + 10k) <=> Uxl0k-50k = 5xRl Table 1: Reference voltage for each IC IC-nO. Ratio [dB] Ratio Uref [V] IC1 0 dB 1.000 5.000 IC2 -1 dB 0.8913 4.456 IC3 -2 dB 0.7943 3.972 IC4 -30 dB 0.0316 0.158 IC5 -31 dB 0.0282 0.141 IC6 -32 dB 0.0251 0.126 www.elektor-magazine.com June 2014 41 •Projects Component List Resistors Default: 0.25 W 1% R1 = see text and Table 2 R2 = lOkft R3,R6,R9 = 820ft R4a = 36kft R4b,R7b = 2.4kft R5,R8,R11 = 47ft R7a = 9.1kft RIO = 1.6kft R12,R13,R14 = 680ft P1-P6 = 100ft trimpot, horizontal Capacitors Cl = lOOOpF 35V, low ESR, 5mm pitch, 13mm diam. C2 = lOpF 16V, low ESR, 2mm pitch, 5mm diam. C3 = lpF 100V, MKT, 5mm pitch C4 = InF, 5mm pitch C5-C10 = lOOnF, 2.5mm pitch C11,C12,C13 = 22nF, 2.5mm pitch Semiconductors B1 = DB101 D1-D50 = 10-element LED bargraph display, green, 10.16 x 25.40 mm D51-D60 = 10-element LED bargraph dis- play, red, 10.16 x 25.40 mm IC1-IC6 = LM3915N IC7 = LM7812 (TO220) Miscellaneous J1,J2,J3 = 2-pin pinheader, 0.1" pitch 6 pcs. DIP-20 IC socket for LED bargraph displays 6 pcs DIP-18 IC sockets for LM3915 ICs PCB # 120698-1, see [2] Figure 2. The printed circuit board layout designed by the author. The LEDs can be fitted at either the component side or the solder side, whichever is preferred (but note the correct polarity). 42 June 2014 www.elektor-magazine.com LED VU Meter Table 2: Value of Rl for different powers Loudspeaker- Impedance R l 4 ft 4 ft 4 ft 8 ft 8 ft 8 ft 16 ft 16 ft 16 ft RMS Power P RMS 10 W 50 W 100 W 10 W 50 W 100 W 10 W 50 W 100 W Peak Voltage 0 8.9 V 20.0 V 28.3 V 12.6 V 28.3 V 40.0 V 17.9 V 40.0 V 56.6 V ri (n) 7889 30000 46569 15298 46569 70000 25777 70000 103137 Rl - 22k//12k 47k//82k 47k 15k 47k 220k//100k 47k//56k 220k//100k 330k//150k implementation (-1.58%) (-0.41%) (+0.9%) (-2.0%) (+0.9%) (-1.8%) (-0.87%) (-1.8%) (0.0%) And finally we can solve this for R x : R\ = Ux2k-\tik Using the formulas for 0 and Rl, Table 2 can be populated with various values of P RMS and R L . The purpose of capacitor C4 at the input is to prevent undesirable RF interference and together with Rl forms a low-pass filter. A 12-V voltage regulator provides a stable power supply voltage. Design of the reference voltages The generation of the reference voltages requires a little extra attention. For one thing, since the range of 60 dB is reasonably large this has the consequence that the reference voltages can become quite small. A voltage ratio of 60 dB does, after all, mean a ratio of 1000 to 1. The bottom-most LED will therefore already turn on at only 5 mV! A good printed circuit board design with ground and power planes is essential for a successful implementation! The LM3915 generates a constant voltage of 1.25 V between pin 7 (Ref Out) and pin 8 (Ref Adj). The current that is required to generate this voltage also determines the current that will flow through each LED. Using a resistance value of 820 ft there will be a current of about 15 mA running through each LED. This is sufficient to turn the LEDs on with plenty of brightness. As the first step, the reference voltage at IC1 can be set to 5 V using potentiometer PI. This voltage is measured at test point TP1. Once this is done, the voltage at IC4 can be set to 158 mV (see Table 1) using potentiometer P4. This volt- age is measured at test point TP4. After this proceed to adjust the center sections. Using potentiometer P2 adjust the reference volt- age for IC2 to 4.456 V. This voltage is measured at test point TP2. This is then followed by setting the voltage for IC5 to 141 mV using potentiom- eter P5. This voltage can be measured at test point TP5. Next use potentiometer P3 to set the reference voltage for IC3 to 3.972 V. This voltage is mea- sured at test point TP3. Finally use potentiome- ter P6 to set the voltage for IC6 to 126 mV. This voltage is measured at test point TP6. Circuit board assembly Assembling the circuit board should present few difficulties. For his prototype the author chose to mount the LEDs on the solder side of the circuit board. These, however, could also be fitted with- out any problems on the component side, if pre- ferred. Just make sure that the LEDs are mounted with their polarity the correct way around. One of the four corners of the LED has a bevel. This side must face the long edge of the board. With some resistance values (for example Rl, see Table 2) it may be necessary to solder two resistors is parallel in order to obtain the correct value. You can, of course, also use 1%-resis- tors, but these are not always all available in the assortment of resistors in the (hobby) lab. After all the parts have been mounted (but do not yet fit the LM3915 ICs in their sockets) you can begin with testing the power supply section. There are two options here: • Connect a transformer with an output of 12 V AC to connector J1 and mount Bl, Cl and IC7. • Use an external 12 V DC power supply and connect this to connector J2. In this case IC7 must not be fitted. Measure that there is a stable 12-V signal every- where (pin 3 and pin 9 of each IC socket). If www.elektor-magazine.com June 2014 43 •Projects Table 3: Adjustment of the reference voltages PI P2 P3 P4 P5 P6 TP1 TP2 TP3 TP4 TP5 TP6 5.000 V 4.456 V 3.972 V 158 mV 141 mV 126 mV The Author Emile van de Logt works at Hogeschool Rotterdam, Netherlands, as Head of Department for the Electric Engineering and Health Care Technology departments. He studied Electric Engineering at Eindhoven Technical University, and Management Studies at Open University. An enthusiastic electronics hobbyist, Emile looked after Elektor's Embedded C Programming and FPGA-VHDL workshops. He builds tube amplifiers, guitar effects equipment and is an amateur beer brewer with an entirely automated brewing system, the hardware and software of which he designed himself. not, switch off the power supply and track down the fault. Once all is well, you can fit (with the power supply off) all the LM3915 ICs carefully in their sockets. Turn the power supply back on and adjust all the reference voltages to their correct values according to Table 3. After this the board is ready for use. The loud- speaker signal is connected to connector J3. ( 120698 - 1 ) Web Links [1] www. elektor-magazine. com/000083 [2] www. elektor-magazine. com/120698 The Logarithm The logarithm is often used in order to allow large ratios between numbers to be expressed clearly. Normally the logarithm with base 10 is used. There are a few rules that are important when calculating with logarithms: log a (b) = x can also be written as a power: a x = b. The knack of working with logarithms is to transform one of these forms into the other. For example: how big is log 10 (1000)? If we call the answer x, then we can also write: log 10 (1000) = x, that is 10 x = 1000, that is 10 x = 10 3 , therefore x (the answer) is 3. Consequently log 10 (1000) equals 3. Similarly, log 2 (8) = 3. The Decibel is named after Alexander Graham Bell. The Bel (B) was originally used to indicate the power loss in cables. An unwieldy unit it was soon redefined to deci-bel (0.1 bel). When working with decibels it is important to make a distinction between power and voltage ratios. The definitions of these are as follows: number of dB's = 10 log 10 (Pi/Po)- When P lf for example, is 100 times bigger than P 0r then this ratio corresponds to 20 dB. With voltage ratios the definition is as follows: number of dB's = 20 log 10 (UJUq). When U lr for example, is 100 times bigger than U 0 , then this ratio corresponds to 40 dB! Assuming we want the difference between two voltages U 1 and U 0 to be 30 dB we can write: 20 log 10 (C/ 1 /L/ 0 ) = 30 that is, log 10 {UJUq) = 1.5. According to the notations defined for the logarithm this can also be written as: 10 1 - 5 = (UJUq), that is, UJUq = 31.62. Consequently U 1 has to be 31.62 times bigger than U 0 . Power and voltage: RMS and peak? For a pure sine wave signal it holds that the peak value (indicated with 0) is bigger by a factor of V2 compared to the RMS (root-mean-square) value (indicated with l/ rms ). We know that P (power) = U (voltage) x I (current). Ohm's Law tells us that U = I x R, therefore P=UxI=Ux U/R = U 2 /R. It is important to indicate which power is used: RMS power (P rms ) or peak power? You only get RMS power if you use the RMS value of the voltage: P rms = U rms 2 /R = ( U/V2) 2 /R = LJ 2 /2R. The RMS power is therefore half of the peak power! An RMS power of 100 watts into a loudspeaker of 8 ohms is thus realized by a sine wave signal with an RMS voltage U rms = 28.28 V. This signal has a peak voltage U of 40 V. 44 | June 2014 www.elektor-magazine.com Retronics 80 tales of electronics bygones This book is a compilation of about 80 Retronics installments published in Elektor magazine between 2004 and 201 2. The stories cover vintage test equipment, prehistoric computers, long forgotten components, and Elektor blockbuster projects, all aiming to make engineers smile, sit up, object, drool, or experience a whiff of nostalgia. 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. 'VL Own H If.' Dun A 0 2*1 iSfilhP SfZ J.dP> r.n •IKOE'J m 2W® ;■ -= J. : *.-i Sa'ti Av-iss* (***$*’ L: JC » J- itoCtertn [fl-SjHI 1 . Jc-»- tllK Ml Mb-r — i.ji -JL*. -*.e I I 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 EAGLE V6 Getting Started Guide Learning to fly with Eagle BEST- SELLER V t ^RNIN«*OFLTlMTH« OU - Eagle OCT."* S**™ i ■ I i ' e This book is intended for anyone who wants an introduction to the capabilities of the CadSoft’s EAGLE PCB design software package. After reading this book while practicing some of the examples, and completing the projects, you should feel confident about taking on more challenging endeavors. The book will quickly allow you to: • obtain an overview of the main modules of EAGLE: the schematic editor; layout editor and autorouter in one single interface; • learn to use some of the basic commands in the schematic and layout editor modules of EAGLE; • apply your knowledge of EAGLE commands to a small project; • learn more about some of the advanced concepts of EAGLE and its capabilities; • understand how EAGLE relates to the stages of PCB manufacture; • create a complete project (a proven design from the engineering team at Elektor), from design through to PCB fabrication. 208 pages • ISBN 978-1-907920-20-2 Incl. CD-ROM containing EAGLE 6.4.0 for MS Windows, Linux and Mac £30.95 •€34.50 •US$47.00 10% OFF for WttN and r &0Lp Me nbe $ Further Information and Ordering at www.elektor.com/eaale. L •Projects DIY PC for Raspberry Pi Using a PIC16F88 microcontroller are not suitable for direct connection to the I/O header. You can buy a wide range of I 2 C slave devices and connect them to the Raspberry Pi without further ado, including temperature sen- sors and I/O extenders. However, you can't buy devices for every possible application, and some- times the available devices don't do what you want. If you build your own I 2 C slave using a microcontroller, the potential uses are virtually unlimited. For example, the 16F88 used in this article has several analog inputs, digital I/O, high-resolution PWM, a TTL RS-232 port, fre- quency counters, SPI and I 2 C ports and EEPROM all integrated into the device. The possibilities are only limited by your imagination. What do you need for this? Actually not that much: a Raspberry Pi board, an SC card with the Raspberry Pi operating system and I 2 C drivers (which you can obtain from the author's Raspberry Pi book, among other sources), a PIC 16F88 microcontroller, a PIC programmer, and a breadboard with an LED, an LDR and a few bits of wire. What can you do with an I 2 C slave device? The Raspberry Pi has a GPIO header for connect- ing external circuitry, such as I 2 C slave devices. The advantage of these I 2 C slave devices is that you can use them to connect components that By Bert van Dam (Netherlands) This small article describes how to build your own I 2 C slave device using a PIC microcontroller, and how to control it with the Raspberry Pi. This approach combines the power of the mi- crocontroller with the flexibility of the Raspberry Pi. There are many things that you can implement with an I 2 C device, such as a light me- ter, remote sensor, relay control or motor controller. 46 | June 2014 www.elektor-magazine.com DIY PC for RPi Basic I 2 C bus structure An I 2 C data bus consists of one master and one or more slaves. They are connected to each other by data and clock lines as shown in Figure 1. These two lines are held High by a pair of pull-up resistors. Consequently the voltage on the I 2 C bus depends on the voltage rail to which the pull-up resistors are connected. It also means that it's entirely possible for the master and slave devices to operate from different supply voltages. In the case of the Raspberry Pi, the pull-up resis- tors are built in and connected to 3.3 V, so the slaves must be able to handle 3.3 V and see this voltage as a logic high level. The PIC sees any voltage above 2 V as a logic high level, so it has no problem communicating with a Raspberry Pi operating at 3.3 V. The bus master places a clock signal on the clock line by pulling it low at a specific frequency. The line automatically returns to the high level due to the pull-up resistor. The bus master also puts data pulses on the data line in the same manner, coordinated with the clock pulses. This means that the master controls the communication process and the slaves have to follow. When a request is sent to a slave, it must respond. However, the slave may not be able to respond before the next clock pulse— for exam- ple, if it first has to compute something. In this case the slave can pull the clock line low. Now the master cannot issue another clock pulse because the slave has already pulled the clock line low, and releasing the line has no effect as long as the slave holds it low. This gives the slave the time it needs to generate the required response. When it is ready, the slave releases the clock line so the master can again supply the clock signal. Of course, the clock signal timing is skewed at this point because the pulse was too long. This procedure is called clock stretching. We also use this procedure in our project. Setting up the I 2 C bus between RPi and PIC In the schematic in Figure 2 you can see the Raspberry Pi header on the right and the 16F88 on the left. The microcontroller pins that are not connected to anything in the schematic are left open. The two pull-up resistors required on the I 2 C data bus are built into the Raspberry Pi and are therefore not shown on the schematic. The LDR and the LED with the associated resistors are included to show how the circuit works. You probably won't need them for your own projects. Figure 1. We use the LED in our first demo project and the Basic I2(= bus structure. LDR in the second one. If you build this circuit on a breadboard as shown in Figure 3, you must fit a 100 nF capacitor in each corner to suppress noise on the supply lines. These capacitors are not shown on the schematic. Note that if you previously used the microcon- troller in other projects, pin 7 and/or pin 10 may already be configured as outputs. In that case they will have an output voltage of 5 V, which can damage the Raspberry Pi. To avoid this, load the I 2 C program into the microcontroller before you connect it to the Raspberry Pi. After this you can reprogram the microcontroller without any risk. One option for programming the microcontroller is to use the Wisp648 in-circuit programmer. In that case you can simply leave the microcon- Figure 2. The PIC microcontroller is connected to the Raspberry Pi over the I 2 C bus. R1 R3 AO R2 LDR 3_ 2 _ 1 _ 1 8_ 17 14 VDD IC1 RBO/INT RA5/MCLR RB1/SDI/SDA RA4/AN4 RB2/SD0 RA3/AN3 RB3/PGM/CCP1 RA2/AN2 RB4/SCK/SCL RA1/AN1 RB5/SS RAO/ANO RB6/AN5 RB7/AN6 PIC16F88 0SC2 0SC1 VSS Cl 15 X 20MHz 16 C2 20^P ^20p RPi master SDA 8 9 B3 l 2 C databus i_ SDA 3 SCL 5 10 11 12 _ 13 SCL R4 LED1 7 9 11 i3_ 15 _ 1 7 19_ 21 _ 23 25 O o o 8 40 O^ 0 12 14 HO o-t ^ 6 18 20 22 4-0 OF 24 26 +5V GND www.eIektor-magazine.com June 2014 | 47 •Projects troller plugged into the breadboard during pro- gramming. This is particularly handy when you are experimenting with the circuit and constantly making changes to the software. However, when you use an in-circuit programmer it is a good idea to use an external power source for the 5-V portion instead of the Raspberry Pi, to ensure that you always have enough power available. In that case the 5 V pin of the Rasp- berry Pi must be left open, since you can't power the circuit from two sources at the same time. However, the rest of the pins (including ground) should remain connected. Software structure For the sake of simplicity, we omit any descrip- tion of the settings (you can read about them at your convenience in the source code) and limit ourselves to a number of basic instructions. Here we use Python, the standard free programming language for the Raspberry Pi. We use the following Raspberry Pi instructions: bus.write_byte(address, command) This sends the content of the variable 'command' to the I 2 C slave device with the given address. This means that the slave receives an address and a command. data = bus. read_byte_data (address , command) This sends the content of the variable 'command' to the I 2 C slave device with the given address. After this the master waits for a response from the slave, which is copied to the variable 'data'. In this case the slave receives an address, a command, and then another address. data = bus . read_byte (address) Sometimes the slave does not need any com- mand. For example, it may only be able to mea- sure one thing, so that is the only thing the mas- ter can request. In that the case we can omit the command and simply send the address with the Read bit set. Of course, the software in the slave device must know in advance what it has to send back. sudo i2cdetect -y 1 You can issue this instruction when you want to know which I 2 C slaves are present on the bus. This is not a Python instruction, so you must enter it in a command line or use LXterminal if you are working with Xwindows (LXDE). In return you will receive the following reply: pi@raspberrypi $ sudo i2cdetect -y 1 0123456789abcdef 00 : 10 : 20 : 20 30: 40: 50: 60: 70: Here you can see that a single I 2 C slave has replied and its address is 0x20 in hexadecimal notation. On the microcontroller side we also skip all the settings. Here we use JAL, a widely used free programming language for microcontrollers. We use the following PIC instructions: i2c_slave_enable (address) You can use this instruction to configure the com- munication unit of the 16F88 for I 2 C and set the slave address. The maximum address value is 127 (7 bits). data = i2c_slave_read_byte_timeout (error) This function reads a bytes and uses a timeout counter. The bytes normally arrive one after the other, but if it takes too long a timeout occurs. When this happens, the function stops waiting and sets the variable 'error' to true. data = i2c_slave_read_byte This function also reads a byte, but without a timeout. You can use this to wait for the first address. There is no timeout here because it does not matter how long you have to wait, since it is entirely possible that the master never tries to contact the slave. i 2c_slave_wri te_byte (data , error) This function writes a byte of data. The clock line is held low until this function is ready, which means that the master must wait for the slave. If the write operation fails, the variable 'error' is set to true. 48 ! June 2014 www.elektor-magazine.com DIY PC for RPi Demo project 1: LED switching The first project involves controlling a LED over the I 2 C bus. This requires the Raspberry Pi to send a command to the microcontroller, with no response expected. We use the following instruc- tion at the Raspberry Pi end: bus .wri te_byte (address , command) This means that the microcontroller receives the address and a command. Figure 3. Circuit layout on a breadboard. -- wait for address (and ignore) dummy = i 2c_slave_read_byte -- wait for command command = i2c_slave_read_byte_timeout (error) The LED must be switched on or off, depending on the content of the command. A '1' causes the LED to light up, while a '0' makes it go dark. A timeout during reading or a hung bus during writing is a serious error. Normally these errors do not happen, but users may send incorrect commands or there can be a technical problem with the bus. I 2 C slaves usually do not have users, so there is nobody who can do anything to clear these errors. The best solution in such cases is to perform a soft reset on the microcontroller. This takes practically no time to execute, and it automatically restores all registers and flags to good states without requiring the user (that means you) to know exactly what was wrong. if error then -- unexcepted I2C event, soft reset asm CLRF PCLATH asm GOTO 0x00 end i f Demo project 2: Light Meter The second project is a light meter using an LDR. The microcontroller is blessed with five unused analog channels. Here we use just one of them to connect the LDR. In this case it is not neces- sary to send a command to the microcontroller, since there's only one thing it can measure. We simply send the address with the Read bit set: data = bus . read_byte (address) The microcontroller receives this address with the Read bit set and knows that it has to return a response. It prepares the response and sends it back: -- wait for address (and ignore) dummy = i 2c_slave_read_byte -- prepare reply and send it mydata = ADC_read_low_res (0) i 2c_slave_wri te_byte (mydata , error) This is followed in the code by the usual error handling routine, which you can read at your leisure in the downloadable source code for this article. With a few minor changes, you can also use the code to read a temperature sensor or operate an ultrasonic distance sensor, such as the SRF05. The software necessary for this article is avail- able for download at [1]. For more projects of a similar nature, see the books Raspberry Pi - Explore the RPi in 45 Projects , 50 PIC Microcon- troller Projects for Beginners and Experts , and PIC Microcontrollers - 50 Projects for Beginners and Experts, all available in the Elektor Store. ( 130583 - 1 ) Web links [1] www.elektor-magazine.com/130583 About the author Bert van Dam is a freelance author of books, course material and articles about PIC and ARM microcontrollers, Arduino, Raspberry Pi, Artificial Intelligence, and the programming languages JAL, C, assembler, Python and Flowcode. ten Yin Dacji ■ Raspberry Pi EKptore "hr ~-i Pi in 4; ElHErDnir-t ft g jet n, www.eIektor-magazine.com June 2014 49 •Projects We're going to start with a reminder of the basics of photo- voltaic energy and the commonest techniques, followed by simplified calculations for a small installation and the princi- ples for implementing one. I won't be going into greater depth on any specific points, but at the end of the article you'll find a number of references to useful books and links. By Pascal Rondane (France) pascal.toursrondane@gmail.com Many techniques are still at the research lab stage. Others, like those using gallium arsenide (GaAs), which currently offer the greatest effi- ciency (20-25%), are used for powering satel- lites. Their cost puts them out of reach for private individuals. Here are the commonest techniques. Monocrystalline silicon Monocrystalline silicon cells, very widespread, offer good efficiency: 15% (under stan- dard test conditions). These bluish colored cells consist of a sin- gle crystal and have a uniform appearance. The manufacturing process involves melting bars of silicon then cooling them slowly to achieve a homogeneous crystal. Polycrystalline silicon As their name indi- cates, polycrystal- line silicon cells are made up of multi- ple crystals, with an appearance rather like a mosaic; their efficiency is 12-14% below that of monocrystalline cells; they are also less expensive. Amorphous silicon Amorphous silicon cells have only low efficiency (5-7%), but they work just as well indoors as out, which means they are used primarily in con- sumer applications (watches, calculators, etc.) CIS cells CIS (copper/indium/selenium) cells represent the new generation of thin-film solar cells. The 50 June 2014 www.elektor-magazine.com PV Panel Calculation materials used in making are not toxic and are easy to obtain. This type of cell can be made on flexible modules, but the manufacturing process for them is quite complex. They offer good efficiency (10-14 % or even higher) and are starting to be produced, in partic- ular by Saint-Gobain in the author's home coun- try, for industrial installations. Definition of solar energy It's important to make it clear that the function of photovoltaic solar panels is to convert light radi- ation into electric current; if their operation was associated with direct solar radiation, the slightest cloud would compromise their reliability in use. The efficiency of a photovoltaic panel depends first and foremost on the exposure : in strong sunshine out of a cloudless sky, this can reach 1000 W/m 2 . In cloudy weather, it is still around 500 W/m 2 , while in overcast, rainy weather, it remains at best between 100 and 50 W/m 2 ! If it doesn't drop to 0 W/m 2 ... The watt-per-square-meter is the unit used to quantify solar irradiation. Solar panels are char- acterized by the electrical power they produce under solar radiation of 1000 W/m 2 at a tem- perature of 25 °C. In concrete terms, a so-called 20-watt solar panel produces these 20 watts under light radiation of 1000 W/m 2 (strong sunshine in cloudless sky); in overcast weather, only around half of this power Global irradiation* {kWh/m] <600 <450 800 600 1000 750 1200 1400 900 1050 1600 1200 1800 1550 2000 1500 >2200 >1850 Solar electricity** [kWh/kWpeak] PVG 1 S htt pi// re.j re. e c eu ro p a.e u/pyg i s/ PVGJS European Union, 2001-2012 Yearly sum of global irradiation incident on optimally inclined Yearly sum of solar electricity generated by optimally-inclined south -oriented photovoltaic modules IkWp system with a performance ratio of 0.75 www.elektor-magazine.com June 2014 51 •Projects will remain. Not forgetting the junction tempera- ture of the photovoltaic cells, which also influ- ences the panel's efficiency: the modules lose 0.4 % per degree. Solar panel operating tem- perature depends on the incident radiation, the ambient temperature, the color of the materials, and also the wind speed (5-14% cumulative loss). The second determining factor is the exposure duration, as even on a fine Summer's day, the lighting varies throughout the day in a not-in- significant way. The time window during which the solar panel receives its maximum energy is only a few hours. In Winter, the light radiation diminishes, and can even disappear for several days in the event of snow or fog. Calculations and implementation In order to size and then implement a photovol- taic system, we have to proceed in stages. Evaluating requirements Before starting to calculate, let's remember the difference between energy and power. Power is an instantaneous dimension (rate of flow). Example: a lamp consumes 20 W; a solar panel produces 40 W at instant t. Energy is an element that is integrated over a period of time. Electrical power is measured in watts (W), kilo- watts (kW), or megawatts (MW). Power is the transfer of energy per unit time. energy = power x time Energy is expressed in watt-hours (Wh). If the battery voltage is known, the unit of consump- tion normally used in calculations is the ampere- hour (Ah). Evaluating consumption Photovoltaic panels only supply energy during the day, but the unit of time used is the whole 24 hr period, which means we'll be working in Ah per day. Sizing the battery As the photovoltaic panel supplies energy only when it is receiving light radiation, a battery is needed to store the energy. The battery life expectancy is the time for which the battery can keep the load operating without being recharged by the photovoltaic panel. We generally allow for a battery life of five days, to cover severe winter weather conditions with extremely low light radiation. In order to calculate the battery (accumulator) capacity, we multiply the electrical consumption (Ah) by the battery life required, and then apply a safety factor (0.7) corresponding to the bat- tery's loss of charge at the lowest operating tem- perature considered and to the additional losses (battery charging efficiency, regulator conversion efficiency, battery self-discharge). The calculation indicates the capacity actually available at any moment. In the example below, this is equal to 70 % of the nominal capacity. Table 1 device(s) number of devices current drawn (A) duration of use in 24 hrs energy = current x duration photovoltaic regulator 1 0.020 24 h 0.020 x 24 = 480 mAh LED lamps 3 0.150 4 h 0.150 x 3 x 4 = 1.8 Ah total energy consumed over 24 hrs: 2.28 Ah power consumed per day: 2.28 x 12 V = 27.36 Wh/day 52 June 2014 www.elektor-magazine.com PV Panel Calculation useful capacity = nominal capacity x usable percentage C(Ah) = consumption of the system in 24 hr battery life in days OJ C(Ah) = 2.736 / dx3 d OJ = 12 Ah The battery capacity has been rounded off. It is preferable to choose a maintenance-free lead-acid gel battery (e.g. Yuasa 12 V 15 Ah) rather than a motorbike -type battery, where you have to check the level of the liquid electrolyte periodically. Calculating recoverable solar energy The solar irradiation (in W/m 2 ) falling on the photovoltaic panel varies during the day, depend- ing on the time and weather conditions. Various websites give the amount of sunshine in Wh/m 2 according to the time of day and geographical location. The average values are spread over the year. For sizing the installation, we'll take the least favorable value (December). A few average solar irradiation values: • Paris region: 1.12 kWh/m 2 /d • South of France: 3 kWh/m 2 /d • North Africa: 5 kWh/m 2 /d W/m2 Example of measuring exposure These readings taken in December show that the exposure level was low (50 W/m 2 on 12/18 and 200 W/m 2 on 12/19) in the French city of Tours. The measurements were taken using a solarime- ter, which gives an instantaneous reading of the solar irradiation in W/m 2 . Using photovoltaic panels The position and orientation of the photovoltaic panels are determining factors for the efficiency of the installation. Orientation: the cardinal point is located towards the sun's highest point; in the northern hemi- sphere, that's the south, and towards the north if you are in the southern hemisphere. panel power = Inclination: the optimum inclination with respect to the horizon is usually taken as the latitude of the location plus 15°. consumption of system over 24 hr (Wh/d) daily exposure ( kWh I m 2 I d)x loss factor 32.8 " 1.120x0.7 The "L+15°" inclination rule of thumb optimizes the production of energy in the least favorable months (Winter); for Summer use only, the opti- mum angle would be much smaller. You can refer to the website [2] which gives the optimum incli- nation for each month of the year (Table 2). The panel power again has been rounded. Which gives requirement for a solar panel with a power of 50 W. Note: Settling for a 20-watt panel to power a load of the same power is a (frequent) error to be avoided! Shadows falling on the photovoltaic panels will affect their efficiency. These are mainly caused by chimneys, trees, or nearby buildings. Or by dead leaves or any other object liable to cover part of the panel. Watch out! This is not harmless. You must take care to eliminate any obstacles of this type, as the cells in the panel that are no longer illuminated become current www.elektor-magazine.com June 2014 53 •Projects Table 2. Solar Irradiation for a site in central France, drawn up by PVGIS (Photovoltaic Geographical Information System) [2] Monthly Solar Irradiation | PVGIS Estimates of long-term monthly averages. Location: 47°13'10" North, 2°H'50" East, Elevation: 113 m ASL. Solar radiation database used: PVGIS-CMSAF. Optimal inclination angle is: 36 degrees from vertical (= 54 degrees elevation). Annual irradiation deficit due to shadowing (horizontal): 0.0 %. Month Hh " opt H(36) I opt ~^24h N D d Jan 1070 1710 1710 63 4.5 400 Feb 1780 2580 2580 57 5.4 341 Mar 3160 4120 4120 47 8.2 273 Apr 4590 5180 5180 33 10.4 173 Mei 5370 5390 5390 19 14.6 65 Jun 6050 5820 5820 13 18.3 16 Jul 5860 5780 5780 17 20.1 2 Aug 4960 5360 5360 28 20.2 15 Sep 3920 4920 4920 43 16.4 97 Okt 2290 3250 3250 54 13.3 214 Nov 1220 1910 1910 62 7.4 368 Dec 971 1530 1530 63 4.7 414 Year 3440 3970 3970 36 11.9 2378 H h : Irradiation on horizontal plane (Wh/m 2 /day) H opt : Irradiation on optimally inclined plane (Wh/m 2 /day) H(36)\ Irradiation on plane at angle: 36deg. (Wh/m 2 /day) I opt \ Optimal inclination (deg.) T 24h \ 24 hour average of temperature (°C) N dd \ Number of heating degree-days (-) PVGIS © European Communities, 2001-2012 consumers and start heating up. It's sometimes called the hot spot effect, and can have undesir- able consequences. Maintenance With an inclination of L+15°, rain does a good job keeping photovoltaic panels clean. You'll need to periodically check the connections are in good condition (tightening, oxidation). Charging regulator operating principle The charging regulator [1] checks and protects the battery from over-charging and also deep discharge, which would damage it irreversibly. A photovoltaic installation is made up as follows. Reverse blocking diode Generally inserted in the circuit at the solar panel connecting box, this avoids the battery's discharg- ing through the solar panel at night or when the battery is fully charged and its voltage is higher than that of the panel under low illumination. Schottky diodes are preferred for their low for- ward voltage (0.4-0. 6 V). On bottom-end pan- els, we find conventional diodes, which entail a voltage drop of 0.8 V. This higher threshold is not negligible in our calculations, as on a 12 V solar panel it entails a 7% loss. Charging regulator Its function is above all to preserve battery life. When the battery voltage reaches 14.4 V (nominal threshold), the regulator interrupts the charging of the battery, starting it again when the voltage drops below 12.6 V again. Most modern chargers use a battery charge / 54 | June 2014 www.elektor-magazine.com PV Panel Calculation discharge calculation algorithm so as to make the best possible use of it. Discharge limiter Here, the aim is to protect the battery against deep discharge. When the battery voltage drops below 11.6 V, the limiter disconnects the load being powered by the photovoltaic installation in order to relieve the battery; the load is connected again when the battery voltage reaches 12.6 V. Batteries do exist that can withstand deep dis- charge, but they are markedly more expensive than a standard battery. A graph provided by the battery manufacturer makes it possible to calculate its life in accordance with the level of discharge accepted. The heavier and more frequent the discharges, the shorter the overall battery life. Modes The drawings opposite show the system's three different modes of operation. At the top, the bat- tery is fully charged and powering the installation. In the center, the battery is deeply discharged. Consequently the load is disconnected and the bat- tery is being charged by the PV panel. The lower drawing shows the battery partly charged, and connected to the solar panel as well as the load. To complement all these notions and put them into practice under the best conditions, I'll con- clude by proposing a spreadsheet for calculating the battery life for your photovoltaic installation. Download it from the page for this article on our website [3]; it will enable you to find the opti- mal size for your panels, regulator, and battery. ( 130404 ) Web Links [1] www. elektor-magazine. com/080305 [2] http://re.jrc.ec.europa.eu/pvgis/apps4/pvest. php# [3] www. elektor-magazien.com/1 30404 Sources http://en.wikipedia.org/wiki/Photovoltaic_panel www.elektor-magazine.com June 2014 55 •Projects Hack-Your-Own Reflow Oven Fan-assisted oven for SMDs Electronics is an activity where not moving forward equals going backward ! From electronic tubes to microcontrol- lers, via 40xx CMOS and transistors, I've always tried to get to grips with and make use of the new techniques, while remaining cautious. The SMD step was a tricky one, but I managed it, and I'm very pleased with the outcome. I just hope you can benefit from my experience! By Jean-Pierre Duval (France) Although the name doesn't actually say so, a reflow oven is used to solder surface-mounted devices or SMDs. Now certain integrated circuits exist only in an SMD version, it's more difficult for an electronics enthusiast to get by with- out these omnipresent SMDs. They are often cheaper than conventional through-hole com- ponents. Thanks to SMDs, printed circuits are getting smaller— and thus the cost of projects. The fact remains that for soldering these minia- ture components, you need little fairy fingers... or a reflow oven! You're hesitating? Well, I'm not hesitating any more. Before getting into the reflow oven proper, it's worth taking a quick look at SMD technology (see inset) if this is new to you. This is also the moment to remind ourselves of the steps in pro- ducing a PCB using SMDs: o a • If you use a program like ISIS/ARES, Eagle, etc. for designing the circuit, define right at the design stage the package to be used, allowing for the power to be dissipated. • The layout itself isn't a problem, unless from the outset you are looking for a very high density. • The solder paste can be applied either using a mask, or by syringe. The latter lets you reduce paste consumption. Using the mask, you spread a (larger) amount of paste, then remove the mask carefully to avoid overspill. The Author Passionate about his profession, electronics, through measurement and now particularly measuring time, Jean-Pierre Duval spent most of my career in electronics and robotics in the field of medical, biological, and agro-food laboratories. With the CECOS laboratory at the Cochin hospital in Paris, he perfected the first morphological sperm counters, which are still on the market today. 56 June 2014 www.elektor-magazine.com Reflow Oven After use, the paste has to be kept in the ice-box and must be heated up at least 2 or 3 hours before you want to use it. • Place the components on the paste pads (a delicate stage!) • Baking or reflowing. • Cleaning the circuit using a suitable chemical. • Magnifier inspection to get rid of the lit- tle blobs of paste that are liable to create shorts. Making the move to SMD involves a certain amount of investment, which you can minimize by making a sum of the tools yourself— includ- ing the reflow oven itself and the squeegee for applying the solder paste. But I will just point out that the project described here is not intended to be copied exactly. It should simply provide you with the initial inspiration, just as I myself drew inspiration from earlier projects [3]. Why fan-assisted? Having worked for a long time inspecting ovens, incubators and autoclaves and measuring their characteristics, I know that an oven is only usable if its temperature is uniform at all points— whence the use of a fan-assisted oven. Imagine a cell culture to be carried out in an oven at 37 °C (98.60 °F). At 40 °C (104 °F) it will be cooked; at 35 °C (95 °F) it won't grow at all. So we need the same temperature everywhere. The same M nine Imperial comparrswi cpcie mrlri 0 1 :