Edition 5/2015 | September & October 2015 www.elektormagazine.com LEARN DESIGN SHARE VFD Shield for Arduino Cell Replacement on USB AC/DC Power Meter • Android I/O Board • Arduino Sound-Level Protector • ARM Micros and the Analog World • Bike Inclinometer • BL600 e-BoB • I 2 C and temperature sensor • Camelback Water Level Indicator • Dimensioning a 3D Model • Err-lectronics • FFT Analysis in VB • Hexadoku • I/O App (2) • Learn-'n-Go Infrared Remote Controlled Dimmer • Over-Air LiPo Battery State Monitor • PIC Assembler Crash Course • Retronics: Preco 39 Years On • RPI Measures Electricity Consumption • Selected Gerber Files • Selenium Rectifiers • Single Wire LCD Interface • SMD Codes Revealed • TinkerForge Bricks & Bricklets • USB Pseudo Battery • VFD Shield for Arduino • Wireless I 2 C Sensor ... and more AC/DC Power Meter PC OSCILLOSCOPES SiSS 1 Technology = Low cost MSO Eight channels Flexible resolution 2 GS memory 20 GHz sampling 10 MHz to 200 MHz bandwidth 100 MS to 1 GS/s sampling 8 bit resolution (12 bit enhanced) 8 to 48 kS buffer memory USB powered Prices from $129 €99 £79 2 or 4 analog channels + 16 digital 50 to 200 MHz bandwidth 8 bit resolution (12 bit enhanced) 64 to 512 MS buffer memory USB or AC adaptor powered Prices from $819 €659 £499 20 MHz bandwidth 80 MS/s sampling • 12 bit resolution (16 bit enhanced) • 256 MS buffer memory • USB powered Just $2305 €1845 £1395 8, 12, 14, 15 & 16 bits all in one device 60 to 200 MHz bandwidth 250 MS/s to 1 GS/s sampling 8 to 512 MS buffer memory USB or AC adaptor powered Prices from $1155 €929 £699 250 MHz to 1 GHz bandwidth 5 GS/s sampling 8 bit resolution (12 bit enhanced) 256 MS to 2 GS buffer memory AC adaptor powered Prices from $3295 €2645 £1995 DC to 20 GHz bandwidth 17.5 ps rise time 16 bit, 60 dB dynamic range AC adaptor powered Sig. gen, CDR, diff. TDR/TDT Prices from $14,995 €12,035 £9,085 Full software included as standard with serial bus decoding and analysis (CAN, LIN, RS232, 12C, I2S, SPI, FlexRay), segmented memory, mask testing, spectrum analysis, and software development kit (SDK) all as standard, with free software updates. Five years warranty real time oscilloscopes, 2 years warranty sampling oscilloscopes. www.picotech.com/PS411 Edition 5/2015 Volume 41, No. 464 & 465 September & October 2015 ISSN 1947-3753 (USA / Canada distribution) ISSN 1757-0875 (UK / ROW distribution) www.elektor.com, www.elektormagazine.com Elektor Magazine, English edition is published 6 times a year by 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/member UK / ROW Memberships: Please use London address E-mail: service@elektor.com Internet: www.elektor.com/member Advertising & Sponsoring: Johan Dijk Phone: +31 6 15894245 E-mail: johan.dijk@eimworld.com www.elektor.com/advertising Advertising rates and terms available on request. Copyright Notice The circuits described in this magazine are for domestic and educational 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 repro- duced or transmitted in any form or by any means, including photocopying, 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 failing to identify such pat- ents) or other protection. The Publisher disclaims any responsibility for the safe and proper function of read- er-assembled projects based upon or from schematics, descriptions or information published in or in relation with Elektor magazine. © Elektor International Media b.v. 2015 Printed in the USA Printed in the Netherlands Beyond Repair, never Beyond Measurement If we have to accept that the electronic engineer is no longer the highly respected tech wizard on the block or street, always ahead of mass produced consumer stuff on the shelves, and forever pushing the performance of 'his' components, let's content ourselves with doing measurements and spreading the word on perfecting the art of measuring in the world of electronics. Even if your daughter's 14-inch super VGA LCD monitor is not worth repairing as it would have been 20 years ago, there is value and satisfaction in hunting down the one elec- trolytic capacitor with the bad ESR, replacing it, and finally moving that monitor to your workspace where an old PC is running programs Windows 8 does not like. As a spinoff there should be enough impressive numbers and Dilbert-ish commbuzzwords that can be linked to your repair job, for your daughter to copy-paste a report with for her economics classes, like "bathtub curve", "costing estimate" and "parts resources", as well as a ton of acronyms like DOA, FOA, BR, DIY. And she can have a new HDMI 23-inch LED screen. Your part of the job requires knowledge, basic test equipment and some confidence. If designing a circuit is fun and creative, so is repairing and restoring one labeled BR (beyond repair). In both cases, expert test gear is required and a deep knowledge of what you are measuring. Browsing this edition of Elektor I hope you have as little dif- ficulty finding measurement-related articles as I had while compiling the lot and going through the pre-press phases: the PIC Assembler Course this month touches on analog circuitry, this intrinsically involves ADC'ing real-world quantities; FFT Analysis on page 30 should be obvious; just like AC/DC Power Meter on page 46; and of course the RPi Electricity Consumption Meter (page 59). Challenging articles, all three. At a less ambi- tious level at least electronically there's the Cameiback Water Level Indicator (page 76) and the Bike Inclinometer (page 80). Although all projects mentioned here appear designed for a purpose, the articles hope- fully contain elements that widen, trigger or channel your own creativity. Our humble contributions this month include how-to's of power metering the proper way, water level metering the cheap way (with two 4060's), and LiPo voltage metering, hey, over-air! Measure it — understand it — stay in the lead! Enjoy reading this edition Jan Buiting, Editor-in-Chief The Circuit Editor-in-Chief: Jan Buiting Publisher: Don Akkermans Membership Manager: Raoul Morreau Client Executive: Cindy Tijssen 4 International Editorial Staff: Harry Baggen, Jaime Gonzalez-Arintero, Denis Meyer, Jens Nickel % Laboratory Staff: Thijs Beckers, Ton Giesberts, Luc Lemmens, Clemens Valens, Jan Visser Graphic Design & Prepress: Giel Dols Online Manager: Danielle Mertens www.elektormagazine.com September & October 2015 3 ^ THIS EDITION Volume 41 - Edition 5/2015 No. 464 & 465 September & October 2015 6 Elektor Circuits & Connections 34 Industry: News & New Products 36 Industry: Man & Machine: the Distance that Brings us Closer 38 Welcome to Elektor Labs 104 Elektor Store LEARN DESIGN SHARE 9 Welcome to the LEARN section 10 From 8 to 32 Bits: ARM Microcontrollers for Beginners (5): The Analog World 15 Peculiar Parts: Selenium Rectifiers 16 DesignSpark Mechanical CAD Tips & Tricks (2): Dimensioning a 3D Model 18 PIC Assembler Crash Course (2): Mini dev board and electronic die 24 I/O App (2): Control external hardware with a Windows app 29 Tips & Tricks: Safety Tip for AVR Control- lers; Variometer Tuning 30 FFT Analysis in VB LEARN DESIGN SHARE 40 Welcome to the DESIGN section 41 Learn-'n-Go Infrared Remote Controlled Dimmer 46 AC/DC Power Meter 54 VFD Shield for Arduino 59 RPI Measures Electricity Consumption 64 Android I/O Board (1) 71 BL600 e-BoB (4): The I 2 C port and the temperature sensor VFD Shield for Arduino Nixie tubes have enjoyed renewed popularity for some time with retro & vintage enthusiasts and on the Internet there are countless designs for Nixie clocks to be found. In Elektor too, we have published several projects with Nixie tubes in recent years. However, in this project we do not use Nixies, but instead make use of VFD (Vacuum Fluorescent Display) tubes. These are somewhat different from the well-known Nixie tubes and are currently gaining popularity. This Arduino shield has been designed from an educational viewpoint and therefore does not have any SMD components or parts that are difficult to obtain. 76 Camelback Water Level Indicator 80 Bike Inclinometer 84 Wireless I 2 C Sensor 88 Arduino Sound-Level Protector 92 Single Wire LCD Interface 96 Over-Air LiPo Battery State Monitor 102 USB Pseudo Battery 4 september/oktober 2015 www.elektormagazine.nl 46 AC/ DC Power Meter This project consists of a measurement board holding the ADS1115-eBoB together with a small filter board. Good isolation is guaranteed between the power connections (AC or DC) on the primary side and the measurement signal outputs on the secondary side. The signals on the secondary side are digitized by the ADS1115, and the digital data is fed to an Arduino Uno with an Elektor Prototyping Shield. The displayed quantities for AC are effective power, voltage and current, as well reactive power and power factor. © ektor magazine LEARN DESIGN SHARE 111 Welcome to the SHARE section 112 Review: German Brickwork (TinkerForge Bricks & Bricklets) 116 Escaped from the Labs: Selected Gerber Files 118 What's Hot at dot Labs: It's been a hot, hot summer 120 Err-lectronics: UART/RS-232 Data Logger; J2B Synthesizer; USB Hub; ARM Course (3); USB-to- Multiprotocol Converter; AVR Port Toggle; TCA580 Gyrator 122 Web Scouting: SMD Codes Revealed Android I/O Board Part 1 Control embedded electronics from your Android phone or tablet 124 Retronics: Preco 39 Years On 128 Elektor World News 130 Play & Win: Hexadoku ^ NEXT EDITION MEASSY Audio Measurement System This compact device combines a high-quality microphone preamplifier with phantom power supply with a small audio output stage in a single enclosure. You guessed it: MEASSY is geared to loudspeaker system measurements. Compact 60-watt Audio Amp This audio output stage is an all-discrete design. The circuit contains only commonly available components, is easy to build, takes up little board space, yet delivers fine sound quality. Red Pitaya Does FM Stereo Radio This article underscores the sheer versatility of the Red Pi- taya development system. By adding a small prestage, and doing efficient digital editing, FM broadcasts (stereo and RDS) can be decoded. Edition 6 / 2015 covering November & December is published on October 15, 2015. Delivery of printed copies to Gold members subject to transport. Contents and article titles subject to change. www.elektormagazine.nl september/oktober 2015 5 - * tor J Bp" Elektor breaks the corfstraints of a magazine. . , ar^ It s a community of active e-engineers — from noviceg to professionals — eager to learn, make, design, and share surprising electronics. - j 4 4 r \Z1 J/ up 3 V Countries Circuits & r >1 r □UC01 ~ l_ IUU 1 / ) l J V Enthusiastic Members in iu Experts & Elektor Post The e-inspiration weekly v Never monostable and with trigger signals % all over the contents, Elektor's dot-Post weekly newsletter has the ability to ring in the weekend with gossip, techtalk, stray bits, previews and news flashes. And a project every other week. www.elektor.com/newsletter Elektor TV We're tubed too No film set, suits, or Action! but you can rely on a camera rolling when- ever things start humming, booting, displaying or smoking at Labs, or indeed any place or event our pre- senters find video compatible. Check out elektor.tv. www.youtube.com/ user/ElektorIM Elektor Labs Learn, Design & Share The techno creative center of Elektor that's k steeped in hard core electronics all the way W from scribble to PCB, component and kit. Wide open and accessible through its own website, Labs is where projects large, small, analog, digital, new and old skool are sketched, built, discussed, debugged and fine-tuned for replication and use by you. www.elektor-labs.com ||| Elektor Community Become a member. Green or Gold Membership of the Elektor Community is the surest way to enjoy classic electronics and embedded technologies side by side, ranging from beginner to pro. With direct access to Elek- tor Labs, forums, discounts, weekly newsletters, biweekly online projects, article archives, search engines, and back articles Green and Gold Mem- bers have permanent priority seating. Go GREEN if you want the magazine front to back delivered online only, or GOLD for the sumptuous package including printed copies. www.elektor.com/memberships Elektor PCB Service Boards at your service Forget the chemicals, get your electronic project to work as expected by ordering a ready-manufactured circuit board. Fast turnaround, pure quality, worldwide shipping. www.elektorpcbservice.com Elektor Academy Ride the learning curve Webinars, seminars, courses, presen- tations, workshops, lectures, in-company w trainings, DVDs, and demos are just a few of the methods Elektor is using to spread the word about electronics both at hobby and professional levels. www.elektor-academy.com 6 September & October 2015 www.elektormagazine.com Connections Guide L U 3 Authors Publications Montly Visitors' Print Time Elektor Magazine Close to 1024 pages of surprising electronics a year If you prefer to absorb electronics over k being absorbed, stick to reading Elektor's flagship product DMA'ed to you by their international editorial team. Whether arriving online or on paper every magazine edition is packed with electronics all- sorts for you to enjoy and explore in your own time. Free! Sign up! www.elektormagazine.com Elektor Web Store Fill your shopping cart > Elektor has confidence in the products and services generated by Labs, Magazine, and selected business partners. That's why a brightly illuminated online retail store is open 24/7/365, with ordering and payment facilities for clients all over the world. An Aladdin's Cave of electronic parts and gizmos. www.elektor.com (fki Elektor Books & DVDs E-Information Powerpacks It's hard to find a field of electronics not covered in depth and with authority by the products in our book and DVD portfolio. From reference work to programming course, 8-bit to ARM, Antenna to Zener diode; it's all there. www.elektor.com Become a member today! w GOLD € 1.75 per week £1.27 / US $1.97 GREEN € 1.31 per week £0.97 / US $1.49 FREE ✓ Elektor Annual DVD X Elektor Annual DVD X Elektor Annual DVD 6x Elektor Magazine (Print) X 6x Elektor Magazine (Print) X 6x Elektor Magazine (Print) 6x Elektor Magazine (Digital) 6x Elektor Magazine (Digital) X 6x Elektor Magazine (Digital) Access to Elektor Archive Access to Elektor Archive X Access to Elektor Archive Access to Elektor.LABS Access to Elektor.LABS X Access to Elektor.LABS 10% Discount in Elektor Store 10% Discount in Elektor Store X 10% Discount in Elektor Store Elektor.POST Newsletter Elektor.POST Newsletter Elektor.POST Newsletter 25 Extra Elektor Projects 25 Extra Elektor Projects 25 Extra Elektor Projects Exclusive Offers Exclusive Offers Exclusive Offers www.elektor.com/gold www.elektor.com/green www.elektor.com/newsletter www.elektormagazine.com September & October 2015 7 CC2200 All trademarks mentioned herein belong io their respective owners. KCS TraceME product tine offers an intelligent location based positioning solution for indoor and anti-theft applications.The solution is based on RF with an intelligent algorithm of measuring the propagation time of transmitted (proprietary protocol) signals. Unique features are: minimum size (46x£lx6.5mm), weight (7 grams for fully equipped PCS) and a standby battery lifespan of more than 10 years. 'Listen before talk' algorithm makes it practically impossible to locate the module, which secures the valuable vehicle or asset. Supporting GPRS/SMS and optional 3G, Wi-Fi, Bluetooth LE, AhFI7AtsTr+ and iBeacon provide easy integration with existing wireless networks and mobile apps. ANTI-THEFT modu e based on RF loRa‘ TM) BLE M£M idium Sensor Bluetooth SMS iBeacon CM) Glonass GPRS RF GPS UOe MI5FA-03-ST0 MS5FARD1A01 FA sz-wmz $M:MP£4912N4Q00189 FMEf:503071Q 15649037 LoRa ™ Internet of Things KCS has extended their successful TraceME product line with an advanced module, targeted for worldwide mobility in the Internet of Things era. The latest development of the TraceME GPS/GPRS Track and Trace module will combine the RF location based positioning solution with the LoRa™ technology. This combination offers 'smart objects' being even smarter, since LoRa™ enables long range, battery friendly communication in a wide variety of (M2M) applications Supporting GPRS/SMS and optional 3G, Wi-Fi, Bluetooth LE, ANT/ANT+ and iBeacon™ provides easy integration with existing wireless networks and mobile apps. Other variants in the high/mid-range and budget-line will follow soon. LEARN DESIGN SHARE Welcome to the LEARN section By Jens Nickel @ the Maker Faire By the time you read this the last discarded coffee cup, wire clipping and solidified solder blob will already be swept up and con- signed to the trash after this year's Maker Faire held in Hannover, Germany. I would like to thank all our colleagues at Make: for ensuring this event was such a success. I don't know how, but they even man- aged to arrange good weather! The hands-on activ- ities were particularly inspiring for all the (really) young engineers in attendance. The eight solder- ing stations at our workshops (photo) were only allowed to cool down once the last 'Electronic Dice' kit had been fully assembled. It was also a good opportunity to check out many of the latest developments, boards and projects that were on show. One product that caught my eye was the system of hardware modules from Brick ,R' Knowledge (www.brickrknowledge.de); these well designed modules look particularly use- ful for (but not just for) the teaching of electron- ics. Another interesting project is the 'SenseBox'. This IoT sensor kit is also targeted at education and includes an Internet platform to collect data from numerous environmental sensors measuring air pressure, temperature, humidity and incident light levels. Two versions of the system are avail- able; one for education and another for DIY use. Learning to Program (2) I have already received a number of emails in connection with the '(High)School Board' sug- gestion and the 'Learning to program' editorial, many thanks for those, your feedback is always welcomed. Amongst other things a reader pointed me toward 'Project Oberon' by Niklaus Wirth. I must admit I had not been aware of this FPGA- based processor hardware (see for example www. xilinx.com/publications/archives/xcell/Xcell91.pdf, from page 30). Another reader suggested the low-cost Launchpad range of development kits from TI. Once again I was grateful for the com- ments from another reader who, like me, wanted a board programmable using C# supporting both PC and embedded environments that could be programmed by using just one programming lan- guage. Perhaps we should begin with a Raspberry Pi 2 running Windows — quite intriguing. And then there was... Another episode from the ongoing 'stupid-mis- takes-made-while-designing-and-developing' saga. I would of course prefer to keep these to myself but that way nobody would profit from my errors. Finally I got to porting the MIDI Analyzer (featured in the last edition) firmware from the Arduino Uno to the Elektor Xmega Webserver board. My EFL con- figurator had been set up so that with just a single key press an Xmega project is generated with all the necessary files and the hardware-independent source code for the MIDI analyzer. Now all I need to do is change the number of the UART interface in the code which talks to the MIDI module. The compiler worked its magic without any errors but something here didn't look right; the power LED on the MIDI module did not light up when it is plugged into the Xmega board. I chose a second board, this time it worked. A quick look at the sche- matic revealed the reason why: The first board was missing a jumper! Sometime in the past I had, for some reason, removed it. The lesson here is that it always pays to double check the documentation before you bring a board back into use again. This is especially true when you are totally confident you already know the board inside out! M ( 150319 ) www.elektormagazine.com September & October 2015 9 By Viacheslav Gromov (Germany) So far in this course we have looked at the SAM D20's wide range of digital peripheral blocks; now it is the turn of the analog circuitry. It will come as no surprise to readers with experience from the world of 8-bit microcontrollers that we will be looking in detail at both the analog-to-digital converter (ADC) and analog comparator (AC); and to those we also add the digital-to-analog converter (DAC). Our SAM D20 includes a powerful ADC with a resolution selectable between eight, ten and twelve bits. Its structure is illustrated in Figure 1. The same rule of thumb applies as in the case of eight- bit microcontrollers: the lower the reso- lution, the shorter the conversion time. The SAM D20's ADC can manage up to 350,000 conversions per second, while in oversampling mode it can achieve a res- olution of 16 bits. As many as 32 inputs to the converter are available, of which up to ten can be used as inverting inputs and 25 as non-inverting inputs (some being able to function as either). Some of the inputs are designed to be used with internal sources such as the DAC or temperature sensor. As can be seen from the block diagram, the ADC always requires a non-inverting and an inverting input and will convert the voltage differ- ence between these two inputs into a digital value. The inverting input can of course simply be connected to ground. The ADC also requires a reference volt- age, of which several are available. If, for example, the voltage reference is 1 V, the maximum voltage the ADC can measure will also be 1 V; if the resolution is set to 12 bits, then the output will be expressed in steps of approximately 0.0002 V. Other functions available include amplifying the input signal with a gain of between 0.5 and 16, and a window comparison mode to monitor whether the measured values fall within a specified range. An inter- rupt can be triggered if the limits are exceeded. The ADC can be configured to carry out a single conversion or to carry out continuous conversions when started. Further information on the ADC can be found in the datasheet starting on page 481. First experiments with the ADC The ADC is an important peripheral block, and so we of course want to see what it can do in practice. Figure 2 shows a simple circuit that can be built using an LM335 analogue temperature sensor. The two components can easily be soldered together in mid-air (see Figure 3). To obtain accurate readings the cable should be kept reasonably short. The temperature sensor is easy to use and exhibits good linearity [1]. We would like to measure the temperature using the ADC and output the readings once per second to the PC over the virtual serial port (UART). The project 'ADC Testl' shows how this is accomplished: like all the code accompanying this article it is available for download at [2]. Supplemen- tary documents including code listings are also available from the same location. At the beginning of the main file are the commands to create the instance struc- tures for the U(S)ART and for the ADC, the function prototypes, the declaration CTRLA WINCTRL AVGCTRL WINLT Figure 1. Outline structure of the analog-to-digital converter (ADC). 10 September & October 2015 www.elektormagazine.com ; jh TRAINING SOF Q&A TWi of various variables and the by-now-fa- miliar configuration function to set up the U(S)ART for EDBG communication at 9600 baud. Next comes the configu- ration function for the ADC, as shown in Listing 1 [2]. As is usual when using the ASF, we begin by declaring a configura- tion structure called config_adc whose members will be filled with the required settings using symbolic constants. The variables posi ti ve_i nput and nega- ti ve_i nput select the source for the non-inverting input (AINO on PB00) and for the inverting input (GND). The struc- ture member reference is used to set the reference source to AREFB on pin PA04. We have connected AREFB to VCC, which means that the reference voltage will be 3.3 V. The overall 3.3 V range is converted at a resolution of 12 bits, as specified by the structure member res- olution. The input gain is set to unity using the member gain_factor, which means that the input voltage will be con- verted at 1:1 without amplification. We disable division of the ADC result and disable window mode using the mem- bers di vi de_result and window_mode respectively. At the end of the function the settings we have written to the con- figuration structure are passed to the ADC and it is enabled. From this point on the ADC can be referred to via its instance structure adc_instance. In the main function we first initialize the microcontroller and then call the two con- figuration functions described above. Then there is an infinite loop containing the core of the program (see Listing 2 [2]). It begins with a call to carry out a single conversion, passing the instance structure as the argument: adc_start_conver- si on (&adc_i nstance) ; . The we wait in a while-loop repeatedly calling the func- tion adc_read (&adc_i nstance, &data) ; which attempts to read the ADC conver- sion result. The loop terminates when the conversion is complete and the func- tion no longer returns STATUS_BUSY; the result will be stored in the variable 'data', a pointer to which was passed to the read function. The calculation volt = data * 0.000805; converts the reading into a value in volts, the quantity 0.000805 being equal to 3.3 V/4096, the smallest step the ADC can resolve in 12-bit mode. The command temperature = 25 + (volt - 2.945) / 0.01; converts the voltage measured across the LM335 into a temperature value. The first step Figure 2. The analog temperature sensor with a resistor. is to subtract 2.495 V, which is the volt- age we expect to see at our reference temperature of 25 °C. The result of this is divided by 0.01, which corresponds to the 10 mV/°C slope characteristic of the device. Finally we center the result about the 25 °C reference. It is possible to adjust this calculation to calibrate the sensor. The next two commands convert the floating-point temperature value into ASCII format in an array ready for send- ing to the UART. First the value is multi- plied by 100 so that the first two digits after the decimal point are brought before Figure 4. Structure of the analog comparators. Figure 3. The two components can be hooked up in mid-air. it. The sprintf () function (similar to the print command in other systems) for- mats this value as a string in tempera- ture_buffer. The following for-loop, in which the variable i is incremented by 1 on each iteration, sends the four char- acters to the UART using the command usart_wri te_wai t (&usart_i nstance , temperature_buffer [i ] ) ; .The if-state- ments before that call determine where the decimal point should be inserted. If the value is greater than or equal to 1000, the decimal point (ASCII 46) is output after the second digit; if the value is less than 1000, in which case there is only one www.elektormagazine.com September & October 2015 11 digit before the decimal point, it is out- put after the first digit. The final if-state- ment inside the for-loop sends a line feed (ASCII 10) character after the final digit, so that the next reading will be output on a new line. The infinite loop finishes with a one second delay, implemented by a call to the function delay_s(l) ;. Read- ings are thus output at approximately one per second. To keep things simple and to make the demonstration clearer, for this project we use the ASF Wizard to include the polled variants of both the U(S)ART and ADC libraries. In the polled variants it is nec- essary to wait until the command to send a character to the U(S)ART returns the value STATUS_OK to indicate the success- ful transmission of the character before proceeding, and this is why the while- loops are needed in the code. If you transfer the program to the board and establish a connection with it using the terminal emulator program (not for- getting to activate the DTR signal!) you should see the readings on the screen. For various reasons the readings may deviate by a couple of degrees from the true temperature value and may fluctu- ate a little [3]. The analog comparator The SAM D20 includes two analog com- parators (ACs) which can compare two voltages and indicate whether the differ- ence is positive (the first input is higher than the second) or negative (the second input is higher than the first). The struc- ture of the ACs is shown in Figure 4: it is clear that there are many possible sources for the inputs to the compara- tors and that, like the ADC, it is possible for them to operate together in window mode. The analog comparators can trig- ger interrupts or events, and a hysteresis can be set to reduce sensitivity to noise. A digital filter is also available, again to control noise sensitivity. Like the ADC, the AC can be configured to operate con- tinuously or, to conserve power, to carry out a single comparison. More on the AC can be found starting on page 521 of the datasheet. The AC in practice We will now look at a quick project to demonstrate the analog comparator. We will arrange for LEDO on the SAM D20 Xplained board to light when the voltage on potentiometer PI is higher than that on potentiometer P2, and to go out oth- erwise. The two potentiometers are con- nected as shown in Figure 5, most con- veniently, as shown in Figure 6, using a breadboard. The potentiometers are wired as voltage dividers so that a variable volt- age from 0 V to 3.3 V is presented to each of the two comparator inputs. The code for the project 'First step with AC is relatively easy to understand. Note that the callback variant of the AC ASF library is selected in the ASF Wizard. At the beginning of the main program file we include the header file 'asf.h' as usual and then give the function prototypes. We then create an instance structure ac_instance of type ac_module. Next we come to a small function with the three lines: struct ac.config config_ac; ac_get_conf i g_def aults (&conf i g_ac) ; ac_init(&ac_instance, AC, &config_ac) ; The seasoned eye will recognize this as nothing more than the declaration of a configuration structure, its population with default values and then its transfer to the AC peripheral block. We will subse- quently be able to refer to the comparator using the instance structure ac.instance. The default settings basically cover the selection of the clock source: in this case the source is GCLK generator 0, which also drives the CPU and hence does not need to be enabled separately. The longest and most important config- uration function is the one that sets up channel 0 of the comparator and the required input pins (see Listing 3 [2]) and the code is rather more complex. We do not need the second channel for our project, as we only want to compare two voltages. As can be seen from the listing, we start by declaring the config- uration structure confi g.ac.chan and initialize it with its default values using ac.chan.get.conf i g_def aults (&con- fi g.ac.chan) ; . Using the dot operator we then populate several of the mem- bers of the structure with the values we require. First we set the member sample, mode to single shot, so that the com- parator only performs a single compari- son when started. We then make internal connections between the non-inverting input of the comparator and AINO (PA04), and between the inverting input and AIN1 (PA05). These are different from the AINO and AIN1 pins used by the ADC: be care- ful not to mix them up! Next the so-called 'majority of five' digital filter is enabled to increase immunity to noise on the input signals. The member i nterrupt.selecti on is set to specify when an interrupt is to be triggered:. In this case we set it to the symbolic con- stant AC.C HAN. I NT ERRUPT.S ELECTION. END_OF.COM PARE which causes the call- back function to be called after each AC comparison operation. The function then proceeds to specify the configuration of the input pins PA04 and PA05 more precisely. In each case we first declare the configuration structure acx. pi n.conf (where x is 0 or 1) for the pin and then load the values SYSTEM.PINMUX. PIN.DIR.INPUT and MUX.PAOxB_AC.AINx into the structure members direction and mux.position respectively. As its name indicates, the first variable deter- mines the direction of the pin (whether it is an input or an output): in this case we use the symbolic constant shown to configure it as an input. The second vari- able determines the function of the pin. The first section of code refers to the required symbolic constants and struc- ture members for pin PA04 (AINO) and the second section to those for pin PA05 (AIN1). At the end of each section the settings stored in the configuration struc- ture are transferred to the corresponding pin, using the command system.pinmux. pi n.set. confi g (PIN.PAOxB_AC.AINx , &acx_pi n.conf ) ; which simply requires the appropriate symbolic constant and a pointer to the configuration structure. Following these two sections we have a call to the function to transfer the set- tings in the configuration structure con- fi g.ac.chan that we had set up at the beginning of the function to channel 0, followed by a call to enable the channel. In both calls we use the instance struc- ture ac.instance as a parameter. Next in the file is the callback function, called callback.f uncti on.ac ( ) . This interrupt service routine (ISR) is called every time an analog comparison com- pletes and triggers its interrupt. The ISR contains the most important part of the program, taking the form of a switch-case statement, which, depending on the result of the comparison operation, turns LEDO on the Xplained Pro board on or off. The relevant part of the code is: 12 September & October 2015 www.elektormagazine.com case 10: port_pi n_set_output_ level ( LED_0_PIN , 1); break; case 12: port_pi n_set_output_ level ( LED_0_PIN , 0); break; This code uses the output of the command ac_chan_get_status (&ac_i nstance, AC_CHAN_CHANNEL_0) ; to determine the result of the last analog comparison. The command returns a bit mask of the chan- nel flags: 10, if the voltage on PI (AINO) is greater than that on P2, and 12 if it is lower. In the second case LEDO is turned on: note that the output is active low. The advantage of using the on-board LED is that we do not have to configure its pin manually, as it is automatically config- ured for us. Following the switch-case block the ISR proceeds to trigger the next comparison operation with the command ac_chan_ tri gger_si ngle_shot (&ac_i nstance , AC_CHAN_CHANNEL_0) ; . Again, we simply require a pointer to the instance structure for the AC and the symbolic constant to specify the channel to be used. The last function declared before we reach the main loop is configure_ac_call- back(), which registers the interrupt and enables it. The two commands to do this follow the conventional ASF pattern: the first, to register the callback, requires a pointer to the instance structure for the AC module, the name of the callback ISR and the type of interrupt (in this case AC_CALLBACK_C0MPARAT0R_0); the sec- ond is similar, but it does not require the name of the ISR. Now we come at last to the main function, which begins by initializing the micro- controller and then calling the configura- tion functions we have described above. There then follows the command ac_ enable (&ac_i nstance) ;, which enables the whole AC peripheral block, and then the command to initiate the first compar- ison operation. The infinite loop is empty, as from this point on all the work is done in the calls to the ISR described above: after each call to the ISR, it starts the next comparison which will in turn trig- ger the ISR again. Thus, after the inter- rupt is triggered for the first time, the code effectively runs in an infinite loop of interrupts. The 'Start without Debugging' command of the development environment can be PA05 PA04 VCC 1 | PI GND \ \ 00k N 00k lin I lin P2 150229-21 Figure 5. This circuit with two potentiometers Figure 6. The two potentiometers on a allows the analog comparators to be tested. breadboard. used to load the project onto a board to which the potentiometers have been connected [4]. The DAC A digital-to-analog converter (DAC) is a comparatively rare feature of eight-bit microcontrollers. A DAC converts a digital value into an analog voltage, the opposite function to the ADC, and is often used in audio applications. Our SAM D20 includes one DAC, whose block diagram is shown in Figure 7. The SAM D20's DAC only offers one channel, but has a reasonably high resolution of 10 bits and a maximum sample rate of 350 kHz. On the left of the block diagram you can see a number of registers, mostly to do with the configuration of the DAC, which we will not examine here in detail. We will however mention that the data reg- ister that holds the ten-bit value cur- rently being converted is accompanied by a buffer register of the same size. If required, the two registers work on a first-in-first-out (FIFO) basis, so the most recently loaded data is not always con- verted immediately. If the DAC receives a command to convert a digital value to analog when the DATA register is empty it can be made to trigger an EMPTY event. Conversely, another peripheral within the microcontroller, such as a timer, can be used to trigger a START event that causes the DAC to initiate a conversion. The block diagram shows the wide range of reference sources and output options. As in the case of the ADC, the DAC can be configured in software for operation with an external voltage reference, with the power supply (AVCC) as the reference, or with the internal accurate 1 V reference Figure 7. The arrangement of the DAC block. www.elektormagazine.com September & October 2015 13 voltage. The converted voltage can be output on the external VOUT pin (PA02), routed to an ADC input (with an optional internal amplifier in between), or routed to an input of an analog comparator. As with most of the peripheral blocks on the SAM D20 the DAC can receive its clock from a range of sources, and its clock must be synchronized with that of the internal data bus when a read or write operation occurs. More on this can be found in the datasheet starting on page 550. To get to know this peripheral a little bet- ter, we have developed a small exam- ple program using the polled variant of the ASF DAC library that generates a sinewave signal with an amplitude of 3.3 V and a frequency of approximately 500 Hz. A piezo sounder can be connected as shown in Figure 8, or the waveform can be inspected using an oscilloscope. Because of the low amplitude the sound from the piezo crystal is rather quiet: to improve matters it can be attached to a sound box. Now to the code in the main file. After including the header file 'asf.h' and pro- totyping the functions we declare a vari- able Y, which will subsequently be used in a for-loop, and we declare and initialize an array 'sinus' (English: sine) that con- tains 360 sine values as provided by the handy online sinewave generator at [5]. The lowest value is zero and the highest is 1023, and so the full 10-bit resolution Figure 8. The circuit consists of just the board and a piezo sounder. of the DAC will be used. The two configuration functions for the DAC (with instance structure dac_ instance of type dac_module) in List- ing 4 [2] set up the DAC block according to the usual pattern. First a configuration structure called config_dac is declared. Then it is populated with default values, and then the dot operator is used to set the members of the structure to reflect the required settings. In this case the DAC receives its clock from GCLK gen- erator 0, the output of the DAC is taken to output pin PA02, and the 3.3 V supply voltage is used as the reference using the command confi g_dac . reference = DAC_REFERENCE_AVCC ; . Finally the set- tings stored in the configuration structure are transferred to the DAC with the com- mand dac_i nit(&dac_i nstance, DAC, &confi g_dac) ; . The second configuration function is even easier to understand. Here DAC chan- nel 0 is configured separately using the declared configuration structure confi g_ dac_chan, which is populated with the default settings. The command dac_chan_set_confi g(&dac_i nstance , DAC_CHANNEL_0 , &conf i g_dac_chan) ; is then used to transfer the settings to the channel. The main function initializes the micro- controller and the SysTick timer (needed for the delay function). It then calls the two configuration functions and finally enables the DAC module with the com- mand dac_enable (&dac_i nstance) ; . The infinite loop is the core of the whole program. It consists of a single for- loop in which the function dac_chan_ wri te (&dac_i nstance , DAC_CHANNEL_0 , si nus [i ] ) ; is called to transfer the sam- ples stored in the 'sinus' array without delays to the DAC for conversion to a volt- age. After compiling and transferring the program '500Hz with DAC' a clean sine- wave signal at 500 Hz appears at the out- put. But, given that there are no delays in the code, why does it not run faster? It is simply the case that the DAC requires time to execute the write command. If the clock frequency is increased, or the sinewave table made shorter, a much higher output frequency can be achieved. Conversely, if a delay is introduced into the for-loop, the output frequency will be reduced. With a little more work it would be possible to play music using the DAC, or it could be used, for example, as part of an analog circuit tester [6]. This installment of the course has looked at the important analog interfaces of the SAM D20. With the foundations now firmly in place, we will look in the next install- ment at an ambitious and exciting project using the SPI bus. N (150229) 2V 31.25kS/s 1ms Figure 9. The clean output signal of the DAC shown on an oscilloscope. Web Links [1] www.ti.com/lit/ds/symlink/lm235.pdf [2] www. elektormagazine.com/1 50229 [3] www.atmel.com/images/atmel-42109-sam-d20-analog-to-digital-converter-driver-adc_application-note_at03243.pdf [4] www. atmel.com/Images/ Atmel-42106-SAM-D20-Analog-Comparator-Driver_Application-Note_AT03242.pdf [5] www.daycounter.com/Calculators/Sine-Generator-Calculator.phtml [6] www. atmel.com/Images/Atmel-42 110-SAM-D20-Digital-to-Analog-Driver-DAC_Application-Note_AT03244.pdf 14 September & October 2015 www.elektormagazine.com TIPS & TRICKS in collaboration with DESIGNSPARK Selenium Rectifiers Peculiar Parts, the series By Neil Gruending (Canada) Everyone knows that rectifying an AC voltage will generate a DC voltage. Silicon based rec- tifiers do this very well but in they weren't available for sub- stantial currents in the 50's and 60's so selenium rectifiers were used instead. They are quite a bit bigger than their silicon coun- terparts but still relatively effi- cient for a metal based device — at that time. A selenium rectifier is made by sandwiching a thin layer of sele- nium between steel or aluminum plates which are then stacked like in Figure 1. The plate surface area determines the current capacity and the number of stacked plates determines the rectifier voltage rating. Each plate adds about 20 V to the reverse voltage so for example the rectifier in Figure 1 has a PIV (peak inverse voltage) rating of 160 V because it has eight plates. Selenium rectifiers were used in power supplies quite a bit because they have a significant efficiency advantage over vac- uum tubes from that era. For example, a 120-V selenium rec- tifier will have a typical forward voltage drop of 5 V whereas a vacuum tube rectifier could have a drop of 10 to 25 V. The tube would also need some heating current which also reduces its efficiency. If you have any 1950's and 1960's era radios, televisions, test equipment or boatanchors then they will probably contain selenium rectifiers in their power supplies. It's always a good idea to replace them with silicon diodes even if everything is working properly. That's because as selenium rectifiers age their forward voltage and leakage currents will increase which can affect a circuit's performance. In a worst case scenario this can cause them to overheat and catch fire, releasing a toxic foul smelling smoke. Many people say that the smoke has a garlic or onion smell to it. Fortunately selenium rectifiers whether single or bridge can't handle a lot of forward current and are typically rated for a for- ward current of about 100-250 mA which makes them easy to replace with a silicon diode. The lN400x, lN540x, and BYxxx series diodes are commonly used since they come in a wide range of voltages and a 1-amp rating is usually more than enough. Just make sure that you allow for a pretty wide safety margin siction , HSIONAt i*25 Jr--- **«£ SUG Gtsret> MtTHOOs WlT ml f ***“■ *»T — because selenium rectifiers are much more tolerant to momentary voltage spikes than silicon rectifiers. Some selenium bridge rectifiers follow this nomenclature to identify the main electrical ratings: BxxxCyyy, where xxx = PIV and yyy = milli-amps. Easy. The numbering system was continued with their silicon counterparts. Once you've chosen a Si diode the next step is to add a series resistor to emulate a selenium rectifier's natural current limiting ability and larger voltage drop. The easiest way to determine the resistance value is to divide your desired voltage drop (5 to 10 volts) by the expected forward current. Also make sure that you use a resistor with a high enough wattage rating; 5-watt, 100-ohm to 200-ohm resistors are typically used. I normally don't like to replace older parts like that but unfor- tunately it's necessary for selenium rectifiers because it's not a matter of if they will fail but when. And when they do, it can take days for the smoke and foul smell to clear and the missus will be unhappy. Flowever, if you want to stick to your guns there is a Selenium Rectifier Flandbook [2] available if you want to learn more about them. H (150283) [1] http://en.wikipedia.org/wiki/Selenium_rectifier#/media/ File: Selenium_Rectifier.jpg [2] www.tubebooks.org/Books/srhbst.pdf Please contribute your Peculiar Parts article, email neil@gruending.net www.elektormagazine.com September & October 2015 15 DESIGN SHARE DesignSpark Mechanical CAD Tips & Tricks & Dimensioning a 3D Model By Neil Gruending (Canada) In the previous installment I showed you how to add a connector to a PCB model and then modify the enclosure for it. Now let's add some dimensions to the enclosure for the connector cutout. Creating Annotation Planes Before we can dimension our model we need somewhere to place them. DesignSpark Mechanical does this with annotation planes which are a flat surface in a design to store documen- tation information like dimensions. Annotation planes are just like regular planes because they can be aligned to an edge, line, axis or a combination of all three. The easy way to set up an annotation plane is to click on the Dimension tool in the Investigate menu tab and select the enclosure face with the connector cutout like in Figure 1. The Dimension tool will highlight the line or face under the cursor and the associated plane as a wireframe rectangle to indicate where the plane would go. In this example you can see where the plane would go with the selected face but since the enclosure has tapered sides the annotation plane is slightly angled relative to the Z axis. Sometimes this is ok but if you wanted an annotation plane without the angle then we have to select an axis first. You use the Axis tool is in the Insert menu tab to create an axis for the annotation plane. For this example you would then click on the upper inside edge of the connector cutout face Figure 1. Connector cutout face. to add a dashed and dotted line that we can then use for our annotation plane like in Figure 2. Now we have an annotation plane that's parallel with the Z axis that we can use to add dimensions to model. Adding dimensions Now let's add some dimensions to the annotation plane we just created and finish up with the Dimension tool. I find that it's easiest to view the annotation plane head on, so I rotated the model by clicking on the Plan View button in the Orient menu to get the view in Figure 3. Then I used the Dimension tool to add the linear dimensions shown. Adding dimensions is really easy with the Dimension tool because most of the time you just have to click on the two elements that you want to measure. The elements can be any point, line or face. If the elements are parallel with each other the Dimension tool will create a linear dimension that mea- sures the distance between them. Otherwise the Dimension tool will measure the angle between them. Once the dimen- sion is created then you can then place it with your mouse. Figure 2. Connector face annotation plane. 16 September & October 2015 www.elektormagazine.com Advertorial Q&A TRAINING REVIEW TIPS & TRICKS SOFTWARE in collaboration with DESIGNSPARK The Dimension tool is still active at this point so it will modify the measurement lines and arrows as necessary while you move the dimension around. Another nice feature of the tool is that when only one element is selected it will display what the measurement would be as you mouse over other elements in the design. You can also easily add radius dimensions which only require one measurement point. The trick is that you have to click on the top, bottom, left or right portions of the arc. Otherwise the Dimension tool will assume that you are trying to measure between two points. It's also possible to measure an arc by using the CTRL key while clicking on it. If you hold down CTRL while clicking on an arc it will measure the length of the entire arc or you can hold the CTRL key while dragging the dimension. The lower left corner of Figure 3 also shows the option panel when the Dimension tool is active. Here is where you can set the dimension and reference orientations used by the Dimen- sion tool when adding new dimensions. The default settings are all automatic but it makes sense to set the orientations you want if you were adding a large number of dimensions. Editing dimensions Dimensions in the model are also intelligent objects. This means that you can edit them at any time by clicking on them. For example, if you click on the dimension text it will be highlighted like in Figure 4. You adjust the size of the text by clicking on the small circles and moving them in the appropriate direction. If you hover the mouse pointer over the dotted box then you can move the text. Right clicking on a dimension will open the floating toolbar shown in Figure 5. Here is where you can add a note to the dimension, change the tolerance type, add a data field or insert symbols into the dimension text respectively. Other things like the arrow type can be set properties window. O o - -o “c|> 4 . 4 mm o o* - -o Figure 4. Modifying dimension text. HI ▼ Unear ^ [*13 Q ^ Figure 5. Dimension toolbar. So far all of the dimensions have been in millimeters but if you wanted to change the measurement units you can go into the File menu, select DesignSpark Options and then click on Units. Here you can change the units used for length, angles, mass, etc. You can also specify measurement precision. Using Annotation Planes Once you're done adding dimensions to the annotation plane you will get something like Figure 6. As you can see, all of the dimensions are contained to the one plane which makes them very easy to manipulate as a group. For example, to disable displaying the dimensions you can clear the Annotation Plane checkbox in the model structure window. Conclusion The DesignSpark Mechanical Dimension tool is a really pow- erful way to add dimensions to a model. I've only touched on its flexibility here — I encourage you to try it out to see what it can do! N (150218) ' j ^ d *9 ’ 1551n_dimensions2 - DesignSpark Mechanical _ □ Design Display Help / Resources A £ n & ti\ § Clipboard Orient Sketch 3 Ed,t Intersect Mode File Import Download 3D PCB Models Insen o w H Output & Bill Of Materials’ Investigate BON* Gluot OrdJ Structure 4 v S5 1551n_dimensions2* t V {§, 1551N Box t* nT PCB Outline > LO Keepout l> y](^ U SB_C on nectar ■/ [3 Annotation rtonc 0 |J) Annotation Plane □ \ Axis □irk a reference tn start creating dimension Ctri+C.lick twn objects to create a virtual pi — R0.7mm 1.2mm |Structure||Layere | Selection| Options - Dimensions Dimension Orientation •)Auto '^Aligned -^Horizontal 1 Vertical 1st Reference Orientation I (®)Auto [lOpti pro Dimcnaiona [|Propcrtic3 1~ 11.919mm 8.2iiiffi — 4.4mm G i X © J EAQinuIcBceliuiHcDcsiuir 1551 ii djme>csimcs2* x ^jPCB Outline* Click a reference to start creating dimension Ctrl+Click two objects to create a v._ . l x Z Cj * [I] * ; -/■ d *9 1551n_dimensions2 - DesignSpark Mechanical _ □ Rle f Design Display Help / Resources A G n % tgi 4 a \ y o & @ 30 o Clipboard Orient Sketch m Edit Intersect k m File Import PCB Download 3D Models Output Mode Insert mil Of BON* Materials’ Uuot Investigate 0rd< Structure A •/ @ 1551n_dimensions2‘ t> >/(& 1551 N Box k DCy PCB Outline l> UC Keepout t> V US8_Connector y (§) Annotation Plane Annotation Plane □ \ Axis IStructurejLayere Selection Properties Click a reference tn start creating dimension Otd+Clir.k twn objects tn create a virtual pi 8 |Opti ons Dimensions || Properties Z L J si ExanmleBeclioiiicDcsiuii* si 1 551 II cfcinensimp?* x l^pPCB Outline* Click a reference to start creating dimension Ctd+Click two objects to create a v_ 1 Plane 1 ► x : r k - Figure 3. Dimensioned cutout. Figure 6. Dimensioned annotation plane. Advertorial www.elektormagazine.com September & October 2015 17 PIC® Assembler Crash Course (2) Mini dev board and electronic dice Main Lacs delay jcoutine GfclO.D’OOi' nfcir._laopl disp \ ■* GPIoT O’ 302’ te_:eleased iisp _2 •* fclO.O’ 032’ to released ®’ ® !52 ' to_sel« as « d SS&U o* * teleasc* g ,xo.d'0W bJ :ele» s# * Making an ultra-simple adapter board for the PICkit2 programmer does not take long. A board of this kind makes programming of compatible microcontrollers extremely easy: just plug in the chip, connect the board to the programmer, start the program- ming software, transfer the ready-assembled firmware and it's done. You can make adapter boards for controllers with varying pin-counts with very little effort, as every microcon- troller from Microchip has these necessary programming pins: V pp , ICSPDAT and ICSPCLK. With adapter boards all you need do then is to connect these pins (plus V cc and GND of course) with the pins of the same name on the PICkit programmer. For the PIC12F675 8-pin controller used here we make an 8-pin variant shown in Figure 1. As you can see, things don't come much simpler than this. All you need is a scrap of perfboard, an 8-pin IC socket and a 6-way header. You can even do without the LED and its series resistor, although having a visible check that the controller is powered up is a handy feature. Figure 2 shows how the finished adapter board plugs into the programmer. By Miroslav Cina (Germany) miroslav.cina@t-online.de In the first part of this course we learnt the basics of Assembler programming and the fundamental hardware characteristics of the PIC controller used. Now we move on, making a homebrew mini development board and learning some additional Assembler commands. For our demo application we shall program an electronic die. Register report Before we discuss the additional Assembler commands needed for our demo application, let's just take a quick glance at the most important Registers. Config Register Almost all Registers in a microcontroller are stored in SRAM but the Configuration Register is an exception. The Register contains a total of 14 bits, of which at this stage only four bits are relevant initially. The three LSBs (Least Significant Bits = lowest value Bits) 'FOSC2:FOSCO' are provided for configuring the oscillator. In this training exercise the following two settings are used for these three bits. 010 : Use crystal-controlled RF oscillator. In this mode an externally controlled oscillator is used. The frequency is deter- mined with an external crystal connected between pins 2 (GP5) and 3 (GP4). This method enables you to have a clock rate of 20 MHz maximum. The crystal uses up two pins, so only four out of the total of six remain usable for I/O purposes. 100 : Use internal oscillator. In this mode the internal oscilla- tor is activated, with a clock rate of 4 MHz. The clock speed is Figure 1. Schematic of the adapter board (which is really a minimalist version of a development board). Figure 2. Finished adapter board, hooked up to the PICkit2 programmer. 18 September & October 2015 www.elektormagazine.com PIC, PICKit and MPASM are registered trademarks of Microchip Inc TRAINING IRP RP1 RPO TO PD Z DC C bit 7 bitO Figure 3. Assignment of the bits in the Status Register. not as accurate as when using crystal control but its tolerance of ±1 % is still perfectly adequate for many applications. The great advantage is that no additional components are required, also GP4 and GP5 are available for general I/O use. Bit 5 (MCLRE) of the Configuration Register controls the func- tion of pin 4. If MCLRE = 1, pin 4 functions as 'Master Clear' — in other words as the reset pin. When MCLRE = 0 pin 4 can be used as an input, at the cost of losing the reset function. Status Register The Status Register is where we find information on arithmetic operations already carried out. Figure 3 shows the allocation of the individual Bits of the Register. The two MSBs (Most Significant Bits = highest value Bits) IRP and RP1 are reserved and should always be 0 when writing. They are not used at all with the PIC12F675. Bit 5 is RPO, the Register Bank Select Bit. Its function (as already described in Part 1) is for toggling (switching within) the memory bank. When its value = 0 all subsequent com- mands will access the memory locations OOh to 7Fh. Alterna- tively when its value = 1, locations 80h to FFh are accessed. The two bits TO and PD reveal how the last reset came about (for further details see the data sheet [1]). Bit 2 Z (= Zero) is activated the result of the last operation is zero — this need not necessarily have been an arithmetic operation. In addition and subtraction the two LSBs indicate overflows that have arisen (carry and borrow situations). Option Register The Option Register enables other settings to be activated. An example is given in our demo application (see below), where clearing Bit 7 activates the pull-up function for the inputs. Memory organization For programming in Assembler you need to be well-versed in the memory organization of the microcontroller being used. Memory is typically (and in this case, definitely) classified into three types: • Program memory (Flash) • Data memory (SRAM) • EEPROM Program memory is used in the main for installing the software — and exclusively for this purpose in the case of the PIC12F675 we are using. A 'word' in the program memory amounts to 14 bits here. For programming this information is not partic- ularly significant but it's definitely worth making clear that the program memory of a PIC12F1675 contains not merely 1024 Bytes (each of 8 bits) but 1024 Words (each of 14 bits). The data memory is where all the specific processor and appli- cation Registers are located. With the exception of the pre- defined Processor Register, the content of the data memory is undefined at switch-on. Its content is lost when power is disconnected — we're dealing with volatile SRAM here. Unlike program memory, the data memory is organized in the classic manner using Bytes each 8 bits long. A detailed representation of the memory map can be found starting on page 9 in the data sheet [1]. It's worth noting here that the 64 Bytes of appli- cation memory lie within the address range from 20h to 5Fh. In the similarly Byte-organized EEPROM you can store soft- ware values that will safely survive any reset or reboot (we are dealing with non-volatile memory here). All the same, writing data too frequently should be avoided. Other commands Next follows a description of the commands required for our demo project that are in addition to those already covered in the first part of this crash course. Incidentally you will find a handy list of all commands in the datasheets for every micro- controller from Microchip [1]. Our description begins by rounding off a command that we already used in Part 1. DECFSZ In Part 1 we described the function of this command (= DEC- rement F and Skip if Zero) for Looping. As well as Loops we can also use the DECFSZ command for creating Branches in the program flow (a Loop is really only a special case of Branch- ing). Figure 4 illustrates the flow diagram of the command. It's assumed that a Variable 'X' is located at memory location 20h. A complete Branching operation requires three commands (see Figure 5). By employing the Argument 'O' in DECFSZ the result of the subtraction (value in 'X' minus 1) is written to the W Register. If the result is OOh, the next command is skipped and the third command 'goto Brnch_B' is carried out. This takes place only when the value of 'X' is Olh prior to dec- rementing Olh. In all other situations we end up at 'Brnch_A'. no A yes x / Branch A Branch B Figure 4. Flow diagram for conditional branching. www.elektormagazine.com September & October 2015 19 DECFSZ branching example decfsz H'20',0 yoto Brnch-A goto Brnch-B W-register I? |? i?|?|?|7T? I m = n - 1 memory location 20h In |n In | n | n| n| n| rj \ f n In n 1 n 1 n n| n 3 Figure 5. Sample code for conditional branching. INCFSZ The DECFSZ command has now been described in detail. INCFSZ is identical except that it handles incrementing instead of decrementing. BTFSS and BTFSC Branching operations also use the two commands BTFSS ( = Bit Test F and Skip if Set) and BTFSC (= Bit Test F and Skip if Clear). Using these we can poll the status of individual Bits of a memory location and Branch off accordingly. The syntax of the command is: btfss f , b and correspondingly btfsc f , b Argument 'f' has a value ranging from OOh to 7Fh and indicates the address of the memory location. Argument 'b' is a numer- ical value from OOh to 07h and defines the Bit to be checked. These commands do not alter the content of the W Register nor of the memory location. Figure 7. Sample code for ADDWF: result written to W Register. Figure 6. Sample loop using the commands BTFSS / BTFSC. In the example shown in Figure 6 a value of 98h (= 10011000b) is stored in memory location 20h. On the left-hand side the command BTFSS checks whether the value of Bit OOh is '1'. If yes, we skip the next command 'goto Brnch_A'. When the value of Bit 0 is y 0', however, it is not skipped and instead the command 'goto Brnch_A' is carried out. On the right-hand side we see the operation of the command BTFSC. Flere we skip when Bit 0 has the value 'O' — which applies to the value at memory location 20h. The command 'goto Brnch_A' is therefore skipped and the program resumes with the command 'goto Brnch_B'. ADDWF This command adds the content of the W Register to the con- tent of a memory location. The syntax is: addwf f,d Argument 'f' stands for the target address and has a value of from OOh to 7Fh. Argument 'd' can be either 'O' or '1' and defines where the result is to be stored. If d = 0, the result is saved in the W Register and the memory location remains Figure 8. Sample code for ADDWF: result written to SRAM memory location. 20 September & October 2015 www.elektormagazine.com TRAINING ADDLW example: result is (always) returned to W register W-register ? 1? ? 1 ? ?| ? ?| ?| movlw H'03’ * |o lo olo ol 0 l| i| addlw H, 10 ' oL li L o 0 ll Figure 9. Addition of a Constant to the W Register. Figure 10. Prototype of our electronic die. untouched. When d = 1 the store position is overwritten with the result. In the following example the sum of 3 + 16 (decimal) is calcu- lated. First we deposit the '3' into memory location 20h, after which '16' is written to the W Register and then the addition is carried out. The result is written either into the W Register (Figure 7) or in memory position 20h (Figure 8). ANDWF As regards syntax and handling this command works identically to ADDWF. The difference lies in the function: ANDWF executes the logical operation 'AND' bitwise (bit-by-bit). ADDLW ADDLW also executes an addition in a similar way to the com- mand ADDWF. Flowever, ADDWF adds a value in memory to the W Register, whereas ADDLW adds a Constant to the W Register. The syntax is: addlw k Argument 'k' has a value of from OOh to FFh and is the Con- stant that is added to the contents of W Register. The result is saved to the W Register. In the example shown in Figure 9 we first load the value 03h into the W Register, after which the Constant lOh is added. ANDLW Apart from an AND operation instead of an addition, this com- mand is identical to ADDLW. CLRF and CLRW The CLRF command appeared already in Part 1 (a specified memory position is set to OOh). Analogously to this, the CLRW command sets the W Register to OOh. The syntax is: clrf f and correspondingly for clrw INCF and DECF Using these command we can increment (INCF; +1) or dec- rement (DECF; -1). The syntax is: incf f,d and correspondingly decf f,d Arguments 'f' and 'd' have the exact same meaning as in the ADDWF command. The result is written either to the W Register or at the original memory location, according to 'd' (either '0' or '1'). Electronic dice Creating an electronic die (or several dice, which as you know is technically the plural of the word die!) is no more compli- cated than making an LED flash. In Figure 10 you will see a USB connection, as (for simplicity's sake) the circuit is pow- ered from a USB port on a PC. Beyond this the die has nothing else to do with the USB interface. You could power it just as easily using a wall-wart power supply or with three standard or rechargeable batteries connected in series. If you look closely at some real dice you will note that the spots on them are arranged in seven different positions. The appearance of the individual numbers follows the scheme shown in Figure 11. If you use LEDS to represent the spots, this will use up exactly four outputs of a microcontroller. If that surprises you, here is how we do it: LEDs 6 and 7, 2 and 3 together with 4 and 5 are always lit or unlit together. These pairs are therefore always controlled together by a single GPIO port pin. LED1 needs one control wire only, with R1 wired in series so that it does not light up brighter than the others. • 4 6 • 1 • 7 5 # Figure 11. The numeric values of a die depicted. www.elektormagazine.com September & October 2015 21 Figure 12. Schematic of an electronic die. Connecting LEDs direct to GPIO-Pins (see schematic in Fig- ure 12) is definitely not rule-conformant but it's not really a problem, considering the low currents involved. To do our bit for energy-saving the 5 V from the USB port is dropped by around 0.7 V to 4.3 V using Dl. If you are using three NiMH rechargeables (3 x 1.2 V) as your power source you can omit the diode (and fit a wire link instead). You can 'throw a die' by pressing push button SI briefly. One more little tip: because of their higher forward voltage, blue and white LEDs will not work in this circuit. Dice firmware Before we go poking buttons, it's worth examining precisely what the software needs to do with them. The specification for these dice looks like this: At start-up (reset) the die should display a demonstration. This demo is executed, displaying each of the counts (1 to 6) sequentially, until press button SI is pressed. Dice v 1.05 - 14.05.2015 Hurd*.: PT01 2F57S u.ird CSC : Internal osc. used POWER. INCLUDE "P12r67S.INC" _U002 CONFIG U002 5V USD Tins connection: GV'l — button tn -- N/C GP4 GPO GPO GP1 GPO GPO GP4 EOU D'OOOOOIIOOOOIOO’ ;MCLR “ input ; Variables 51 T1MKK1 EOU h’20* T1MKK2 KQU H'21* 0 bsf STATUS, RPO movlw D' 11001100' movwf TRISIO clrf ANSEL 0 bet OPTION WtGfU'UOV movlw movwf B '00000100 ' WPU bcf STATUS, RPO .•Used in delay routine m< 0 0 ; Switch to ieuislei Lank 1 ;GPO, 1, 4, 5 - out; GP2. 3 - in ;GPIC are digital I/O's ; enable pull-ups .■enable pull-up for GP2 ; Switch Sack tu leg. Bonk 0 Figure 13. Dice code: Initialization. The dice logic is implemented as an endless loop: If SI is pressed it counts up through the values 1 to 6 con- tinually and displays these. The persistence of vision makes it looks as if value 7 is being displayed (all LEDs illuminated). The rapid counting ceases when SI is released. The current count status is then displayed permanently. You're now ready to start. The firmware for the die is divided into two parts: the die and the display. It goes without saying that a fair amount needs to be initialized following a reset or starting from scratch. In the code shown in Figure 13 you can see this configuration where we put marker 1. The internal oscillator and GP3 are defined as the input — consequently no MCLR. At marker 2 Variables TIMER1 and TIMER2 are defined at memory locations 20h and 21h. At markers 3 and 4 we are operating in memory bank 1, which is why Bit RPO of the Status Register is set to '1' initially. At marker 3 the first two commands (movlw B'11001100' and movwf TRSIO) arrange for GPO, GP1, GP4 and GP5 to be configured as outputs, at the same time as the relevant Bits of the TRISIO Register are set to 'O'. The four LEDS are con- nected to these four pins. GP2 is configures as an input that is used to poll the press button status. To achieve this Bit 2 of the TRISIO Registers is set to '1'. The command 'clrf ANSEL' disables the analog functionality. At marker 4 an external pull-up resistor for the press but- ton is made redundant. The PIC12F675 microcontroller makes so-called 'weak pull-ups' available for all GPIO pins (apart from GP3) configured as inputs, you see. For this purpose Bit 7 of the Option Register must be set to 'O'. The command 'bcf OPTION_REG,D'007" handles this in the program. Next we use the Bits of the WPU Register to determine for which Pins the internal pull-ups should in fact be active. If Bit x of the WPU Register is set to '1', the pull-up resistor of the relevant GPx pin is active. The internal pull-ups are not active by default, as they can consume up to 400 pA additional current. Where it matters, you can then install a high-resistance external pull-up or if necessary, even an external pull-down. Following initialization the program jumps into the demo loop (Figure 14). Implementation is very simple at this stage — everything takes place in the subroutine 'start_effect', which is invoked here simply. The demo section is cancelled by press- ing SI. Demo routine The demonstration routine in Figure 15 is very straightforward. You will recognize six near-identical program segments for each numeric result. A subroutine is employed for representing the numbers: sub-program 'disp_l' looks after lighting the cor- rect LEDs for '1'. Sub-program 'disp_2' handles 2' and so on. After a count is displayed, the software waits briefly for the next one. The 'delay_routine' command — already used in the first part of this course — handles this. An interesting point at this stage is the command: btfss GPIO,D'002'. This ensures that if the push button is not pressed, the 'Return' command is skipped and the next count is displayed. When the button is pressed the skipping stops, as the input is now presenting a 'O'. The program is resumed by hitting 'Return'. This again 22 September & October 2015 www.elektormagazine.com TRAINING makes sure that the subroutine 'start_effect' and hence the demo are closed. The main program now restarts. Now for the display routines. The code in this section (Fig- ure 16) is particularly straightforward. There are six routines in total. In each of these the first command 'movlw' uses a Constant to determine which LEDs should be on and off. In the binary Constants a '0' stands for LEDs that stay dark and a '1' those that are illuminated. The 'movwf GPIO' command passes this information to the Port. A brief pause (sub-pro- gram 'dr2') follows this and then the display routine ends. In the demo section this short delay would not be required but it does not cause any further problem either. Main program This section is constructed on the same lines as the demo routine. In Figure 17 the section with the label 'mainjoopr ensures that when the button is not depressed, the current count is displayed constantly. In the main program we also poll the current value of input GP2 and, once the button is pressed, continue counting and displaying the current figure, just as we did in the demo routine. The whole thing happens so rapidly that to all appearances the figure '7' is being displayed. After releasing the button the 'goto b_released' command is performed and the counting stops. The current status is dis- played permanently. This numeral is the result of throwing the die. On the line labeled 'b_release' we jump straight back to 'mainjoopr and consequently the program flow is stopped. We could have also jumped straight back to 'mainjoopl' but if you had the intention to add extra features to the program (to give it more life), you could implement extra effects at the label 'b_release'. You could for instance fade out the count slowly or flash the result, and only after this revert to the static display. The sub-program 'dr2' establishes how rapidly the figures are changing. Actually you could omit this altogether. For test pur- poses you could slow down the running of the program enough to make visible how the figures are altered. As always, the software can be downloaded from the Elektor website [4]. Outlook With this we have reached the end of the second part of this Assembler course. A couple of new commands have been described and we have shown how you can create working electronic dice with little effort. Quite complex applications can be achieved along the same lines. Hopefully it is now clear to you that Assembler programming really is simpler than you imagined. I hope that you enjoyed this too! The next installment will demonstrate how you can use a simple microcontroller like the PIC12F675 as a substitute for the NE555 timer. N ( 150274 ) Effect clrf GPIO call start effect Figure 14. Dice code: Jumping straight to the demo routine. start effect call call btfss disp_2 delay_routine GPIO, 5' 002’ call call btfss return call call btfss return call call btfss return disp_3 delay_routine GPIO, D’ 002’ disp_4 delay_routine GPIO, 5' 002' •*1 disp_5 delay_routine gpio, D’002’ call call btfss dlsp_6 delay_routine GPIO, D' 002' •^1 goto start_ef fact call call btfss return 4- displ d«lay_routine GPIO, 5’ 002’ Figure 15. Dice code: Outputting the figures in the demo routine. disp_l movlw movwf call return B’00000010' GPIO dr 2 disp 2 movlw B* 00000001 ’ movwf GPIO call dr2 return Figure 16. Dice code: Display routines. Main Loop main_loopl call delay_routin« btfsc GPIO, D’ 002 ' goto main_loopl nain_loop2 call disp_l btfsc GPIO, D’ 002’ goto b_released call disp_2 btfsc GP10,0'002‘ goto b_rel#ased call di*p_3 btfsc GPlo7b'002' goto b_released < call disp_4 ♦ btfsc gpio7d’002’ goto b_released ■+ call disp 5 ♦ btfsc GPIO, D'002' goto b_released call disp_6 btfsc GPIO,D'002' goto b_released goto main_loop2 b released goto main_loopl Figure 17. Dice code: Main program. Web Links [1] PIC12F675: www.microchip.com/wwwproducts/Devices.aspx?product=PIC12F675 [2] MPLAB IDE: www.microchip.com/pagehandler/en-us/family/mplabx [3] First part of this course: www.elektormagazine. com/130483 [4] Software: www.elektormagazine. com/150274 www.elektormagazine.com September & October 2015 23 By Dr Veikko Krypczyk (Germany) The basics of how to program apps for current versions of Microsoft Windows are fairly simple to master. Here we use one such app to control LEDs and relays and to display the status of inputs on a PC or tablet. Figure 1. Modular hardware brings greater flexibility. Windows Store 'apps' are modern in design, cut down to the essentials in func- tionality, and fun to use. In the 'Learn' section of the previous edition we gave a handy introduction to programming Windows Store apps for the Windows 8.1 operating system. For electronics hobbyists communicating with external hardware is of particular interest, with a wide range of possible uses. Touch-based operation and a mod- ern, minimalistic user interface are ideal for many control applications. The apps can be run on a conventional desktop PC, on a notebook or on a tablet. Home-made microcontroller-based hardware can be connected to the USB port, allowing com- munication to occur in both directions. Hardware For our simple project we will make use of an Arduino Uno single-board computer equipped with some expansion hard- ware that has appeared several times in previous Elektor magazine projects. At Elektor Labs we have designed our own shield [2a] that allows external hardware such as relays to be connected to the Arduino. The board includes two LEDs that can be used for testing, an LCD panel, two buttons and a potentiome- ter. On the input side the shield is con- nected to the computer over USB via an RS-485 module and an USB-to-RS-485 converter. RS-485 signaling is relatively immune to interference and so connec- tions can be made over long distances. But the most important aspect is the possibility of connecting additional hard- ware, and this is readily done using the 14-pin Embedded Extension Connector provided. The connector is also known as a Gnublin connector, as the Gnub- lin module designed by Benedikt Sauter and his team can also be attached here. Another module that can be connected is an expansion board carrying eight relays. The hardware modules and their con- nections are shown in Fig ure 1 , and the overall set-up is described at [2b]. Simple control commands The highlight of this project is the firm- ware, which is described at [2b] and which can be downloaded via the web page accompanying this article [1]. Using a simple protocol (see [2c]) ASCII com- mands are sent to the Arduino Uno. For example, the command 110+ ' turns on the LED on the shield. If the relay board is connected, one of the eight relays can be turned on using the com- 24 September & October 2015 www.elektormagazine.com mand 'R 0 X + ', where X is a digit from 0 to 7 that determines which relay is affected. If the '+' is replaced by a '-' in these commands, the LED or relay will be turned off. The state of the buttons on the shield can be interrogated using the commands 'BOO? ' and 'B 0 1 ? '. The command 'A 0 0 # ' returns the position of the potentiometer as a value from 0 to 1023 represented in hexadecimal. Virtual COM port In order to have our app interact with the hardware we simply need to be able to send and receive data over a virtual COM port, or VCP. The COM port is Vir- tual' because in fact the characters are sent back and forth over USB, with the Windows VCP driver emulating a standard serial interface as far as the higher-level software, such as a terminal emulator or our own app, is concerned. Real COM port serial interfaces are increasingly rarely found on modern PCs, but the advantage is that the COM port API provided by the operating system makes setting up communications easy. To control our hardware we install a vir- tual COM port driver supplied by device manufacturer FTDI. Our program then sees a serial COM connection and can use it to transmit and receive data. A terminal emulator program can be used to check that everything is working as it should. It is necessary to tell the termi- nal emulator which COM port is allocated to the FTDI chip on the USB-to-RS-485 converter board, and to set its commu- nication speed to 9600 baud. Tricky situation It is easy to use the .NET framework to send and receive characters over a (vir- tual) serial interface using the dedicated 'SerialPort' class. The class encapsulates the Windows API calls that have to do with controlling a serial port. The prop- erties of the class can be managed to set the communication speed, the name of the port and other parameters. Sim- ple methods ('Write', 'Read') allow data to be written and read. This approach works without problems in a conventional Windows desktop application. However, Store apps are unfortunately not allowed to have direct access to the class: the apps run isolated from the system envi- ronment and from other applications in a 'sandbox' provided by the operating system. The sandbox approach improves security, but comes with disadvantages. Direct access to many system functions, to sensors and in particular to external hardware is restricted or impossible. Also, even in the case where the required access is possible, it must be requested by declaring it in the application manifest when the program is developed. Then, when the app is installed, the user must agree to the requested access permis- sions. In general it is not possible to use system functions for direct access from an app, and in particular the Win32 APIs are not available for use by Store apps. In some cases alternatives are available (see Table 1), but unfortunately not in the case of the serial interface. However, there are some potential solu- tions. With the release of Windows 8.1 Microsoft has made improvements that allow (generic) access to the USB port. This is done using the 'Winusb.sys' sys- tem library, which must be available on the target computer. From the app side we use the classes in the namespace Win- dows. Devices. Usb [5]. There is a descrip- tion at [6] of how to talk to the FTDI device using this method, which it would be feasible to use in our case. However, most readers will be more familiar with working with virtual COM ports, and so we have tried to find an alternative approach which allows us to get around the limita- tions of the sandbox. Kommunikation meistern Die Losung besteht darin, in die Projekt- mappe eine Brokered Windows Runtime Component einzubinden [7]. Nachfol- gend werden die einzelnen Schritte bes- chrieben, um den Zugriff auf die Hard- ware uber einen COM-Port (via USB) zu ermoglichen [8]: 1. First create an app as explained in the article in the 'Learn' section of this issue. 2. Using the Solution Explorer add two further projects based on the 'Brokered WinRT Component Project Templates'. If these templates are not available on the development machine they must be located on-line (see Figure 2). The first of the two projects that are added is a C# project, which we call 'Serial- PortSampleAppBroked': it is this proj- ect which will contain the code that carries out the communication using the SerialPort class, implementing the interfaces that will be needed by the app. However, the project cannot be included directly as a reference in the app, as this will be rejected by the com- piler; to obtain access to the interface we must do so indirectly, via a proxy. The proxy is a separate project (writ- Table 1. Alternative libraries for low-level access from Store apps [4]. System function under Win32 (for desktop applications) Alternative API for Windows Store apps Bluetooth Windows. Networking. Proximity Device enumeration (Function Discovery, PnP-X, WSD) Windows. Devices. Enumeration FAX access not possible Location API Windows. Devices. Geolocation Print Windows. Graphics. Printing Sensors Windows. Devices. Sensors Serial and parallel ports access not possible SMS Windows. Devices. Sms UPnP Windows. Devices. Enumeration.Pnp Windows Portable Devices Windows. Devices. Portable WSD Windows. Devices. Enumeration www.elektormagazine.com September & October 2015 25 j)(ir^6fur Figure 2. Adding a project (using the Brokered Windows Runtime Component template). ten in C++) within the solution, and we have decided to call it 'SerialPortSam- pleProxy'. No code is implemented within the proxy project: it acts only as a bridge between the Store app and the Windows components. 3. With all the projects in place we can now set up the necessary references. In the Solution Explorer under 'Ref- erences' for the proxy project 'Seri- alPortSampleProxy' add a reference to the 'SerialPortSampleAppBroked' project. Then, likewise, add a reference from the 'SerialPortSampleApp' proj- ect to the proxy project: see Figure 3. The overall architecture is shown in Fig- ure 4. Although the procedures above seem complicated they do not really present an obstacle to the developer. Once the references between the proj- ects have been set up, we do not need to be concerned with them further as we develop our app, and we can simply use the SerialPort class to provide com- munication. However, there is a disad- vantage that should not be overlooked: the use of 'Brokered Windows Runtime Components' is regarded by Microsoft as a critical security weakness, and so it is not possible to distribute the app via t>^ SerialPortSampleApp - Microsoft Visual Studio (Administrator) BATH SCAfBCITIN ANSKTHT WOJEICT CR5TEUEN BEBUOGEM TEAM EXTRAS TEST ARCMITEKTV* ANAIVSEMN EEH5TE* HATE O • O Q • Ss f ► loAikr CcmjHAV • -]j p , I HI “I , H Scfi«tPort$4mp4«Appfiroked 4 using Sysiea.Linq; > using SyltM.Ttxt; fc using SyitM.Thrt*41ng.Tftiks; lO SPdtnng commwd) - n«Msp*ce [f S public scaled class S* { priv^ // t _ t Aiwmb»yl publ ( Piojrttrmppr Name [H $*fiMPort$*mplfApp6re_ W Semtf'oitSamplfPrcwy Pfad CAUsenVsetltlr.CCOOesirtopSenalPortSjmpieApeiSma^ertV- CMJsm ■.♦< If k.XC Desktop Sen alPoftSampi# App SwiaiPeitS.. S#r«*lPo«lWnpl*£*jp6iok»d f CXjkKsuc hen Dutcbswchen... OK d a 0 Projcfctmappc* - bploref o < <2 o - a o Prcyefctmappen-Uipi. Projeltmappe *$erialPc*tSampl< J • SeriaV net Sample App (WWu ► > Piopartm b Assets > jO App^jml a £) MeinPegexaml §3 Package appwnarWest P $enalPo>t$ampitApp a T e» {?•' Se»iaiPcrtSampleAppBrgked * A Pfopert>« a C* Ass«tnblytnfo.cs a 0 Wt1ir«gi.i«4t*Mjt a • ■ Veewetse a c $a^, *♦ '•» • • 1 . i ■ i * ► Figure 3. Reference from the app to the proxy project. the Store. The only way to install the app is via 'side loading', which requires a developer account on the target device. Side loading is therefore only appropri- ate for apps that are not intended for widespread public distribution [9]; for homebrew projects this is not too severe a limitation. Example app We implemented the ideas above in a small app which allows a couple of out- puts to be activated and deactivated using buttons, and which also displays the status of the hardware inputs (see Figure 5). The user interface can easily be adapted to suit any particular appli- cation, adding simple icons to support intuitive touch-based operation. The XAML code that defines the user inter- face is shown in Listing 1. Listing 2 shows the SP class that we have written ourselves, which must be included in the 'SerialPortSampleAp- pBroked' project. Output of data on the serial interface is done using the 'Write' command, and likewise input is done using the 'Read' command. The listing shows only the construc- tor for the SP class. It is inside the constructor that the relevant port is selected and the various parameters, including the baud rate, are initialized. Furthermore the constructor can also accept a parameter in the form of a command string as described above, which will be output to the port. This makes accessing the port from the app COM-Port (virtuell via USB) Solution Figure 4. Overall software architecture to allow access to the COM port from an app. 26 September & October 2015 www.elektormagazine.com very straightforward: for example, sending the command 111 + ' can be done in a single line as follows. Seri alPortSampleAppBroked . SP client = new Seri alPortSampleAppBroked . SP(“L 1 1 +\r\n”) ; Other methods in the SP class allow the inputs to be interrogated by read- ing from the serial port. If it is desired to react to a change in levels on the inputs they must be polled in sequence, for example under control of a timer (see the DispatcherTimer class [10]). Figure 5. The example app can control LEDs and relays. Listing 1. Excerpt from the XAML code that describes the user interface for the example app. < RowDef i ni ti on/> < /Gri d . RowDef i ni ti ons> www.elektormagazine.com September & October 2015 27 Conclusion Apps are attractive because of their ease of use and focus on a single function. Windows Store apps can run on tablets and on notebooks; in most cases these have at least one USB port and so an app can offer an alternative to a conventional desktop program for controlling exter- nal hardware. The required programming, with the logic expressed in C# and the user interface in XML, is by no means a black art; and it is possible to make the user interface simple and attractive, fol- lowing the maxim 'less is more'. There are indeed technical obstacles in inter- facing to the hardware, but these can be overcome. N ( 150276 ) Web Links [1] www.elektor-magazine.com/150276 [2a] Elektor July & August 2014: www.elektormagazine. com/140009 [2b] Elektor November 2014: www.elektormagazine. com/140328 [2c] Elektor June 2013: www.elektormagazine. com/130154 [3] www.ftdichip.com/Drivers/VCP.htm [4] https://msdn.microsoft.com/en-us/library/windows/apps/hh464945.aspx [5] https ://msdn.microsoft.com/en-us/library/windows/hardware/dn303342%28v=vs.85%29.aspx [6] www.ftdichip.com/Support/Documents/InstallGuides/AN_271%20D2xx%20WinRT%20Guide.pdf [7] https://msdn.microsoft.com/en-us/library/windows/apps/dn630195.aspx [8] http://ioi.solutions/serial-port-access-metro-style-app/ [9] https://technet.microsoft.com/en-gb/windows/jj874388.aspx [10] www.wpf-tutorial.com/misc/dispatchertimer Listing 2. C# code for communicating over the COM port. public sealed class SP { private SerialPort _serialPort; public SP(string command) { string portName = string[] ports = Seri alPort . GetPortNames ( ) ; if (ports . Count ( ) > 0) { int portlnt = 0; foreach (var port in ports) { var portNumber = port . Substri ng (port . Length - 1) ; if (portlnt < Int32 . Parse (portNumber) ) { portlnt = Int32 . Parse (portNumber) ; } } if (portlnt != 0) { portName = “COM” + portlnt; _serialPort = new SerialPort( portName , 9600, Pari ty . None , 8 , StopBi ts . One) ; _seri alPort . ReadTimeout = 200; if (_serialPort != null && _seri alPort . IsOpen) _seri alPort . Close ( ) ; _seri alPort . Open ( ) ; _seri alPort .Wri te (command) ; _seri alPort . Close ( ) ; } } } } 28 September & October 2015 www.elektormagazine.com TIPS & TRICKS Tips and Tricks From readers for readers Here are some more neat solutions from our readers, sure to make life a little easier for engineers and electronics tinkerers. Safety Tip for AVR Controllers From Andreas Riedenauer (FAE), Ineltek Mitte GmbH The Watchdog Timer (WDT) issues a reset to the con- troller if it stops functioning correctly or ' hangs' . This sit- uation can occur not only as a result of a software failure but also by a powerful electromagnetic event or exposure of the controller to x-rays from sources such as cosmic radiation. In normal operation the WDT will continually be prevented from generating a reset by the regular execution of the WDR (Watch Dog Reset) instruction performed in a loop somewhere in the pro- gram. If the instruction is not issued in sufficient time the timer runs out and issues a system reset. When this occurs ; the Special Function Register (SFR, also known as the 10 register) and the ports are returned to their default state. They will be configured as inputs with inactive pullups. It is important to ensure that this state does not cause a problem for the circuitry connected to the I/Os ; in particular if they are used to control the current to induc- tive loads where a loss of signal could allow unacceptable levels of curren t (sa tura tion ! ) . Sometimes operation of the controller's clock crystal can be influ- enced and even stopped by severe mechanical vibration; the watch- dog mechanism will come to the rescue here and protect the power driver stage , but beware; should the system clock stop just as the WDR command is executed (according to Murphy's Law the probability of this unlikely event occurring is equal to 1) the outputs will remain frozen in their last state! The advice here is to make sure the WDR command is issued when all other outputs are in a benign state i.e. if they were to stay in that condition for any length of time , no harm would result. s Variometer Tuning From Burkhard Kainka ™ The fixed value inductor shown has a nominal value of 22 pH. When a magnet is brought close to the coil it has the effect of reducing its inductance. In general if a ferrite core is exposed to a strong magnetic held it can become partially or fully saturated , decreasing its permeability. Using this technique the value of inductance can be adjusted in a range of 1:10 and can be used to alter the resonant frequency of an LC filter. This type of variometer or 'permeability tuning' is in fact used in some radio receiver designs (particularly in older car radios) where it replaces the variable tuning capacitor. There can however be a prob- lem with damping. While the inductive resistance at higher frequencies falls , the series damp- ing resistance of the coil remains constant , reducing the hlter's Q factor. Using variable capacitor tuning , the bandwidth at the upper end of the fre- quency band is about the same but with variometer tuning the bandwidth becomes wider. Partially magnetizing the ferrite rod of a medium-wave direct-conversion receiver demonstrated this to good effect. Tuning at the lower frequency end of the spectrum is easy but the upper frequency range has poorer sensitivity. N £20 ( 150227 ) Got a neat solution for a tricky problem? Using components or tools in ways they were never intended to be used? Think your idea to solve a problem is better than the usual method? Have you discovered a work-around that you want to share with us and fellow makers? Don't hang around; write to us now, for every tip we publish you'll earn 40 pounds! www.elektormagazine.com September & October 2015 29 FFT Analysis in VB Display spectral curves over time too By Kurt Diedrich (Germany) Versatile as it is, the oscilloscope is not normally up to the task of examining the frequency components contained in a signal. But the combination of a PC — the other universal tool — and suitable software renders them superbly. This article explains how you can achieve this using Visual Basic. Fourier analysis, named in honor of the French mathematician who developed it in 1822, identifies in purely arithmeti- cal terms the amplitude of the frequen- Figure 1. Result of a classic FFT: intensity display of the frequencies (up to 25 Hz here) contained in a signal extract as lines of varying height. cies contained in a signal. On this basis the FFT (Fast Fourier Transformation) commonly used today was developed in 1965 by James Cooley and John W. Tukey. With its help we can represent a signal as a two-dimensional diagram, in which its amplitude is plotted over frequency (Figure 1). This has been exploited for decades in physical formats; besides simple imple- mentations such as LED bar-graph dis- plays based on fixed bandpasses and used largely as eye candy, for laboratory applications there are also special very accurate and correspondingly expensive Figure 2. This TFT versus Time' graphic arises from calculating consecutive time intervals (Figure 2a). Representing the spectrum over time is produced by tilting and rotating (by 90 degrees), also aligning the display shown in Figure 1. We replace the height of the bars by color values that can be interpreted intuitively (Figure 2b). spectrum analyzers, with which we can display the frequencies present in a sig- nal as a spectrum. Today, however, the processing power of normal PCs extends easily to handling digitized (audio) signals not only in file form but also to calcu- lating informative spectral displays from this data at lightning speed, without any need for specialized hardware. Time vs. frequency A problem arises with signals that vary over time: the more accurate the analysis required, the longer the time period we must investigate. Since we are indentify- ing the frequency amplitudes contained over an interval of time, the principles involved mean we are battling with a kind of 'Fourier uncertainty principle' in which the higher the temporal resolution of the analysis, the briefer the interval for inves- tigation, which leads us back to coarser frequency resolution— and vice versa. The FFT versus Time analysis adopted in the program shown here goes one step further. It generates not just the static spectrum of a defined signal segment but also captures consecutive time intervals (Figure 2a). In this way we can display the variation of the frequencies contained in a signal as a spectral progression even over lengthy periods of time. To display the results we require three dimensions: time, frequency and intensity. The X-axis corresponds generally to time and the Y-axis to frequency. The amplitude is rep- resented by the color or brightness of a point in the time-frequency area (Figure 2b). This produces a series of color-coded spectra. A frequency-modulated sinewave tone (such as a police siren) in a display of this kind appears as bright, horizontal wavy line on a dark background. 30 September & October 2015 www.elektormagazine.com Q&A Listing 1. Private Sub FFT() For n = 0 To 512 a(n) = 0 b(n) = 0 Next n For n = 0 To 512 For i = 1 To 1024 a(n) = a(n) + samp_buf(i) * Math.Cos(2 * pi * n * i / 1024) b(n) = b(n) + samp_buf(i) * Math.Sin(2 * pi * n * i / 1024) Next i Next n For cnt = 0 To 512 grafik(cnt) = Math.Sqrt( (a(cnt) * a(cnt)) + (b(cnt) * b(cnt))) Next cnt End Sub Formulae and code The Internet offers a vast amount of infor- mation on the subject of FFT, requiring unfortunately a solid mathematical back- ground on account of the complex for- mulae involved. It is far simpler to go straight to the code for calculating an FFT. First of all then, here is the VB code (Listing 1) for a frequency analysis at a specific moment (time interval). A (fairly long) .wav file of a piece of music will serve as an example. We are looking for the amplitudes of the frequencies for a specific time segment At, beginning at the moment t. For this purpose we shall copy, let's say, 1,024 samples from the moment t into the Array samp_buf (see Figure 3). The code required for this is not included in the sample script above. To calculate the FFT we require both the buffer Arrays a and b (reset to zero before each analysis) and the Array grafik for the results, the content of which will be displayed later. The two nested loops (with n and /) are responsible for calculating the FFT anal- ysis. The outer loop subdivides the fre- quency range (sampling rate / 2) pres- ent in the file into 512 parts. Each value of n therefore indicates the intensity of the frequency in the time domain under examination on a scale from 1 to 512. The Variable / in the inner loop deter- mines the length of the time interval to be examined. An optimal result arises when / = 2n. The sample values in the inner loop are multiplied with Sine and/ or Cosine 2 Pi and the loop Variables and also summed in the Arrays a and b. Only after a complete iteration of the inner loop is a single intensity value calculated in the frequency scale from 0 to 512. In the final loop cnt the content of the Arrays a and b are squared, added and the root thereof is taken. This root is the final result and is then stored in the Array graphic. It contains the averaged ampli- tudes of the frequencies on a scale from 1 to 512 and represents the spectrum of the time interval from t to t + 1,024 samples. All Arrays are declared as 'single'. For graphical representation of FFT vs. Time the results contained in the Array graphic need to be converted into integer color values. You can find more about this in the commentary to the source code. Saving calculation time For the spectrum of a specified moment in time within a file such as shown in Figure 1 the code listed is completely adequate. Nevertheless several hundred (or even thousand) analyses of this kind need to be performed sequentially during an FFT versus Time analysis. To avoid the need to wait several minutes, the execution of the code shown above should ideally last no longer than a couple of milliseconds. We can achieve this with one of many tricks. The expression included in the inner loop: Math.Cos(2 * pi * n * i / 1024) contains no values from the file under examination, only constants that had already been calculated previously and could then be recycled. Since every mul- tiplication already inside a nested loop extends the calculation time drastically, these values are calculated in a Function of their own called pre_FFT before the actual FFT activity. The results of pre_FFT are then available in the Arrays mem- oryl and memory 2 (German ' speicher ' originally used for memory). We then need merely to read out their content and transfer this into the actual FFT loop. Calculating time is reduced significantly in this manner. Listing 2 shows the code for the Function pre_FFT. The relevant lines in the Function FFT are altered as follows: Figure 3. The graphic seen in Figure 1 emerges when an FFT analysis of a time interval At with a fixed number of samples is undertaken at a defined moment in time t. a(n) = a(n) + samp_buf(i) * memoryl(n, i ) b(n) = b(n) + samp_buf(i) * memory2(n, i ) There are two other means of accelerating the process, although we won't examine them in depth here. Anyone interested can find further references both in the program source code [1| and in the online help for the program. Resampling Let's assume that the sampling rate of a file amounts to 400 Hz. An FFT made with the code shown above produces the amplitudes of the frequencies from 1 to 200 Hz (on the basis of the sampling the- orem) with a resolution of 1/512 of the entire range. We will also assume that the low frequencies between 1 and 10 Hz are of particular interest. Here, unfortu- nately, we cannot identify much about them, as the scale is squeezed together at the bottom edge. A Y-zoom feature would be helpful here — and nothing could be simpler than this. Within the inner loop www.elektormagazine.com September & October 2015 31 Listing 2. The code for the function pre_FFT private sub pre_FFT For n = 0 To 512 For i = 1 To 1024 spei cherl (n , i) = Math. Cos (2 * pi * n * i / 1024) speicher2(n, i) = Math. Sin (2 * pi * n * i / 1024) Next i Next n End Sub tfurn F«|jlcirr* 1 4 | G3 Lergth of fit* n e«ccnde 107.7058437 Dotyieebetw. FFTj 28l3Jon'jng 05_D*mo_S'j^jle .0 l_DEMC> J3EMO_DEMD\04_Pf« loch fcjHp 1 im/m. 3 : .?.S43 @| SONS - 1’ )2 BN ■€ * O ^ *> % t»» 0 « 0 l t Q! OC 0 | ^ ij) (».WWr X » ■ > at • c The PicoScope serial decoding display can be viewed as a basic bus waveform correlated with the source analog or digital channels. This layout helps to troubleshoot data errors caused by noise spikes, faulty line drivers and mismatched impedances. Alternatively, the table view lists every packet or frame with timings, decoded data, status flags and optional voltage measurements. You can filter and search the table by any field, export data to a spreadsheet, and even define human-readable names for specified address data values by creat- ing a link file'. PicoScope can decode multiple serial buses at once, with any mixture of protocols, limited only by the number of chan- nels (maximum of 20 for MSO models). PicoScope R6.11.4 beta can be downloaded, free of charge, from www.picotech.com/downloads. To read more details on Pico Technology's serial decoding pro- tocols please visit: www.picotech.com/library/oscilloscopes/ serial-bus-decoding-protocol-analysis www.picotech.com (150335-1) Microchip: CAN Flexible Data-Rate Transceiver Microchip Technology Inc., announced a new family of CAN FD (Flexible Data-Rate) trans- ceivers, the MCP2561/2FD. As an interface between a CAN (Controller Area Network) pro- tocol controller and the physical two-wire CAN bus, these transceivers can serve both the CAN and CAN FD protocols. This product family not only helps automotive and industrial manufac- turers with today's CAN communication needs, but also provides a path for the newer CAN FD networks that are increasingly in demand. With their robustness and industry-leading fea- tures, including data rates of up to 8 Mb/s, the MCP2561/2FD transceivers enable cus- tomers to implement and realize the benefits of CAN FD. These new transceivers have one of the industry's lowest standby current con- sumption (<5 pA typical), helping meet ECU low-power budget requirements. Additionally, these devices support operation in the -40C to 150C temperature range, enabling usage in harsh environments. The new family of MCP2561/2FD CAN FD transceivers is available in 8-pin PDIP, SOIC and 3x3 mm DFN (leadless) packages, providing additional design flexibility for space-limited applications. The family also provides two options. The MCP2561FD comes in an 8-pin package and features a SPLIT pin. This SPLIT pin helps to stabilize the common mode in biased split-termination schemes. The MCP2562FD is available in an 8-pin package and features a Vio pin. This Vio pin can be tied to a secondary supply in order to internally level shift the digital I/Os for easy microcon- troller interfacing. This is beneficial when a system is using a microcontroller at a Vdd less than 5V (for example, 1.8V or 3.3V), and elimi- nates the need for an external level translator, decreasing system cost and complexity. The MCP2561FD and MCP2562FD transceivers are both available now for sampling and volume production in 8-pin PDIP, SOIC and 3x3 mm DFN packages. www.microchip.com/CAN-Transceivers-032315a (150335-3) www.elektormagazine.com September & October 2015 35 Industry Feature Article Man and Machine: the Distance that Brings us Closer Distance measuring sensors mirror human biology to enhance accuracy By Yuji Hamatake (Manager, Sharp Devices Europe) The devices that surround us are rapidly becoming more automated and intelligent. Enhanced functionality and sophistication requires these machines to perceive their surroundings with greater accuracy and reliability. Distance measuring sensors are just one technology that is making a wide range of devices including everything from highly autonomous robots to paper towel dispensers smarter and more responsive to the needs of their human creators. Predictably, the technical means of establishing more natural man-machine interactions frequently reveals interesting par- allels to human biology. Stereopsis (also known as binocular parallax) is an important part of the human body's ability to perceive depth using both eyes. And it just so happens that stereopsis functions accord- ing to the very same principle that more sophisticated dis- tance measuring sensors employ to yield precise results. It's known as triangulation, which lets us calculate the location of an unknown point in a triangle based on the distance between the two known points and knowledge of the respective angles. Is there anybody out there? Many of the photoelectric sensors in use today rely on a much simpler design that does not involve triangulation. These devices instead use an emitter of light (most often infrared) coupled with a photoelectric receiver capable of sensing the emitter's light. The emitter and light sensor can either be mounted together within a single component or be installed as two discrete units to form what is known as a through-beam arrangement. Ret- roreflective sensors send out a beam of light towards a reflec- tor which returns the light back to the unit. In both cases, the receiver detects when the beam is interrupted by an object. Diffuse reflectance proximity sensing devices rely on the reflec- tance ( syn . reflectivity) of objects in their vicinity. When no object is present, the light emitted by the sensor is not returned to it. When an object enters the sensor's range, it reflects a portion of the emitted light back to the integrated photode- tector, signaling the presence of an object. Of the three types of photoelectric sensing described here, only the last (diffuse reflection) is suitable for small or portable devices which can't accommodate a two-piece retro reflective assembly. Devices such as touchless water taps in restrooms, for instance, are unable to accommodate separate emitter and receiver components. But estimating distance based on the amount of reflected light can be problematic. Diffuse reflective sensors happen to have an Achilles' heel: color. The color and texture of an object's surface can have a great impact on how much of the emitter's light is reflected back to it. And since simple sensors such as these are not able to detect and adjust for the color of objects, the accuracy of diffuse reflection sensors is limited. An interesting angle As an illuminated object approaches you, it's not only the intensity of the light reflected that changes. The angle does, too. Provided, of course, one measures that angle from a slightly different spot than where the emitter is located. Cal- culating the angle of incidence of the light hitting the offset receiver would yield the distance between the emitter and the 36 September & October 2015 www.elektormagazine.com Triangulation: a natural approach to distance measurement Stereopsis aids human depth perception by detecting distances In Sharp distance measuring sensors, a position sensitive detector of objects projected onto the retina. (PSD) functions as the light receiving surface. Far point ►+ rnmn receiver if we apply a little trigonometry, which is of course based on the theory of triangulation. But trigonometry is not exactly how sophisticated infrared distance sensors, such as those manufactured by Sharp, determine distance, although the underlying principles are the same. Instead, two optical lenses are utilized, one covering the emit- ter and one covering the receiver. Behind the receiving lens, there is a position sensitive detector (PSD) that measures the intensity of the incoming IR radiation using a linear array of photodiodes. For the analog distance sensors from Sharp, the PSD's output varies in relation to the angle of incidence of the incoming light and generates the output voltage, which can then be used to calculate the distance of the object using the following formula: Ax = xl — x2 = Precisely the right sensor The demands of individual applications often vary greatly. It's important to choose the right sensor according to a number of parameters including digital vs. analog output, minimum detection distance, maximum range, and not least of all cost and size. That's why so many engineers and product develop- ers rely on Sharp distance measuring sensors — it's difficult to find a better selection of accurate components than Sharp's comprehensive lineup. With over a dozen different models covering ranges from as close as 1.5 cm and extending all ( 1 V ii h A-f the way out to 550 cm, Sharp's infrared distance measuring sensors are well-known across a number of different indus- tries for their accuracy. Potential applications cover everything from document processing, sanitary equipment, and robotics to consumer electronics, gaming consoles, and more. With affordable and reliable choices like these available, it's clear that the hard-working and ubiquitous IR distance sensor is destined to bring a more human touch to an ever-increasing number of man-machine interactions. M ( 150238 ) www.elektormagazine.com September & October 2015 37 Welcome to Elektor Labs Elektor Labs is the place where projects large, small, analog, digi- tal, new and old skool are sketched, built, discussed, debugged and fine-tuned for replication by you. Our offer: Become Famous Most engineers and budding authors we come across are just too modest. If they do not see the attraction and beauty of a design idea scribbled on a coaster and worked out later at home, others may, and should. Let Elektor Labs help you hone your design to perfection, let the editors assist with text & graph- ics, and reap the rewards by seeing your name in print in Elektor magazine's celebrated LABS section. Sure, we are happy to negotiate payment, but the actual remuneration will be fame & glory in elec- tronics land, and your name added to the long list of extremely successful e-authors. Our get-u-fa- mous formula also applies to book authors, blog- gers and video makers. Students and youngsters: being in publication is a current boost like no other in getting a job! Our Experts and Designers Besides experienced sup- port staff and BSc, MSc qualified engineers with a total working life in electronics of about 200 years, the Lab has access to Elektor's vast network of experts for consulta- tion, critical advice, and assistance with specialized assignments. Our Facilities We are sumptuously housed in three spacious rooms at Elektor House where we try unsuccess- fully to keep our solder jobs and prototypes off ■ our computer desks. We have water, 218 volts w electricity and coffee nearby. PCB milling, pro- totype assembly, SMD reworking, audio testing, pizza cooking, and mechanical work are deferred to converted cellars in the basement. Our Standards All projects and products going through the Labs pipeline are produced to high engi- neering standards. In practice, prototypes of projects labeled LABS in the magazine must be demonstrated to work to specifi- cation on certified, calibrated test equip- ment available locally. BOMs and schemat- ics must match perfectly. Kits are sampled for completeness. We are ROHS compat- ible, lead free and comply with electrical safety standards applicable in our location. If engineering errors are found these will be put up for public notification. 38 September & October 2015 www.elektormagazine.com Our Products Our products are visible in Elektor magazine, as well as on the Elektor.Labs and Elektor Store m websites. The range includes text write-ups for ^ editors, prototype photography, PCBs includ- ing SMD-prestuffed, PCB files, project software, programmed devices, semi-kits, tools, modules, videos, and service desk information. Our Webinars The more talkative of our Lab engineers do not stop at testing prototypes, they happily share tech- k nology related problems, insights, get-u-going m information, and design skills on live camera at Elektot.tv. Labs' webinars are free to attend and extremely interactive. They are announced in Elek- tor.POST, and webcast live from Elektor House in Holland. Do plug in! L J Our History The origins of Elektor Labs go back to the early 1970s when soldering and writing was a one-man, single-desk job. Ove the years Labs staff have not only witnessed the arrival of the transistor, the IC, the microcontroller, and the SMD, but actually jumped on these parts as soon as they were out of the profession- al-only woods. Once special branches, Audio Labs, Micro Labs, PCB Labs, and Mechani- cal have converged back again into a single activity. elektor©labs Sharing Electronics Projects & IrfiriTi HtiffiiE Upload your own projects! On our very own Elektor-Labs website, you can share and showcase your ideas and project proposals to thousands of other electronic engineers. The site also allows you to follow other specialists' activities, supply comment, and so push the projects forward. Here's the best part, the top projects are eligible for processing in our test lab, in preparation for publication in Elektor magazine. Who's this for? Although only members can log on to our Elektor.Labs website to publish projects and contributions, anyone can view along with the other projects. If you'd like to see your project published in Elektor magazine, which is published in four languages and read by tens of thousands of electronics specialists all over the world, then become a Green of Gold member (www.elektor.com/member) or log in as an existing member of our Elektor community! www.elektormagazine.com September & October 2015 39 LEARN DESIGN SHARE Welcome to the DESIGN section By Clemens Valens, Elektor Labs Licence to... gosh, whom/what exactly? Wk One of the most convoluted subjects today in electronic design is licensing. If your design is closed as most commercial products are, it is assumed to be protected by international trade and copyright laws. These appear pretty complicated to understand and apply by a layman, but there is lots of jurisprudence detailing what can and what can't be done. However, when you want to release a design as open source, be it hardware, software or both, things get really complicated. The problems emanate from very nature of the open source movement itself. A typical open source license allows the licensee to adapt the licensed work, which often results in numerous 'derived' designs, all slightly dif- ferent. The same effect is seen to encroach upon open source licenses. There are now so many different open source licenses out on there on the web that it is hard if not impossible to find the one that's just right for you. The licences being legal documents that have to stand up in court — globally if possible — they are very hard to understand. What's more, they keep evolving. Where all you wanted was donate your design to the world by stick- ing some open source license on it, you got bogged down in a swamp of legal gibberish. And you can't get away with something like "this is free, do whatever you want with it, no responsibility taken" because that will be considered too light hearted in a lawsuit after someone did something terrible with your work. Free as in Free L " s’ A A Useless & Incomplete List of Licences (in alphabetical order) AAL, AFL-3.0, AGPL-3.0, Apache-2.0, APL-1.0, APSL-2.0, Artis- tic-2.0, BSD-2-Clause, BSD-3-Clause, BSL-1.0, CATOSL-1.1, CC BY, CC BY-NC, CC BY-NC-ND, CC BY-ND, CC BY-SA, CC-BY-NC-SA, CDDL-1.0, CECILL-2.1, CERN OHL, CNRI-Python, CPAL-1.0, CUA- OPL-l.O, ECL-2.0, EFL-2.0, Entessa, EPL-1.0, EUDatagrid, EUPL- 1.1, Fair, Frameworx-1.0, GPL-2.0, GPL-3.0, HPND, IPA, IPL-1.0, ISC, LGPL-2.1, LGPL-3.0, LPL-1.02, LPPL-1.3c, MirOS, MIT, Motosoto, MPL-2.0, MS-PL, MS-RL, Multics, NASA-1.3, Naumen, NCSA, NGPL, Nokia, POSL-3.0, NTP, OCLC-2.0, OFL-1.1, OGTSL, OSL-3.0, PHP-3.0, PostgreSQL, Python-2.0, QPL-1.0, RPL-1.5, RPSL-1.0, RSCPL, SimPL-2.0, Sleepycat, SPL-1.0, TAPR, UPL, VSL-1.0, W3C, Wat- com-1.0, WXwindows, Xnet, Zlib, ZPL-2.0. N as to Freed \ (150332-1) otri 40 September & October 2015 www.elektormagazine.com LABS PROJECT Original design: Juan Canton (Mexico) Post Engineering: Ton Giesberts (Elektor Labs) Editing: Jan Buiting This IR remote controlled dimmer works with a triac and in its standard configuration is suitable for light electric heaters and incandescent lamps up to about 1000 watts. The PIC microcontroller used in the project can learn control codes from almost any remote control. Here's power dimming from the comfy chair. Learn-'n-Go Remote Controlled Dimmer Infrared for lamps and heaters The initial requirements for the project, a "multipurpose remote control receiver for AC line powered lamps" were formulated by the author as follows: 1. Operation off 50 Hz or 60 Hz power grids; 2. Operation off 117 or 230 VAC power grids; 3. Operation with only one button; 4. Suitable for controlling the brightness level of any incan- descent or halogen lamp, or the heat produced by a small electric furnace or other heater; 5. An ability to learn up to eight control codes of a common infrared remote control. With the above in mind a circuit was designed by the author, posted on elektor-labs.com and subsequently perfected by Elektor Labs for the purpose of this publication. The transi- tion from Juan's original circuit proposition to the final project published here is well documented by Ton and may be read at the Elektor Labs website [1]. Basically the circuit was chan- ged from an in-line power dimmer to one with 115 or 230 V AC-IN, and dimmed AC-OUT. The best thing about the circuit, its learning ability, was fully retained though. Towards a circuit The result is pictured in the schematic, Figure 1 , which is typical of today's black box-ish microcontroller-based circuitry: little to see in the way of external components, and mucho PIC handling many things in software. To the in-crowd, the triac and the IR decoder are telltale of "something to do with AC-line, amperes and remote control". To better understand the operation of the circuit, it can be thought of as divided in six sections, each of which is discussed below. AC-line power supply What's needed? In a nutshell: V = 5 volts; I. = 4 mA or so net, "stolen" from the domestic 115/230 VAC line with accep- tably low dissipation. Cost and space considerations were found to rule out a dedicated power transformer with its usual com- plement of rectifier and reservoir capacitor(s). The next option traditionally is using a dropper resistance to lower the voltage from 230 (or 115) volts AC down to 5 volts DC, in this case with a minimum load current you'd think is 4 mA. Alas this has to be doubled at least, due to half-wave rectification only. As an example, the following calculation was done for a dropper R (based on 230 VAC line); *= ('/line- Kc)/2I load R = 225 / 0.008 R= 28,125 Q. which sadly dissipates: P = I 2 R P = 1.8 W www.elektormagazine.com September & October 2015 41 1N4007 GPO/ANO/CIN+/ICSPDAT GP1/AN1/CIN-/VREF/ICSPCLK GP2/AN2/TOCKI/INT/COUT GP3/MCLR/VPP GP4/AN3/T1G/OSC2/CLKOUT GP5/T1 CKI/0SC1/CLKIN ™ d k|° b| ■■ r| “o “q lOOpnr Control I Program! VSS 7 PIC12F675 140279 - 11 Figure 1. Schematic of the learning dimmer for AC line powered incandescent lamps and (light) electric heaters. or about 0.9 watts at 115 VAC using a 14 kft resistance. This result seems just about tolerable, but in case the circuit is connected in series with the load, when the lamp lights at it brightest, not enough voltage may be left to power the circuit Figure 2. Software flow diagram. The actual program was written in PIC assembly code. reliably, particularly with 115 VAC grids. The third option is a combination of a resistance (K), a capaci- tance (C), and a clamping device (i.e. rectifier). In the R5-C2-D2 constellation we have here, at 50 Hz and 8 mA current draw, the 0.47 pF capacitor used (C2) is adequate for reliable powering of the triac control circuitry, also considering that the trigger action lasts only microseconds. Besides the all-important dropper capacitor C2, the power sup- ply circuit comprises R3+R4, D2, Dl, C4 and C3, and its ope- ration is truly simple. The reactance X c of dropper C2 together with the resistance of R5 and the clamping/rectifying action of D2 effectively limits the current applied to 5.6-V zener diode Dl. C3 removes most of the mains-borne voltage variations, and finally C4 suppresses any high frequencies and noise. The AC line voltages and the appliance are connected to connec- tor pairs K1-K2 and K3-K4 respectively. The incoming line vol- tage is protected with 5-amp (115 V; 10-amp) fuse FI and any switching noise due to the triacs gets suppressed by choke LI. Zero-crossing detector Looking at D3, R7+R8, and R9-C9, we have a half-wave rec- tifier rather than a zero-crossing detector. Consequently only one crossing is detected and the microcontroller software cal- culates the trigger instance to go with the second half cycle. Trigger circuit Both the A1 pin of the triac and the microcontroller supply rail (+5 V) are tied to the AC line voltage. To trigger the triac, its gate G is driven to ground via current limiting resistor R2. This combination takes advantage of the fact that the microcontrol- ler has higher current sink capacity than source capacity, and triggers the triac with "negative" current into its gate, which is where most of these elements need least current to operate. Snubber network This is composed of Cl (note: Xl-class cap here) and Rl, and its function is to avoid false turn-on of the triac. Triac type BTB16-600SWRG is a 'digital' one (suffix SWRG) with a rela- tively low trigger current of 10 mA (min.). On the down side it's not snubberless, hence the need for RC network Rl/Cl. Infrared (IR) receiver module Receiver module IC2 decodes the signal of any common infra- red remote control transmitter. We tested a number of RC5 remotes. When the microcontroller is in programming routine (discussed further on) it receives the code and stores it in its on-chip EEPROM. When in normal use the same code is recog- nized, the micro responds as if the local Control switch (SI) is pressed. This allows you to operate the dimmer from a distance. Filters The circuit has a filter to avoid radiation and disturbances on the AC grid owing to the triac operation. This filter inductor LI is either an off the shelf Murata type, or can be home made from 10 turns of 22 AWG (0.6 mm diam.) enameled copper wire on a 25-mm toroid core. Without experience in winging a suppressor choke for use at AC line, we strongly suggest going for the Murata device. Considering that the circuit is powered with a voltage that may have severe variations, the supply voltages to the microcon- 42 September & October 2015 www.elektormagazine.com LABS PROJECT troller and the infrared receiver need to be filtered. For the microcontroller this is done by RIO, C5 and C6; for the IR module, by R6, C7, and C8. That concludes the description of the design as far as the hardware goes. Software One way of getting to understand the software executed magi- cally & invisibly by the PIC micro is to look at the flow diagram in Figure 2. When the supply is applied, the following happens. Note that for all instances of "brightness" you can also read "heater power" if an electric furnace is connected as a load. 1. The microcontroller calculates the AC line frequency (50 Hz or 60 Hz — Elektor is read all over the world) and completely turns off the lamp. It waits for Control switch SI to be pressed. 2. If Control is pressed and released immediately, the brightness will increase slowly until it reaches the maxi- mum level. 3. If Control is pressed and remains pressed, brightness will increase until the switch is released. 4. If Control is pressed and released, and the lamp lights fully or partially, the dimmer will decrease brightness to zero. 5. If Control is pressed and remains pressed, and the lights fully or partially, the dimmer will decrease brightness until switch released. Fitting with an Elektor publication aimed at enthusiasts like you, the source code for the microcontroller is available for free downloading from the web page created for the project [2], for studying and of course home burning of a controller (Figure 3). The software was written in assembly language — a piece of the program is shown in Listing 1. Archive file 140279-11. zip is for 4 codes, while no. 140279-12.zip is for 8 codes (see below). Further advice on electrical safety aspects and component choice may be viewed at the Elektor Labs page [1]. IR response code programming It is very simple to program the dimmer. To start programming it is advisable but not necessary that the lamp lights at max. brightness. To program, follow the next steps: 1. Hold the Program switch pressed for 3 seconds. This will turn the lamp (heater) on and off twice, showing that the Figure 3. PIC fuse settings for all you embedded moonshiners out there. Listing 1. Program extract (PIC assembly language) ;################################################# GET_PULSE BTFSS REC_SW GOTO RUN CLRF TMR0 GET_P0 BTFSC TMR0 , 5 GOTO GET_P1 BTFSS IR_SIGN ;WAIT FOR HIGH ON "IR_SIGN" PIN GOTO GET_P0 GET_P1 CLRF TMR0 GET_P2 BTFSC TMR0 , 5 GOTO GET_P3 BTFSC IR_SIGN ;WAIT FOR LOW ON "IR_SIGN" PIN GOTO GET_P2 GET_P3 MOVFWTMR0 ; GET PULSE TIME MOVWF INDF MOVLWB '00001111' ANDWF INDF CLRF TMR0 GET_P4 BTFSC TMR0 , 5 GOTO MS3A BTFSS IR_SIGN ;WAIT FOR HIGH ON "IR_SIGN" PIN GOTO GET_P4 MS3A CLRF TMR0 MS4 BTFSC TMR0 , 5 GOTO MS4A BTFSC IR_SIGN ;WAIT FOR LOW ON "IR_SIGN" PIN GOTO MS4 MS4A MOVLWB' 00001111' ; GET PULSE TIME ANDWF TMR0 SWAPF TMR0 , W ADDWF INDF RETURN ;################################################# END_IR MOVLW IR_TIMEOUT MOVWF WAIT_IR MOVLW .158 MOVWF TMR0 BCF INTCON , TOI F BTFSS IR_SIGN GOTO END_IR BTFSS INTCON , T0I F GOTO $ -3 DECFSZ WAIT_IR GOTO $ -8 RETURN ;################################################# Web Links [1] Project history: www.elektor-labs.com/project/ir-re- mote-control-learning-dimmer-or-heat-control- 140279-i.l4109.html [2] Project software: www.elektor-magazine. com/140279 www.elektormagazine.com September & October 2015 43 circuit has entered the programming routine. 2. Using your remote control transmitter at a distance of 3 feet, press the button you want to store. When the dimmer receives and stores the code, it will turn the lamp on and off as a confirmation that the code has been programmed. 3. Repeat step 2 seven more times. Once the eight codes have been stored the lamp will turn on and stay on to show the end of the programming. Software version 140279-12 supports 8 codes, which may be preferable over 4 in case of RC5 remote controls, which do not necessary send the same code twice on pressing the same button. Ready-programmed PIC no. 140279-41 from the Elektor Store supports 8 codes. The IR code can be the same for the four (eight) available positions. Also, different remote control transmitters can be used (of the same standard though). Once the dimmer is pro- Component List Resistors R1 = 1200 . 5%, 5W R2 = 1200 5%, 0.25W, 250V R3,R4,R7,R8 = 470kft 5%, 0.25W, 250V R5 = 100ft 5%, 1W, 350V R6 = 100ft 5%, 0.25W, 250V R9 = 39kft 5%, 0.25W, 250V R10 = 10ft 5%, 0.25W, 250V Capacitors Cl = lOOnF 20%, 1000V, XI class, 15mm lead spacing C2 = 470nF 20%, 275 VAC, X2 class, 22.5mm lead spacing C3 = 470pF 20%, 50V, diameter 13mm, 5mm lead spacing C4,C6,C8 = lOOnF 10%, 50V, ceramic X7R, 0.2" (5.08mm) mm lead spacing C5 = lOpF 20%, 50V, diameter 5mm, 2 mm lead spacing C7 = 47pF 20%, 50V, diameter 6.3mm, 0.1" (2.54 mm) lead spacing C9 = lOOpF 5%, 100V, ceramic C0G/NP0, 0.2" (5.08mm) lead spacing Inductors LI = lOOpH 10%, 7. 8 A, R(DC) = 0.04ft, Mu- rata Power Solutions type 1410478C Semiconductors D1 = 1N4734A, 5V6 zener diode, 1W D2,D3 = 1N4007, 1000V, 1A TRI1 = BTB16-600SWRG IC1 = PIC12F675, programmed, Elektor Store # 140279-41 IC2 = TSOP4838 Miscellaneous K1-K4 = 0.25" (6.35mm) terminal, Faston, screw type, 3.3mm hole S1,S2 = switch, tactile, 6x6 mm, PCB edge, Alps SKHHNKA010 (Mouser # 688-SKHHNK) HS1 = heatsink, PCB mount, Fischer type SK 129 38,1 STS, 6.5 °C/W. For 1250 watts max. FI = fuse holder, 20x5 mm, 500V, 10A FI = 5A fuse, slow-blow, (T), 5x20mm PCB 140279-1 v2.0 Case: Hammond type 1591ETBU Not on PCB: electrical outlet socket, DIN 49440, 16A, 250V, IP20, panel mount (Schuko; German style); RS Components part no. 824-5627. UK and US socket types: see text. Figure 4. The single-sided printed circuit board for the dimmer was designed with all due attention given to electrical safety. 44 September & October 2015 www.elektormagazine.com LABS PROJECT reader's project grammed, the programmed buttons to control will have the same function as the control switch. Construction The circuit is connected to, and operates off, the AC power line which requires great attention to be paid to electrical safety. This was implemented by Elektor Labs doing the PCB design (Figure 4) and building the prototype in an isolated (but trans- parent!) case, drilled to accept a certified AC power inlet and outlet. The short pieces of AC wiring used are 2.5 mm 2 (13 AWG approx.) in view of the maximum load power of about 1000 watts (note 5 amp fuse @ 230 V). The triac is specified 16 amps max. so output powers up to 2000 watts are within reach provided you use a larger heatsink than the one pictured here and indi- cated in the parts list (still observing electrical safety). The little Control and Program pushbuttons are actuated with plastic pins protruding from holes in the short side panel, again respecting minimum distance requirements for 230 VAC. Protective earth (PE) is not indicated in the schematic, meaning it is not present on the circuit board. It must be wired though straight from the IEC appliance inlet to the outlet socket. To avoid having to drill a hole for the optical receiver in the enclosure and so create a potential safety issue, we used a type 1591ETBU blue transparent polycarbonate housing from Hammond Manufacturing which is not too expensive (less than €14 at Newark/Farnell). The IR signal is weakened somewhat by the case but we still achieved a distance of 5 m (15 ft) before the circuit quit responding. Nylon M3 screws are used Finally, serious words of caution: Do not operate or work on the finished circuit at any time when it is not fully enclo- sed and secured in its isolating case. All requirements, recommendations and legislation relevant to electrical safety in your country, state or area apply. to secure the board to the case bottom at a height of 4 mm minimum. This distance may be secured with the help of two M3 nuts on each screw to create a standoff. The AC inlet is an IEC appliance socket, the AC outlet used will depend on the country you live in. At Elektor Labs, a light blue, Schuko-type earthed AC power socket was used that fits the size and mat- ches the color of the case beautifully. Readers in the UK should go for RS Components part # 824-5646, those in the US, for # 824-5655 — both come with a cover lid. The total cost of the Hammond box and the AC power socket is not high given their essential role in electrical safety of the project, not for- getting an attractive yet professional look. Sticklers for splash proofing: the Schuko outlet is also available with a lid, it's RS part # 824-5630. In case a light flickering is visible when fully dimmed, try lowe- ring R7 and R8 to 220 kQ. Also upping the value of C9 can help (<10 nF). A larger value will cause a larger shift in the triggering point of the triac. N ( 140279 ) ( \ ■ ■ ^ 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 • 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 EAGLE Version 7.3 with simplified interface to c/o IDF-to-3D* by Simplified Solutions: • Providing free 3D-view in PDF format • Supporting 3D print through simplified STL file generation • Enabling STEP file export Advertisement www.elektormagazine.com September & October 2015 45 LEARN G In the December 2014 issue of Elektor we described a breakout board with a 4-channel, 16-bit A/D converter, dubbed the ADS1115-eBoB [1]. This IC was previ- ously used in the ELF receiver [2] and the 16-bit ADC module [3]. With the advent of a convenient breakout board holding this tiny IC, we thought it would be fun to come up with some other appli- cations. The IC has a fairly low sample rate of just 860 Hz, so it is only suitable for use in very low-frequency measure- ment circuits. With that thought in mind, an AC power meter is an obvious choice. Although you can buy ready-made power meters these days at fairly low cost, they are closed systems — and that goes against the grain with true electronics enthusiasts. In addition, they do not have an output for connection to an oscillo- scope or multimeter. The project presented here consists of a measurement board holding the ADS1115- eBoB together with a small filter board. 46 September & October 2015 www.elektormagazine.com LABS PROJECT reader's project AC/DC ! Power Meter With high accuracy and a wide measuring range Hardware: Ton Giesberts (Elektor Labs) Software: Luc Lemmens (Elektor Labs) When making voltage, current and power measurements on AC line-powered devices, you need an instrument with good galvanic isolation between the primary and secondary sides. The instrument described here, based on an Arduino Uno with the Elektor Prototyping Shield, provides Class II insulation and displays several quantities directly on an LCD. It also has separate measurement signal outputs for connection to a multimeter or an oscilloscope. Jhe circuitry on the measurement board provides good isolation between the power connections (AC or DC) on the primary side and the measurement signal out- puts on the secondary side. The signals on the secondary side are digitized by the ADS1115, and the digital data is fed to an Arduino Uno with an Elektor Prototyping Shield (no. 140009-91), which processes the data and shows various readings on the display. The displayed quantities for AC are effective power, voltage and cur- rent, as well reactive power and power factor. If you connect a DC circuit to the input, the meter shows the power, volt- age and current. Galvanic isolation Power meters are mainly used to make measurements on line-powered equip- ment, and it is very important to have good galvanic isolation between the mea- surement circuitry on the one side and the data and measurement connector outputs on the other side. This is often imple- www.elektormagazine.com September & October 2015 47 Features • Three measuring ranges: 10 A, 1.77 A and 0.177 A • Maximum input voltage 500 V AC /300 V DC • Minimum measurable power 0.1 W • Separate isolated measurement outputs for voltage and current • Class II insulation between primary and secondary sides • Measurement data processing by Arduino • Measured values shown on a two-line LCD • Displays voltage, current, effective power, reactive power and power factor for AC • Displays power, voltage and current for DC mented with optocouplers and opamps, but that approach results in a fairly high component count. Another option is to use a special isolation amplifier. Our search for a suitable type led us to the AMC1100 from Texas Instruments. This fully differ- ential isolation amplifier has a minimum bandwidth of 60 kHz and a rated gal- vanic isolation of 4250 V peak , with a rated working voltage of 1200 V peak . With this isolation amplifier and a good PCB lay- out, you can obtain Class II insulation, which makes the circuit very safe. The IC is housed in a gullwing-8 SMD package, which looks like an 8-pin DIP package with the pins bent out to the side. The circuit also needs two completely sepa- rate power supplies — one for the input side and the other for the output side. In theory you could use standard power modules with unregulated output voltage for this purpose, but most of them are not specified for Class II and you would need extra components, including sepa- rate voltage regulators. A better solution is to us an IC specifically designed for this purpose. Here we chose the ADuM6000 from Analog Devices, which is an iso- lated DC/DC converter with a regulated D1 500V AC/1 OA max K1 ~/+ 0 ~/- ~/+ ♦ -/■ 1 K2 K3 K4 +5VP +5V O O C8 lOOn GNDP IC2 R1^ 12R C6 +5VPO- 500V D3 R1^ 12R 330p +5V o MODI 140169-1 ° C9 lOOn VDD1 VDD2 VINP VOUTP VINN VOUTN GND1 GND2 AMC1100DUB g“ndp C7 lOOn GNDP +5VP +5V O O 500V e R16 SP0502BAHTG GNDP R17_ 12R ^0 GNDP IC3 lOOn CIO R1^ 12R 330p ^0 Cl 3 lOOn VDD1 VDD2 VINP VOUTP VINN VOUTN GND1 GND2 +2V AMC1100DUB g“ndp C11 Q o > AINO AIN1 AIN2 AIN3 o z CD AL/RDY SDA SCL Q Z CD T* Jl 9 C14 lOOn 8 7 K5 _7 _9 11 13 O O o o 8 _ 10 12 14 R22 470p EEC Jl H C30 470p C31 K6 O R26 470p lOOn D1,D2, D4 = HSMS-2822 IC1, IC4 = AD8639ARZ I U +5V O R30 C32 R3^ 5k6 470p C33 470n LM311 _L 6 -2V8 +5 VP +5V NCP5501DT50G Figure 1. The power meter uses a pair of AMC1100 ICs to measure voltage and current. 48 September & October 2015 www.elektormagazine.com LABS PROJECT output voltage of 5 V or 3.3 V. The max- imum working insulation voltage V I0RM is 846 V peak . The circuit The easiest way to measure current is to connect a resistor in series with the load and measure the voltage over the resis- tor. That's how virtually every multime- ter works. Figure 1 shows the complete circuit diagram, with the measurement terminals on the left (two inputs and two outputs; K1 to K4). The sense resistor R1 (0.01 Q) is connected between K1 and K3. There is also a 10-amp fuse in series with the resistor. Faston blade ('spade') terminals mounted on the PCB with screws are used for the measurement inputs and outputs. They provide good mechanical and electrical connections and can easily accommodate fairly thick wires. To minimize the effect on the load, the resistance of the sense resistor should be kept as low as possible, but the voltage drop over the resistor also needs to be high enough for accurate measurement at the lowest current level you want to measure. If the sense voltage is very low, you can always boost it with an opamp. Here this is handled by an adjustable gain stage built around an additional opamp (IC1) ahead of the isolation amplifier. For this we choose the AD8639, a dual opamp with auto-zero inputs and rail-to-rail out- puts. The typical offset voltage of this IC is 3 pV (9 pV max.), and the maximum offset drift is only 0.06 pV. It is therefore an outstanding choice for this application, for both AC and DC measurements. The gain bandwidth product is 1.35 MHz. This means that the bandwidth at the max- imum desired gain is still greater than 10 kHz, which is more than enough for our purpose. IC1 is configured as an instrumenta- tion amplifier with a differential gain of 1 + 2 x (R6 + R7)/R g , where R4 or R5 can be selected for R G . The gain (the ratio of the voltage between the outputs of IC1A and IC1B to the voltage over Rl) is 1 when no jumper is fitted on JP1. You can fit a jumper on JP1 to obtain a gain of 10 or a gain of 100. In combination with the gain of IC2, these gain settings provide three current ranges with sinu- soidal currents: 17.7 A (gain = 1; limited to 10 A by fuse FI), 1.77 A (gain = 10), and 0.177 A (gain = 100). The maximum RMS values will be lower for signals with high crest factors. Depending on the noise level, the minimum power that can be measured with the circuit is less than 0.1 W (ADC output at -50 dB full scale). To keep the signal on the sense resistor within the common-mode range of IC1, one end of Rl is connected to a +2 V bias voltage provided by an LED (D5) on the isolated side of IC5, which acts as a ref- erence diode. D5 also serves as a power indicator for the isolated side. The maximum allowable differential volt- age of the input signal to the AMC1100 isolation amplifier in the next stage (IC2) is 250 mV. The IC has a gain of 8, resulting in a maximum output voltage of 2 V. IC2 has a differential input with a switched-capacitor circuit. The output noise level is specified as 3.1 mV rms with- out further details. If this specification applies to the full bandwidth, the actual noise level will be lower if the bandwidth is limited ahead of the ADC. For this rea- son, we developed a filter board with four sections, which is inserted ahead of the ADC module (see the Filter Module inset). If the ADC were connected directly to the output of IC2, the signal to noise ratio would be 645. This can be increased by a factor of V 60 by reducing the input band- width of the ADC, yielding an S/N ratio of 5,000. This makes it possible to measure smaller signals over the sense resistor. The voltage over terminals K1 and K2 is measured by a second AMC1100 (IC3). The voltage divider R14-R15-R16 attenu- ates the voltage over these terminals by a factor of 5,900, resulting in a voltage of 39 mV at the input of IC3 at 230 VAC line voltage. Resistor R16 of the volt- age divider is connected to the +2 V ref- erence voltage. The outputs of the two AMCllOOs are connected to the four inputs of the ADS1115 BoB. As previously mentioned, the circuit can also be used to measure high voltages safely with an oscilloscope or multimeter. The differential outputs of the AMCllOOs are not particularly suitable for this; a single-ended output is easier to use. An additional AC8639 dual opamp (IC4) is included for this purpose. It converts the differential signals from the two isolation amplifiers into single-ended signals with the same amplitude. The common-mode offset at the outputs of the AMC1100 (2.55 V typical at V DD = 5 V) is reduced to nearly zero but not entirely eliminated. An offset of several millivolts (less than 12 mV) is possible at the individual out- puts of IC4, depending on the difference between the DC voltages at the individual outputs of the AMC1100. The common-mode input range of the AD8639 extends from -0.1 V to 3 V with a single 5 V supply voltage. To bring the output voltages of the AMCllOOs within that range, voltage dividers R21/R22 and R25/R26 reduce the DC voltage on the outputs of each AMC1100 from 2.55 V to 1.275 V. According to our measurements, the maximum differential output signal that the AMC1100 can deliver is approx- imately 2.5 V (1.25 V peak ) This means that the maximum voltage on the inputs of IC4 will not exceed 1.9 V (1.275 V DC plus 0.625 V, which is half the peak AC voltage). That is well within the com- mon-mode range of the AD8639. An LM311 comparator (IC7) is included to detect zero crossings. It has an open-col- lector output. This IC operates with +5 V and -2.8 V supply voltages instead of +5 V and ground to allow zero crossings to be detected fairly easily without a lot of extra components. Resistor R37 is a pull-up for the output, and R35/R36 pro- vide strong positive feedback to ensure reliable zero crossing detection. The com- parator output is connected to pin 12 of K5. The best zero crossing detection accuracy is obtained with negative pulses. In that situation the output of IC7 is still negative and there is no hysteresis, and the non-inverting input of the compara- tor is at ground level. An EEC connector (K5) is provided for transferring the data to the Arduino. It allows the I 2 C signals from the A/D con- verter and several other signals to be sent to connector K2 on an Arduino pro- totyping shield mounted on the Arduino Uno board. The 5 V supply voltage for the second- ary side is provided by a low-drop volt- age regulator (IC6). That is sufficient for most of the ICs in the circuit. However, IC4 also needs a negative supply voltage in order to deliver an AC signal without any DC offset, and we additionally want to be able to measure DC voltages. This means that the outputs of K6 also need to be able to deliver negative voltages. For this purpose, a virtual ground is cre- www.elektormagazine.com September & October 2015 49 ated with the aid of a 2 V Zener diode (D7) in series with the ground pin of the low-drop voltage regulator (IC6). The isolated supply voltage for the input sections of the AMCllOOs and the input amplifier IC1 is provided by the ADuM6000 (IC5). The integrated volt- age regulator is set to 5 V by connect- ing VSEL to Viso. A common-mode choke (LI) is used with this IC to suppress any noise that may be present. It is somewhat overdimensioned with a current rating of 3 A, but we chose it for its low series resistance (50 mQ per winding). Measuring with Arduino The maximum sample rate of the A/D converter in free-running mode is only 860 Hz and the IC has just one physical ADC to serve the four inputs, so simul- taneous measurement of voltage and current at the maximum sample rate is not possible. In order to make voltage and current measurements at nearly the same time, the ADC would have to be switched back and forth by I 2 C bus com- mands, and that would cause too much delay between the two measurements. (For a more detailed explanation, see the Escaped from the Labs article "And Then Just a Bit of Software" in the July & August 2015 edition). We therefore chose a measuring method in which a series of voltage measure- Component List Measurement Board Resistors R1 = 0.01ft 2W, 1% (Ohmite FC4L64R010FER) R2,R3 = 22ft, 0.25W, 5%, SMD 0805 R4,R31,R33 = 2.20kft, 0.125W, 1%, SMD 0805 R5 = 200ft, 0.125W, 1%, SMD 0805 R6,R8,R34,R37 = 5.6kft, 0.125W, 1%, SMD 0805 R7,R9 = 4.3kft, 0.125W, 1%, SMD 0805 R10,R11,R17,R18 = 12ft, 0.125W, 1%, SMD 0805 R12,R13,R19,R20,R29,R30 = 47ft, 0.125W, 1%, SMD 0805 R14,R15 = 220kft, 1.5W, 1%, 500 V, SMD 2512 R16 = 75ft, 0.125W, 1%, SMD 0805 R21-R28,R36 = lOOkft, 0.125W, 1%, SMD 0805 R32 = 39kft, 0.125W, 5%, SMD 0805 R35 = 100ft, 0.125W, 1%, SMD 0805 Capacitors C1,C2 = InF 50V, 5%, SMD 0805, C0G/NP0 C3,C7,C11,C14,C23,C24,C34,C35 = lOOnF 50 V, 10%, SMD 0805, X7R C4,C15,C17,C19,C21 = 10|jF 10V, 10%, SMD 0805, X7R C5 = lOOpF 6.3V, 20%, SMD Case A (1206), tantalum C6,C10 = 330pF 50V, 5%, SMD 0805, C0G/NP0 C8,C9,C12,C13 = lOOnF 50V, 10%, SMD 1206, X7R C16,C18,C20,C22,C28 = lOOnF 25V, 10%, SMD 0603, X7R C25,C26 = 4.7|jF 6.3V, 10%, SMD Case R (0805), tantalum C27 = 1 0|J F 25V, +80/-20%, SMD 1206, Y5V C29-C32 = 470pF 50V, 5%, SMD 0805, C0G/NP0 C33 = 470nF 16V, 10%, SMD 0805, X7R Inductor LI = ACM4520-231-2P-T, SMD, common mode choke 3A, 2 x 50mft, 230ft @100MHz Semiconductors D1,D2,D4 = HSMS-2822-TR1G, SMD SOT-23 D3 = SP0502BAHTG, SMD SOT-23 D5,D6 = LED, green, SMD 0805 D7 = BZT52C2V0-7-F, SMD SOD-123 (zener diode 2 V 0.5W) D8 = PMEG2010AEH, 20V 1A, SMD SOD-123F IC1,IC4 = AD8639ARZ, SMD SOIC-8 IC2,IC3 = AMC1100DUB, SMD Gullwing-8 (SOP-8) IC5 = ADUM6000ARWZ, SMD RW-16 (SOIC_W-16) IC6 = NCP5501DT50G, SMD DPAK3 IC7 = LM311D, SMD SOIC-8 Miscellaneous K1-K4 = 0.25" Faston plug with 3.3mmm screw terminal K5 = 14-pin (2x7) pinheader, 0.1" pitch K6,JP1 = 3-pin pinheader, 0.1" pitch K7 = 2-pin pinheader, 0.1" pitch MODI = 10-pin (2x5) socket, 0.1" pitch FI = fuseholder, PCB mount, 32A 600V, 6.3 x 32mm FI = 10A, 500V ac / 300V dc , antisurge, 6.3 x 32mm Module no. 140169-91 (ADS1115-eBOB) Filter PCB no. 140169-2 PCB no. 140409-1 Figure 2. The PCB layout of the measurement board. The wide copper-free strip visible in the middle under the three large ICs provides galvanic isolation between the primary and secondary sides. 50 September & October 2015 www.elektormagazine.com LABS PROJECT Figure 3. The A/D converter BoB and the filter board are stacked on top of each other and inserted in connector MODI on the measurement board. merits (172, to be precise) are first made, followed by a series of the same number of current measurements. Both series are triggered by zero crossings of the voltage in order to define the phase relationship between the voltage and current measurements. For this pur- pose, the hardware of the power meter includes a comparator (IC7) connected to pin 9 of the Arduino board (I/O pin Bl), which detects the zero crossings. When this synchronization signal is missing, the software automatically switches to DC measurement mode, and it switches back to AC mode when the signal is again present. The software for the power meter (a sketch for the Arduino Uno, which can be downloaded for free from [4]), measures and/or calculates the following quantities (see also [5]): For AC: N ^RMS “ f N 2>T] V i=\ IN J RMS f N \ \i=l IN J ^RMS “ MlMS X ^RMS P - factor = ^ RMS Pva For DC: V = ( N \ Sv[(] V i=l IN 1 = ( n \ Z'W V i = 1 IN measurement board by a piece of 14-lead flat cable with matching IDC headers, as shown in the photos. It is essential to mount the measure- ment board safely in a properly insu- lated enclosure in order to prevent accidental contact with high volt- age (AC line voltage) while making measurements. P = VxI These quantities are displayed on the LCD in a cyclic loop. The screens for the various readings are shown in Figure 4. Construction The measurement board PCB (140409- 1) has a fairly spacious layout (Fig- ure 2). Nearly all the components are SMDs, which of course makes assem- bly more difficult for relatively inexperi- enced builders, but none of the compo- nents are extremely small. Mount all of the SMDs first, followed by the headers, connectors and fuse holder. Then attach the blade connectors firmly to the board with small screws, nuts and split washers. The ADS1115 BoB (140169-1) is available fully assembled from the Elektor Store. You will have to assemble the associated filter board (PCB 140169-2) yourself. It has SMDs on both sides. The filter board has two 5-position connectors on the top side for connection to the ADC BoB and two 5-position pin headers on the bot- tom side for attachment to the measure- ment PCB. Plug the ADC BoB on top of the filter board, and then plug the filter board into the MODI connector on the measurement PCB. The Arduino Uno with the prototyping shield is connected to the You can let the blade connectors protrude from the enclosure at one end, but a safer option is to connect them to banana jacks or suitable AC power connectors. At the other end you need an opening for the flat cable, and you can fit some jacks or sockets for the measurement signals from K6 and a power connector wired to K7. On the Arduino prototyping shield you have to fit two extra connectors to trans- fer the signals to the EEC connector already present on the shield. For this purpose, connect K2 pin 11 to K4 pin 1 and K2 pin 12 to K4 pin 2, using thin insulated wire or enameled copper wire. The measurement board can be powered from an AC adapter with an output volt- age of 9-12 V DC and a current rating of 200 mA or more. The Arduino board must be powered from a separate AC adapter. Calibration The software allows the offset and gain (or attenuation) of the analog front end on the measurement board to be adjusted to calibrate the voltage and cur- rent measurement. The adjustment fac- tors are saved in the internal EEPROM of the Arduino at the end of the calibration procedure, so you should only have to do the calibration once. After a reset the software checks whether the relevant memory locations have been www.elektormagazine.com September & October 2015 51 Filter Module As mentioned in this article, the sensitivity of the meter can be increased considerably by using filters to drastically reduce the bandwidth ahead of the ADC module. For this purpose we developed a filter module containing four third-order active filters (one for each input of the module). They are dimensioned for a cutoff frequency of 1 kHz. That value may appear fairly high, but it was selected to keep the effect on the phase relationship of 50 Hz or 60 Hz measurement signals and their first harmonics as small as possible. We chose a Sallen & Key configuration for the filters (Figure A) with a third-order Butterworth characteristic, as shown by the frequency response curve in Figure B. We opted for OPA377 opamps. These opamps feature rail-to-rail operation and have very good noise characteristics for types with CMOS inputs. The input bias current is typically just 0.2 pA, so the filter resistors do not cause any additional offset. The typical input offset and offset drift versus temperature are just 0.25 pV and 0.32 pV/°C, respectively. The compact PCB fits precisely beneath the ADS e-BoB. To make this possible, the SMDs are placed on both sides of the board (Figure C). The board has two connectors on the top side (socket headers or SIL IC sockets) and two pin headers on the bottom with thin round pins, so that everything can simply be plugged together. With components mounted on both sides of the board, assembly is certainly not easy, but that is the price for keeping the board so small. Work carefully and use a magnifying glass, which comes in very handy here. A AINO 0 AIN1 AIN2 AIN3 VDD C Component List Filter Module Resistors Capacitors Semiconductors R1,R4,R7,R10 = SMD 0603 21.5kft 1%, 0.1 W, C1,C4,C7,C10 = lOnF 50V, 5%, C0G/NP0 or X7R, SMD 0603 IC1,IC2,IC3,IC4 = OPA377AIDBVT R2,R5,R8,R11 = 24.3kft, 1%, 0.1 W, C2,C5,C8,C11 = 22nF 50V, 5%, Miscellaneous SMD 0603 C0G/NP0 or X7R, SMD 0603 K1,K2 = 5-pin connector, 0.1" pitch R3,R6,R9,R12 = 23.2kft, 1%, 0.1 W, C3,C6,C9,C12 = 1.5nF 50V, 5%, K3,K4 = 5-pin pinheader, 0.1" pitch SMD 0603 C0G/NP0 or X7R, SMD 0603 C13,C14,C15,C16 = lOOnF 50V, 10%, X7R, SMD 0603 PCB # 140169-2 52 September & October 2015 www.elektormagazine.com LABS PROJECT reader's project written, which means they do not con- tain the value '255'. If they do, the pro- gram automatically jumps to the calibra- tion routine; otherwise it goes directly to measurement mode. You can redo the cal- ibration at any time by pressing SI right after the supply voltage is switched on. At each step of the calibration procedure, you first see a screen that tells you what you are about to do, and after you press SI the screen for the actual calibration adjustment appears. The first step is to zero the offset of the voltage measurement (OV input). Leave terminals K1 and K2 unconnected, and press buttons SI and/or S2 on the Arduino prototyping shield to adjust the reading on the LCD to 0 V. After a 5-sec- ond interval with no button presses, the software goes to the next step: setting the gain factor for voltage measurement ( input V). For this adjustment, connect a known high voltage (50 V or more) to the K1/K2 terminals together with a reliable multimeter, and again use SI and S2 to adjust the reading on the LCD to match the reading on the multimeter. Here again, a 5-second interval with no button presses takes you to the next step: zeroing the current offset (0A input). Start with K1/K2 again disconnected and adjust the offset with the two buttons to obtain a zero reading, the same as for the voltage offset. The final step is setting the gain factor for current measurement (input I). For this adjustment, connect a DC voltage source to K1/K2 and connect a load and an ammeter to K3/K4. Then you can adjust the gain factor for cur- rent measurement in the same way as previously described for the voltage. N ( 140409 - 1 ) Web Links [1] www.elektormagazine.com/140169 [2] www. elektormagazine. com/140035 [3] www. elektormagazine. com/1 30485 [4] www. elektormagazine. com/140409 [5] http://openenergymonitor. org/emon/buildingblocks/ ac-power-arduino-maths Figure 4. The readings appear sequentially on the display. For AC they are voltage, current, effective power, reactive power and power factor. For DC they are voltage, current and power. Figure 5. The calibration screens. These are dis- played in the following sequence: offset for voltage measurement (a & b), gain for voltage measure- ment (c & d), offset for current measurement (e & f), and gain for current measurement (g & h). www.elektormagazine.com September & October 2015 53 VFD Shield for Arduino With several example programs POWE By Use Joostens (Belgium) The Arduino shield presented here contains four Russian IV3(a) 7-segment VFD tubes, together with the necessary control electronics. In addition, a quartet of 3-mm LEDs provide an attractive background illumination. The shield can be combined with an Arduino Uno and there is software available to implement a clock, a voltmeter, a thermometer and a demonstration program. Nixie tubes have enjoyed renewed popu- larity for some time with retro & vintage enthusiasts and on the Internet there are countless designs for Nixie clocks to be found. In Elektor too, we have pub- lished several projects with Nixie tubes in recent years. However, in this project we do not use Nixies, but instead make use of VFD (Vacuum Fluorescent Display) tubes. These are somewhat different from the well-known Nixie tubes and are cur- rently gaining popularity. This Arduino shield has been designed from an educational viewpoint and there- fore does not have any SMD components or parts that are difficult to obtain. There is a good chance that the typical electron- ics hobbyist will have the majority of the necessary parts already. In addition, this shield does not make use of dangerous voltages (maximum of 35 V). Operating principle of the IV- 3 VFD tube The IV-3 VFD tube (Figure 1) is a min- iature VFD tube with a digit height of 8 mm. It comprises a glass tube with a vacuum, a grid and seven phosphor coated segments plus a decimal point on a ceramic substrate. An electric current flowing through the filament it will heat it up and cause elec- trons to be released. Because this fila- ment is covered in a thin layer of alkaline metal oxides it already starts to release electrons efficiently at relatively low tem- peratures. As a result of the low tempera- ture, the glow of the filament is barely perceptible and therefore does not inter- fere with the display. When a positive voltage is applied to one of the segments, the electrons that 54 September & October 2015 www.elektormagazine.com GND LABS PROJECT rr 1 II III! PHI h > > : m |— h p ► > > > o u A ui Py ANALOG IN 1 ^ Characteristics • compatible with Arduino development boards • regulated 12-V power supply voltage, via Arduino board • possible applications: clock, thermometer, voltmeter, counter, scoreboard, ... • multiple Arduino example ketches available Figure 1. Front and back of an IV-3 VFD tube. are in the vicinity of the filament will be attracted and collide with the phosphor layer. The energy liberated through this impact causes the phosphor to light up in the familiar green-blue color. This oper- ating principle is comparable to that of a cathode ray picture tube (CRT), but here the phosphor was chosen so that it will light up clearly at the low energy level of these electrons. As a consequence, about 30 V is sufficient for the segments to glow brightly, this is in contrast with the many kilo-volts required in a standard cathode ray picture tube. The tube also contains a grid, which is placed between the filament and the segments. By applying a small negative voltage to this grid the electron stream towards to segments is blocked, irrespec- tive of the voltage on the segments. In this way you can turn the VFD tube 'on' or 'off' in its entirety. In this aspect the VFD tube actually functions like a triode and in theory you could even use it as an amplifier, see [1]. Now it is — obviously — not the intention to build an audio amplifier, but the grid permits the control of multiple VFD tubes (just as with 7-segment LED displays) to be multiplexed, which we have effectively implemented with this shield. Finally, the dark-gray/silver colored layer at the top the VFD tube is the 'getter'. This is a chemically reactive layer which helps maintain the vacuum by absorbing any remnant gas molecules. Design and operation of the circuit The circuit of Figure 2 consists mainly of four parts: a voltage converter which increases the power supply voltage of www.elektormagazine.com September & October 2015 55 12 V to about 32 V, a power supply for the filaments, a driver circuit (buffers) for the segments and grids, and finally a switching transistor and four LEDs for the background lighting. The voltage converter is essentially a voltage tripler built around a 7555 IC, a buffer stage and a few capacitors and Schottky diodes. In theory the output voltage should amount to 36 V when the supply voltage is 12 V. But in practice it is a little less and also because of the pres- ence of D1 in the ground line a voltage of about 32 V is reached, which is suffi- cient for the IV-3 tubes that we use here. The 7555 (IC1) is configured as an oscil- lator, where Cl and R5 determine the output frequency. Since the output of the 7555 can only supply a limited amount of current, a push-pull driver stage around T26 and T27 has been added. This does, however, create a problem in that the out- put voltage of the 7555 in the High state is not high enough to drive T26 fully into saturation. For this reason the 7555 is powered via R4 from the doubled power supply voltage at the node of D3/D4/C6. v +UB © o R43 J T14 BD BC 557B ~7~ +UB © Js R44 J ^J 15 j!) BC 557B ~7~ +UB © Js R45 J ^J 16 .© X BC 557B ~7~ +UB © R46 J ^J 17 JO. X BC 557B +UB © JE R47 ■X I T18 fl© X BC 557B +UB © X Li- es □ R48 J __ T19 t© X § Q X BC 557 B +UB © R49 X o o' Q J 720 •:© > cd o X JE BC 557B +UB © R50 J ^J 21 © 0 1 o X JE BC 557B | R31 | R32 | R33 i R34 i R35 i R36 i R37 i R38 Jj 1 rtl XT 2 ft] XT3 ft] XT4 ft] Xt 5 ft] XT6 ft] X™ ft] X™ ft r ®0 r ®0 r ®ll r ®0 r C)0 r C)0 r C)0 r C)ll [* 6V2 bc X 7V2 bc J4 8Va BC X 9V2 bc J4 1oV2 bc X 1iV2 bc X 12V2 bc > 3V2 bc * 547 B „ 547 B . ^ 547B ^ 547B ^ 547B .. ^ 547B „ 547B ^ 547B § O X +12V X © T^ 2 ~~| R 3 +UB 9 Cd O K1 © K ©- +12V DRV 1 ✓ A DRV 2 DRV 3 DRV_4 AREF GND r D13 RESET D12 3V3 *D11 5V *D10 GND *D9 GND „ D8 2 VIN 3 Q_ D7 < cs *D6 o AO -| *D5 A1 D4 z A2 o *D3 o A3 < D2 z A4 TX A5-I L RX R18 10k DRV_DP JE R51 T22 E© DRV G X DRV F DRV E ^ DRV D ^ DRV C ^ DRV B ^ DRV A ^ \ ARDUINO_SHIELD BC547B BC 557B X +UB 9 Cd cs © JE R52 J T23 t© BC 557B X +UB 9 Cd O © JE R53 J ^J 24 ,:© o X BC 557B +UB 9 Cd o © JE R54 L© £ Q X JE BC 557B rC 0 ill® r© 0 E 14V2 bc JE 15V2 bc JE 16V,2 bc JE 17V2 bc * 547B ^ 547 B „ 547B ^ 547B § Q X R5 C9 lOOu 50V Cl 2n2 8 RESET vcc TRIG IC1 DIS OUT ICM7555 TRSH CV GND T. +12V ©- R4 H ;t7 h T26 R1 C4 i-| 51 OR Hh 100n © BC639„ D4 D5 C5 D2 1N5819 D3 1IH-W4 K 1N5819 __ T27 40 £ 100u BC64 0 50V 1N5819 1N5819 C7 22u 50V C6 22u 50V C8 22u 50V +UB ■© C3 8n2 VFIL2 / VFIL1 / C2 8n2 vx TUI IV-3 X CL O 8 GRID FIL FIL DP y O. B C D E F 2 1 10 6 5 4 X TU2 IV-3 11 X Q. D 8 GRID FIL FIL DP > V O. A G B C D E F 2 1 10 6 5 4 X TU3 IV-3 11 X D. Q 8 GRID FIL FIL DP y o. B C D E F 1 10 6 5 4 ^ 1 TU4 IV-3 11 8 GRID FIL FIL -< X DP yo M B C D E F 1 10 6 5 4 11 /////// /////// /////// ////// D1 Jn4007 150064 - 11 Figure 2. The circuit for the control of the VF tubes comprises a voltage tripler around IC1 and a number of driver stages for the segments and grids (T1 through T12 and T14 through T25). 56 September & October 2015 www.elektormagazine.com LABS PROJECT N No Nixies for a change, but VFD tubes In practice, the power supply voltage of the 7555, because of the voltage drop across R4, amounts to about 14 V. How- ever, the base voltage of T26 is now much higher than its collector voltage, which causes its base-collector diode junction to go into conduction and which would limit the output voltage from the 7555. R1 and particularly C4 have been added to prevent this from happening, where C4 also provides a sufficiently high base-cur- rent impulse towards T26 whenever the output of the 7555 switches from low to high. This allows capacitors C5 through C8 of the voltage-tripler to be charged quickly. This increases the efficiency of the circuit considerably, which also has the advantage that there is no need to heatsink T26 and T27, even when there is a sizable load connected to the out- put voltage. Finally, the voltage drop across D1 ensures that the entire power supply is raised about 0.7 V above the ground level. When the voltage on a segment or grid of the VFD tube is pulled to ground then this voltage is actually slightly negative with respect to the filament so that the segments are guaranteed to stay dark. The filaments of the VFD tubes in this design are connected in series for sim- plicity and to limit the number of com- ponents that are required. Additionally, the filaments are not powered with DC but with AC, so that the voltage gradient across the filaments does not result in a visible difference in brightness between segments (and VFD tubes). For this pur- pose, one end of the filaments is con- nected to the common emitters of T26 and T27 and the other end with the junc- tion of C2 and C3. Because C2 and C3 block any DC current the result is not just an AC voltage, but their impedance also limits the current into the filaments. For this reason the values of C2 and C3 (in combination with R5/C1, which determine the frequency) are quite critical. Finally, the control of the segments and grids is obtained with the aid of NPN/ PNP transistor pairs. At a logic High level from the Arduino (5 V), the PNP transistor switches the 32-V power supply voltage to the corresponding segment or grid. At a logic Low level the segment or grid is con- nected to ground via a 100-kft resistor. The segments and decimal points of the four tubes are connected in parallel so that a total of 12 data lines are required for the multiplexed control. Consequently the SDA and SCL signals from the Arduino remain available and therefore an I 2 C RTC, for example, or another I 2 C IC can be used in combination with this shield. Software Several different example programs are available for this shield: clock, voltmeter, thermometer and a demonstration pro- gram. All programs are Arduino sketches and the complete set can be downloaded as a zip file from [2]. The source code for each program contains a detailed expla- nation about how to use it, how it works and any external libraries that may be required. The clock indicates the date and time. The Arduino does not have a real-time- clock, so the user has to set the date and time via the serial connection. This is easily done with the 'Serial Monitor' in the Arduino IDE. The voltmeter measures the voltage at pin A5 of the Uno and shows the mea- sured value on the VFD tubes. The input range goes from 0 to 5 V (display: 0.00 to 5.00 V). The thermometer reads the temperature from a 1-Wire sensor and shows the value obtained in degrees Celsius. This program supports the DS18B20, DS18S20 and DS1820 devices. The program enumer- ates the 1-Wire bus periodically. When a supported chip is found the program reads the temperature from it and then shows the value on the tubes. Because of this method of operation, it is possible for the user to change the 1-Wire device while to program is active. The demonstration program shows an animation on the tubes and a PWM ani- mation on the LEDs. This program can also be used to verify that the shield has been built correctly. Each example program contains a driver section for the tubes. This driver is inter- rupt based with the aid of an ISR (inter- rupt service routine). The tubes are acti- vated one at a time in a continuous cycle. There is therefore only one tube illumi- nated at any one time. The driver con- tains the following steps: • Switch the grid and segments of the active tube off as quickly as possible. • Wait 40 ps to prevent 'ghosting'. • Select the next tube according to the cyclic pattern. • Write to pins 2 through 9 to update the segments. • Switch the grid of the tube on. When the time between switching off the previous grid and switching on the next grid is too short, then segments of the previous tube can inadvertently have a faint glow. This phenomenon is called 'ghosting'. The waiting time of 40 ps pre- vents ghosting. This waiting time was determined experimentally. Note that the actual time of switching from one grid to the next is a little longer, because other code is executed as well. The multiplexing of the tubes is done at a rate of 250 Hz. Each tube is visible 62.5 times per second for a period of nearly 4 ms. This frequency is high enough so that he human eye perceives a flicker-free image. The information to be displayed is stored in a data structure (tube_list), an array of four elements, one for each tube. Each element contains an on/off-flag for the decimal point and an index into a table with the combinations for the segments. The demonstration program also contains the PWM drive for the LEDs. One PWM cycle is divided into eight steps. The step frequency is 500 Hz, the PWM frequency is 62.5 Hz. At this frequency the LEDs do not appear to flicker to the eye, even at the minimum duty cycle of 1/8. The ISR is associated with Timer 1. The Arduino 'programming language' contains no elements to work with timers. The source code for the programs uses AVR Libc to implement Timer 1 and the ISR in C code. Note that he Arduino 'program- ming language' itself also makes use of AVR Libc. www.elektormagazine.com September & October 2015 57 Construction The printed circuit board designed for this circuit can be seen in Figure 3. Only through-hole components have been used, so that construction should not be a problem, even for those with modest soldering skills. Elektor offers a complete kit with four tubes for this project (available from the Elektor Store). There is an extensive description of the assembly procedure of the shield in a separate (English-lan- guage) assembly manual, which is also available from [2], but here we will briefly touch on the salient points. All parts are mounted on the side with the screen print. Fit the resistors, diodes, capacitors and the IC socket first. The resistors are all placed upright, so one wire is bent back along the resistor body. The electrolytic capacitors are mounted horizontally on the board, so the connect- ing wires have to be bent into a right-an- gle first. After this the headers are fitted. It is a good idea to insert these into the circuit board and then temporarily plug it all into an Uno. Turn everything over and solder a few pins on each connector. Then you know for sure that everything fits. Remove the Uno and solder the remain- ing pins. Now it is the turn of the transistors, fol- lowed by the four LEDs for the background illumination. The LEDs are mounted in the holes underneath the tubes. The con- nections for each LED are a little further away. Bend the wires into the correct shape and check a few times until the LED and the wires fit neatly in the appro- priate holes. The VFD tubes are mounted last. These or provided with relatively long connect- ing wires which are threaded through the circuit board. If this turns out to be dif- ficult, then you can cut a short length from each of the wires in a spiral shape, so that each wire has a slightly different length. Place each tube above the circuit board at such a height that the bottom is just below the top of the headers. With four tubes inserted into the board, sol- der one wire per tube. Check again that they are all in a neat line and upright and then solder the remaining wires — it is not possible to correct the position of the tubes afterwards! Finally the 7555 IC is plugged into its socket. Now download the software from [2] and load the demonstration sketch via the USB connection on the Arduino. Discon- nect the Arduino from the PC and plug the shield on top of the Arduino, after the USB connector on the Arduino is cov- ered with a small piece of insulation tape (to prevent it coming into contact with the soldered connections on the shield). Connect a AC power adapter, which can supply a regulated output voltage of 12 V (300 mA min), to the Arduino. When you plug the adapter in, and every- thing is fitted correctly and soldered, the tubes will count in an endless loop and the brightness of the LEDs will vary slowly. Congratulations, your VFD shield works as it should. Now you can try one of the other software examples or perhaps start to program for the application that you have in mind for this shield. N (150064) Web Links [1] https://www.youtube.com/ watch?v=aiszksJs9C8 [2] www. elektormagazine.com/1 50064 Component List Resistors R1 = 510ft R2,R3 = lkft R4 = 2.7kft R5 = 3.9kft R6-R18 = lOkft R19-R30 = 68kft R31-R42 = lOOkft R43-R54 = 220kft Capacitors Cl = 2.2nF C2,C3 = 8.2nF C4 = lOOnF C5-C8 = 22|jF 50V, radial C9,C10 = 100pF 50V, radial Semiconductors D1 = 1N4007 D2-D5 = 1N5819 Schottky diode D6-D9 = LED, 3mm, select color T1-T13 = BC547B T14-T25 = BC557B T26 = BC639 T27 = BC640 Miscellaneous TU1-TY4 = IV3(a) 7-segment VFD tube 8-pin IC socket for IC1 Set of Arduino compatible pinheaders (1 pc 6-pin, 2 pcs 8-pin, 1 pc 10-pin) Construction kit including 4 VFD tubes: # 150064-71 from www.elektor.com Figure 3. The circuit board contains only through-hole components so construction is straightforward. 58 September & October 2015 www.elektormagazine.com RPi Measures Consumption Using Python, PHO and MySQL By Zeno Otten (The Netherlands) (www.zenot.nl) This article describes how to build a smart meter remote readout using a Raspberry Pi. With just a few components and a bit of programming, Electricity you can collect and process data from a smart electricity meter and display it on a web page in various forms. In the author's country household electricity bills have risen by more than 5 percent per year over the last 17 years. Two fac- tors are responsible for this: rising fuel prices on the international market and a constantly increasing number of household appliances and devices that consume electricity. As a result, electricity bills have become a significant factor in household budgets. If you want to reduce your electricity consumption, you first have to be aware of it and you need some way to measure it effectively. Inline measurement and recording of your electric- ity consumption can help you reduce your consumption and determine how much power individual devices use. Armed with this understanding and information, you can make decisions that cut your electricity bill. Measuring your electricity consumption Every electricity customer has an electricity meter somewhere about the premises. Most older-model meters have a rotat- ing disk. The faster this disk turns, the more electricity you are using. The meter is typically read once a month, and you receive a bill corresponding to your consumption. Clearly, if you want to see how you can reduce your electricity consumption you need real data more often than just once a month. Inline measurement, which means continuous measurement, gives you a lot more data. You can determine the power consump- tion of individual appliances by measuring how fast the meter disk turns [2, 3]. As result of technological progress and computerization, utility companies are increasingly installing smart meters. These meters can be read remotely, and the meter readings are automatically sent to the utility company. Smart meters can also measure the power fed in from a solar power system, so you can get a deduction for feeding electricity into the grid. This type of meter has a serial data port for inline measure- ment of electricity consumption. It's easy to read the data from the meter in digital form through this port. The data can be read out every 10 seconds, which is ideal for recording all sorts of variations in your electricity consumption. If you store the data and process it for displaying on a web page, you can view your electricity consumption any time you want on a PC, smartphone or tablet. www.elektormagazine.com September & October 2015 59 Figure 1. Input circuit for connecting the electricity meter to the RPi. Many companies are already taking advantage of this ability to monitor and manage energy consumption. They offer various types of "energy management" tools. However, it's more fun to build one yourself. If you already have a smart meter at home, you can get started with this project. Otherwise you can ask your utility company to install a smart meter. In this article we show you how to use a Raspberry Pi com- puter (type 1) with a smart meter to measure, record and analyze your electricity consumption and present the results on a web page. It can also record and display infeed energy from a solar power system. Hardware The Raspberry Pi, nicknamed RPi, is presently one of the most popular single-board computers. It gives you a complete Linux- based computer in credit-card format. The RPi has enough I/O and ports to read and process the data from smart electricity meters. In addition, you can store the data on the RPi and even run a MySQL database directly on the RPi. You can also view the results from the RPi with an Apache web server and a PHP web page installed on the board. The author's electricity meter has a serial output port with an inverted data signal. Figure 1 shows the circuitry neces- sary to input this signal to the RPi. Pin 2 is the request input (RTS), pen 5 is the data output (RxD) and pin 3 is the ground connection. The signal levels are 5-V compatible. The data signal is inverted by the BC547 transistor and then applied to GPIO pin 10 of the RPi with a high signal level of 3.3 V, which is the maximum allowable input voltage on the GPIO pins of the RPi. As you can see from the schematic, the signal input circuitry is very simple. The meter sends a data package every 10 seconds over the RxD line, formatted as a set of lines containing the consumer data (see below). The meter keeps on sending data as long as the RTS line is held at a High level. Software Although the hardware for this project does not require much effort, the software will take a bit of your time. The following description of the necessary steps, interleaved with extracts from the program code, clearly shows how a Raspberry Pi can be used as the basis for a remote smart meter readout. The Raspbian Linux distribution is installed on the SD card of the RPi. The commands that must be sent to the RPi in a command prompt window are shown in green in this article. Code lines in Python are shown in red, MySQL instructions are shown in blue, and PHP code lines are shown in brown. In order to use the serial port as shown in Figure 1, the serial port login must be disabled (see also [1]). Open the file /etc/ inittab in a word processor and place a # character before the line TO : 23 : respawn : /sbi n/getty -L ttyAMAO 115200 vtlOO in. The RPi normally uses the serial port to send data during the startup process. You have to disable this if you want to program the serial port yourself and use it for your own purposes. To do this, edit the file /boot/cmdline. txt and delete all references to ttyAMAO, which is the name of the serial port. After editing, the file will look like this: dwc_otg . lpm_enable=0 console=ttyl root=/dev/mmcblk0p2 rootfstype=ext4 elevator=deadli ne rootwait Then reboot the RPi. Python The Python programming environment is installed on the RPi as standard. All of the data capture software is written in Python version 2.6 and is available in the download for this project [2]. The following instruction installs a special library with functions that support programming of the serial port: sudo apt-get install python-serial (see [3] for more information) The smart meter uses the RS232 protocol with the attributes defined as follows in Python: ser = seri al . Seri al ( ) ser.baudrate = 9600 ser . bytesi ze=seri al . SEVEN BITS ser . pari ty=seri al . PARITY_EVEN ser . stopbi ts=seri al . ST0PBITS_0NE ser . xonxof f=0 ser . rtscts=0 ser . ti meout=20 ser . port=” /dev/ ttyAMAO” The data is read in on the RxD line (GPIO 10) [here Dutch "regel" means "line"]: regel = ser . readli ne ( ) The lines in the data set from the electricity meter look rather cryptic at first: 0- 0:96.1. 1 (8549D313736438764837648364834) 1- 0 : 1 . 8 . 1(01238 . 000* kWh) 1-0 : 1 . 8 . 2(02224 . 000* kWh) 1-0 : 2 . 8 . 1(02327 . 000* kWh) 1-0 : 2 . 8 . 2(04528 . 000* kWh) 0-0:96.14.0(0002) 60 September & October 2015 www.elektormagazine.com 1-0:1. 7. 0(0000. 00*kW) 1-0:2.7.0(0000. 12* kW ) 0-0:17. 0.0(999*A) 0-0:96.3.10(1) 0-0:96.13.1() 0-0:96.13.0() 0-1:24.1.0(3) 0-1:96.1. 0 ( 8549 D3 13 73 643 8 7 6483 7 6483 64834) 0-1:24.3.0(121106150000) (00) (60) (1) (0-1 : 24. 2 . 1) (m3) (00054.386) 0-1:24.4.0(1) The output ends with an exclamation mark (!). You can dis- cover the meanings of all of these lines from the manual for the meter, but the numerical values that we are mainly inter- ested in are easy to see. We store the values in lines 1-0: 1.8.1, 1-0:1. 8. 2, 1-0:2. 8.1, 1-0:2. 8. 2, 1-0:1. 7.0 and 1-0:2. 7.0 in the variables varl to var6 of the Python program. The numerical values are located in positions 10 to 15 of each line: if regel[0:9] == “1-0:1. 8.1”: varl = regel[10:15] print “Consumed (L) “, varl varl = Consumption (L) in kWh var2 = Consumption (H) in kWh var3 = Infeed (L) in kWh var4 = Infeed (H) in kWh var5 = Current power consumption in W var6 = Current power infeed in W The values of variables varl to var6 are stored in a MySQL database every 10 minutes. For this purpose we have to import the MySQLdb library into Python: import MySQLdb as mdb The database is assigned the name "databasenaam" here and the table where the measurements are stored is named "metin- genl". The Dutch terms "inlognaam" and "wachtwoord" mean "login name" and "password": con = mdb. connect ( ‘localhost’ , ‘inlognaam’, ‘wachtwoord’, ‘ databasenaam ’ ) with con: cur = con.cursorQ cur . execute (“INSERT INTO meti ngenl (ti j d , - Datal) VALUES (96s)” , ( now, varl)) print now, “Data written in database “ cur . close ( ) In the actual program Pl.py in the download [2], the six vari- ables are stored in the database together with the variable "tijd" [time]. MySQL The MySQL database can be stored on a computer connected to the same network as the RPi, but it can also be installed directly on the RPi. The author opted to store the database in the microSD card on the RPi board because there was plenty of room for it (the author has an 8-GB SD card). In order to use a MySQL database on the RPi, you first have to install several items listed below. To do this, enter the fol- lowing command in the command prompt window: sudo apt-get install mysql-server python-mysqldb During the installation you will be asked for a root password for the database. After this you can create a new database. In this example, we create a database to hold measurement data for the user "user_name". Start the MySQL browser by entering the following command in the command prompt window: $ mysql -u root -p Then type the following MySQL commands (replace "user_ name" by the actual user name and "databasename" and "databaseName" by the actual database name): mysql> CREATE DATABASE databasename mysql> USE databasename mysql> CREATE USER ‘ user_name ’ @ ’ localhost ’ IDENTIFIED BY ‘ password ’ ; mysql> GRANT ALL PRIVILEGES ON databaseName . * TO ‘ user_name ’ @ ’ localhost ’ mysql> GRANT ALL PRIVILEGES ON databaseName . * TO ‘ user_name ’ @ ’ localhost ’ mysql> FLUSH PRIVILEGES; mysql> quit Now you can create a table to hold the measurement data, such as "metingenl" in this example. In the following exam- ple the table is created with the two variables "tijd" [time] and "Datal", with the first variable in time-date format (day- month-year-hh:mm:ss) and the second variable defined as a string with a maximum length of 11 characters. mysql > CREATE TABLE metingenl (tijd ti medate , Datal varchar (11) ) ; A total of six data fields are defined in the actual Pl.py program. MySQL is a complete and very extensive programming lan- guage. However, in this project we only use the commands (queries) necessary to store the data. Information about other commands and extensions is readily available on the Internet. We also need queries to retrieve the stored data from the data- base and present it somewhere, for example on a web page. These queries are described further on. Now you can start filling the database with measurement data captured from the meter by the Pl.py program in the down- load [2]. Web server The data needs to be accessible and suitable for presentation on a tablet, laptop or other smart device. To do this with the www.elektormagazine.com September & October 2015 61 Electricity consumption / production Date: 19-05-2015 Time: 22:57:47 Consumed (L): 2217.333 kWh Consumed (H): 2057.824 kWh Produced (L): 249.367 kWh Produced (H): 594.197 kWh Consumption : 220 Watt Production : 0 Watt 22:57:47: A device has 590 Watt disabled Figure 2. Overview with current meter readings. RPi as well, you first have to turn it into a web server. For this purpose we installed the Apache web server software (see [4] for information and the manual). Install the following pro- grams on the RPi by typing the commands listed below in a command prompt window: sudo apt-get update sudo apt-get install apache2 sudo apt-get install mysql-server Next you have to install the following software in order to work with PHP: sudo apt-get install php5 sudo apt-get install php5-mysql sudo apt-get install php5-gd To test the web server and PHP, enter the address http : // localhost/i ndex . html in a browser window to navigate to the web page on the RPi. The test page should appear if every- thing is working properly. The web pages are stored at /var/www/i ndex. html by default. To implement the web server, replace index.html by /var/ www/i ndex . php with your own content. Now the web server is running on the RPi. It will most likely also be available on your home network. Computers on your home network can access the RPi at http: //RPi_lP_address/ i ndex . php. If you want to be able to access the RPi from the Internet as well, you will have to adjust some settings on your router. However, that is highly dependent on your home network and the specific router model. PHP web page The web page you access from your web browser needs to link up with the database where the meter data is stored. You also need to be able to choose which data you want to see and how much data should be shown. This project displays the current meter readings on the web page along with three charts. The charts show the trends in electricity consumption over the last eight hours and the last 24 hours. The average consumption is also determined and shown on the charts. The third chart shows when appliances are switched on and off and how much power they consume. Linking to the database Creating a link to a MySQL database in PHP is easy. The follow- ing code lines provide access to the database with the name "database" (replace the user name, password and database name with suitable values). $host = “localhost”; $user = “user_name”; $pass = “password”; $dbase = “database”; $link = mysql_connect ($host , $user, $pass) ; if (!$link) { die( ‘Could not connect: ‘ . mysql_error ( ) ) ; } echo ‘Connected successfully
’ ; mysql_select_db ($dbase , $link) or die( ‘Could not select database . ’ ) ; Now data can be read from the database. For this you use a query which selects the desired data. The following is an example of a query formulated in PHP: $query = ‘SELECT tijd, Datal , Data2 , Data3 , Data4 , Data5 , - Data6 FROM metingenl ORDER BY tijd ASC LIMIT 144’ This query selects the readings for the last 144 time intervals with the corresponding Datal to Data6 values from the "met- ingenl" table, arranged in increasing time order. It effectively forms a new table containing the requested data, which can be used to generate the charts. Results When a browser visits the website at http : //77 . 162 . 137 . 240/ p4 . php, the RPi generates a web page with the current meter readings at the top (Figure 2). The "Consumption (L)" figure in kilowatt-hours is the consump- tion during the low rate period, which is typically between 11pm and 6am and on weekends. The high rate (H) applies the rest of the time. The amount you have to pay per kilowatt-hour depends on your electricity supplier. If you know the rates, you could modify the code to show actual costs here. If you generate your own electricity, for example with solar panels, the amount of energy fed into the grid is shown by the Production (H) and Production (L) figures. The current power consumption in watts is also shown. Trends We use the tool phpgraph.php [5] to produce the charts in PHP that show the curves of electricity consumption versus time. This library makes it easy to draw charts from a set of data, which in this case consists of energy consumption fig- ures over a specific time period — for example, the last eight hours in Figure 3. 62 September & October 2015 www.elektormagazine.com reader's project In this example time is plotted on the horizontal axis and electricity consumption in watts is plotted on the vertical axis. The zero point is set to the current time and the time axis is negative, so the readings go back in time as you move to the right along the time axis. The actual times are not shown on the X axis because they would take up a lot of space on the chart. The number of read- ings per hour is six. This figure was chosen to keep the size of the database within reasonable bounds, but in principle it is also possible to store readings every ten seconds. From the chart you can see that the consumption during the night (approximately the last five hours on the chart) was approximately 150 to 200 watts. That was mainly due to the refrigerator/freezer and several other small loads. The peaks in the chart were caused by a ceramic cooktop that we are presently using. When the solar panels generate more power than your current consumption level, the extra power is fed into the grid. This is also measured by the meter, and it can be seen in the chart shown in Figure 4. In that case the consumption is negative. With the data stored in the database, you can also use another query to display a curve of consumption over the past 24 hours with six readings per hour (Figure 5). The query necessary for this takes the following form in PHP: $query2 = ‘SELECT tijd, Datal , Data2 , Data3 , Data4 , Data5 , - Data6 FROM metingenl ORDER BY tijd DESC LIMIT 144’; // laatste 24 uur, 6 metingen per uur The high peak at roughly 2.4 kW was caused by the cooktop. From this you can also see that the refrigerator/freezer con- sumes about 160 watts. The final trend chart (Figure 6) shows when loads are switched on or off and how much power they consume (in watts). This is determined by calculating how much the consumption increases or decreases in the previous chart. The resolution for detecting load switching is approximately 10 watts, which is determined by the output from the elec- tricity meter. Conclusion The remote smart meter readout is built around a Raspberry Pi. With some simple circuitry and relatively little effort, you can collect and process data from a smart electricity meter. The software necessary for this takes more effort, but it allows all of the functions to be implemented on the Raspberry Pi. This makes the remote readout inexpensive and easy to build yourself. Thanks to the use of standard programming environments such as Python, PHP and MySQL, doing this project yourself should not create any significant problems. Storing the data in a local MySQL database allows the current and historical data (trend charts) to be presented on a web- site. This lets you see how much the various appliances in your household impact your monthly electricity bill. With this knowledge, you can reduce your consumption and see the results directly. You can also see how much power a particular appliance uses by briefly switching it on and off. ( 150313 - 1 ) Web Links [1] www.hobbytronics.co.uk/Raspberry-pi-serial-port [2] www.elektormagazine.com/150313 [3] http://elinux.org/Serial_port_programming [4] www.penguintutor.com/linux/RaspberryPi-webserver [5] www.ebrueggeman.com Figure 6. Here you can see when an appliance is switched on or off. Figure 3. Electricity consumption during the last eight hours. Figure 4. The net consumption can even be negative when the solar panels deliver a lot of power. Consumption last 24 hour< 5:>0 (Watt) <0=actual time) Ovv DUO 400 Z . ^ r\[U loo V u u v \A V Figure 5. Electricity consumption during the last 24 hours. www.elektormagazine.com September & October 2015 63 .EARN DESIGN SHARE Android I/O Board (i) Control embedded electronics from your Android phone or tablet * l»- Ik* 37 ^ r ? ® nG pi* ^ -*f M * pio p * # *£ * ^ O $ * - * \ V a * W C Note: The component numbering on the prototype in the photos does not match the number on the final schematic drawing and the PCB layout. 64 September & October 2015 www.elektormagazine.com LABS PROJECT By Elbert Jan van Veldhuizen (Netherlands) Android devices are ideal for controlling all sorts of electronic circuitry: low cost, lots of processing power, touchscreen interface and various wireless communication options. With this 22-channel universal I/O board and a matching app, you can easily switch devices on and off, make measurements, control motors, input or output analog signals and much more, all from your Android device. The hardware is described in this article, the first of a series. Figure 1. Schematic diagram of the I/O board. The actual number of components on the board is a lot less because only one communication module is mounted. Table 1. Overview of the Android I/O board features. Function Pin count (max. 22) or value Remark Digital inputs 22 8 pins with optional weak pullup Digital outputs 22 Maximum lout 25 mA ADC 11 Resolution 10 bits; approximately 20 kS/s Cap-sense switch 8 7 pins, overlapping with the ADC pins PWM output 8 Software generated; 4 x 2 in bridge mode Counter 16-bit counter 8 MHz max. Data rate Max. 100 transactions per second Connection 9,600 baud Data flash memory (I2C) 32 Kbytes Populated with 25FC256 On-board extras 4 LEDs, 1 NTC, 1 touch pad Supply voltage 4-13 V DC, unregulated 3.3 V DC, regulated Current consumption (without load) 30 mA max. (Bluetooth) 250 mA max. (Wi-Fi) 5 mA max. (USB), plus USB module current Supply voltage connection Micro USB, PCB connector 66 September & October 2015 www.elektormagazine.com LABS PROJECT reader's project In this series of articles we describe a circuit board and a demo Android app that let you read and control 22 I/O pins using very simple commands. The board can communicate with an Android smart- phone or tablet over Bluetooth, Wi-Fi or USB. The I/O pins on the board can be used not only for digital inputs and out- puts, but also for analog to digital con- version, capacitive-sense buttons, analog PWM output and pulse counting. The firmware of the on-board microcon- troller can easily be modified to add func- tions for real-time applications. This is supported by a boot loader in the microcon- troller. The author has developed Java classes (libraries) with consistent method naming for driving the Android I/O board. This enables users to start program- ming app functions right away without having to first delve into the details of the software. The circuit board and the microcontroller functions are described in this first arti- cle. In the subsequent articles we will describe the Bluetooth, Wi-Fi and USB options and an app for controlling the Android I/O board. In addition, we will look at some data logger func- tions and show you how to modify the firmware and download it with the boot loader. Jr Before getting into the details of the hardware, let's take a quick look at the features. The Android I/O board has 22 I/O pins available as standard. It also has a capacitive sensing pad (etched on the board), four LEDs and an NTC thermistor. The board can contact tablet using Bluetooth, an Android smartphone or WiFi or USB. Incidentally, this board is also a handy demo board for trying things out. Table 1 lists the features of the Android I/O board and the various power supply options. The circuit Figure 1 shows the schematic dia- gram of the Android I/O board. The number of com- BL600 e-BoB Bluetooth module (# 14270-91) for Bluetooth V4, a breakout board with the widely used HC-06 module for Bluetooth V2, a PCB daughter board with the FIC-06 module, and the RN41 or HC-06 mod- ule in ZigBee format. nan? Q eg r ^ CtExa CD 9 O (J U S3 Touch ponents actu- ally mounted on the board is much lower than in the sche- matic because the PCB is designed to hold various types of communication module. There is room for the most popular Blue- tooth modules, in particular the Elektor Among the Wi-Fi modules, the board supports the RN171-VX (ZigBee for- mat) and the ESP8266 (PCB daughter board). The board also has connectors for the Elektor Android breakout board Advertisement MM HAMMOND AtW /l/MNUMCTURING, W Housings for Raspberry Pi, Arduino and many other bareboard computers • Enclosure • Platform + 44 1256 812812 sales@hammondmfg, 1 The choice is yours. • Enclosure for all round protection • Platform for all round access • Design-specific versions for all popular models • Visithammondmfg.com for full details 9 f H & 4-s-iOi , V- % v r Mkz 5-*' & V -Ea / www.elektormagazine.com September & October 2015 67 Component List Resistors R1,R2,R3,R4 = 4700 . 1%, SMD 0805 R5,R7,R8,R10,R14,R15 = 330ft 1%, SMD 0805 R6,R9,R16 = lOkft 1%, SMD 0805 Rll = lOkft NTC, SMD 0805 (e.g. Vishay NTCS0805E3103JHT) R12,R13 = 2.2kft 1%, SMD 0805 Capacitors C1,C2 = lOOnF 25 V, 10%, SMD 0805 C3 = 4.7|jF 25V, 10%, SMD 0805 C4 = lpF 25V, 10%, SMD 0805 Semiconductors LED1,LED2,LED3,LED4 = low-current LED, green, SMD 0805 IC1 = PIC16F1938-I/SO, SOIC28, programmed, Elektor Store # 150057-41 IC2 = 24FC256-I/SN, SOIC8 IC3 = MCP1702T-3302E/CB, SOT23A Miscellaneous K1 = micro-USB 2.0 connector type B, SMD K2 = 26-pin (2x13) pinheader, 0.1" pitch K3 = 6-pin (2x3) pinheader, 0.1" pitch K4 = 2-pin pinheader, 0.1" pitch K5 = 6-pin pinheader, 0.1" pitch S2 = toggle switch, 0.1" pitch PCB # 150057-1 or PCB with SMD parts preassembled: Elektor Store # 150057-91 Figure 2. The PCB for the I/O board. The board has room for mounting seven different module types. Connection Module (fit one only): Modi = HC-06/-05 Bluetooth breakout module soldered straight onto board Mod2 = HC-06/-05 Bluetooth ZigBee-shaped module Mod2 = RN41XVC Bluetooth module Mod2 = RN171 WLAN module (with wire antenna) mount onto two 10-way pinheader receptacles, 2mm pitch Mod3 = Android Breakout- Board (Elektor Store # 130516-91) mount onto two 10-way pinheader receptacles, 0.1" pitch Mod4 = ESP8266 WiFi module (2x4-pin connection) mount onto 2x3-way pinheader receptacles, 0.1" pitch Mod5 = FT232R USB/Serial Bridge BoB (Elektor Store # 110553-91) mount onto 3-way pinheader receptacle, 2.5mm pitch (3-pin pinheader on BoB) Mod6 = HC-06 module (6-pin version) mount onto 6-pin pinheader receptacle, 0.1" pitch Mod7 = BL600 E-BoB (Elektor Store # 140270-91) mount onto two 8-way pinheader receptacles, 0.1" pitch Table 2. Functions of all headers and connectors. Kl Micro USB connector for power to board and module K2 2xl3-pin header for all 24 I/O lines of the PIC microcontroller, 3.3 V and ground K3 2x3-pin connector for daisy-chaining several I/O boards K4 2-pin supply voltage connector for board (4-13 V) K5 6-pin programming connector for PICkit 2 or PICkit 3 K6 2-pin header for launching the boot loader by touch switch or jumper JP1 2-pin header for modifying the firmware of the EPS8266 module JP2 2x4-pin header for configuring the signal and supply lines to the other modules MODI to MOD7 Connectors for mounting various Bluetooth, Wi-Fi and USB modules (see components list) (# 130516-91) and the Elektor FT232R USB/serial Bridge BoB (# 110553-91), both of which provide a USB link to a PC, tablet or smartphone through a UST to OTC adapter cable. All of these modules output the data received from the Android device or PC as serial data. This serial data goes to a PIC microcontroller, namely a PIC16F1938 with 24 I/O pins. As will be described later, the firmware in the microcontroller interprets the commands and configures the I/O pins as inputs or outputs for dig- ital or analog signals. All I/O pins of the microcontroller are accessible on a two-row pin header. Two of these pins are used for serial data transfer to the communication module. That completes the general description; now let's look at the components in the schematic diagram. To start with, the board has a 3.3-V voltage regulator (IC3). There are two options on the board for connecting a power source to the volt- age regulator: a micro USB connector (Kl) and a pair of solder pads, which can optionally be fitted with a pin header (K4). IC3 is an MCP1702-33 low-drop voltage regulator. It provides the 3.3 V supply voltage for the Bluetooth or Wi-Fi module and the rest of the circuit. Power can be switched with switch S2. If you do not need a power switch, you can bridge the two mounting holes on the board with a piece of wire. The microcontroller is a 28-pin PIC16F1938 from Microchip (IC1). The link between the PIC16F1938 and the Bluetooth, Wi-Fi or USB module runs through jumper station JP2 (for debug- ging) and the protection resistors R5 and R7. All I/O lines are available on con- nector K2. For extra storage capacity (for use as a data logger, for example), the board has a 32 Kbyte serial I 2 C flash memory (IC2). The PC pins of this IC have protec- tion resistors (R14 and R15) and pullup resistors (R12 and R13). There is also an NTC thermistor (Rll) on board for temperature measurement. It forms a voltage divider in combination with R9. The LEDs LED1 to LED4 are provided as indicators for various signals. LED1 is lit when the 3.3 V supply voltage is present, and LED2 is only active when the FIC-06 breakout module is mounted. LED3 and LED4 can be used for various purposes; LED3 also indicates that the boot loader is active. SI is the capacitive sense switch, 68 September & October 2015 www.elektormagazine.com LABS PROJECT reader's project which consists of a pad etched on the PCB. Header K6, which is necessary for activating the boot loader in the PIC, is wired in parallel with SI. The board also allows a clock crystal to be connected to the microcontroller. The boot loader software described in this series of articles does not support this option, which requires a different boot loader and the appropriate configuration word set- tings. In that case pins A6 and A7 on K2 can no longer be used by the firmware. Universal PCB At first glance the component overlay for this circuit board (Figure 2) appears rather cluttered due to all the module mounting positions marked on the board, but on closer examination you will quickly see exactly where the connections for modules MODI to MOD6 are located. After you decide which module you want to use, you only have to mount that module and the other positions remain unused. Except for the connectors and the switch, all of the components are SMDs, which means that manual assembly is not especially easy. That is why we offer a pre-assem- bled board (# 150075-91 [1]) with all of the SMDs and some of the connec- tors already mounted. Of course, you can also order a bare PCB and solder all the components on it yourself. However, we recommend that you wait with this until next month, when we will describe the various. There are several pins and headers on the board for configuring all sorts of settings. For the sake of clarity, Table 2 provides an overview of all the connectors and headers along with brief descriptions. In normal operation, JP2 passes the Tx and Rx signals between the installed mod- ule and the PIC microcontroller. Usually pin 3 is connected to pin 4 and pin 5 is connected to pin 6. Pins 7 and 8 are joined together by a PCB track, which is handy when an external module is con- nected to JP2. The 3.3 V supply voltage from the voltage regulator is available on pin 2, and pin 1 is connected to the supply voltage line for the module. There are two options for supplying power to a module: The module has to be supplied with power from the 3.3 V voltage regulator. This applies to the Bluetooth and Wi-Fi mod- ules. For this purpose, pins 1 and 2 must be connected together. If an FT232R USB/serial bridge BoB Figure 3. The assembled board fitted with the Elektor BL600 e-BoB. Table 3. I/O pin functions and function numbers. Pin High- impedance input (0) Weak pullup input (1) Output (2) ADC (3) Cap sense (4) PWM (5) Speciaal (6) AO X X X A1 X X X A2 X X X A3 X X X A4 X X X A5 X X X X A6 XI X X A7 XI X X PWM bridge with A6 BO X X X X X X B1 X X X X X X PWM bridge with BO B2 X X X X X B3 X X X X X B4 XI XI X X X B5 XI XI X X X B6 X X X X B7 X X X X PWM bridge with B6 CO XI X Counter Cl XI X X C2 XI X X PWM bridge with Cl C3 XI I2C: SCL C4 X I2C: SDA C5 X X C6 TX (to Bluetooth, WiFi or USB module) C7 RX (from Bluetooth, WiFi or USB module) S Data logger X Real Time Clock Y Version / Serial Number Z Global settings X A new value can be sent www.elektormagazine.com September & October 2015 69 (110553-91) or an Android breakout board (# 130516-91) is mounted, the BoB is powered by 5 V from its USB con- nection. In that case pins 1 and 2 must never be connected together. Commands Even though you can't work hands-on with the I/O board just yet, let's look at the commands you can use to control the board. Here we assume that a link to the board has already been established over Blue- tooth, Wi-Fi or USB. That means there is a transparent serial connection between the Android device and the microcontrol- ler on the Android I/O board. Commands can therefore be sent to the microcon- troller from an app. The firmware inter- prets these commands and controls the I/O pins accordingly. The names of these pins match the microcontroller designa- tions: AO to A7, BO to B7 and CO to C7 (see also Table 3). There are four types of command: • W for "write", which writes a specific value to a specific pin. The format is W < pin > . For example, "w a3 1" sets I/O pin A3 high. • R for "read", which reads the value of a specific pin. The format is R < pi n > . For example, "r b4" reads the value of pin B4. The format of the microcontroller response is R < pi n > (in this example "R B4 1"). • S for "settings". This defines the function of a pin. The format is S < pin > , where is a number. Here "0" makes the pin a high-impedance input, "1" makes it a weak pullup input, "2" makes it an output, "3" makes it an ADC input, "4" makes it a capacitive sensing input, "5" makes it a PWM output, and "6" is reserved for a spe- cial functions. For example, "s b3 3" makes pin B3 an ADC input. Several other parameters can also be set. Each pin has three additional 8-bit status registers that can be accessed by putting "1", "2" or "3" after the pin name. For example, the command "s b32 8" sets the status 2 register of pin B3 to a value of 8. The previously described pin functions are defined by the status 0 register, so "s b3 3" is the same as "s b30 3". • G for "get". This can be used to Figure 4. Some of the modules that can be mounted on the board. read a setting or value. The for- mat is G < pi n > . The microcontroller responds with G < pi n > . For example, "g b3" yields "G B30 3". The commands and pin names are not case sensitive, but the response from the microcontroller is always upper case. The microcontroller echoes the input in debug mode, so it is handy to use lower case for the commands. That way it is clear whether the text comes from the Android device (lower case) or the Android I/O board (upper case). All of the functions are described in detail in a separate document. This document (150057-W) can be downloaded for free from [1]. In part 2 we will talk about the Blue- tooth, Wi-Fi and USB modules and look at an app that uses the Android I/O board to expose and etch PCBs. We will also describe the standard classes that make it easy for you to control the Android I/O board from your own app. N ( 150057 - 1 ) Web Links [1] www. elektormagazine. com/150057 Free Webinar on Android I/O Board On September 17, the author presents a webinar on his project, hosted by ElektorAcademy/elementl4. Attendance is free, do not miss out and register at www.elektor.com/webinar 70 September & October 2015 www.elektormagazine.com LABS PROJECT BL600 Part 4 The I 2 C port and the temperature sensor By Jennifer Aubinais (France), elektor@aubinais.net f Our little wireless communications module has only seven input/ output ports, but its I 2 C port gives it considerable possibilities for extension. We can use it for communication with various components such as temperature sensors, D-A and A-D converters, etc. Here we will use it for exchanging data, the new service Health Thermometer via Bluetooth Low Energy instead of the UART service used in previous installments. I /C\ Figure 1. Schematic of a wireless thermometer with a DS1621 temperature sensor which communicates with the BL600 by I 2 C. The implementation of the e-BoB FT232 has been described in previous installments. We have learned how to use events in smartBASIC in the pre- vious issue. Now we can start with the I 2 C port of the BL600 by connecting it with the DS1621 temperature sensor [1] from Maxim Integrated. It may seem surprising to communicate via I 2 C with a Blue- tooth module... well, "you ain't seen nothin' yet", because this module has several more amazing resources, which will be the subject of future articles. For the moment, we will measure the temperature and display it on a smartphone, either under Android in an Android application which may be downloaded from Google Play [2], or under iOS with an application which may be downloaded from the Apple Store [7] or a small program which can be downloaded from the Elektor site [6]. www.elektormagazine.com September & October 2015 71 Listing 1 DIM rc, handle, txt$ r c= I 2c0pen (100000 , 0 , handle) IF rc ! = 0 THEN SPRINT #txt$, INTEGER. H' rc DbgMsg ( " Fai led to open I2C interface with error code 0x" + Right$ (txt$ ,4) ) PRINT "\nDO RESET" STOP ELSE DbgMsgVal ( "\nI2C open success \nHandle is " , handle) ENDIF Listing 2 DIM x, nSlaveAddr, nRegAddr, nRegVal, txt2$ nSlaveAddr = 0x48 : nRegAddr = 0xAC : nRegVal = 0xAA rc = I2cWri teReg8 (nSlaveAddr , nRegAddr, nRegVal) IF rc ! = 0 THEN SPRINT #txt$, INTEGER. H' rc DbgMsg("Failed to Write to slave/ regi ster " + Ri ght$ (txt$ ,4) ) ELSE SPRINT #txt$, INTEGER. H'nRegVal SPRINT #txt2$, INTEGER. H'nRegAddr DbgMsg("0x" + Right$ (txt$ ,2) + " written successfully to register 0x" + Ri ght$ (txt2$ , 2) ) ENDIF Figure 2. Photo of the whole assembly on a breadboard. Note: the use of the tools and commands to which I refer here is covered in previous instalments of this series [3] to which the reader may refer. I 2 C port and temperature sensor The DS1621 temperature sensor is an ideal illustration of the read and write functions of the PC port: the port SDA (data) on pin 8 of the e-BoB BL600 is connected to pin 1 of the DS1621; the port SCK (clock) on pin 9 of the e-BoB is connected to pin 2 of the DS1621 (Figure 1). Laird Technologies confirm that pullup resistors (between 4.7 and 10 kft) must be used on the PC bus lines. Following the documentation of the DS1621, we will send it some commands and then read its different registers in order to calculate the temperature. The application Temperature for Android issued by Laird Technologies allows us to trace a graph of the temperature measured by the sensor. The application which we give you for use with iOS, which uses the service Health Ther- mometer, allows us to do the same thing on an Apple product. a. Open I 2 C The first step is the opening of the PC port, followed by the processing of the returned code by a simple if statement (Listing 1). Rc = I2C0pen (100000 ,0 , handle) • nClockHz = 100000; clock frequency • nCfgFlags = 0; must be set to 0 • nHandle = if the returned code is 0, this variable is further used to read, write and close the PC interface rc = the returned code must be 0 to continue. If not, we con- vert its value to a chain of characters using the SPRINT function with the INTEGER. H option to convert to hexadecimal, then display the error code (see doc. Laird Technologies), before stopping the program using STOP. b. Write a byte to I 2 C The next step is to write a byte to the PC port, to be sent to the DS1621. We have chosen the Access Config register (OxAC), which is read/write, and as an example we will write to it the value OxAA (Listing 2). Rc = I2CWriteReg8 (nSlaveAddr ,nRedAddr, nRegVal) • nSlaveAddr = slave address of the component, between 0 and 127 • nRedAddr = register address of the component • nRedVal = value (8 bits) to write to the address of the desired register Component List Resistors R1,R2 = lOkft Semiconductors IC1 = DS1621 Miscellaneous K1 = pushbutton connection MODI = FT232e-BoB, assembled, # 110553-91 (www.elektor.com) MOD2 = BL600e-BoB, assembled, # 140270-91 (www.elektor.com) 72 September & October 2015 www.elektormagazine.com LABS PROJECT Listing 3 nSlaveAddr = 0x48 : nRegAddr = OxAA re = I2cReadReg8 (nSlaveAddr , nRegAddr, nRegVal) IF rc ! = 0 THEN SPRINT #txt$, INTEGER. H' rc DbgMsg( " Fai led to Read from slave/ regi ster " + Ri ght$ (txt$ ,4) ) ELSE SPRINT #txt$, INTEGER. H'nRegVal SPRINT #txt2$, INTEGER. H'nRegAddr DbgMsg( "Value read from register 0x" + Ri ght$ (txt2$ , 2) + " is 0x" + Ri ght$ (txt$ , 2) ) ENDIF rc = the returned code must be 0 to continue. If not, we con- vert its value to a chain of characters, then display the error code (see Laird Technologies' documentation.) c. Read a byte from I 2 C We read the register OxAC which is the register of the high byte of the temperature of the DS1621. As we have not done the initialization procedure of the DS1621, it will not contain a usable value (Listing 3). Rc = I2CReadReg8 (nSlaveAddr ,nRedAddr, nRegVal) • nSlaveAddr = slave address of the component, between 0 and 127 • nRedAddr = register address of the component • nRedVal = value (8 bits) read from the address of the desired register rc = the returned code must be 0 to continue. If not, we con- vert its value to a chain of characters, then display the error code (see doc. Laird Technologies) d. Close I 2 C The last step is to close the I 2 C port. Laird Technologies rec- ommend doing it twice (Listing 4). I2Close (handle) • nHandle = value created by I2c0pen The file demoI2C.sb may be downloaded from the Elektor site [6]. e. Read the DS1621 using the serial port of the e-BoB FT232 We will not discuss the DS1621 [1] in detail, but we have made available for you a complete program for using it, notably using the functions I2C0pen, I2CWri teReg8, I2CReadReg8 and I2CClose described above. The datasheet of the tem- perature sensor suggests the following equation to transform the measured data of the DS1621 to a temperature value: ( COUNT PER C-COUNT REMAIN) TEMPERATURE = TEMP READ - 0 .25 + = = = COUNT PER C Figure 3. Writing to, and then reading from, the I 2 C port passing correctly. Figure 4. Display of the temperature in degrees: after bit 7 of the configuration register OxAC goes to 1 (0x43 -> 0xC3), we can read the temperature register and do the calculations. Figure 5. Don't panic, it wasn't 106.9 °C at the author's house or at Elektor Labs! www.elektormagazine.com September & October 2015 73 Listing 5 FUNCTION InitI2C() DIM re, txt$ // DIM Handle is defined at top of library DIM re, — x^ — a-, — t€^ — flag, — handle , — txt$ r c= I 2c0pen (100000 , 0 , handle) IF rc ! = 0 THEN SPRINT #txt$, INTEGER. H' rc DbgMsg ( " Fai led to open I2C interface with error code Ox" + Right$ (txt$ ,4) ) PRINT "\nD0 RESET" STOP ELSE DbgMsgVal ( "\nI2C open success \nHandle is " , handle) ENDIF ENDFUNC rc FUNCTION Ini tDS1621 ( ) DIM rc // Tout = active high; 1-shot mode DbgMsg ( "SetConfi g" ) rc = SetConfi g(P0L | 0NE_SH0T) ENDFUNC rc FUNCTION Con vertDS 1621 ( ) DIM rc, tC DbgMsg ( "DS1621" ) 00 DbgMsg (" \nSt a rtCon version") rc = StartConversion ( ) // initiate conversion tC = GetHrTempQ // read high-resolution temperature ENDFUNC tC FUNCTION ConvertTempTxt$ (tC) DIM rc, x, a, flag, txt$ flag = 0 IF (tC < 0) THEN tC = -tC // fix for integer division flag =1 // indicate negative ENDIF SPRINT #txt$ , tC SELECT StrLen(txt$) CASE 1 txt$ = "0.0" + txt$ CASE 2 txt$ = "0." + txt$ CASE 3 txt$ = Left$ (txt$ , 1) + "." + Ri ght$ (txt$ , 2) CASE 4 txt$ = Left$ (txt$ , 2) + + Ri ght$ (txt$ , 2) CASE ELSE ENDSELECT IF (flag == 1) THEN tx t $ = + tx t $ ENDIF PRINT "The temperature is " h — txt$ — i — " ' C\n" for x - 0 to 40000 next DOWHILE (1) ENDFUNC tx t $ FUNCTION CloseI2C ( ) I2cClose (handle) //close the port I2cClose (handle) //no harm done doing it again ENDFUNC 1 As the BL600 can only use integers (from 0 to 65535), all the values are multiplied by 100, after which the temperature will be in lOOths of a degree Celsius. This suits us well for display- ing text in the form of a temperature in degrees: it is only necessary to correctly place the decimal point (Figure 4). tHR = (tHR * 100 - 25) + ((slope - cRem) * 100 / slope) The file DS162l.sb may be downloaded from the Elektor mag- azine website [6]. f. The DS1621 in HTS (Health Thermometer Service) mode In my article Bluetooth Low Energy Wireless Thermometer pub- lished in the January & February 2015 edition of Elektor [4], it was the smartphone application which did the calculations. Here, it's the BL600 that does them. It's easy, thanks to Laird Technologies who offer software for our e-BoB BL600 and an application Temperature for Android. We thus have a wireless thermometer with the BL600 and the DS1621, which displays the temperature on your Android smartphone. Use of the file from Laird Technologies We simply compile the file htss . health . thermometer . sen- sor. sb. To verify that it works, we launch the application Temperature. You will notice that the temperature displayed is over 100 °C ! This is normal, as we have not connected an LM20 sensor on pin 4 of the BL600 as is expected with the development kit DVK-BL600-SA. The file htss . health . thermometer . sensor . sb is in the soft- ware package you can download for the BL600 [5] (Figure 5) Transformation of the program DS1621.sb to a library First step: we copy our program DS1621.sb to DS1621 . sblib. We are separating the main program (main) into several func- tions (Listing 5) which we will call in our new program. Second step: we modify the program htss. health. thermom- eter . sensor . sb and rename it $autorun$ . htss . dsl621 . sb. Here are the modifications: • Modify DEVICENAME: 3A_HTS • Add the library that we have just created: dsl621. sblib • Delete the following functions: Adc2mv, Mv2Temperature • In the function HandlerTimerO, replace the code in red by the code in green in Listing 6 74 September & October 2015 www.elektormagazine.com LABS PROJECT reader's project N Communicate via I 2 C with a Bluetooth module? You ain't seen nothin' yet! Listing 6 mv = Adc2Mv (Gpi oRead (4) ) DbgMsg( "\nAdc mV=") PRINT mv tmp = Mv2Temperature (mv) tmp = ConvertDS1621 ( ) tmp = tmp / 10 Listing 7 Ini tTempSensor ( ) re = InitI2C() re = ConvertDS1621 ( ) Ti merStart (0 , TEMPERATU RE_POLL_MS , 1) • In the main program (main) replace the code in red by the code in green in Listing 7 Nothing complicated; in place of the original analog LM20 sen- sor we have simply substituted our DS1621. For starters, it's I 2 C and further, it has a higher resolution. The file $autorun$ . htss . dsl621 . sb may be downloaded from the Elektor website [6]. The program under Android We now use the application HTM (Health Thermometer Per Min- ute), from the Laird Toolkit that we have already downloaded. After the scan, we choose the DEVICENAME JA_HTS given to our e-BoB. A red graph line appears; the author amused her- self well here — guess how? (answers in the caption of Fig- ure 6.) Amazing, huh? The iOS program After this example of the use of the HTS service with Android, instead of the Bluetooth Low Energy module's UART service, used since the beginning of this series, we also offer licensed iOS developers the source code of an equivalent small program for Apple (Figure 7). This file BLE HTS. zip can be downloaded from the Elektor website [6]. On the website of Laird Technolo- gies [5], you can find the complete source code for their appli- cation Toolkit for iOS comprising the services UART, HTS.... Call for contributions In this series of articles, we have called upon the program Serial from the Toolkit from Laird Technologies. This has made our lives much easier, but isn't it now time to make your own application for your Android phone? From the next article we will offer you a source code, the simplest possible, which will ••ooo SFR 9 10:06 $ 91 % Hi • 26.7°C Laird Technologies Figure 6. Graph obtained with Figure 7. Screen capture of the BLE the DS1621 connected via I 2 C to HTS application on iPhone. our e-BoB BL600. You will notice the peak of over 60 °C (using a hair-dryer) and a dip to -20 °C (obtained with a Freezit aerosol). The DS1621 offers a measurement range of -55 °C to +125 °C. allow you to increase your knowledge of the e-BoB BL600. Thanks to this module, available ready-to-use from the Elek- tor Store [8], implementation of Bluetooth communication is easy. Elektor is ready to publish other applications. If you have any ideas for using this module, or designs or projects in development, we invite you to share them with us, the author, and the Elektor community on the website www.elektor-labs. com. Your project might be chosen to appear in a forthcoming edition of Elektor magazine or the Elektor.POST newsletter. N (150130) Web Links [1] www.maximintegrated.com/en/products/analog/sen- sors-and-sensor-interface/DS1621.html [2] https://play.google.com [3] Elektor edition 2/2015 (March & April) [4] Elektor edition 1/2015 (January & February) [5] https://laird-ews-support.desk.com/2b_id = 1945 [6] www. elektormagazine. com/1 501 30 [7] https ://itunes. apple. com/en/app/bl600/id594855763?mt=8 [8] www.elektor.com/bl600-e-bob- 140270-91 www.elektormagazine.com September & October 2015 75 Camelback Water Level Indicator Lonely Planet approved 4 sure By Laurent Labbe (France, China) Easily outranking GPS, a credit card and fair weather, a supply of drinking water (H 2 0) is the first, foremost and quintessential requirement of any backpacker or hiker keen on surviving in the jungle, desert, New York, or the outback. Hence the availability of 'camelback' rucksacks specially designed to contain a collapsible water bag with a tube and mouthpiece. Sadly with the water tank on your back it's not easy to tell how much there's left to drink. With our solar-charged level indicator though you're good to go Into the Wild , come rain or snow. This project — originally called Camel Bag Water Indicator — went through the Full Monty of Elektor Labs, mean- ing it was posted there in the Proposals class where it was seen, discussed and rated by members. Next it got moved to In Progress, and finally to Finished meaning you can now read about it in Elektor magazine. During the In Progress stage the proj- ect got adopted by lab worker Luc Lemmens who produced an Elektor-style PCB for it and went through the rigors of making the proj- ect reproducible by you, readers of Elek- tor magazine. Luc worked closely together with project author Laurent Labbe, whose story on developing the project is ren- dered below. Triggers and considerations During many mountain bike tours in hot weather conditions in and around my domicile, I am used to carry a 'camelback' for my drinking water supply whilst on the move (the commer- cial product name is Camelbak, Ed.). 76 September & October 2015 www.elektormagazine.com LABS PROJECT Figure 1. Schematic of the camelback (Camelbak) water level indicator. Note how, as a power- saving kluge, the first 4060 powers the second. During these trips I was always frustrated to be guesstimating the quantity of water left in the bag. I spent a long time think- ing about this issue during these trips. I imagined I could put a sensor inside the water bag, or some water debit sensor, but nothing satisfied me. Until I saw Paul Cordonnier's capacitive liquid detector in his 'Siphonic Rain Gauge' article in Elektor magazine, edition March & April 2015 [1]. Paul's idea to place the sensor outside the water vessel rather than inside it, really appealed to me. Great idea, Paul, thanks a lot, merci bien. Not a fata morgana I began by doing a few tests with a 74HC4060 oscillator/divider IC supplied at is 3V3 Q K1 a R2 100k R4_ Tok 11 10 12 CO V 3D RCX Q3 Q4 RX Q5 IC1 Q6 cx Q7 Q8 74HC4060D Q9 Q11 RST Q12 Q13 GND i 7_ 5_ 4_ 6 _ 14 13 15 1 Cl lOOn R3_ £20k PI 11 10 100k II C2 ■ ■ 270p 12 R1 CO V DD RCX Q3 Q4 RX Q5 IC2 Q6 cx Q7 Q8 74HC4060D Q9 Q11 RST Q12 Q13 GND I 14 13 15 Jr 2 |oo 1 1-^ 1 3_ CO 1 LED1 £. Btl ! 3V9 5 L -0 r-C> I - I I L J C3 1u XC6206 P 332MR 3V3 IC3 1 0 $ ♦ C4 1u BAT USB IC4 MAXI 551 DC POK GND LED5 140375-11 www.elektormagazine.com September & October 2015 77 Component List Resistors Default: 5%, 0.125W, 0805 R1 = 820ft R2 = lOOkft R3 = 820kft R4 = lOkft R5,R6,R7,R8,R9 = 3.3kft PI = lOOkft trimpot, SMD Capacitors Cl = lOOnF 5%, 50V, 0805 C2 = 270pF 5%, 50V, 0805 C3,C4,C5 = lpF 10%, 16V, 0805 Semiconductors LED1,LED2,LED3,LED4,LED5 = LED, green, low current, 0805 IC1,IC2 = 74HC4060 (SOIC-16) IC3 = XC6206P332MR (SOT23-3) IC4 = MAX1551 Miscellaneous Solar panel 5V, 150mW 4.2V cellphone Li+ battery PCB 140375-1 VI. 0 Two adhesive copper strips, length 15-20cm Figure 2. As we're talking portability here, every ounce and millimeter counts. Hence the PCB got designed to take SMD parts. 3.3 V (to allow it running off a lithium cell) and with a plastic bag, first filled with water and then emptied out. It worked: a variation of frequency could be observed. To make it simpler, I used the 4060's Qll output on pin 1, which gave a fre- quency of 150 Hz when empty, and 60 Hz when full. Figure 3. The author's prototype of the camelback water supply, hinged to the front of his rucksack. Figure 4. The water reservoir with the capacitive sensor secured to it. Oh yes, these reservoirs can be bought at hiking and outdoor outlets. At this point we can proceed to discuss the schematic in Figure 1 . How to dis- play the 'data' from the DIY capacitive sensor connected to Kl? As the Qll fre- quency is lower when the bag is full, the logic l's are effectively longer. The idea arose to use this signal to launch another 4060 to count during this time and using its 128/256/512/1024 divider outputs to create a water level readout using LEDs. The RST (CLR) input on the 4060 is active-High, and to save precious current the 4060 reading the sensor (IC1) powers the 4060 doing the readout (IC2). With a pulse at power-on to clear the count- ers, this works if we choose the clock frequency just right at around 30 kHz. Here, high-efficiency LEDs are used with 3.3-kft resistors (R5-R8) ensuring the readout is visible even in bright sunshine. The sensor consists of two parallel run- ning adhesive strips of copper foil or cop- per laminate, secured vertically © on the outside © of the water container. For calibration it is useful that the clock of the second 4060 be adjustable. Admit- tedly it is a bit tricky to find the right Figure 5. The DIY sensor works equally well when mounted at the other side of the reservoir. 78 September & October 2015 www.elektormagazine.com LABS PROJECT adjustment on PI between 'empty' detec- tion and 'full'. The prototype worked though, and was accurate enough for my needs. I put the lot into a transparent box on my camelbak — very light and useful. At a later stage while contributing on the project at www.elektor-labs.com I thought of adding a solar power panel to recharge the lithium battery, and even later, to use a microcontroller to implement automatic calibration for 'empty' and 'full'. Of these ideas, the first was worked out, the sec- ond is 'under active consideration' at the time of writing this article. The circuit is powered by a small (150- mAh) LiPo battery, which is being charged by a 5-V, 50-mA solar cell via a dedicated charger IC, the MAX1551. Again using my prototype I found that the battery was charged from 3.3 V to 3.7 V after a few hours under sunshine. I'm thinking of adding another cell to increase the current. After a small trip (two hours biking) enjoying some sun- shine, by the end of the afternoon I mea- sured 3.72 V, meaning the battery was at same level as on departure. So, although conditions were not perfect, the battery did not discharge. The overall consumption of the circuit is roughly 3 mA, hence long-term autonomy of operation should not be a problem. An external plug for a USB charger may be considered as a cool extension. Construction Small as the circuit board and the parts may be, it is a challenge, not a fata mor- gana, to assemble at home using manual soldering on the PCB design for the proj- ect (Figure 2). Luc Lemmens at Elektor Labs proved it using patience, pure skill, and the now well-published bag of tricks to get these tiny parts properly secured first and then soldered. Good attention has to be paid to boxing up the camelback water level indicator, as well as the sensor construction, and for this it is useful to view the photos of the author's prototype in Figures 3, 4 and 5. Make sure everything is secure in and on the box and you're good to go. First hiker or pedaler to arrive at Elektor House [2] with a working CWLI and at an outside temperature exceeding 30 °C (86 °F) gets a free tour of the Elektor Labs, an Elektor Labs ruler, and a visit to the water well in the castle basement. Competition closes October 1, 2015. Competition not open to employees of Elektor International Media, it subsidiaries, licensees, and/or associ- ated publishing houses. ( 140375 ) Web Link [1] Siphonic Rain Gauge, www. elektormagazine. com/120554 [2] @ 51.016224, 5.838898; Mon-Thu 8 am - 5 pm, Fri 8 am - 1 pm. Ring doorbell. Advertisement The Easiest Way to Design Custom Front Panels & Enclosures You design it to your specifications using our FREE CAD software, Front Panel Designer We machine it and ship to you a professionally finished product, no minimum quantity required • Cost effective prototypes and production runs with no setup charges • Powder-coated and anodized finishes in various colors • Select from aluminum, acrylic or provide your own material • Standard lead time in 5 days or express manufacturing in 3 or 1 days M 'FRONT PANEL EXPRESS FrontPanelExpress.com Best Scopes at the Best Prices Owon, Siglent, Rigol, Pico Technology and Teledyne LeCroy Passport-Size PC Scopes S 1 29+ Up to 200MHz bandwidth with IGSa/s, high speed data streaming to IMSa/s. built-in 1 GSa/s AW Gi wf m gen. PS22QG A ser re s ■> ... . Vi mm jr sill! - ■. — -VI r J ~m S 23 =i 30M Hz Scope *289 m „ Remarkable 30MHz. 2 channel, 250M$a's scope ».* 8-in color TFT-LCD and AntoScale function, FREE carry case! SDS5032E 50MHz Scope s 399 5QM"tz.4di scope at 2 charnel price! Up to IGSafs rate. 12fttets memory! "Ultra Vam" technology far realtmewfm reoordhg. DS1Q54Z 60MHz Scope *349 Best selling 60MHz, 2 channel, 5DQMSa/s scape with huge 10M$a memory. Includes FREE carry case! 3DS6062V 70-1 GHz Scopes *1189+ Selection of fast, versatile 2 or 4 channel scopes, some with MSO logic analysis, 1 2-bit precision, large memory, touch interface! www.saelig.com • Free Technical Support * Excellent Customer Service www.elektormagazine.com September & October 2015 79 Bike Inclinometer Compact solution using a PIC By Jelle Aarnoudse (NL) BikeInclinoMeter@Ziggo.nl Cycling enthusiasts who enjoy riding through hilly terrain (and this doesn't necessarily have to be a col of the first category) will often want to know how steep that slope is that they are attempting to climb. This is not a function that is normally found on a cycle computer, but with only a few components you can build such an inclinometer yourself. Hello World... a small part of the Neth- erlands is neither flat nor below sea level. Cycling though the hills of South Limburg, I was often surprised how one incline would cost me much more energy (and sweat) than another. While my lit- tle cycle computer keeps track of all kinds of things, gradient is not one of them. I couldn't find anything appropriate in the bike shop and if you enjoy playing with 80 September & October 2015 www.elektormagazine.com reader's project H PIC microcontrol- lers and the like, then, well, you devise some- ng yourself. This became iclinometer, which for this i I named the 'bike incli- It is a simple thing, with features, that is housed plastic enclosure which 5 top tube of my bicycle for a suitable sensor, I H"I Technologies (these days part of Murata), which generates an analog sig- nal that is proportional to the angle of inclination (see [1] and the connection details in Figure 1). At the time, my PIC supplier also sold nice, small LCDs for €2, which were probably intended for mobile phones and could be controlled with I 2 C. These were ideal for my application. To complete the circuit a few other components were necessary to provide the PIC with a positive and the LCD with a negative power supply voltage. This finally resulted in the schematic of Figure 2. The microcontroller For those projects that do not require exact time mea- surements, the PIC16F88 controller is a fantastic, versatile workhorse: an internal oscillator (which avoids the need of a crystal), flash program memory for 4096 instructions, 386 www.elektormagazine.com September & October 2015 81 SHARE LEARN G Figure 1. The schematic for the bike inclinometer. N The program for the inclinometer was written in assembly language bytes of RAM, 256 bytes of data EEPROM, 10-bit ADC, PWM output, USART, two comparators, two 8-bit timers and one 16-bit timer. The power supply The PIC operates from a 5 V supply, while the LCD requires 3 V and -8 V. The first two are provided by a 9-V battery, a 78L05 and a voltage divider. How to generate the -8 V supply for the LCD required a little bit more thought. Until I realized that the PIC, after run- ning the inclination program, had plenty of time to spare to generate an addi- tional clock signal, which could serve as the control signal for a simple switch- ing power supply. This consists of T3, R3, R4, Dl, LI, C4 and D2. When RA1 (pin 18) is low, T3 conducts and stores energy in LI. When RA1 is high again, T3 blocks and LI reacts with a back-EMF. As a consequence, Dl starts to conduct and this charges C4, which results in a negative voltage which is nicely limited to -8 V by zener diode D2. I always forget to turn off a gadget like this, so an auto-switch-off was definitely an essential feature. I solved this with T1 and T2. When SI is pressed, the PIC starts. One of the first actions it carries out, is setting RB4 high, which turns on both T1 and T2 and so continues to provide power to the unit. The PIC pro- gram is configured in such a way that RB4 remains high, provided the output voltage from IC1 changes regularly. If this hasn't changed for more than 5% for about 20 minutes then the bike is apparently stationary. RB4 is then made low and the unit switches itself off. The SCA600 C21H1G, an angle of inclination meter??? Initially I didn't question how such a chip manages to measure the angle of inclination. I only did that after I was surprised to find that the thing worked perfectly well when stationary, but the value on the display changed con- stantly while cycling, although the gra- dient didn't change. I noticed that the value was higher on the down-stroke of the pedal compared to when the pedals where about vertical and therefore little pedaling force was applied. This thing therefore does not measure inclination at all, but instead measures accelera- tion! I should have know this, of course, because at the top of the datasheet it states in big letters: accelerometer. The solution to this problem was simple: just average over a longer period of time. How this is done will be dealt with in the description of the program. The program The program for the inclinometer has been written in assembly language using MPLAB, since this allows the code to be kept as small and efficient as possible. The entire hex-code fits neatly in the 4 KB of available program memory. The assembly language and hex code files can be freely downloaded from [2]. The program has to carry out the follow- ing tasks: provide the negative power supply voltage for the LCD; read the Web Links [1] www. datasheetarchive.com/SCA600-C2 lHlG-datasheet.html [2] www. elektor-magazine. com/140458 82 September & October 2015 www.elektormagazine.com chips, which you can use to generate just about any desired voltage from two AA bat- teries. This is much more efficient than a linear voltage regulator. But, as a reassur- ance: In this circuit the 9-V battery easily lasts 2 years, because the circuit draws very little current. The top tube of my bicycle, where I mounted the meter, is exactly horizontal. This is not true for every bicycle. For a next iteration of the circuit I would add another button, which would allow a zero-calibration to be carried out. This is not a ready-to-build project, but more of a description of how I arrived here, the challenges I encountered and how I solved them. The display described here is no longer available and there are now better acceler- ometers. But this is a good starting point for similar projects and, if necessary, I'm certainly prepared to help readers with their implementations. ( 140458 ) Figure 2. This is how the prototype fits together. accelerometer chip; calculate the moving average and dis- play the result via the I 2 C protocol on the LCD. To generate the negative LCD voltage requires a square wave. This is produced by TimerO, which generates in inter- rupt every 25 microseconds and which in turn toggles RA1. We read the output from the accelerometer using the ADC in the PIC. The result of which is placed in a circular array of 64 bytes. After each update the average is determined and this is then sent to the display. The characters that are to be shown on the display are stored as bitmaps in the program memory and are retrieved from there as required and sent to the display. Immediately after switching the unit on, an image of a bicycle is shown as a welcome message, which is also stored as a bitmap in the program. In a few places in the program, the unused outputs of the PIC are made high or low. I had LEDs connected to these outputs during the testing phase of the software, so that I could check whether all the individual program parts oper- ated correctly. The construction Because this is a simple, one-off circuit, I built everything on a small piece of prototyping board. This sits as a sandwich between the display and the 9-V battery. This all fits snugly in a small enclosure and is therefore held tightly in place. Finally If I was to build this thing again, then for the power supply I would use one of those modern switching power supply Advertisement Schaeffer Free Front Panel Designer YOU DESIGN IT - WE MACHINE IT Professional quality front panels From one piece and at a fair price! Simply download our free Front Panel Designer at www.schaeffer-ag.de, design your front panel and order it directly. www.elektormagazine.com September & October 2015 83 Wireless I 2 C Sensqr i Enhances Elektor's nixie tube thermometer/hygrometer I I By Hans Oppermann (Germany) The nixie tube thermometer/hygrometer featured in Elektor June 2012 combined components from the good old days of electronics with a modern microcontroller. To make the device even easier to use, this upgrade uses two wireless modules to connect the sensor and temperature display. Time-honored nixie tubes and ultra-mod- ern microcontroller technology were first brought together by Dieter Lues in Elektor for January 2011 in a thermometer. Hans Oppermann (that's me!) then refined this design to create a thermometer/hygrom- eter with improved characteristics. Both versions fascinated many Elektor readers and despite the unconventional mixture of components, people have reproduced them over and over. All the same, this nixie thermometer/ hygrometer device (from now on we'll call it NTH for short) suffered from one major shortcoming: where you position the circuit is not necessarily the place where you want to measure the tem- perature. If you put the sensor on the PCB directly next to the electronics, heat from the nixies and the decoder IC will falsify the result measured. Having forked out $20/£15/€17 already for the SHT21 sensor [1] alone, then you might be more interested in accurate measure- ment results than fabulous aesthetics! It's true that you could separate the sensor, with its I 2 C interface, from the rest of the circuit by several meters of cable (that's the most that an I 2 C bus can manage), but then the cable would degrade the visual impression again. No, it's better to stick with the wireless solution, using a radio connection alone. Redesign for wireless The most important prerequisite for this redesign was the freedom to re-use the sensor and existing assembled PCB with- out needing any modification to the soft- ware in the Microchip PIC16F876 control- ler. Sensor and controller alike should be unaware of (and unaffected by) the modification. As far as the controller on the nixie board is concerned, the inbound radio connection towards SHT21 (I 2 C slave) should act as a (virtual) sensor and in the outbound direction, towards the sensor, as a (virtual) controller (I2C master). The transmitter can then read data from the SHT21 sensor (transmit- ted by radio) to the receiver, which then decrypts the data and converts it back into I 2 C signals. Given these requirements, would any- body consider any device other than the RFM12B module [2] from HopeRF? The module (Figure 1) is small, affordable, easy to handle and well known to most Elektor readers from other projects (and consequently available also from the Elek- tor Store [3]). The wireless module is a transceiver, which means that it works both as transmitter and as receiver oper- ating in the 433 MHz ISM frequency band. The RFM12B has another feature that is very advantageous here, namely extremely low current consumption. The last thing to mention is that the transmit- ter and sensor combination is not a fixed device and therefore needs to manage a very long time using the energy from its CR2032 battery. Therefore at each end (transmitter and receiver) we employ extremely low-power PIC LF controllers. I was able to stretch the battery life to about eight months in practical operation by devising special settings for the status of the ports and programming the Ion- 84 September & October 2015 www.elektormagazine.com LABS PROJECT Figure 1. Small and keenly priced with high- performance: the RMF12 transceiver. gest possible sleep times! Naturally the quality of the CR2032 batteries used also has some bearing on this. Transmitter As the schematic in Fig ure 2 shows, the transmitter consists of the proces- sor PIC16LF1847, the wireless module RFM12B and the sensor SFIT21 in the NTFI. The sensor is unplugged from the NTFI and inserted into K1 on the transmit board. The controller is distinguished not only by extremely low current consumption but also by its 'bug-free' I 2 C components, which could not be claimed for the PIC16LF819 that I used originally. The software for the transmitter reads out data from the SFIT21 and sends this to the NTFI using the RFM12B wireless module. The trans- mit cycle is set to be active for three minutes, which con- sidering the lifespan of the batteries is very useful, as during the periods of 'radio silence' the current consumption of the complete transmitter is a negligible 3 pA. R1 and R3 form a voltage divider for checking the battery voltage when the transmitter is powered up. Battery status is indicated by the number of times that the LED flashes (lx: >2.5 V; 2x: >2.7 V and 3x: >2.9 V). At other times the LED flashes only briefly (50 ms), whenever data is being transferred. So no worries about squandering valuable button cell energy. If the battery voltage drops below 2.5 V during active operation, a tempera- ture value of 77.7 is transmitted (so long as the feeble transmitter is still in a posi- tion to do this). Receiver When you look for a schematic of the receiver you won't find one! Fear not, we didn't forget to include it, because actu- ally it's concealed inside Figure 2. The circuits are so similar that we made do without a second illustration. The com- ponents marked in gray are not included in the receiver circuitry. In fact the receiver consists almost only of the PICLF1847 with an LED and the wireless module RFM12B plus antenna. The circuit is plugged into K2 on the nixie board close to the sensor. The LED here functions as an indicator for the watchdog timer, which is initi- S1 ft VDD O £ 16 ■ BT1 — CR2032H ^1 © ^7c MCLR o a > RB7 RB6 RB5 RB4 IC1 RB3 RB2 RBI RBO PIC16LF1847 RA4 OSC1 RA3 OSC2 RA2 RA1 eo RAO C/5 > K2 a 13 12 11 10 18 17 D1 VDD O VDD O VDD Q K1 Jc2 ^pOOn y a a RES > ANT CLK MODI DCLK/CFIL/FFIT INT/VDI FSK/DATA/FFS SDI IRQ RFM12 SCK SDO GND GND SEL T ANTI Socket 11 12 13 14 transmitter only 120586-11 Figure 2. The transmitter and receiver share almost identical circuitry. Overview of the most important software functions of the transmitter: • Initialize the PIC, the RFM12B and the SHT21 • While loop • SHT21_measure : • measure temperature with “Hold Master Mode (HM)” • measure humidity with “Hold Master Mode (HM)” • Arrange the bytes into the same format as the SHT21 would deliver them if it was connected direct and not over a wireless link. • 6 values are stored in the Array mres for transfer (2 bytes temperature, CRC, 2 bytes humidity, CRC) • rfml2_snd_msg : • send 6 values from mres using RFM12B • Check_voltage : • test battery voltage. If below 2.4V, send 77.7 (as far as this is still possible). • Sleep state TX_CYCLE minutes • End of While loop www.elektormagazine.com September & October 2015 85 ated every time that a data packet is received. If no data packet is received within around 3 to 5 minutes, then the LED is illuminated. Absence of data packets can occur temporarily, or else permanently when the battery in the transmitter is exhausted. You can check the latter case easily by turning the transmitter off and back on again, counting how many times the transmitter LED flashes (everyone can count up to three!). The receiver software essentially emu- lates the SHT21 sensor and replicates an I2C slave. The way readings are pro- cessed is of course fine-tuned for the needs of the SHT21 but it should never- theless be simple to adapt the software to other sensors as well. Altering the cycle time for the transmitter is achieved using the constant TX_CYCLE. The same-named constant must of course be changed in the receiver, in order to match the watchdog timer. People who wish to program the two PIC16LF1847 chips themselves should perform the fuse settings as shown in Table 1. Construction As with the schematics, so also for the printed circuit boards. Thanks to the almost identical circuitry for the PICs (albeit with differing firmware) and wire- less modules, we have only one PCB layout for transmitter and receiver. A double set of unpopulated boards is available in the Elektor Shop [4] and the same applies for the PIC controllers already provided with the transmitter or receiver software. Fit- ting components on the PCBs differs only in the couple of passives that need to be installed for the transmitter and are absent on the receiver. Not mentioned at all yet is the six-pin connector K2. This provides an in-circuit programming interface for the PIC16LF1847, which is pin-compatible with the connector of PICkit2/3. Table 1. Fuse settings for programming the transmitter and receiver controllers. Fuse settings 120586-41 Receiver 120586-42 Transmitter Oscillator internal RC, I/O on oscillator pins Watchdog timer ON Protect OFF LVP OFF PUT ON OFF Brownout detection OFF Config word 1 39DC 39FC Config word 2 1EFF Populating the two PCBs, whose layout can be seen in Figure 3, should not be problematic. All components (SMDs in the main) are soldered on the side of the PCB marked with the component desig- nations; only the battery holder for the transmitter belongs on the rear side, as shown clearly in Figure 4. In order to be able to plug the receiver board into the header strip on the nixie board, we solder a straight pin header at Kl, but fixed the 'wrong way round' (i.e. on the back of the board). On the transmitter board we mount a straight female connector strip at Kl, the right way round this time, so that the sensor board with its angled pin header can be plugged in, as shown in the photo. The wireless section on each PCB uses socket headers having a 2-mm pitch; these match the pinheader strips pro- vided on the modules themselves. There are two reasons for this: firstly, there are components located directly under the modules, and secondly, programming of the microcontroller on the board should take place only when the radio module and the sensor are not plugged together. The supply voltage for these components is in fact 3.3 V, whereas the voltage on the programming interface is higher (5 V). Not a big difference but sufficient to damage or destroy the components! Therefore we need to plug the wireless module into a socket and remove the module and the sensor (and of course the battery) before carrying out any program- ming. PICkit2/3 can certainly be set to use 3.3 V (and adjusts itself automatically to 3.3 V when PIC16LF1847 is selected), but this is an important warning in case you use a different programmer or you accidentally choose the wrong control- ler setting. The RFM12 wireless modules are supplied not only for 433 MHz but also for two other ISM/LPR frequency bands, 868 MHz and 915 MHz used in North and South America. Each version demands its own initializa- The receiver firmware turns out rather simpler than that of the transmitter: • Receive the 6 mres bytes from the transmitter in the Function isrO and file them in the Array str or strl as appropriate • Pass the 6 bytes from strl on command from the Master into the Function sspinterupt. This represents the core function of the Slave software. sspi i nterrupt : state = i 2c_i sr_state ( ) ; // Indicates the status of the data transfer (read/write and which data is to be transferred. For details see CCS C-Compiler documentation. According to function code 0xE5 or 0xE3 data is stored in the Array str . 86 September & October 2015 www.elektormagazine.com LABS PROJECT reader's project Figure 3. A small printed circuit board for receiver and transmitter, with the battery conveniently fitted on the other side. tion, since at switch-on the relevant fre- quency needs to be written to one of the internal registers of the RFM12 module. The software covers all of the frequencies and to determine which frequency you wish to use the following pins need to be set either High (1) or Low (0): RB6 (K2-5) RB7 (K2-4) Frequency 0 0 433 MHz 1 0 868 MHz 0 1 915 MHz At switch-on the software reads these settings and sets up the corresponding frequency. VDD (K2-1) and GND (K2-3) are also present at connector K2. The best thing to do is take a small female header strip (partly visible in Figure 5 behind the far right-most tube), solder together some scraps of wire (to set RB6 and RB7 to the correct levels) and plug this 'assem- bly' into the header. Incidentally, K2 on the receiver board is a straight header (intentionally so) but a right-angled on the transmitter board. The latter is not necessary and you can choose to have whichever you wish. Figure 4. The button cell fits here on the rear side of the PCB. One final modest but important detail: the quarter-wave antennas. These can be made very simply from stiff wire about 17 cm long (8.5 cm for 868 MHz and 7.8 cm for 915 MHz), corresponding to a Figure 5. Nixie board with receiver installed in action. quarter wavelength in these LPR bands. A solder pad is provided in one corner of the board for connecting the antenna. N ( 120586 ) Component List, Transmitter Resistors All 5%, 0.125W, SMD 0805 R1,R3 = lOMft R2,R4,R6,R7 = lOkft R5 = 220ft Capacitors C1,C2 = lOOnF, ceramic, SMD 0805 Semiconductors D1 = LED, red, 3mm IC1 = PIC16LF1847-I/SO, programmed, Elek- tor Store # 120586-42 Miscellaneous Modi = RFM12B-433-S, 433-MHz transceiv- er, Hope RF Electronic, Elektor Store # 130559-91 with 17-cm wire antenna (see text for ISM/LPR band alternatives) SI = switch (lx on) or jumper K1 = 4-way pinheader receptacle strip, vertical 2 pcs 7-way 2-mm pitch socket strips and pin- headers, (Farnell # 547-3239, 605-8796) BT1 = CR2032 Lithium button cell with PCB mount holder (Multicomp CH25-2032LF) Component List, Receiver Resistors All 5%, 0.125W, SMD 0805 R4 = lOkft R5 = 220ft Capacitors C1,C2 = lOOnF, ceramic, SMD 0805 Semiconductors D1 = LED, red, 3mm IC1 = PIC16LF1847-I/SO, programmed, Elek- tor Store # 120586-41 Miscellaneous Modi = RFM12B-433-S, 433-MHz transceiv- er, Hope RF Electronic, Elektor Store # 130559-91 with 17-cm wire antenna (see text for ISM/ LPR band alternatives) PCB # 120568, set of 2, from Elektor Store 2 pcs 7-way 2-mm pitch pinheaders and receptacle strips (Farnell # 547-3239, 605-8796) Web Links [1] Sensor SHT-2x: www.sensirion.com/en/produkte/feuchte-und-temperatur/feuchte-temperatursensor-sht2x/ [2] Wireless module: www.hoperf.com/upload/rf/RFM12B.pdf [3] www.elektor.com/130559-91 [4] www.elektormagazine.com/120586 www.elektormagazine.com September & October 2015 87 Arduino Sound-Level Protector &VVilk j With three-color traffic light By Clemens Valens (Elektor Labs) The Arduino is a real jack-of-all-trades. You can use this inexpensive microcontroller board for all kinds of things thanks to the expansion connectors for which countless 'shields' are available. In this article we show you how you can realize a 'sound-level traffic light' using an Uno, together with an Elektor-developed multipurpose shield and a handful of common parts. The book "Mastering Microcontrollers — helped By Arduino" [1] is an excellent starting point for anyone who would like to get started using microcontrollers and their programming, without the requirement for a lot of prior knowledge. The book also describes several different hardware examples, which you can usually build on a small piece of experimenting board. In the second edition of the book an extra chapter was added, which contains even more examples. A universal shield was developed for these examples (no. 129009-1), which is available from the Elektor Store, either by itself or as part of a kit. This can be used to quickly build the various circuits. This circuit board offers space for an LCD, two pushbuttons, two power transistors, tempera- ture, air pressure and humidity sensors, a micro- phone preamplifier, an LDR, an IR sensor and a remote control receiver. In addition there are two LED outputs and a buzzer, and there is a protected and filtered analog inputrFurthermore, there are also two protected digital inputs and outputs, which can also function as a serial port. 88 September & October 2015 www.elektormagazine.com LABS PROJECT Arduino is a veritable multitalent that fits a thousand and one applications complex and simple! ns Figure 1. The entire circuit comprises only a few components which can all be fitted on the multipurpose shield. Not everything can be fitted on the circuit board at the same time, but it still accom- modates many of them simultaneously. The idea behind this circuit was to use a few LEDs to make a kind of sound- level traffic light, where the colors of the traffic light indicate different sound lev- els. In this case red means 'too loud'. Handy for a concert or when the neigh- bors are having a loud party again. It is, of course, possible to realize such a circuit entirely using only discrete com- ponents, but here we will show you how you could build one using an Arduino and a multipurpose shield. Besides the LEDs there is also an LCD that operates as a VU meter and with a few push- buttons it is easy to set the different thresholds. This is an excellent project to gain some programming experience with an Arduino! The circuit On the multipurpose shield 129009-1 there is space available for a microphone preamplifier. This can be used by the Arduino to react to sound. The microphone is an electret type and the amplifier is a classic single-transistor stage with a gain of about 1000 (see Figure 1). The output of the amplifier is connected to the Ardu- ino's analog input A0. Originally it was intended to use two LEDs for the indication, a green one and a red one. The shield also has space for these. However, as I was building this circuit I realized that I did not have a usable, 5-mm, green LED on hand. But I did happen to have a bi-color red/green LED with a common cathode, so I used that instead. Fitting it in the position of LED2, the third con- nection can then easily be connected to LED1, because the buzzer, which shares an output with LED1, is positioned close to LED2 on the circuit board. Thanks to the bi-color LED I now have a third color available, namely orange. So this ultimately became a Year traffic light. www.elektormagazine.com September & October 2015 89 Component List Resistors Default: 5%, 0.25W R1 = 330ft R2 = 150ft R3,R4 = 2.2kft R5 = 680kft R6 = 100ft PI = lOkft preset, horizontal Capacitors Cl = 220nF C2 = lOOnF C6 = lOpF 50V Semiconductors LED1 = green, 5 mm LED2 = red, 5 mm Alternatively, LED2 = bicolor, common cathode T1 = BC547C Miscellaneous S1,S2 = pushbutton, make contact, 6x6mm MIC1 = electret microphone, 6mm JP1 = 2-pin pinheader, 0.1" pitch K2,K3 = 6-pin pinheader, 0.1" pitch K4,K5 = 8-pin pinheader, 0.1" pitch mm LCD1 = 2 x 16 characters, with backlight K6 = 16-pin pinheader, 0.1" pitch For LCD: 16-pin connector, 0.1" pitch Jumper PCB # 129009-1 Figure 1. The entire circuit comprises only a few components which can all be fitted on the multipurpose shield. Figuur 3. De opgebouwde print, het LCD is voor de duidelijkheid nog niet op de connector gestoken. Because we don't have a sound-level meter at the Elektor lab any more, I was not able to calibrate the circuit in dB. To make the circuit as general-purpose as possible, it would be very convenient if the user could adjust the thresholds themselves. For this reason I have added an LCD in 4-bit mode to the circuit, as well as two pushbuttons. The display can show the raw values as well as the processed ones, and using the buttons a menu can be navigated. PI is used for the contrast setting of the LCD and a jumper on JP1 can be used to turn on the backlight. All these components will also fit on the multipurpose shield with- out any problems. The software The program, an Arduino sketch, of course, ultimately became quite exten- sive in order to demonstrate a number of different tricks and techniques. The sound level is measured with analogRead. This happens four times in a row, after which the values are averaged. The reason for this is not so much to filter the noise, but to slow down the program. As it happens, the function analogRead is very slow and four of these, one after the other, reduce the loop time of the main loop down to about 2 kHz. This is then also the sample rate of the sound signal. The peak amplitude of the measured sig- nal is determined with the aid of a leaky integrator, so that the peak value follows the sound level, but reduces to zero when the sound is gone. The peak value is filtered by a first-order low-pass filter with a cut-off frequency of about 0.1 Hz, to build in some delay. For this a genuine floating-point HR fil- ter-algorithm has been used (with expla- nation), so that you can see how this is actually implemented in practice. Once per second the actual filtered peak value is compared with the configured thresholds and the result is shown on the display and via the LEDs. During this update the sound level is not sampled, because it appeared that the switching of the LEDs had an impact on the analog input of the Arduino. There are three thresholds for the sound level: green, orange and red. 'Off' is no or very quiet noise (background noise), green is a little bit louder (a quiet bit of background music, default value = 100), orange is a little louder still (singing along, 90 September & October 2015 www.elektormagazine.com LABS PROJECT default value = 200) and red is very loud (yelling along with the music, deafeningly loud music, default value = 300). The display shows the sound level as a numeric percentage of the highest (red) threshold. This value is also displayed as a horizontal bar on the second line. This makes it possible to read the display from a distance, but is also used as a demonstration of how you can program such a thing. The display also indicates the peak value as a number from 0 to 1023. This is very useful when selecting the thresholds. Setting the thresholds is done by simul- taneously pressing the two pushbuttons. There now appears the option of setting the green threshold (0 - 1023). Press- ing both buttons again brings us to the orange threshold and once more gives the red threshold and finally the setup mode is exited by pressing both buttons for the last time. The selected threshold levels are stored in the EEPROM of the microcontroller. Construction Figure 2 shows the layout of the mul- tipurpose shield. For a schematic of all the individual circuits that can be built on this board we refer to the book [1]. Only those components that have to be fitted for this particular application are shown in Figure 2. Note that connectors K2 through K5 have to be mounted on the solder side. The LCD is connected to the shield using a 16-way pin header and a corresponding connector. The manner in which the bi-color LED is connected can be clearly seen in Figure 4. The built-up shield is plugged on top of an Arduino Uno, after this it can be loaded with the ino-file that is available as a free download from [2]. Figure 4. This is how the bicolor LED is mounted. The lead for the green LED goes to the + connection for BUZ1. Figure 5. Setting the threshold level at which the red LED turns on. Conclusion As you can see, this circuit demonstrates all kinds of things: • Sound-level measurements with an Arduino • Generating an alarm • Digital filtering • Driving an LCD • Driving LEDs • Reading switches • Implementing a Setup menu • Displaying a bar graph • Using LCD custom characters • Storing and then retrieving values from the EEPROM As an exercise for the reader there is still the serial port. This can be used to send the measured values to a PC or so, where they can be logged. Handy as evidence in the event of a protracted disturbance. N ( 150242 ) Web Links [1] www.elektor.com/mastering-microcontrollers-helped-by-arduino [2] www. elektormagazine. com/1 50242 www.elektormagazine.com September & October 2015 91 Single Wire LCD Interface Control your LCD display using just one data wire By Detlef Hanemann (Germany) Anyone with hands-on experience of installing multiple types of microcontroller knows that in the process of circuit development they are often forced to add one extra function after another. Eventually they reach the stage where the number of I/O pins available is no longer sufficient. Only three options remain now: do without some of the functions (reluctantly), employ a larger chip (sometimes one doesn't exist) or use a so-called port expander (at extra cost). All three workarounds have their pros and cons. A developer's life would be made considerably easier using peripherals that took up only one port pin of the microcontroller. And that's precisely what the interface for commonly used LCDs described here does. Using small microcontroller like, say, an 8-pin ATtiny from Atmel, we're left with just five GPIOs remaining after discount- ing the two supply pins, assuming we wish to retain the reset pin. That's not many. A larger chip with more pins not only takes up more surface area of the PCB but we still run out of pins rapidly after connecting all the press buttons, LEDs and other peripherals, especially if they demand that data is transmitted Technical specification • Universal interface for parallel LCDs • Serial addressing using only one GPIO line • Plugs into LCD modules with differing pin configurations • Compatible with low-cost LCD modules • Minimum transfer time for a character = 0.8 ms • Compatible with all microcontrollers in parallel, as many LCD modules do. In addition, the increased pin-count usually complicates the soldering, because the inter-pin distances are reduced. If you neither wish to use larger control- lers nor forego functions, then you are forced to use a port expander, consist- ing usually of shift registers connected either by I 2 C (slow) or by SPI (requiring an extra pin). Even then, the shift regis- ters use up at least two or even three pins of the microcontroller for converting the data into parallel format and transferring this to suit the particular interface of the LCD module. This kind of kludge certainly leaves potential for optimization. Optimal solution The attainable optimum just has to be the use of a single data line. Anything fewer would be impossible and any more than one not really necessary, as an LCD only receives data; it doesn't send any. An optimum solution should not require reinventing the wheel each time either. Therefore we have relocated the neces- sary conversion from serial to parallel away from the actual microcontroller circuit into a module that contains the necessary conversion electronics, so that inexpensive, widely available LCDs can be used. A display upgraded in this way can then be connected to any microcontroller with minimal effort. Single-wire solution Long before the Internet age people were already aware of methods of tricking a shift register into accepting serial data using fewer inputs than were actually nec- essary. The simplest possible shift register has at least two inputs, one for data and one for the clock. The clock is necessary to determine the point in time at which the level on the data input is valid. How- ever, if you generate a special combined data + clock format, you can then sepa- rate the data from the clock using a sim- ple resistor and capacitor (RC) element. Figure 1 shows how this process works 92 September & October 2015 www.elektormagazine.com LABS PROJECT in principle. There is one prerequisite, that the shift register is edge-triggered and reacts to a rising edge — which is the case with many of these chips. When there is no signal transfer happening, the quiescent level is High. In this state both inputs are at High level and there is no activity. If a short pulse (measured by the time constant of the RC low-pass) occurs, the data input remains High and as a result the rising edge of the (nega- tive-going) pulse clocks a High into the internal register. If we now wish to push a Low into the register, then we need only make the negative input pulse much longer, so that the voltage at the data input falls to Low. The input signal now consists of a sequence of short and long negative pulses — depending on the bit pattern being transmitted. If you select the timings appropriately, the solution functions very reliably. To avoid the data piling up sequentially bit by bit on the parallel outputs and caus- ing indeterminate states there during the clocking-in period, shift register ICs are generally provided with an output reg- ister that takes in data from the actual shift register only 'on demand' and then defines and organizes the data at the outputs in one fell swoop. To this end, therefore, a third input is necessary. As would seem natural, a solution was found from authors on the Internet such as [1] by simply using a second RC element with greater time constants. Here, however, short and long pulses would not suffice for bringing the input for data transfer down to Low. This pulse must then be very long. Altogether we now require a control signal containing the short (High), long (Low) and very long (acceptance) pulse. This solution also works well, albeit with a couple of restrictions: the final bit must always be Low and can therefore not be used for serial-parallel conversion. For connecting an LCD module we're left with one further problem, however. Although data is transferred to com- monplace two-line LCDs using the Hita- chi HD44780 controller (or compatible types) mainly in the '4-bit parallel' mode, which handles seven data bits easily, it expects to see a positive pulse in order for the LCD to accept the data delivered by the shift register. To generate a pulse of this kind we need to transfer each data word twice over, which is inconvenient and wastes time [3]. Therefore the author came up with a circuit using a simple alternative control signal to achieve a different method of data acquisition into the output register and delivery to the LCD module. Single-wire circuitry As seen in Figure 2, the control signal passes from Pin 3 of K1 to the two dif- ferent low-pass filters. The fast filter (R1 and Cl) has a time constant of approx- imately 10 ps and drives the data input Pin 14 of IC1. The slow one (R2 and C2) has a time constant of around 200 ps, however, and does not control the inter- nal data acquisition for IC1 (as with the solution in [1]). Instead it enables a reset of its Pin 10. Data acquisition is therefore solved in a different way. Figure 1. Block diagram for controlling a shift register via an RC low-pass filter using only one data line. +5V R6 ©~ 1 68R I K3 BACKLIGHT 4n7 3 % J / I - ’ y vi BS170 130397 - 11 Figure 2. The author's solution with two RC low-pass filters uses one element of the 74HC595 shift register. www.elektormagazine.com September & October 2015 93 HM02524 (HW 0xlQ12D007; SW Q4.20Q) 2015-01-13 11:14 Norm-Trig. / Complete TB: 100|1S T: 50 pS Ext. =: 500 mV /DC 5MSa Refresh C H 1 AC DC G N D B W L I N V Figure 3. Oscillogram with the following signals: yellow = control signal, violet = data input Pin 14, blue = reset input (Pin 10) and green = signal at QH' (Pin 9 of IC1). Responsibility for data acquisition into the output register of IC1 is handled by Pin 12 , which also looks after the LCD_ Enable input of the LCD module at K3 or K4 respectively. The positive pulse for the LCD is produced at the end of each data word transferred using the monostable constructed around Tl. This is feasible thanks to a special feature of the 74HC595 shift register employed, in which the very first High applied for bit 7 arranges on the last clock timing for the acquisition of data into the output register of IC1. Pin 12 of IC1 is linked to its QH' output, which in fact is responsible for cascading ICs of this kin d and is conse- quently linked directly to the shift register. The reset input of IC1 deletes — in this IC only — the status of the shift register but not the output register. With all the Component List Resistors All 5%, 0.25W. R1 = 2.2kft R2 = 47kft R3,R5 = lOkft R4 = 22kft R6 = 68ft PI = 2.2kft trimpot, large, horizontal Capacitors C1,C3 = 4.7nF, 0.1" pitch C4 = lOOnF, 5mm pitch Semiconductors Tl = BS170 IC1 = 74HC595, DIL Miscellaneous K1 = 3-pin pinheader, 0.1" pitch K2+K4,K3+ K5 = 16-pin pinheader or 16-way pinheader receptacle*, 0.1" pitch JP1 = 6-pin (2x3) pinheader, 0.1" pitch 2 pcs jumper, O.T'pitch LCD module, 2x16 characters* PCB # 130397-1* * see text Figure 4. Component side of the PCB for single-wire LCD interface. bits clocked in and a reset triggered by a fairly long negative control pulse on Pin 10, QH' is now set to Low, with QH and the other outputs remaining as they were. C3 and R3 together activate the monostable of Tl to enable acquisition of data for the LCD. After some recovery time for R2/C2 the next data word can be transferred. Figure 3 shows the progress over time of the various signal levels at the relevant stages of the circuit. The timings for the Low, High and Reset pulses selected by the author mean that the transfer of an 8-bit data word to the LCD takes around 1.3 ms. As you can see, other than the four data bits QA to QD (bits 0 to 3), the only other infor- mation needed is QG for controlling the register selection of the LCD. QE and QF offer two additional pins you can define for your own purposes. While Luc Lem- mens in Elektor Labs was doing some fine tuning and developing a PCB layout, he provided K2/K4 along with K3/K4 as pinheader strips for connecting the LCD display. Regular two-line LCD modules vary mainly in whether physical connec- tors are provided on the upper or lower surface of the device (and in which order) or not at all. Other variations concern the polarity of the backlighting (and fre- quently even the pin assignment). This makes it impossible to say whether our interface truly works with all modules. Luc is certain, however, that by providing K2 plus K4 together with K3 and K5 (and selectable polarity for the backlight using JP1), he has achieved the best possible flexibility and compatibility. In addition, Luc has reduced the time constants of the RC elements against the author's version for more stable data transfer. Inciden- tally, in your own programs you should not make the duration of the Low pulses any shorter (to avoid jeopardizing stabil- ity). On the other hand you are free to lengthen the High pauses. In the demo software Luc has also made provision for a trigger signal to Arduino Digital pin 9 (see prototype photo). This is for test purposes and you can of course omit this in your own implementation to save pins. Construction and operation There is really not very much to say about populating the board seen in Figure 4. With only one wired IC and ten passive non-SMD components, there is nothing insurmountable even for raw recruits to 94 September & October 2015 www.elektormagazine.com LABS PROJECT soldering. The only thing to watch out for is the functional order of the connection pins of the LCD and whether it is equipped with male or female connectors. The pin assignment is usually printed on the LCD board — if not, the data sheet will assist. Figures 5 and 6 show the prototype plus LCD, together with an Arduino. Take care with the connections and polarity of the LCD back- light. Two jumpers look after the latter. When jumpers JP1 are closer to K3 (linking 1 with 3 and 2 with 4), they arrange for the (positively charged) anode to be on the outermost terminal of K3 and on the innermost terminal at K4. However, if the two jumpers of JP1 are closer to K4, the situation is reversed. The combination of interface and LCD is linked direct to the microcontroller extension board via Kl. It's important here that the supply voltage of the microcontroller being used is the same as that of the LCD module. If the character stream output by the (correctly) programmed microcontroller cannot be read on the display, it's worth first checking whether the contrast is set correctly using PI. Figure 5. Prototype of the single-wire LCD interface, mounted on the rear of an LCD module. As usual the layout files for the PCB as well as the sample code (for the Ardu- ino) are available free at the web page for this article. Configuring this for the particular microcontroller used should not pose any problems thanks to the ample commentary provided. You can of course also obtain the small double-sided PCB ready etched, drilled and overprinted in the Elektor Store [1]. N ( 130397 ) Web Links [1] Roman Black's solution: www.romanblack.com/shiftl.htm (and do check out the rest of his 'minimalist design' website) [2] www. elektormagazine. com/130397 [3] www.elektor-labs.com/node/3598 Figure 6. Single-wire LCD interface in action, connecting an Arduino board to a display. www.elektormagazine.com September & October 2015 95 Over-Air LiPo Battery State Monitor Zigbee'd measurement of voltage, temperature, and current up to 170 amps By Michel Kuenemann & Gilles Krebs (France) The board described here measures the voltage and the current up to 170 A supplied by the battery in your scale model, then transmits these data via radio to your remote-control transmitter, or via USB to a Qt (say: cutie ) application on a PC. And even if you're not into modelling, you can adapt this project for your home automation or robotics applications, based on ZigBee and 1-Wire or I 2 C buses. Most electrically-propelled scale models are currently fitted with Lithium polymer batteries. Thanks to con- stant improvements in manufacturing processes, these accumulators, at least the most powerful of them, are now able to comfortably supply currents of several hundred amps. So with currents of this order, it's a good idea to monitor them, as unless appropriate pre- cautions are taken, they can cause major damage: burn up a board, the model, or yourself — or worse. LABS PROJECT When we need to measure high currents, the standard technique of using a shunt is still a good solution, as its low resistance allows us to limit heating and the inevi- table losses it introduces. The 500 pft / 8 W shunt in an SMD package selected for this project dissipates only 1.25 W when carrying a current of 50 A. As you know, when a current encounters a resistance, even as low as the resistance of a cop- per track, a potential difference appears across this resistance. Thus if we insert our shunt into the battery 'negative' rail, a high current can cause a potential dif- ference on the 0 V track that will result in an offset with respect to the 'real' 0 V. To avoid this sort of problem, we have adopted a different solution. If we place the shunt in the 'positive' lead, the battery voltage will be present on one of the measuring amplifier inputs, while the other input sees this same voltage, less the small volts drop across the shunt. Hence both inputs are seeing a voltage that's almost identical (common mode) and which is also very high. In order to amplify this rather special signal, we have used an amplifier capable of handling a common-mode input right up to its sup- ply voltage. The gain of this amplifier has been set for a full-scale reading of 170 A. The battery voltage measurement is achieved via a conventional resistive divider, set for a full-scale of over 30 V. The temperature measurement is achieved using a small analogue sensor in a SOT23 package, which will be posi- tioned under the PCB in contact with the battery. The radio transmission is by way of a Microchip MRF24J40 2.4 GHz RF mod- ule [1]. As this module comes in two versions, one providing 1 mW and the other 100 mW, we have designed the PCB with a dual layout allowing either version to be fitted. The 1 mW version offers a range of around 100 m (300 ft.), while the 100 mW module claims a range of over 1 km (3,000 ft.). This module has already been described in the '2.4 GHz Transmitter and Receiver for Model Aero- planes' [2]. The PIC18F26K20 8-bit microcontroller, running on its internal clock, is tasked with digitizing the signals and feeding them to the RF module that is going to transmit them. USB connectivity is provided by the very standard FT232RL. Two expansion connectors give access to an analogue input port, a 1-Wire bus, and an I 2 C bus operating in 'bit bang' mode, i.e. implemented in software. The board offers several powering options. It can derive its power from the following four sources: • the USB socket; • the serial connection (UART) connector. • the positive pole of the battery; • the battery balancing tap, at the point where the second element is connected (7.4 V); Since one picture is worth a thousand words, Figure 1 shows how to connect up the board in each powering configuration. Diodes Dl, D3, D4, and D7 prevent the various sources from being connected in parallel in the event of more than one being connected at the same time. Note that the regulator's maximum input voltage is 16 V, limited to 15 V by the pro- tective zener diode. So when using LiPo batteries with more than three elements, it will be necessary to power the board from the battery balancing tap (Jll is provided for easy connection), or choose another source (USB or UART socket). 110759 - 13 Figure 1. Four ways of powering the board. A: via the USB socket; B: via the UART connector; C: via the balancing tap; and D: via the power feed (for 2S or 3S LiPo batteries only). www.elektormagazine.com September & October 2015 97 Technical specifications • Compatible with LiPo batteries from 2S (7.4 V) up to 6S (22.1 V) • Continuous current 80 A, 170 A for a few seconds • Current measuring range: 0 - 170 A • Insertion resistance 1 mQ in the battery 'positive' line • Temperature measurement built in to the board • Connections: direct soldered, PK or DEAN sockets • Provides measurements of voltage and current with calculation of instantaneous power drawn • Summing of current supplied • Compatible with previously published 2.4. GHz Transceiver [2] • Open communication interfaces: USB, UART, I 2 C, 1-Wire • ZigBee compatible 2.4 GHz technology • Line-of-sight range of over 100 m (300 ft) or over 1 km (3,000 ft), depending on type of radio module. Figure 2. This block diagram makes it easier to follow the circuit diagram given in Figure 3. VOUT+ © +VMICRO © □ & o & * ♦ ✓ v 4 ♦ # ♦ # #■ * * .♦ ; The IoT Micro Power Supply is a small module intended for powering IoT sensors and other low-power devices. The IoT Micro PSU harvests energy from a small solar cell in a very efficient manner and can even work indoors. A ready-built module of this Solar Panel Voltage Converter for IoT Devices is now available from Elektor at a great price! The Piccolino rapid development board can be used to quickly design microcontroller circuits. The Piccolino has a fast 16f887 PIC microcontroller, voltage regulator, and communications module, and can be easily extended using its four headers. This book contains 30 projects based on the Piccolino. The clear descriptions along with circuit diagrams and photos will make the building of all the projects an enjoyable experience! This kit provides a comprehensive extension for all your Arduino projects. Not only does it give hands-on access to RFID, the other devices in the kit open up a wide range of possibilities for measurement, readout and control. Now available from Elektor! member price: £19.95 • C26.96 • US $31.00 member price: £26.95 • C35.96 • US $41.00 "Njjgtf member price: £32.95 • C44.96 • US $51.00 www.elektor.com/iot-micro-psu www.elektor.com/piccolino-book www.elektor.com/rfid-arduino-kit www.elektormagazine.com September & October 2015 105 REVIEW OF THE MONTH www.elektor.com By Luc Henderieckx Open-source community wakeup call The hardware and its specifications are impressive, what's lacking however is the software needed to use the Red Pitaya in real-world situations. The few examples of available software work well, but lack almost all settings required to perform useful measurements. I fail to see to why Elektor does not start to develop some applications as this hardware is exactly what the magazine is all about, and use them to kick off a course on programming... There are lots of microcontroller articles in Elektor, but this kind of IT-hardware gets as close as possible to the world of electronics DIY. When will this start or is it beyond the capabilities of Elektor? Elektor responds: Brilliant idea! We too are impressed by Red Pitaya and will look at the possibilities of launching some activity in the Elektor.LABS community. Many thanks, Thijs Beckers \ Elektor.LABS Submit a review of your favorite Elektor product and qualify to win a €100 voucher for redeeming in the Elektor Store For further information, please visit www.elektor.com/rotm € 10 ° \ -nisssssr;? ^ ji MEET THE ARDUINO FAMILY WWW.ELEKTOR.COM/ARDUINO 106 September & October 2015 www.elektormagazine.com "\m SHOPPING BOOKS cd/dvd DIY PROJECTS DEVELOPMENT TOOLS SALE T£ JM 1 ▼ Elektor Labs Solder Starter Kit This solder kit offers the basic equipment that anyone who enjoys hands-on electronics should have in his/her 'shack'. The digital solder station is equipped with electronics which allows for setting the soldering tip temperature between 160 and 480°C. The tip is isolated from the AC line and operates on 24 VDC. The station accurately displays the current and set temperature of the tip. The DT-830B digital voltmeter (DVM) measures voltage (AC and DC), current and resistance and has settings for diode check and transistor hfe measurement. Several other tools are included in this kit, like a cable stripper, desoldering tool, a small screwdriver annex voltage tester, and much more. The EAGLE Companion Limited time offer for GREEN and GOLD members: 20% Discount plus free shipping! Elektor Labs Solder Starter Kit Complete DIY kit with all necessary tools! Analog Circuit Design MEMBER PRICE: £97.95 • €134.96 • US $151.00 www.elektor.com/elss Thump! 3k286 Book Pages on Analog Design! Raspberry Pi Advanced Programming This book is about advanced programming of the Raspberry Pi computer using the Python programming language. The book explains in simple terms and with examples: how to configure the Raspberry Pi computer; how to install and use the Linux operating system and the desktop; how to write advanced programs using the Python programming language; how to use graphics in our programs and how to develop hardware based projects using the Raspberry Pi. ~ ^BB member price: £29.95 • C40.46 • US $46.00 Mystery Product Lego LED Kil We dare you ... The LEGO™ LED circuit board is a small PCB compatible with the famous bricks from Denmark that can hold an LED, a current limiting resistor and an optional connector. It is great for adding lighting effects to your constructions and it is 100% customizable. This kit contains 10 circuit boards, 10 LEDs of different colors, 10 current limiting resistors of 390 ohms and 10 current limiting resistors of 820 ohms. A 9 V battery clip is in the kit too. \ji member price: £6.95 • C8.96 • US $11.00 www.elektor.com/rpi-book www.elektor.com/mystery www.elektor.com/legoled www.elektormagazine.com September & October 2015 107 RECOMMENDED 4 SHOPPING www.elektor.com tk' <■' >1* >i 4 >8’ 4' 4' '» ; 4' ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ ✓ GOLD Membership www.elektor.com/gold BL600 e-BoB www.elektor.com/bl600 DVD Elektor 1980 through 1989 www.elektor.com/eighties Raspberry Pi Maker Kit www.elektor.com/rpikit Python Programming and GUIs www.elektor.com/python T-Board Audio Amplifier www.elektor.com/t-b-audio Retronics www.elektor.com/retro Java Cookbook www.elektor.com /java Elektor Labs Ruler www.elektor.com/ruler Electronic Dice www.elektor.com/dice ektor*post : DON'T MISS OUT! Elektor. N if vwre Genre 4wv... Dir Eleane ElKijtcunvi y Itrt n Eft : _r ] : itoAtt+ruu j ut r j4- 1 a --3 ■■■ ^ i> > h r. r'jt it jud /xj ’-f irUf !« t F Jn luteqi. > "i ptytrl ^ ll fai Ei Mi'll til 1 1 ytq Hurt owl rfh> nd httgi Pest jmr Gp. vd md Irts turic ((fiat. ■>*!, .--ji+oi i.:-,; I' Ultra Low Power Wireless 1 -qT Platform T rtv. r . InKTurw^ Jin Artrduiuari r j r#w [Jrrnl#l Ink niira- iriw *r •tAitl*-,'; r:>~ 11 pLagfenr.. Th* Ji'nr— i hki yjf r -;ie|v>t ;n me w Skit* jfsrg.' it £*a hi ',6.-, Jri,i ni'affl hi". v-:'qy y wfil run if.r yean. nn a rfhf. jfell. For wnmllhy L-jgp’.nv irijlbpl* v-lr-e am Oufilinue revdlrq... OT A vacuum: pre order VandcrVeen Trans Tube Amplifiers hook MwtkiihrOM insh«i-tr>iliiH:is' 1a«i brinJ-ttr-ifHlJi fluid meiYreim uT ew r'.Diy duo 0< ll'« t-uviundiKUrc-r nmffiilkr. i t imtm ird £rdb*d tit oT I C tehnoJ.Bn fnMrt [he Cpwitinui. 1 H odin^... j.m uni PKtrjsc i ■ • ■ TedTTfieFuture L ” The IBM. Frwscale and ARM loT Starter Kit r he bt'Vtf is on upgrade- (Von- tht ptathK wrii«*i vhlth used a Cortex m ftoetotit rilling JL >34 WJH2 Wlh 32 Stfi fll KAN. and SI L KJB if (IfclH rwnery. {amiFunkjdtn lini.s«Mjs u o aU-: ’mprof-T^d wT.h Ether 1 *', SPi,. Ijc, A(K:. ItA< , pyurf,, UAKt and GPKte- Cwitlriuo rosd lrtg... Join over 100,000 people worldwide and subscribe to our free Elektor.POST newsletter! • A weekly editorial newsletter packed full of latest news, tips and trends • An exclusive free Elektor project worth €2.50 (£1.95 / US $3.00) every second week • Special offers in the Elektor Store • A free Ebooks Inspiration Bundle valued at €32.95 (£23.95 / US $37.00) REGISTER TODAY, IT'S FREE www.elektor.com/newsletter Getting Started with the Intel Edison Advanced Control Robotics Robot Car Kit for Arduino This book is a must have for all those with an active interest in the Internet of Things. 'Getting Started with the Intel Edison' focuses its attention on the Edison, a tiny computer, the size of a postage stamp, with a lot of power and built-in wireless communication capabilities. In 128 pages, renowned author Bert van Dam helps readers get up to speed with the Edison by making it accessible and easy to use. Explore the wonderful world of the Intel Edison now! Hanno Sander's Advanced Control Robotics simplifies the theory and best practices of advanced robot technologies. You're taught basic embedded design theory and presented handy code samples, essential schematics, and valuable design tips (from construction to debugging). The book is intended to help roboticists of various skill levels take their designs to the next level with microcontrollers and the knowhow to implement them effectively. This four-wheel-Drive Smart Car can be controlled with an Android Bluetooth device or by infrared (included). Driven by an Arduino UNO the robot can avoid obstacles or follow a track. A mobile development platform, the 4-Wheel Drive Smart Car is great for study purposes and of course for the fun of it! The kit is loaded with expansion possibilities that provide sheer endless fun and creativity. "Njj&j member price: £21.95 • C26.96 • US $31.00 member price: £26.95 • C35.96 • US $41.00 "Njjaa member price: £65.95 • C89.96 • US $101.00 www.elektor.com/edison-book www.elektor.com/robotics-book www.elektor.com/arduino-car-kit 108 September & October 2015 www.elektormagazine.com "\m SHOPPING BOOKS cd/dvd DIY PROJECTS DEVELOPMENT TOOLS SALE T£ JM 1 ▼ Analog Circuit Design Bundle Three world renowned and class leading books on the art of Analog Design using the tutorial approach are now available from Elektor. Never before have we seen such thick and heavy books on a subject now going through a rebirth like no other: analog circuit design, the horror of all microcontroller-only people, and the dark skill of what some say are a few older engineers out there of the Bob Pease and Jim Williams generation. These books are guaranteed to unveil the darkest sides of opamp and discrete part based circuit design, as well as designing for low noise and total analog response, something no microcontroller can ever hope to achieve. Be smart. Buy all three volumes as a set and take advantage of a 10% bundle discount! MEMBER PRICE: £129.95 • €179.00 • US $201.00 www.elektor.com/acd-bundle The EAGLE Companion Limited time offer for GREEN and GOLD members: 20% Discount plus free shipping! Elektor Labs Solder Starter Kit Complete DIY kit with all necessary tools! Analog Circuit Design Thump! 3k286 Book Pages on Analog Design! SMARTSCOPE The world's first lOOMS/s open source USB-oscilloscope Voucher VfcUJE I Ur h*Hh mfrtwr *,fervU-fl Pi « r-\ ■- ¥- €229 £149.95 | US$231 MEMBERS ONLY: € 206.10 ■ ■ .», ,■ oAMv r - + '' 1 ' LIMITED OFFER: VOUCHER WORTH CIO INCLUDED! www.elektor.com/smartscope www.elektormagazine.com September & October 2015 109 if offered in collaboration with Generate your own PCB using the Elektor PCB Service 1 Affordable © High Quality © Reliable The Elektor PCB Service is the most extensive fully customized service for printed circuit board production in Europe. With convenient online tools allowing you to visualize and analyze your design before you order and pay . • For beginners, there is the NAKED-Prototype Service: This produces single and double-sided PCBs without solder masks. • For a more advanced service, there is the PCB Visualizer that shows you how your PCB will look after production, with a PCB Checker performing a DRC for you and the PCB Configurator that lets you customize your order details. Smart menus and select options guide you through the ordering process. You can see in advance exactly what our machines can produce so there won't be any surprises! So start your next project here: www.elektorPCBservice.com LEARN DESIGN SHARE Welcome to the SHARE section By Jaime Gonzalez-Arintero jaime. glez.arintero@eimworld.com Play Hard Beware, Cheap Phi- losophy Ahead\ Please let me explain. Last week I was watching a short documentary exploring the reasons why humans enjoy playing games. The conclusion was, more or less, that life is a game on its own, but since the goal is not really clear to every- one, we seem to need milestones to reach. In the absence of milestones, individuals will set them... right, individually. Maybe. As most guys of my generation, I used to play vid- eogames when I was a kid. Since I didn't find high school very amusing, the games were definitely more rewarding. Back then, videogames were acutely expensive, so it was considered normal to share them among friends. Computer games were hacked and shared very often and no wonder they came with more sophisticated copy protec- tion techniques all the time. Internet access was for the happy few, but you could always visit the library, find guidelines at forums, ask someone via IRC, and once back home, try different things offline. Then it was only "You vs. the Game." I'm not especially proud of that, but admit to having done it too. Nowadays I gladly pay for everything, hard copy or digital. Back then, we were kids. And it was challenging and tricky. It was big fun. Most games (and in general commercial software too) could be hacked by means of a cloned CD, or a mounted drive (by means of a virtual drive soft- ware, e.g. "DAEMON Tools"). Other games required more steps like overwriting registers, files, DLLs, using key-gens, and so on. These were widely known, and you could easily find step-by-step guides in a fishy .zip file downloaded somewhere. You just had to follow the instructions, and voila : game up and running. Sometimes things were messier, and (for example) a key was internally generated by the installer based on your comput- er's ID or any other serial number locally avail- able, and "embedded" directly in the executable. If you were lucky and the application itself was not encrypted, such keys could be retrieved using a hex editor. Even though you were just following steps detailed by someone else, it was impossi- ble to suppress the feeling of being the ultimate hacker! (or cracker, I should say) The funny part of the story is that once games were successfully cracked, and properly working in my (offline) machine, I rarely played them. Some- times I didn't even adjust the settings, nor finish the tutorials. Compared to doing the crack playing there was zilch excitement in playing. It turned out that "making it work" was the actual game. After hitting the university, things started to make more sense to me and I could see "goals" every- where, so videogames dropped in importance, as did the act of cracking. At some point, I felt that designing my own (crappy and simple) parking detector, or a brightness controller circuit, was indeed way more amusing than shooting random enemies. Braid is a masterpiece that opened up parts of my brain hitherto unused. Concepts like propagation delay were never depicted so beautifully. If you do not know Portal, you should. It's a wonderful, mind-bending title that will change the way you look at the mirror every morning. Fez makes you solve puzzles and find your way alternating between 2-D and 3-D perspectives. You did that before, right? Well, this way, you didn't. Play Harder But hey, what I really wanted to say is: it's not a complete loss. My disappointment with videogames didn't last forever, and I've always wanted to recommend a few titles to my fellow geeks. If you still feel like playing videogames and you're up for some brain exercise, I compiled some mind-expanding games I love in a brief list. And no, I'm not talking about "The Incredible Machine," or mere puzzle games that obviously resemble circuit design. You probably had a tough day routing that PCB, but anyway: there's always time left for more challenges! Wanna see more screenshots, larger images, active links... Or you just feel like commenting and shar- ing this article with friends? Easy. Navigate to [http://po.st/playharder]. www.elektormagazine.com September & October 2015 111 SHARE German Brickwork Rapid e-prototyping with TinkerForge's Bricks and Bricklets By Clemens Valens (Elektor.Labs) Prototyping a complex electronics control system in a short time is possible by using ready-made modules specifically designed for this purpose. Today so many of these modular systems exist that it is difficult to spot the one that's right for you. Maybe the Brick & Bricklet approach from TinkerForge is what you are looking for? We tried it for you. The test system used in this article consisted of a DC Brick motor driver Rapid Prototyping seems to be a booming market, looking at the sheer number of tools that have been and are being devel- oped. Ranging from low-cost hobbyist approaches like Arduino to the highly professional tools from big-gun multinationals, a system tailored to your application and budget very likely exist. All these tools have the same objective: to make proto- typing electronics systems as easy as possible. One of the rapid prototyping systems that landed on my desk came from TinkerForge [1], a fledgling German company that's trying hard to go all the way. Although I am hard to impress, I must admit to liking the build quality of the modules that came out of the box. module and two Bricklets: Pushbutton and 'Rotary Poti' (potentiometer). What is it? TinkerForge modules are electronic building blocks that can be stacked and wired up to create a complex system. The modules by themselves do nothing, it is up to the user to write software to make the system work. This software is a PC application that can be written in a number of languages, from C and C++ right up to LabVIEW and Mathematica. Mod- ules come as Bricks, Bricklets, extensions and accessories. A Brick is a microcontroller module with a specialization (e.g. a motor driver); a Bricklet contains a sensor (e.g. a potentiom- eter) or an actuator (e.g. a LED). A typical system consists of at least one Brick to which Bricklets may be attached. The PC 112 September & October 2015 www.elektormagazine.com application communicates with the Brick, it sends commands to it and requests data from it; the Brick communicates with its Bricklets, if any. It is important to understand that a PC is invariably involved, and it's the PC running the application, not the Brick. Unless you invest in a RED Brick — a Brick capable of replacing the PC, but more on that later... A Brick can have a limited number of Bricklets connected to it, the exact number depends on the Brick, but Bricks may be stacked to add Bricklet connections. Bricklets on the other hand cannot be stacked and are connected with cables. That's logical, because they usually have to be mounted somewhere in the system, close to a motor, on a control panel, or similar. Stack- ing Bricks is also useful for adding functionality to a system. Extension modules allow the interconnection of Brick stacks as well as the control of a Brick or a stack over a network — great when the system is installed in a remote or inaccessible place but must be controlled from a control room. Finally, accessories are items like connectors, nuts & bolts, displays, etc. that are needed to complete a system and that may be obtained from other sources. The RED Brick with Wi-Fi dongle and SD card. Who is it for? TinkerForge modules are aimed at people who want to build something that needs electronics to operate, but who lack time, skills or a desire (all combinations apply) to design their own electronic hardware. The sub-species is called Makers these days, or tinkerers, which explains the name TinkerForge. Although the user is not supposed to have deep knowledge of electronics, some programming skills are required — actually, the more the better. Detailed tutorials are available to help you getting started, seasoned programmer or not. Applications can be written in C/C++, C#, Delphi/Lazarus, Java, JavaScript, LabVIEW, Mathematica, MATLAB/Octave, Perl, PH P, Python, Ruby, Shell and Visual Basic .NET. Mobile plat- forms are included too so you can also use C/C++ for IOS, C# for Windows Phone and Java for Android. I think there are only few products in the world that support more program- ming languages. What can you do with it? Is it better? To answer these two questions it best to play with the system. Flere's what I did. I started with the First Steps tutorial from the website. It employs the DC Brick and so did I. This Brick is not a power supply for a stack as I had assumed, but a Brick with an on-board DC motor driver. Connect the Brick to the PC using its mini USB port; connect a DC motor to the spring connectors (beware, they are rigid). Now some software must be installed: • Brick Daemon (brickd) — a little program running in the background that handles the communication between the Brick and the user application. • Brick Viewer (brickv) — a nifty tool showing the configu- ration of the system, which Bricklet is connected to which Brick, etc. It also provides interfaces to control the Bricks and Bricklets. Brick Daemon starts automatically when you connect a Brick, while Brick Viewer must be launched manually. Click its Con- Stack 'em! RED Brick (bottom), Master Brick (middle) and an Ethernet extension module (top). nect button to make contact with your Brick system. Now the Brick should show up in the tree and a user interface tab for it should be available too. The viewer also shows the Brick's UID which you will need when you write your own applications. It is the handle by which you address an object in your system. By activating the user interface tab of the DC Brick in the Viewer I was able to control the speed and direction of my little motor. Next step is to check if you can achieve the same thing by writ- ing your own application. In what follows I assume that you know the basics of the programming language you picked, and that the necessary compilers/interpreters are ready installed on your computer. Kick-off is installing the API bindings for your programming language. Detailed instructions on how to do this for your pro- gramming language are available on the TF website. I chose to use Python 2.7, Python 3 is supported too. To test if everything works, download the examples for the pro- www.elektormagazine.com September & October 2015 113 SHARE The Brick Viewer connected to a DC Brick that has two Bricklets connected to it. Note the UIDs you will need for programming. gramming language of your choice. Since I was playing with the DC Brick and Python, I tried the script example_confi g- uration.py. It must be edited to work with your setup and you need Brick Viewer for that. Open the script in an editor and edit the parameters HOST, PORT and UID to match the information found in the Viewer. HOST and PORT are probably correct, but not the UID which is unique for every module, so change it and save the file. If you run the script, the motor will start spinning. When you press the script is halted, but the motor keeps running. You can stop it manually by entering the following commands on the Python command line: >>> ipcon = IPConnecti on ( ) >>> dc = DC(“6qCdtB” , i peon) >>> i peon . connect (“local host” ,4223) >>> dc . set_veloci ty (0) The first three lines mark the steps that have to be taken to establish a connection with a Brick (note the method of using the HOST, PORT and UID parameters); the last line stops the motor. To clean up after yourself, issue the command >>> i peon . di sconnect ( ) When experimenting with the DC Brick do not forget that you must enable the motor before anything happens (why?). Use the command dc.enableQ to do so. If you have gotten this far, then you are ready to explore the rest of the TinkerForge products. Bricklets There exists a substantial number of Bricklets, and there will be more in the future. Examples are the Analog In and Analog Out Bricklets, the Barometer, Distance, GPS, 1016, Joystick Bricklets, and many more. As already said, Bricklets connect to Bricks and only to Bricks, excepting the RED Brick: a spe- cial Brick that does not accept Bricklets. The Master Brick can have up to four Bricklets attached to it, the DC Brick only two. The connection between the Brick and the Bricklet is through a 10-way cable that is hard to manufacture yourself so it is eas- ier to buy; it comes in several lengths. Disconnect the power to your Brick before connecting one or more Bricklets. I connected the potentiometer Bricklet "Rotary Poti" (German origins, remember?) and the Dual Button Bricklet to my DC Brick. After powering the Brick and reconnecting to it in the Viewer, the Bricklets showed up too, hanging under the DC Brick. Also a tab for each Bricklet was added. The potentiometer tab shows a graph of the potentiometer's position (in degrees) and the dual button tab allows you to activate the LEDs on the Bricklet and control the way they work — all pretty neat. With the help of the examples provided it is easy to create a simple application that controls the motor speed with the pot, and the pushbuttons to enable and disable the motor. The LEDs in the pushbuttons can provide visual feedback. Strangely though, the pushbuttons seemed to work the wrong way around or maybe I got something wrong. My example script can be downloaded from the article's webpage [2]. Extensions With Bricks and Bricklets you build a stack that can be used to do something, like controlling a motor as I just did. The stack is connected to a PC that runs the Brick Daemon and the application program. But how do you control a stack that is not sitting next to your computer? This is where Tinkerforge Extensions come in. These modules allow two stacks to com- municate and make the whole system look as if everything is right there on your desk. Currently there are four types: Ethernet, Wi-Fi, RS-485 and Chibi (an open-source wireless 802.15.4 communication stack that failed to achieve the pop- ularity the developers had hoped for). Extensions require the Master Brick — the DC Brick won't do. This is only a financial problem because you can stick a Master Brick on a DC Brick. The Ethernet Extension also works with the RED Brick. I tried the Ethernet Extension with the Master Brick and although everything seemed to be fine & dandy I could not figure out how to use it. The TF website says you can use your phone or some other mobile device to control the stack without the need for the Daemon, but there is no clue on how to accomplish this. Documentation is lacking here and so are the examples. I did discover a little trick to figure out the IP address of the Extension when it is in DHCP mode, i.e. when it gets an IP address assigned 'by the network'. Just change the Address box temporarily to Static IP and it will indicate its current con- figuration. Write it down and change the setting back to DHCP. Do not save the configuration. Since I didn't have any other Extensions to try I left the issue for what it is. RED Brick So far every Brick stack required a PC to run the applica- tion, which is not always desirable. Hence TinkerForge's Rapid Embedded Development (REDJ Brick, a special Brick that can run the PC application. Actually, it is a small Linux (Debi- an-based) computer that executes applications written in most of the supported programming languages (not the proprietary languages LabVIEW, Mathematica and MATLAB). The program can be written, debugged and tested on the PC. Once ready it can be transferred to the RED Brick where it will be executed without any changes. Programs can be scheduled (execution on boot-up, every hour, etc.) and monitored. It is even possi- ble to execute multiple programs simultaneously. If you have ever played around with Raspberry Pi or other embedded Linux systems you may the complexity and frus- trations of their configuration. TinkerForge solved this for their RED Brick by integrating an extensive configuration panel in the Brick Viewer. Thanks to this GUI it's a breeze to set up a Wi-Fi connection (just add a USB Wi-Fi dongle), and to see what's happening on the board. There is also a console where 114 September & October 2015 www.elektormagazine.com command-line warriors can enter Linux commands. Shutting down or rebooting the board is also handled here, but in a less obvious place: the System button in the right upper corner of the RED Brick tab. I say every embedded Linux board should have a configuration tool like this. Once you have the RED Brick connected to a network, either with a Wi-Fi dongle or by using the Ethernet Extension, and you have figured out its IP address, you can connect to the RED Brick web interface that shows information about the installed programs. You can replace this interface with your own; web applications written in HTML/JavaScript, Python and PHP are supported. The RED Brick also has an HDMI interface and if you connect a suitable display, the Brick will boot into a GUI. Our test kit came with a touch screen, but the touch part did not work even though the touch LED on the display said that everything was all right. Maybe a configuration to do somewhere? Stay in touch When you start playing with Bricks and Bricklets it is highly recommended to visit the General Discussion forum [3] on a regular basis (also available in German) because this is the place where software and hardware updates are announced. There is quite a lot of activity going on. When I embarked on this article I downloaded Brick Viewer 2.2.2, when I looked again two months later the version was up at 2.2.5 with many Brick firmware updates in between. Open source Everything related to Bricks, Bricklets and Extensions is open source. Consequently you have access to the source code of everything, and you can consult the schematics of every module. Conclusion Now that we know what we can do with the TinkerForge modules we can try to answer the one remaining question: Is It Better? It depends on your application. Personally I was impressed by this rapid prototyping system. It supports so many program- ming languages that anyone who has ever accomplished some programming in his/her life should be able to get cracking. There is plenty of well-written documentation, and examples galore. Fair enough, there are a few imperfections in the Viewer and yes, it is true that when it comes to the more advanced features you may feel a bit left out, but there is always Tin- kerUnity.org where you can interact with other users and the TinkerForge team itself. And did I say that the quality of the components is second to none? Hats off to TinkerForge! N ( 140543 ) Web Links [1] www.tinkerforge.com [2] www. elektormagazine. com/140543 [3] www.tinkerunity.org/forum/index.php m Brick Viewer 2.2.2 (h) Setup RED Brick UID: 34Jvdz Position: 0 Image Version: 1. 5 (full) Timeouts: 0 System. Refresh in 2.5., Status Uptime: CPU: Memory: Storage: | Processes 2 minutes 0 . 0 % 17.0% [82.30 of -183. 11 MiB] Top 5 r*H processes based on CPU usage Name PID User CPU Memor brickd 392 root 93% 0.1% parcellite 571 tf 03% 1.4% system d 1 root OjO% 0.4% kthreadd 2 root 0.0% 0.0% ksoftirqd/O 3 root 0j0% 0.0% . r m The Linux configuration interface of the RED Brick in the Viewer. The list of active programs includes the 'brickd' Brick Daemon. Here you can view what the potentiometer Bricklet is doing. The user interface for the DC Brick in the Viewer allows you to control the speed and direction of the motor. www.elektormagazine.com September & October 2015 115 SHARE Selected Gerber Files from the Labs By Thijs Beckers (Elektor Labs) Recently as a trial a few 'Gerber' PCB manufacturing files became available through the Elektor online Store. What can you do with them and how does it work? Gerber files are a set of documents that describe how a PCB should be manufactured. They contain descriptions of the various layers of the PCB, like bottom and top copper layer, silk screen layer, solder mask layer, drill information and des- criptions of any extra layer you can think of that is needed for the production of a PCB. The data is saved in a 2D binary vec- tor image open file format. Currently the "Extended Gerber or RS-274X" is the standard industry format. Although a depre- cated "Standard Gerber" format exists, it should be avoided. The Gerber file format was originally developed by the Ger- ber Systems Corp., a division of Gerber Scientific, founded by Joseph Gerber — hence the name. It was designed to drive their vector photo plotters for the PCB industry in the 1960s and 1970s. As Gerber was the market leader at the time, its for- mat became a de facto standard for the industry. And it still is. With the decision to provide access to Elektor Labs' design data files and make a portion of our highly appreciated PCB manu- facturing files available through our online Store (www.elek- tor.com), we hope to stimulate the number of Elektor projects being replicated and so support the booming maker commu- nity. With the Gerber files available at cost through our Store you are now free to have a company of your choice manufac- ture Elektor PCBs exactly as Elektor Labs intended them to be. After all, we use the same set of files for our own prototypes and production. And because of this, you should not have any troubles having 'our' PCBs manufactured professionally by any PCB pooling service. Importantly, the new Gerber file service does not and will not cover all projects published in Elektor. The selection of PCBs supported is governed by Labs. At the time of writing the ser- vice is being rolled out and it is best to search for "Gerber" on the Store website; the items returned are what's available at the time of viewing. Due to the vast number of manufacturers out there we sim- ply cannot show how the ordering works with each and every one of them. As a quick start though we'll guide you through the ordering process with our 'Trusted & Approved' supplier Eurocircuits, which should be similar with your preferred manu- facturer (although the services of Eurocircuits are quite exten- sive and options may not be available at other PCB pooling manufacturers). \< ( 150342 ) V PRICE CALCULATOR O* LOGIN * REGISTER Step 1. Go to eurocircuits.com and select "Price Calculator" PCB proto ► 1, 2 or 5 PCBs in 2, 3, 5 or 7 working days ► 2 and 4 layers; 150pm technology Price calculator ■ Analyse your data j £i Launch inquiry Step 2. On the next page, select "Analyze your data". For single boards you can use the "PCB proto" or "NAKED proto" service. Price calculator | Analyse your data j Launch inquiry Analyse your data PCB name * Upload data file e Purchase reference * Article reference Project reference * Delivery term Quantity * * Mandatory field. 120272-1 Choose File * 120272-1 ...s vl.O.zip First batch Elektor Universal Pream My Board 7 Working days $ 2 Continue Step 3. For Eurocircuits to be able to combine the Gerber files you are about to upload with your personal data (like shipping address and billing), you need to register (or if you're already registered, log in). Step 4. After logging in, the website takes you to a form where you submit your project and PCB data and upload your Gerber files. Before uploading, compress them into one zip file. 116 September & October 2015 www.elektormagazine.com FROM THE LABS fffetxanicA WEB SCOUTING UPDi Price calculator Shopping basket j Checkout items Shopping basket - To start the manufacturing process, select an item(s) and "Proceed to checkout" ! Proceed to checkout •i» View details Download PDF offer I Edit administrative details I O Ask a question Number Item name Service Status Created Items ready for checkout ■ PCB Visualizer® Offer Number Type Status Item name Service Quantity Delivery days Unit price Net price Stencil PCB Visualizer® £ B0433027 PCB Ready to checkout 120272-1 PCB Proto 2 7 Working days 33.68 67.36 You can order all jobs with status 'Ready for Checkout' immediately, even when the PCB Visualizer process is still running or failed. Items in analysis No record(s) found. Visualizer link in [Visualizer] column lets you view PCB layers visually, during processing you will not be able to modify your data files. . Step 5. After submitting your data, clicking 'Continue' takes you to an overview of your submitted data. Eurocircuits offer you extensive preview options for your PCB using their 'PCB Visualizer'. This tool lets you check beforehand for any possible hiccups and difficulties in the production process. Now tick the designs you wish to proceed with (you can add multiple boards to your order and review them before checking out) and click 'Proceed to checkout'. Price calculator Shopping basket Checkout items Add new address Delivery address Invoice address Elektor International Media - 1, AlleeKasteel Limbricht, Limbricht - 6141 AV, Netherlands X 11, Postbus, Susteren - 61 14 ZG, Netherlands A ▼ Elektor International Media Elektor International Media BV Step 6. The final things for you to complete the order are to check your shipping and invoice addresses, and click 'submit'. Then your professionally produced PCB(s) should be on their way to you soon! 3 Visualizer® vl J-1 1 3-15070 1 CPC8 Configurator OPC8 Checker Customer data kf Imported 6 layers PCB proto Delivery format Single PCB X Delivery .-g 7 workings : larm — 1 ° * PCB width (X) (mm) cC-rcgistration compatible PCB Commercial details 90.00 Measured: 90.00 mm PCB quantity Number of layers Board name Measured: 90.00 mm 1 120272-1 Board name 120272-1 (B0433027) Dataset: Customer data X Board buildup ► Stencils T Material Board thickness 1.55 mm X Materiel Tg us-i sox : Outer tayer * copper foil ► Technology | / Classification | ▼ PCB definition | / PCB PIXture | Top view Top legend Top aotfermosk Top coppe* Total material thickness: 1.SS mm Bird ' s Eye View Top soldcrmask Green ; Measured. One r red Top legend White : Mrnortd: Deferred .J .. Green J soldermask MMPunMb Deferred Bottom legend None : Weesured Hot Summary € 67.36 ^ 1 Saw change* Click the ' launch inquiry ' button in cose you are having troubles configuring your PC B Our sales team mil review your input and generate an offer. Eurocircuits' PCB Visualizer shows your PCB's production details and lets you spot and correct issues beforehand www.elektormagazine.com September & October 2015 117 SHARE It's Time to Know a Little More This astronomical clock provides a ton of information based on the coordinates of your current position, and it shows everything using no fewer than four displays! Greenwich time, zodiac sign, time, day, city, season, humidity, temperature, atmospheric pres- sure... it even changes its appearance depending on the day cycles. Control freaks — this clock is for you! Introducing... Our New Drummer. He's Analog. Sure, music production software is con- venient, but moving sliders on a screen will never match the feeling of adjust- ing your own beats and twiddling with real knobs. This beatbox integrates 16-32 step sequencers with an additional MIDI control. We all know that analog is where it's at, so the 12 different sounds are generated by an analog source. Feeling nostalgic for the '80s? I In My Level Sensor I Trust ' Looking for a trustworthy level sensor to monitor liquid in a well or tank? This design consists on an emitter module and three receivers which get alerts gener- ated by three probes (high, low, and critical level/alarm). Apart from this, it can also activate a pump to avoid a flooded basement or automatically control the level in a tank, for example. If you just need a multilevel alarm, the circuit is scalable, so the first part of the circuit can work alone. It's been a hot, hot summer at dot-Labs, at least... M While summer is very much a local experience, electronics is global. So although we cannot claim that summer's been warm all over the globe this year, as far as soldering irons and Elektor Labs members are concerned, it's been a scorcher. To prove it, here's another compilation of projects that have been evolving at .Labs and already look amazing. And this raises the question: will Autumn be even hotter? Who knows! 118 September & October 2015 www.elektormagazine.com FROM THE LABS Don't Cross the Line, USB! You know you gotta keep those USB ports under control... and for that, a unit like this one really comes in handy. It's capable of measu- ring and limiting the current in two ports, according to user-con- figurable values, and prevents effectively against over current. Real-time values are shown in a display, but are also available via an FTDI USB-to-TTL 5V port for further analysis. An Electronic Swiss Army Knife If you need several features in one project, but don't want to split them in single boards... why not design a multi-tool that encompasses them all in one? Yes, that's the advantage of custom electronics! Remember the project 13-in-a-Box? Well, now 6 extra features got added, including a buzzer, voltage measurement, servo control, DCF77 decoding, Neopixel LEDs control, DS1820 temperature decoding and more. It just keeps growing and growing... All You Need Is... 8 Transistors To build an AM radio, we mean, with lots of fun guaranteed during the process. This project details the assembly and testing of a standalone superheterodyne AM radio: it's an excellent way to get your hands on the world of RF. The first four transistors comprise the reception stages (incl. the local oscillator), and the other four are a simple 3-stage amplifier. The circuit can be powered at 6 V by means of four AA-size batteries, making the project suitable for portable designs. .St/T-t-i It Was TTL Time This is the story of a digital clock that wanted to be analog, but could only operate with TTL ICs. Instead of the expected hour and minute hands the clock boasts a cir- cular set of LEDs. MCUs were obviously not an option (too easy, too mainstream!), but that didn't mean it was not user-configurable. Instead, a set of DIP switches was intended to change the LED patterns according to a coding system. A digital clock with an analog soul, and zero microcontrollers... but 100% cool! Bark at the Moon Remember Hacktor, the "convertible" PCB that turns into a dog — he's now ready to bark! Hacktor features an Atmel QTouch proximity sensor which detects when you're near, playing a barking sound with an audio playback IC and a speaker located in its "belly," flashing its LED eyes as well. It's built to hack, so it can be programmed via the onboard SPI header, and incorpo- rated easily in your own projects. Besides, it looks great on your desk, don't you think? N (150338) www.elektormagazine.com September & October 2015 119 SHARE Experimenter's Transistor Tester Elektor 2/2015 (March & April), page 56 (130544) ADDENDUM. Scarce mention is made in the article of the functionality of transistor Tl. After building the unit as specified in the schematic, this component has no special significance to the user. Tl is used for self-calibration under control of port line PA3, and its operation is evident from the project source code written in BASCOM AVR. On another note, there's also no reference to the frequency of the quartz oscillator of the Platino board, which has to be 8 MHz (this can also be checked in the project source code), [www.elektormagazine. com/130544] Err-lectronics Corrections, Updates and Addenda to published articles Compiled by Jaime Gonzalez-Arintero Typos, plain errors, postscripts ... even erroneous historical facts this time! For sure that's not our particular walk of shame. Although our target is to release flawless designs, that's not always possible. Luckily, we have our keen, eagle-eyed readers (you!) to check everything. Not once, but twice, and even three times. Thanks everyone for the contributions! UART/RS-232 Data Logger Elektor 4/2015 (July & August), page 52 (140126) UPDATE. Using Windows 8 and higher versions it may be impossible to install the USB driver for the Data Logger. The problem is Window's 'Driver Signature Enforcement' (DSE) that blocks the driver (which is not signed). To work around this problem you should disable the "Driver Signature Enforcement," which unfortunately is a rather complicated process. Luckily, there are many tutorials on the Internet that explain how to proceed. Please consider the patch linked to below. With DSE disabled, the driver should install without any problems. [http://po.st/disableDSE] J 2 B Synthesizer: an open-minded digital music platform Elektor 1/2015 (January & February), page 10 (140182) UPDATE. Elektor Labs Commander Clemens Valens has expanded the software of his popular J 2 B Synthesizer. Now there are three new firmware versions available in total, and one of them turns the synth into a (rudimentary) drum machine. These are 'ports' from Soulsby's Atmegadrum, Atcyclotron and Delayertron. Together with the original Atmegatron firmware there are now four unique synthesizers in one instrument. You can download the complete archive with all four firmware files via the original project at Elektor Labs, or via the link [http://po.st/J2Bv3]. USB Hub feat. RS-232/422/485 Elektor November 2014, page 10 (140033) CORRECTION. In the published schematic, the pin numbers 2 and 3 of the LM2937 regulator (IC2) are exchanged. The correct pinout is: 1 (INPUT), 2 (GND), 3 (OUT- PUT). The fixed schematic can be downloaded via the link below. The error does not affect the manufactured boards, or the rest of the files. [http://po.st/140033schematic] 120 September & October 2015 www.elektormagazine.com UPDATES From 8 to 32 bits: ARM Microcontrollers for Beginners (3) Elektor 3/2015 (April & May), page 13 (150041) CORRECTION. A single letter can make a big difference! Have a look at the Listing 1: In the configuration functions for the WDT and the EIC, you may find two iden- tical instructions (both in the second part of the code, with a few lines in between). Regrettably the port letter is wrong in both of these: 'B' is required instead of 'A'. Thus, both instructions should look as follows: config_extint_chan.gpio_pin_mux = MUX_PBxxA_EIC_EXTINTx ; Please note that the x's correspond to the pin number and the channel number. Instead of typing it to implement the correction, you can download the corrected code from the web page with this article. This error was spotted by the author; thanks Viacheslav Gromov! [www. elektormagazine.com/1 50041] USB-to-Multi-Protocol Serial Converter Elektor 3/2015 (April & May), page 92 (130542) CORRECTION. The text box 'What's a serial port anyway?' mentions that "connecting the terminals to the computer in an economical way and allowing a certain distance finally resulted in the well-known RS-232 standard." However, the RS232-C standard was originally specified as an interface between DTE (Data Terminal Equipment, i.e. end instruments, such as terminals or mainframes, servers, etc.) and DCE (Data Com- munication Equipment, i.e. data transmission devices, such as modems). This allowed two DTEs to be connected directly by means of a crossover cable. A big thank you to Ernst Stippl from Vienna for his (historical) rectification! :-) Simple AVR port toggle (Tips & Tricks section) Elektor 3/2015 (April & May), page 36 (150027) ADDENDUM. This trick is relatively old, since the first AVR microcontrollers bringing this possibility were already released before 2005 approximately. Digging into the ATtinyl3 datasheet shouldn't be too time consuming, since you can easily go to "I/O Ports," then to "Ports as General Digital I/O", and then check the section "Toggling the Pin" (sometimes also titled "Reading the Pin"). The Pin Registers may normally be found in the first 32 I/O registers (having an address under 0x20), and thus are still accessible at bit level. The expression PINB.5 = 1, used in the code, is converted by BASCOM into an SBI command. If the AVR MCU has a flash memory larger than 8 K, with a 2-word-wide IVT (Interrupt Vector Table) it's possible for example to tog- gle ports directly, by means of an interrupt in the IVT itself. If the pin is set as an input, the internal pullup can be enabled and disabled through the same procedure. Nevertheless, in some AVR series devices (approx. 2007 - 2010) the pullups could not be set via the data direction registers or the port registers, but via their own pul- lup enable registers. If an MCU pin is independent from the registers due to another function (such as a reset), but it's still accessible (working with the ATtiny 4/5/9/ 10, for instance). In this way we can still perform bit-wise XORs, for example to calculate or check a parity bit. Stefan Rosenthal, thank you so much for pointing it out! TCA580 Integrated Gyrator Elektor 3/2015 (April & May), page 35 (150024) ADDENDUM. Our kind reader Christoph Kessler had the German application note for the TCA580 integrated gyrator, together with an awesome 5-page datasheet, so he sent us the scanned files. These were released back in 1974 so if you're feeling nos- talgic you should definitely give them a look. Both files are available for downloading via the link below. And once again, thanks Christoph! [http://po.st/TCA580DE] (150288) www.elektormagazine.com September & October 2015 121 SHARE SMD Codes Revealed What's that under the magnifying glass? Harry Baggen (Editor, Elektor Netherlands) Components are forever decreasing in size and this has the unfortunate consequence that there is also less space for the clear marking of the part type or value. So short codes are used instead, but they are often not that easy to decipher. With the help of the websites that we describe here the identification of SMD components is made somewhat easier. Modern electronic circuits contain SMA (Surface Mounted Assembly) components (SMDs) almost exclu- sively to reduce production costs and to decrease the size of the device. Although leaded components are still available, provided they are fairly standard parts, they are nevertheless becoming increasingly harder to obtain. Semiconductor man- ufacturers typically introduce (new) parts into the market only in SMD packages and then as a developer or hobbyist you have no choice: you have to work with SMD parts. When SMDs started to play in increasingly important role in the 1990's in the electronics industry, many electronics enthusiasts feared that this would be the end of building small production runs or prototypes. But it wasn't all as bad as that. With some patience, some experimenting and the purchase of some new tools it turns out that working with SMD components by hand is quite possible. In the meantime the parts have become even smaller, but this is (still) not a limitation when building a prototype or repairing an electronic circuit. Because of the tiny dimensions of SMD components, many electronics enthu- siasts do require stronger glasses, a magnifying lens or even a microscope when working with these smaller parts. A problem with SMD parts is the device marking. Because there is so little space on the package, the manufacturers have resorted to all kinds of cryptic markings to indicate the type number and these are not straightforward to decode. When you order new components for a project, then the packaging will always clearly indicate the part number. But individual SMD components, and when repairing boards with SMD parts, it is difficult to establish what a particular component exactly is. To help with this we searched for a number of websites which will explain the abbreviations. Resistors and capacitors Let us start with SMD resistors. These use a 3- or 4-digit code, depending on the tolerance of the resistor. The design has a strong resemblance to that of leaded resistors: the difference is that numbers are used instead of colors. The first 2 or 3 digits indicate the value and the final figure is the multiplying factor. For 1%-resistors the EIA-96 code system (3 characters) is often used these days, where the characters no longer cor- respond to the value; a letter is used for the multiplying factor. On the website of Your Hobby-Hour [1] you will find a short explanation and a table for the EIA-96 values and importantly also an 'SMD resistor code calculator' which will translate the printed code into a sensible resistance value. On the website resistorguide.com [2] there is also a clear explanation about resistor codes, including a video which briefly explains the important details. EIA-96 system 38C Significant values Multiply factor I -aw*. res i sto rg u i d e.cow- Code Value Code Value Code Valu< Resistance = 243-100 01 100 17 147 33 21 S| ' 02 102 18 150 34 2211 03 105 19 154 35 226 \ 04 107 20 158 36 232 \ 05 110 21 162 37 2ZL \ 06 113 22 16^" 38 2m 07 115 23 169 ~w ml 08 118 24 174 40 255 / 09 121 25 178 41 261 / 10 124 26 182 42 267| 11 127 27 187 43 274\ 12 130 28 191 44 280 \ 13 133 29 196 45 287 \ 14 137 30 200 46 294 15 140 31 205 47 301 16 143 32 210 48 309 c mmsmm Z 0001 Y/R 0.01 XJS 0.1 A 1 . B/H IQ C 100 i i n ir E lO'OOO F lOO'OOO yoi t guide !o the world of reealore 122 September & October 2015 www.elektormagazine.com WEB SCOUTING W Because there is so little space on the package, manufacturers have resorted to all kinds of cryptic markings With capacitors the situation is already much more complicated. The larger capacitors, such as electrolytics, are not a problem; there is usually sufficient room on the component to print the capacitance value and working voltage. With smaller Cs the same coding (3 numbers) as for resistors (see [3]) is sometimes used, but more often than not there is no marking at all (this is also true for small inductors)! The only solution then is to unsolder the component and measure its value with a capac- itance meter. The maximum operating voltage remains an unknown. Based on the color of the pack- age it is often possible to estimate in which capacitance range this particular capacitor is, without having to measure this [4]. Semiconductors With smaller SMD parts that have 2, 3 or more pins (diodes, transistors, small ICs such as opamps, voltage regulators and reset-circuits) determining the correct part number is much more difficult. Most SMD parts are printed with a two or three character code, often complemented with a few smaller characters which indi- cate the production date and batch number. Because only so few characters can fit on a component and there are so many different components, it is not possible to uniquely identify a particular component based on this short code. On various websites there are overviews and tables which contain a large number of character combinations and the potential type numbers and manufacturers that they indi- cate. Certain combinations have up to 20 possibilities. It then becomes necessary to carefully compare the package shape with the datasheets for all the components with these mark- ings and possibly also study the schematic of the circuit that contained the component in order to discover what kind of component it is/was. The SMD Codebook [5] is an 80-page long document (PDF) that after a few pages of general introduction is full of tables with codes. For each code it indicates the (potential) type number, the manufacturer, the package type and the techni- cal details. The Codebook can be found on several websites, s-manuals.com ■s««h 1 !h» fun 2 vymbcl mirtUnfl SMU tf >F 3 4 5 « 7 s 9 |a|b|c FFF d[FFFFFFF FF P 0 R s FF FF FF z 7 - |o|m FF 03 04 K OS 07 09 09 » |:t 1 jeo (in I I«j |(K ft rr Ofl FF av |«vy « 1 1* k n |u 12 13 If U If u k |iu lie lfi |u [u |ia |ia | |u |is 11 |l“ T !r ua 13 u k i y |ai L5 k \L "Z - - l> t ,F a V 29 27 29 29 FFF 1 F a. k » r 2Q 2fl r F !Y k FF I j \.j 21 |u 22 a £ £ 21 M 2S lis b b x |x |a lx lx | \u |x rrFFrrrr X U rr ^ i rr £ £1 £t iiT r k |* |« *! |*2 « a it « 41 49 |» k i 45 rr n |w IF 4* U k 21 |*2 u £ £ U 01 31 k |ic k & |it | a |i f |u e FFFFFFF a k »r 2 £1 33 u k jy k as k U il i I7F |&2 a « B ■ fiZ &fi a k |« |a a. k a | g OS fu E 1 a |ai £5 k 02 L* fc FF £1 |b a M a n rr n rv |f* |/0 |/i. ro |rt |" | | B |m jm Fr rr rn a Fr rv | nt |rc U L 1* k FF U- it ps 03 04 03 fc 01 00 09 [> |i£ |& oc |:c k k k k |u k a. |a< » i l£ OQ OS 05 a k at k a k oz 1. 93 94 » 99 07 99 99 |m |» \k *FFFr rr »r If rr Fr rF 9 kh |62 *2 aj *£ |v- I' . |&£ *s k k |*5 k k k k n. k t* i A£ *s5 cj k k AS |ai tz FF FF BJ B5 B9 e* w » k |m \k pc |k |y |pc |e- |p> |p: k PC |p« S» |» BP BC S3 f k SY Iff// sx |sy B Z B’ 1 1 tik £3 £i £3 ££ £1 a S3 |ii |ui k cu k k k k r k k a. k U |ui ££ £9 £S £5 a k at k u k U C - FF Cl |C2 D2 D« K - w W U l« |k » k k k k 1 k k n. |w Off |oo DP N D5 ct |w w |tw BX k QZ e- U k u |u U Li L3 ta u Li Li |la |u |u E k k k k l ,j k k u k ip k L? ta ta L3 u k ty k LS k U c - - [f|7 It |f2 □ l£ B Efi u a a |fi |s k ee k k k k 1- k k a k a k EP ta ES E5 a k cy k a k a |c |<» SJ |« W CH <* QJ c* C9 |«a \at |oc so |« k k |w | k k k an | our will be focusing on the lighter side of electronic at all those entertaining (and in no way pointless) ou busy in the lead up to summer. reaomow ^eGonzalez-Arintero oming Df° ne ublic) were RECENT NEWS AND ARTICLES . Linux for Rel‘ ability . The Qdo ino Mlni ojoe pci' READ M 0 ” 6 Also, launching right from each article or news item that's part of the Special on the mag- azine website, there is a small banner that will lead you to the Select Page. It is easy and comfortable to use. We are open for any sug- gestion from our read- ers and would like to get input on themes, subjects or types of content you would like us to Select for you! Let us know your suggestions through webmaster@eimworld.com! Cool Summer Deal Campaign with extra intensity in memberships and products in peripheral networks inviting companies inside and outside Germany to Elektor works closely together with more than 1,000 experts and authors for the publication of books, articles, DVDs, webinars and live events. In each installment of Elektor Word News we put one of them in the limelight. Name: Jason Long Age: 37 Education: Electrical Engineer (B.ScEE) Publications: Large library of online tutorials Training: PIC, ARM, ANT+, BLE, LabVIEW, low power embedded design and intrinsic safety I'm a Canadian who absolutely loves embedded systems. I've celebrated that passion by teaching others as a volunteer for the last 15 years and started Engenuics Technologies in 2010. I have two young boys already fascinated by blinking LEDs. What will be the most key electronics development? I think Personal Area Networks through NFC and very low power radio protocols like ANT+ and BLE are going to drive the explosion of the Internet of Things. Embedded developers flu- ent with hardware and firmware design will be in big demand. What was THE development of electronics? Over the last few years the ARM Cortex family has been hugely significant, especially with devices like the Nordic nRF51 that puts everything you need together with low power wireless (I don't work for Nordic, I just love that part!). What makes Canada different from the US in terms of electronic innovations? Maybe innovation in Canada is driven by people's passion, while in the US it's capitalism? I'll buy beer if I just offended anyone. But really, innovation anywhere comes from a desire to connect to people through great products & service. Suppose you get $500 to buy stuff in the Elektor Store: what's it going to be? Why? Oh man — that's the greatest gift an engineer could get. One of the top things on my to-do list involves quadcopters, so your Crazyflie 2.0 looks pretty sweet. Who is your most admired developer of the world , living or dead? Why? I'm a bit weird because I've never identified with particular individuals. The people I admire are the hobbyists and engi- neers with the passion and commitment to figure stuff out and make things. What's the project you are most proud of? Why? I've evolved our "Razor" / "Blade" development platform over many years and I think it's really solid. I think it fills a gap for engineers as they move from the hobby world or academics into product design in industry. M ( 150344 ) Who is Jason Long? www.elektormagazine.com September & October 2015 129 With summer vacation or camp well behind us, we can return to business as usual. As far as your spare time is concerned, the technology in this edition and a fresh Hexadoku puzzle should keep you busy for a good eight weeks. Find the solution in the gray boxes, submit it to us by email, and you automatically enter the prize draw for one of five Elektor book vouchers. The Hexadoku puzzle employs numbers in the hexadecimal range 0 through F. In the diagram composed of 16 * 16 boxes, enter numbers such that all hexadecimal numbers 0 through F (that's 0-9 and A-F) occur once only in each row, once in each column and in each of the 4x4 boxes (marked by the thicker black lines). A number of clues are given in the puzzle and these determine the start situation. Correct entries received enter a prize draw. All you need to do is send us the numbers in the gray boxes. Prize winners The solution of Hexadoku installment 4/2015 (July & August) is: 981B4. The €50 / £40 / $70 book vouchers have been awarded to: Gerard Lodder (Netherlands); Karl-Josef Wernet (Germany); Olivier Chaufouraux (Belgium); Pascal Jordil (Switzerland) and Dirk Petig (Germany). Solve Hexadoku and win! Correct solutions received from the entire Elektor readership automatically enter a prize draw for five Elektor Book Vouchers worth $70.00 / £40.00 / €50.00 each, which should encourage all Elektor readers to participate. Participate! Ultimately October 30, 2015, supply your name, street address and the solution (the numbers in the gray boxes) by email to: hexadoku@elektor.com Congratulations everyone! 0 3 8 4 E 1 7 2 F S C 9 6 D A 7 8 0 7 0 4 C 6 7 1 8 1 4 A E 2 B A 1 6 9 5 4 C C 4 5 F 0 B 3 1 7 D 0 5 D 6 8 2 7 4 F B 1 E C 8 7 9 1 D 7 E 6 4 3 5 C 9 2 A 4 5 8 0 C F 1 A E 6 6 3 1 5 A D 0 8 F B D A 3 5 6 7 A 5 1 7 5 2 7 B F E 8 4 3 9 1 0 E 6 3 A F B 3 8 C A 4 0 6 E 2 D 9 F 7 5 B 1 D E 9 7 5 F A C 0 1 6 B 8 2 4 3 6 F 1 5 B 7 D 2 3 4 A 8 C 0 9 E B 2 0 4 8 1 3 9 C E 5 7 F 6 A D E 1 3 B F 2 7 A 4 5 D 9 0 C 6 8 C D 2 6 9 8 1 4 A F 0 3 B E 5 7 4 5 7 9 0 C E D B 2 8 6 1 3 F A 0 A F 8 6 3 B 5 E 7 1 C 9 4 D 2 2 0 8 F A 9 4 6 5 3 7 E D 1 C B 5 4 D E C B 8 7 6 9 2 1 A F 3 0 1 6 A C D 5 2 3 F 8 B 0 E 9 7 4 7 9 B 3 1 E F 0 D A C 4 5 8 2 6 8 B 4 1 E A C F 7 6 3 5 2 D 0 9 F C 6 0 2 D 9 8 1 B 4 A 3 7 E 5 9 7 E D 3 6 5 B 8 0 F 2 4 A 1 C A 3 5 2 7 4 0 1 9 C E D 6 B 8 F The competition is not open to employees of Elektor International Media, its subsidiaries, licensees and/or associated publishing houses. 130 September & October 2015 www.elektormagazine.com Professional Quality @ Discount Prices! J i 7reichelt .co.uk elektron ik A &UB&ceiBe now' Newsletter Receive weekly fresh information about product Innovations Vy specials Price reductions IEI PROXIMITY SWITCH g POSITION SENSOR B FLOW | HAIL EFFECT ULTRASOUND | FORCE ^ More than 45 years of experience 24-hour shipping More than 50,000 products Hall effect sensors Radiometric sensor, Honeywell linear • Operating voltage: • Power consumption: • Operating temperature • Linearity: • Response time: Housing: TO-92, Output: 0.2 V/1.5 mA Order Magnetic Sensitivity number range SS 496 A1 2,75 € (~ 1,93 GBP) ±84 mT 2,5 mV/G SS 495 A 1 ,40 € (~ 0,98 GBP) ±67 mT 3,1 25 mV/G SS 495 A1 2,65 € (~ 1,86 GBP) ±84 mT 3,125 mV/G Radiometric sensor, Honeywell linear, SMD • Operating voltage: 2.7 ... 6.5 VDC • Power consumption: 10 mA • Operating temperature: -40 ... +100 °C • Linearity: 1 % typ. • Response time: 3 ps Housing: SOT-89 Output: 1.0 V/1.5 mA Order number SS 59 ET 1 ,40 € (~ 0,98 GBP) ±65 mT 1 ,0 mV/G Hall effect sensor, Honeywell digital, SMD m m m Magnetic Sensitivity range Temperature-compensated digital hall effect sensors unipolar, housing: SOT-89 Output: 0.4 V/20 mA Order number SS 543 AT SS 549 AT 1,40 € (-0,98 GBP) 2,65 € (-1,86 GBP) m Magnetic range 7.5 ... 18,0 mT 23.5 ... 39,0 mT Hall sensors SIEMENS Housing: P-SSO-3-2 Order Magnetic number range TLE 4905L 0,60 € (~ 0,42 GBP) +17 m T unipolar TLE 4935L 0,63 € (~ 0,44 GBP) ±20 m T bipolar/ latch Inductive proximity switch Excellent inductive sensors for contactless detection of metal parts for daily use in automation solutions. Ideal for use in demanding ambient conditions. Excerpt from our product range. For the entire product spectrum please visit: NO contact/PNP Order number 0 x L Switching distance Installation DWAD 623 03 66,80 € (-46,79 GBP) 0 3,0 x 22 mm 1 ,0 mm 2 m cable flush DWAD 623 04 51 ,40 € (~ 36,00 GBP) 0 4,0 x 25 mm 1 ,5 mm 2 m cable flush DWAD 623 M5 51 ,40 € (~ 36,00 GBP) M5 x 25 mm 1 ,5 mm 2 m cable flush DWAD 503 Ml 2 47,90 € (~ 33,55 GBP) M12 x 50 mm 6,0 mm 2 m cable semi-flush DWAS 623 M8 001 32,90 € (~ 23,04 GBP) M8 x 45 mm 2,0 mm M8 plug, 3-pin semi-flush DWAS613 M8 001 30,80 € (-21,57 GBP) M8 x 45 mm 2,5 mm M8 plug, 3-pin not flush DWAS 513 Ml 2 47,80 € (~ 33,48 GBP) M12 x 60 mm 10,0 mm M12 plug, 4-pin not flush Light barrier 0xL 18x50x50 mm CONTRIVE) Humidity sensor 0 — 100% rF, TO 39 Through-beam light barrier, 2 m cable Switching Switching Order number distance method Digital humidity sensor with 1C interface in pressure-resistant T039 housing (up to 16 bar), suitable for dew point measurement. Order number HYT 939 29,90 € TO 39 LLK 5050 000 23,30 € (-16,32 GBP) 15000 mm Transmitter LLK 5050 003 35,99 € (~ 25,21 GBP) 15000 mm antivalent, PNP Pressure sensors, UsV 4.75-5.25 Reflective light barrier, 2 m cable LLK 5050 1 03 42,40 € (~ 29,70 GBP) 800 mm antivalent, PNP t ' freescale semiconductor Distance Sensors SHARP Very high reliability and higher precision compared to conventional Sensors GP2Y0A Measurement LxBxT Order number range ( cm ) (mm) Order number DMC01-SC150 2,15 € (~ 1>51 GBP) 3-pin, Connection cable Order number PR Sens kPa mV/kPA Lin % MPX5010DP 11,60 € (-8,12 GBP) 0-10 450 ±5 MPX 5050DP 14,90 €(~10,44 GBP) 0 - 50 90 ±2,5 MPX5100DP 1 4,90 € (- 10,44 GBP) 0-100 45 ±2,5 MPX 5500DP 9,35 € (~ 8,55 GBP) 0 - 500 9 ±2,5 Ultrasonic sensors Ultrasonic ceramic transmitter and receiver for 40 kHz 0 9,9 mm, H 7,1 mm Order number MUS-40E 3,05 € (~2,14 GBP) Receiver MUS-40S 3,05 € (-2,14 GBP) Transmitter Daily prices ! Price as of : 27.07.2015 Prices in € incl. statutory VAT, plus shipping costs reichelt elektronik, Elektronikring 1, 26452 Sande (Germany) Payment Methods: Order now! www.reichelt.co.uk BANKING VISA amazon P PayPal Order Hotline: +49 (0)4422 955-360 v- -- V ■■ - ■ -» s* f . i ^-L Sr* 1 1 i JjSS; ' b'l S£ : if* ‘t ” v ; '\ & ^ ' r wj j KX . - * Viaabt' The Proteus Design Suite now includes full support for data exchange with Mechanical CAD packages via the 5TEP/IGE5 file formats. This allows you to better visualise your design and helps quickly salve fixtures, fittings and casement problems. Import 3D 5TEP/IGE5 models for your parts and visualise inside the Proteus Design Suite. Export your completed board to Solid works or other MEAD software. Visit www.labcenter.cam Tel: +44 01756753440 E-Mail infa@labcentBr.cani Laiicenter Electronics Ltd, 21 Hardy Grange^ EKD21 5AJ fclcctronVcs www.labcenter.com