March 2012 AUS$ 14.90 - NZ$17.90 - SAR 105.95 " NOK102 £4.90 New series: SDR for the Electronics Lab PTiffeisronisi jijs kx gyjn Dinvimicno: ndroid smartphone as a remote control or user interface for your microcontroller projects The perfect circuit to learn about & reinvent the pleasure of electronics Platino in Arduino Land A guide to integrating custom hardware 770268 451 73 0 3 lektor Brought to you by Eurocircuits rvice The European reference for PCB prototypes and small series Speed up your design cycle and keep costs down using our fast, easy-access online PCB pooling services. We deliver: • Top quality PCBs at low pooling prices • Fast deliveries to suit your requirements • Comprehensive technology support • No set-up or tooling charges • No minimum order charge - order from 1 PCB • Online ordering without pre-payment • Stencil service PCB proto - dedicated engineering prototype service , fast and low-cost • 1 or 2 PCBs in 2, 3, 5 or 7 working days • DRC-checked and fully finished with 2 soldermasks and 1 legend, 150|jnn technology • 1 x 100 x 80mm in 7WD - 2 layer 47,02 € - 4 layer 95,52 € • 2 x 100 x 80mm in 7WD - 2 layer 36,89 € each - 4 layer 74,76 € each Prices quoted include 2 1 % Belgian VAT but exclude transport costs STANDARD pool - widest choice of Eurocircuits pooling options • 1-8 layers 150pm technology PCBs • from 2 working days TECH pool - all the benefits of pooling for high-density PCBs • 2-8 layers 100pm technology PCBs • from 4 working days IMS pool - aluminium-backed PCBs for high heat-dissipation (LED) applications • Single layer Insulated Metal Substrate PCBs • 1.5mm aluminium base with 75|jm thermally conductive dielectric and 35pm Cu foil • from 3 working days On demand - multi-option non-pooling service for specialist needs • 1-16 layers down to 90pm technology • RF and high Tg materials • from 2 working days www.elektorPCBservice.com IN-CIRCUIT EBUGGER ^DU/ (51 \l POWER SUP *(IJi PLY ^ V) 1 f t f mikro iilBUS & mikro BUS Our famous PIC development board enters it's 7th generation of development. State of the art design, funcionality and quality are it's best POWERFUL ON-BOARD mikroProg™ PROGRAMMER AND IN-CIRCUIT DEBUGGER CAN PROGRAM ALL PIC10, PIC12, PIC16 AND PIC18 MICROCONTROLLERS. OUTSTANDING PERFORMANCE AND EASY OPERATION ARE AMONG IT'S TOP FEATURES. YOU WILL NEED IT, WHETHER YOU ARE A PROFESSIONAL OR A BEGINNER. JUST PLUG IN ONE OF YOUR CLICK BOARD™, AND IT'S READY TO WORK. SPECIALIZED mikroBUS™ COMMUNICATION INTERFACE MAKES YOUR DEVELOPMENT EASIER, AND ALLOWS SIMPLE, YET HIGHLY EFFECTIVE CONNECTIVITY. EVERYTHING IS NOW JUST A CLICK AWAY! EasyPIC connectivity features. With four connectors for each port EasyPIC v7 has an amazing connectivity. Port headers are logically grouped with their corresponding LEDs and Buttons. Powerful on-board mikroProg Tm In-Circuit Debugger and programmer supports over 250, both 3.3V and 5V devices. Three types of displays. Serial EEPROM, two Temperature Sensors, Piezo Buzzer, USB connector, RS-232 and FTDI, Oscilloscope GND pins, as well as mikroBus Tm support make this board an irreplaceable PIC development station. Nlikrollektronika get it now DEVELOPMENTTOOLS I COMPILERS I BOOKS WWW.mikrOe.COm DUAL POWER SUPPLY EASYPIC V7 IS THE ONLY DEVELOPMENT BOARD IN THE WORLD TO SUPPORT BOTH 3.3V AND 5V MICROCONTROLLERS. SMART ENGINEERING ALLOWED US TO SUPPORT OVER 250 MICROCONTROLLERS IN A SINGLE BOARD. IT'S LIKE HAVING TWO BOARDS INSTEAD OF ONE! AAA/A Rating achieved - no laurels awarded Elektor at the core is a cheerful conglo- meration of elecsmiths and wordsmiths, each striving for supremacy in prin- ted matter as well as online activities but always aiming to strike balances between quality and quantity, tech and play, beginner and pro, commercial and non-profit, and nice-to-knowand need- to-know. While debating the content of the current edition (and determining its balance) with some colleagues I wondered if Elektor could benefit from a ratings bureau of the Standard & Poor’s variety, so overrated these days for their high school grading of whole nations. Having seen a few critical TV docu- mentaries on rating bureaus and their earnings from other people’s misery, I thought I’d try a personal rating first of this very edition of Elektor. Without too much trouble and by looking at article titles only I was able to give it an AAAA rating. Here we go. AVR: not even Atmel’s USA head office knows what it stands for, but who cares if one of these ATtiny micros can be made to ‘do’ Software Defined Radio like we describe on page 16 in the first part of a new series. Arduino: few people know about the Italian (!) origins of the name, but who cares — it’s a great platform that’s suc- cessfully pulled lots of newcomers into the world of embedded programming and project building. On page 48 Elek- tor’s Platino enters Arduino Land. Android & AndroPod: there’s about five people left knowing the original Greek (!) word, the rest are buying the product on the premise of “24/7 connectivity with the world”. So on pages 24, 36 and 43 you can see what real interfaces for the Android look like and how they work. In my school days, learning one’s ABC meant starting from A you had to reach Z in a sort of orderly fashion and without help from financial people. Today, the whole world seems content with the first letter only, if possible followed by a + sign. Enjoy reading this edition, Jan Buiting, Managing Editor 6 Colophon Who’s who at Elektor. 8 News & New Products A monthly roundup of all the latest in electronics land. 14 DesignSpark chipKIT™ Design Challenge A global electronics design competition brought to you by Circuit Cellar, Elektor and RS Components. 16 AVR Software Defined Radio (1) Making a microcontroller ‘do’ SDR goes beyond receiving any old shortwave station on a PC. Here we kick off a fascinating series starring a simple AVR micro. 24 Android Switch Interface Smartphones are little computers totally designed for ‘connectivity’ we are told. And that’s exactly what our project aims at: remote control! 30 EasyPIC V7 An extensive review of the latest development board in the EasyPIC series from MikroElektronika. 34 Hard Disk Activity Monitor This simple circuit provides a visual indicator of that poor old hard disk having a hard time in terms of head and motor activity. 36 AndroPod (2) In this second instalment we discover the ease of making Elektor’s AndroPod respond to HTML and Java. 43 E-Labs Inside: AndroPod’s 3-way jumper An innovative arrangement of the traditional jumper pins on circuit boards. 44 E-Labs Inside: Wanted: SMPSU DC-out filtering Tuning switch-mode power supplies for cleaner output. 44 E-Labs Inside: Plug-o-(d)rama A showcase of almost fossile connectors we stumbled upon. 4 03-2012 elektor CONTENTS Volume 38 March 2012 no. 423 16 AVR Software Defined Radio (1) *0 v\ \tfi\ - j j Atmel AVR microcontrollers are very popular, not \ - 7 - 1 least because of the free development tools that are ( krs? available. In this series we shall show how these proces- sors can be pressed into service for digital signal processing tasks like SDR. Let’s generate some signals! 24 Android Switch Interface In this article we tell you how to implement various wireless sensing and swit- ching functions using an Arduino board with a Bluetooth shield. We also des- cribe how you can program your own Android app for this purpose and what (free) PC software you need for this. Here we discuss smartphone program- ming in detail, from downloading and installing the software to programming the various components of the desired user interface. 34 Hard Disk Activity Monitor Even using the most up to date PC with super fast hard disks and a powerful processor it can sometimes happen that while some complex application is running you find yourself staring at the monitor, not quite knowing why the machine is performing slowly or has indeed decided to stop responding altoge- ther. In such situations it would be helpful if an add-on independent ‘hardware’ gave some insight into what’s happening inside your PC. Here it is. 36 AndroPod (2) To control your own circuitry, you basically need an Android app that includes a tailored user interface. The obvious approach is to use the powerful Android framework and the Java programming language to implement this user inter- face. However, programming in the Android environment has a very steep lear- ning curve for beginners, so let’s try a simpler alternative first like HTML. 45 54 60 72 73 74 77 E-Labs Inside: SMD LED polarity Finding the polarity indicator on SMD parts can be tricky as we discovered. E-Labs Inside: The Bus Conductors A brief report on a test we ran to see if the ElektorBus can drive 100 feet of Cat5 cable. Platino in Arduino land Here we investigate if the Elektor Platino system is compatible in any way with the Arduino platform. Electronics for Starters (3) This month we present the basics of the transistor’s gain characteristics as well as its amplifier configurations. Economic Longwave Receiver Radio started electronics and some say it will eventually put it to bed. Use this circuit to check if there’s any truth in this statement. Ground Control for Aircraft HSI We found this Horizontal Situation Indicator among vintage aircraft electronics and decided to give it a contemporary application. Low Cost DMX Mixer Desk This ultra-simple circuit allows you to remotely control the colour produced by LED spotlights. / 1 v*. Component Tips: USB Protection Raymond’s Pick of the Month TPDEUSB30ADRTR and NCP380LSN05AAT1G Hexadoku Elektor’s monthly puzzle with an electronics touch. Retronics: Elektor’s Simple Function Generator (1978) Series Editor: Jan Buiting Gerard’s Columns: Consulting The monthly contribution from our US columnist Gerard Fonte. Coming Attractions Next month in Elektor magazine. elektor 03-2012 5 ELEKTOR The Team Managing Editor: International Editorial Staff: Design staff: Membership Manager: Graphic Design & Prepress: Online Manager: Managing Director: Jan Buiting (editor@elektor.com) Harry Baggen, Thijs Beckers, Eduardo Corral, Wisse Hettinga, Denis Meyer, Jens Nickel, Clemens Valens Thijs Beckers, Ton Giesberts, Luc Lemmens, Raymond Vermeulen, Jan Visser, Christian Vossen Raoul Morreau Giel Dols, Jeanine Opreij, Mart Schroijen Carlo van Nistelrooy Don Akkermans The Network Tech the Future explores the solutions for a sustainable future provided by technology, creativity and science. CIRCUIT CELLAR THE WORLDS SOUftCt £MA£Oe£t) EuECl HOWC !■ ENGINEEHiriG INFOHMATlOH VOICES# COIL Our international teams United Kingdom Wisse Hettinga +31(0)464389428 w.hettinga@elektor.com USA Hugo Vanhaecke +1 860-875-2199 h.vanhaecke@elektor.com Germany Ferdinand te Walvaart +31 46 4389417 f.tewalvaart@elektor.de France Denis Meyer +31 46 4389435 d.meyer@elektor.fr Netherlands Harry Baggen +31 46 4389429 h.baggen@elektor.nl Spain Eduardo Corral +34 91101 9395 e.corral@elektor.es Italy Mauriziodel Corso +39 2.66504755 m.delcorso@inware.it Sweden Wisse Hettinga +31 46 4389428 w.hettinga@elektor.com Brazil Joao Martins +551141950363 joao.martins@editorialbolina.com Portugal Joao Martins +351 21413-1600 joao.martins@editorialbolina.com India Sunil D. Malekar +9 1 9833168815 ts@elektor.in Russia Nataliya Melnikova 8107(965)3953336 nataliya-m-larionova@yandex.ru Turkey Zeynep Koksal +90532 2774826 zkoksal@beti.com.tr South Africa Johan Dijk +27 78 2330 694 / +31 6 109 31 926 j.dijk@elektor.com China Cees Baay +86 21 6445 2811 CeesBaay@gmail.com Volume 38, Number 423, March 2012 ISSN 1757-0875 Publishers: Elektor International Media, Regus Brentford, 1000 Great West Road, Brentford TW8 9HH, England. Tel. (+44) 208 261 4509, fax: (+44) 208 261 4447 www.elektor.com The magazine is available from newsagents, bookshops and electronics retail outlets, or on subscription. Elektor is published 11 times a year with a double issue for July & August. Subscriptions: Elektor International Media, Regus Brentford, 1000 Great West Road, Brentford TW8 9HH, England. Tel. +44 208 261 4509, fax: +44 208 261 4447 Internet: www.elektor.com/subs Email: subscriptions@elektor.com Rates and terms are given on the Subscription Order Form. Head Office: Elektor International Media b.v. P.O.Box 11 NL-6114-ZG Susteren The Netherlands. Telephone: (+31) 46 4389444, Fax: (+31) 46 4370161 Distribution: Seymour, 2 East Poultry Street, London ECiA, England. Telephone:+44 207 429 4073 UK Advertising: Elektor International Media b.v. P.O.Box 11 NL-6114-ZG Susteren The Netherlands. 6 03-2012 elektor ELEKTOR Membership Counter We 5IHEH member: ir countries Not a member yet? Sign up at www.elektor.com/member Take out a free subscription to Elektor Weekly Do you want to stay up to date with electronics and information technology? Always looking for useful hints, tips and interesting offers? Subscribe now to Elektor Weekly, the free Elektor Newsletter. Your benefits: . The latest news on electronics in your own mailbox each Friday * Free access to the News Archive on the Elektor website *■ You’re authorized to post replies and new topics in our forum Register today on www.elektor.com/newsletter Supporting Companies AudioXpress www.cc-webshop.com 87 Labcenter www.labcenter.com 88 Beta Layout www.pcb-pool.com 13 Microchip Microchip www.microchip.com 11 DesignSpark chipKIT™ Challenge www.chipkitchallenge.com 15 fTTl MihrotletiTDiiika l. _ ■J rriT.Tn.'y MikroElektronika www.mikroe.com 3 Eurocircuits www.elektorpcbservice.com 2 * NATIONAL INSTRUMENTS National Instruments www.ni.com/dag/usb 59 EzPCB www.siliconray.com 13 pico Tflrbhi Pico Technology www.picoscopemso.com/PS1 32 51 * Jaccartac' Future Technology Devices, Showcase www.ftdichip.com 78 Jackaltac www.jackaltac.com 9 tlrcvn LriLif?' iTulk'nfu Renesas Contest www.circuitcellar.com/RenesasRL78Challenge. . 33 Schaeffer AG www.schaeffer-ag.de 21 Not a supporting company yet? Contact Johan Dijk (j.dijk@elektor.com, +27 78 2330 694) no later than 24 January 2012 to reserve your own space for the next edition of our members' magazine Telephone: +31 46 4389444, Fax: +31 46 4370161 Email: j.dijk@elektor.com Internet: www.elektor.com Advertising rates and terms available on request. Copyright Notice The circuits described in this magazine are for domestic use only. All drawings, photographs, printed circuit board layouts, programmed integrated circuits, disks, CD-ROMs, software carriers and article texts published in our books and magazines (other than third-party advertisements) are copyright Elektor International Media b.v. and may not be reproduced or transmit- ted in any form or by any means, including photocopying, scan- ning and recording, in whole or in part without prior written per- mission 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 patent(s) or other protection. The submission of designs or articles implies permission to the Publisher to alter the text and design, and to use the contents in other Elektor International Media publications and activities. The Publishers cannot guaran- tee to return any material submitted to them. Disclaimer Prices and descriptions of publication-related items subject to change. Errors and omissions excluded. © Elektor International Media b.v. 2012 Printed in the Netherlands elektor 03-2012 7 NEWS & NEW PRODUCTS RS Components introduces new NXP ARM Cortex-Mo based mbed development board RS Components has announced availability of the new NXP LPC1 1 U24 32-bit ARM® Cortex-MO based mbed embedded development board for low-risk and rapid professional prototyping of microcontroller-based systems. The NXP LPC1 1 U24 microcontroller is particularly suitable for prototyping low-cost USB devices, battery-powered applications and 32-bit ARM® Cortex-MO based designs. It is packaged as a small DIP form-factor convenient for prototyping with through- hole PCBs, stripboards and breadboards, and includes a built-in USB drag ‘n’ drop flash programmer. The mbed microcontrollers are supported with an online tools platform available at both mbed.org and designspark.com that provides experienced embedded developers with a productive environment for building proof-of-concepts. For developers new to 32-bit, mbed is an accessible way to build projects with the backing of libraries, resources and support shared in the mbed.org developer community, including: a lightweight online compiler for instant access to a working environment on Windows, Linux or Mac OS X; a C/C++ SDK (Software Development Kit) for high-level programming of peripherals; in addition to a wealth of libraries and code examples. The NXP LPC1 1 U24 MCU runs at 48 MHz and device peripherals -QHD— -G3D— — { T — USB ^ D- ii - TET-j — J2C CET CEE f^— a— -CnTTJ— -CUD— TM include 32 KB of flash memory, up to 8I1 80 VAC input), these compact fan cooled units measuring 279.4 x 1 27 x 1 27 mm (11x5x5 inches) have a power density of up to 9.09 watt per cubic inch. The mechanical chas- sis approach of the fleXPower XI 5 and XM1 5 series provide 20 slots for arrang- ing 2- or 3-slot output modules. The mod- ules, available with single or dual outputs, cover all the popular nominal output volt- ages from +3.3 to +60 VDC in a variety of output current ratings. The ability to par- allel up outputs for more power, or use modules in series for non-standard out- put voltages offer design engineers thou- sands of different output combinations. An auxiliary 5 V / 1 A always-on output is available to power logic or control circuits in the end system without the need for any additional voltage source or step down con- verters. Monitor and control signals include AC OK, Power Fail, DC OK, Global Inhibit, Fan Fail and Module OK / Inhibit. An optional fan speed control is available to order that reduces fan speed, and its asso- ciated noise, at lower power levels. The fleXPower series is available in six power levels from 400 W to 2500 W and offers a high efficiency power source in a configurable format for fast time to market. The fleXPower XI 5 and XM1 5 are avail- able from approved regional distributors, or direct from XP Power and come with a 3 -year warranty. www.xppower.com (120202-V) 10 03-2012 elektor New 8-bit Microcontrollers with integrated configurable logic in 6- to 20-pin packages Microchip's new PIC10F/LF32X and PIC1 2/1 6F/LF1 50X 8-bit microcontrollers (MCUs) let you add functionality, reduce size, and cut the cost and power consumption in your designs for low-cost or disposable products, with on-board Configurable Logic Cells (CLCs), Complementary Waveform Generator (CWG) and Numerically Controlled Oscillator (NCO). The Configurable Logic Cells (CLCs) give you software control of combinational and sequential logic, to let you add functionality, cut your external component count and save code space. Then the Complementary Waveform Generator (CWG) helps you to improve switching efficiencies across multiple peripherals; whilst the Numerically Controlled Oscillator (NCO) provides linear frequency control and higher resolution for applications like tone generators and ballast control. FAST-START DEVELOPMENT TOOLS PICDEM™ Lab Development Kit -DM163045 PIC16F193X TV Evaluation PIC10F/LF32X and PIC12/16F/LF150X MCUs combine low current consumption, with an on-board 16MHz internal oscillator, ADC, temperature-indicator module, and up to four PWM peripherals. All packed into compact 6- to 20-pin packages. Platform - DM164130-1 PICkit™ Low Pin Count Demo Board -DM164120-1 Free CLC Configuration Tool: www.microchip.com/get/eucktool Go to www.microchip.com/get/eunew8bit to find out more about low pin-count PIC® MCUs with next-generation peripherals microchip www.mlcrochipdlrGct.CDm www.microchip.com & Microchip The Microchip name and logo, HI-TECH C, MPLAB, and PIC are registered trademarks of Microchip Technology Inc. in the U.S.A., and other countries. mTouch, PICDEM, PICkit, and REAL ICE, are trademarks of Microchip Technology Inc. in the U.S.A., and other countries. All other trademarks mentioned herein are the property of their respective companies. © 2011, Microchip Technology Incorporated. All Rights Reserved. DS30629A. ME293AEng/09.1 1 Microcontrollers Digital Signal Analog Memory RF& Wireless Controllers NEWS & NEW PRODUCTS Apem: Controlmec™ pushbutton switch APEM Components introduces Control- mec™, a five position integrated switch solution. Designed for easy activation in indoor and non-dusty applications, Con- trolmec can be used to control a unit, navi- gate in a display, or to operate indoor aux- iliary equipment on a vehicle or boat. The Controlmec can also be supplied as an IP67 sealed solution. Controlmec is a single pole/momentary switch, rated for a lifetime of 10 million operations. The solid cap has a tempera- ture range of -40 to +65, while the LED operates from -40 to +85°C. It is available in nine cap colors and eight LED colors or color combinations. An extension of the industry-standard Navimec™ system, the Controlmec includes one complete solid cap, a unit panel plate of the customer’s design, and a printed circuit board (PCB) including the switches. The PCB with the switches is assembled according to MEC specifications and mounted to the back side of the front panel. Configurations can be made with through-hole or surface mount device (SMD) switch versions, pro- vided they are accurately positioned. www.apem.com (120202-IV) Multi-output regulators with supervisory and watchdog timers Analog Devices, Inc. (ADI) is continuing to help industrial, medical and communications equipment designers improve power sys- tem performance by reducing board space with the introduction today of the ADP5041 and ADP5040 multi-output regulators. The regulators meet the increasing demand for greater power density by combining a high- efficiency, 3-MHz, 1 .2-A buck regulator and a Si 1.2A BUCK REG i_ 300mA LOG ; mArw m Reduce Parts Count improve Power Density & Reliability 4mm X 4mm LFCSP two 300-mA LDOs (low dropout regulators) in a small 20-lead LFCSP package. Unlike dis- crete power solutions that require up to 1 4 components and 126 mm 2 of board space, these highly integrated regulators provide a more integrated circuit solution using only nine components and 50 mm 2 of board space, to increase performance and reliabil- ity and lower system cost The ADP5041 and ADP5040 are ideal power management companions to mid-range FPGAs, microprocessor and DSP systems where core, 10 and memory voltages are necessary. The ADP5041 regulator’s on- chip watchdog timer provides greater reli- ability by monitoring code execution integ- rity in processor-based systems and reset- ting the processor if it fails to strobe within a preset timeout period. The ADP5041 also features a high accuracy (±1 .5% over tem- perature) reset generator that can be exter- nally programmed to monitor low voltage power supply rails. A wide range of ordering options also is available to address multiple reset and watchdog timings. The ADP5041 has a special circuit that detects a three-state condition when applied to the watchdog refresh input at the WDI pin typically controlled by a processor/DSP out- put port. When the processor sets this port in three-state mode, the watchdog refresh timer is disabled, preventing a watchdog reset to the processor. This feature is impor- tant when supporting processor/DSP sleep operation where the core is disabled and watchdog timer cannot be refreshed. The ADP5040 and ADP5041 multi-output regulators reduce thermal dissipation by using high-efficiency switching regulators with up 96 percent buck power efficiency. For low-noise analog circuit applications, the LDOs maintain a power supply rejection greater than 60 dB for frequencies as high as 1 0 kHz while operating with a low head- room voltage. The ADP5041 and ADP5040 also provide a three-rail system power sup- ply (1 .2 A buck regulator and two 300-mA LDOs) with adjustable output voltages, which allows output voltages to be easily set using an external resistor divider net- work. The 3-MHz buck regulator switching frequency allows small ceramic inductors to be used to further reduce solution size and cost. These features allow the ADP5041 and ADP5040 to be easily and quickly modified for a variety of applications with short prod- uct design schedules such as portable medi- cal and industrial devices. www.analog.com/ADP 5041 www.analog.com/ADP 5040 (120202-VIII) World’s thinnest waterproof piezoelectric speaker Murata today has commenced mass pro- duction of the ultra thin VSLBG2216E waterproof piezoelectric speaker. With a thickness of just 0.9 mm it is believed to be the world’s thinnest IPX7 speaker. Designed for consumer electronics applications, it is unlike other similar devices in that it does not require any additional waterproof mem- brane to be applied during end-product manufacture. Such additional membranes increase product time, costs and impacts the audio output quality of the speaker. The VSLBG221 6E series offers a flexible, space saving and cost effective design together with a higher quality of music reproduction. By using a piezoelectric element, without any magnet, ensures that the speaker is free of the ingress of metallic particles and has no electromagnetic noise that might affect other magnetic sensors that are incorpo- rated into the product. Typical applications include mobile phones, tablet computers, e-book readers, digital cameras and portable music players. www.murata.eu (120202-VI) 12 03-2012 elektor o L. Ill icon Roy Online Electronics Store Boards • Kits * Modules * Components * Tools • Instruments FOR * Companies * Professionals * Students * DIYers * Amateurs USB STC 8051 MCU Programmer Free For 8051 Developers SEN1060 GPS Module With Antenna Small, Low Cost, Easy To Develope $50 NRF2401 2.4G Transceiver Module Small, Versatile, Simple, Ultra Low Power $7.5 EE rare LM3886 68Wx2 HiFi Audio Amplifier HiFi Sound At Affordable Price $99.9 EEPL ■ i Simplify your electronics projects by visiting http://www.siliconray.com THE ORIGINAL SINCE 1994 PCB-PnQL' ^ Free Stencil Get a free SMD laser stencil with every Prototype order ca-pnrjL' EAGLE order button pcb-pool.com/download-button j on your first PCB order Free Phone UK: 0800 389 856 sales@pcb-pool.com R$-274-X PNMTTI'L. •l-ZXHF eid tnrf D C iir.y ■ PUtMMlJf PCB-POOL® is a registered trademark of www.pcb-pool.com LAYOUT "WO CiCKTOR TetfuTiieFinuiH ' ■ ' ini lb* tH» tl U'miit J ' "» d-, .„ r ^| P|I PIJ elnlitMifcjn!, your own 30 prater U\ IU * Fascinated by technology s impact on the future? Check out Tech the Future! r www.techthefuture.com Computing power and global interconnectivity are pushing tech innovation into overdrive. Pioneering technologies and creative workarounds affect even the couch potato 24/7. Tech the Future reports on technology strides that shape the future — yours included. Follow Tech the Future INFO & MARKET DesignSpark chipKIT™ Design Challenge Now in its final month, DesignSpark chipKIT™ Design Challenge for energy-efficient applications is still open for submissions... so, if you’re quick... DesignSpark chipKIT™ Challenge By Ian Bromley (UK) The DesignSpark chipKIT competition is now in its final weeks, and there remains just enough time to enter for a chance to win a prize. Total cash prizes of $1 0,000 are there to be won, including a first prize of $5,000. The response and enthusiasm for the competition has been fantastic and we’ve been delighted by the high quality of the submitted ideas. As a reminder of what has gone before, or for those hearing about this for the first time, the DesignSpark chipKIT challenge is all about encouraging engineers, students and hobbyists to develop new and innovative energy-efficient solutions, while also maintaining an eco-friendly footprint. So, as the competition approaches its climax, entrants will now be well advanced in their designs for energy-efficient and environmentally friendly applications based on the chipKIT™ Max32™ Arduino-compatible development platform from Digilent. The kit features Microchip’s 32-bit PIC32 microcontroller and enables developers to easily and inexpensively integrate electronics into their projects. Just to wet your appetite for the smorgasbord of ideas we’ve had, here is just a few of them we’ve received — which are also available at the online DesignSpark community at www. designspark.com. One very interesting project is the development of an unmanned underwater vehicle (UUV) that employs gliding as its method of propulsion, enabling the UUV to operate for an extended period of time due to its extremely low power consumption. An extender board being developed for the vehicle will interface to the sensors and actuators required for operation of the UUV. The design will include a 3-axis accelerometer, 3-axis gyroscope and 3-axis magnetometer for underwater orientation, in addition to a GPS receiver to determine global position on the surface. A buoyancy engine, together with pitch and roll actuators will control the UUV’s movement through the water. In addition, a CTD sensor will measure conductivity, temperature and depth, with the data being recorded in Flash memory on board the UUV, enabling profiling of salinity characteristics. Another project is a hydroponics water and nutrient-control system that will monitor climatic conditions to determine the level of nutrient-feed requirements for plants in a hydroponic environment, thereby saving on water usage and nutrient chemicals. As most hydroponics farms currently use established feed regimes that run without adjustment for environmental conditions, the design could deliver both financial and water savings. A ‘smart garden’ project for the control of the natural cycle of a plant with minimal human intervention is yet another innovative entry. The project aims to combine renewable energy sources — such as solar power — with low energy consumption of the board control circuitry operating at significantly reduced power. The system will include various sensors such as those for humidity, temperature and light, and actuators such as an irrigation pump. Additionally, the modular system will also be able to be expanded, for example, adding Bluetooth technology to enable user notifications — a possibility created by the on-going ‘Internet of Things’ revolution — about which we expect to be hearing a great deal more this year. And these are just three of many highly innovative on-going projects. As a quick final reminder on the competition, all entries must include an extension card developed using RS’ free-of-charge and award-winning DesignSpark PCB software tool with code compiled using Microchip’s MPLAB® IDE software. Entrants are also strongly encouraged to engage and interact with other members of the online DesignSpark community by posting information on their projects, providing updates on progress, and sharing comments and ideas on their respective designs. Participants will automatically qualify for entry into bonus Community Choice Awards, in addition to admission into spot prize draws for the best collaboration to win vouchers exchangeable for products ordered from RS Components/ Allied Electronics. The competition entries will be judged on the level of energy efficiency and the quality of the extension card’s PCB design. Entries are due on March 27, 2012 and the winners will be announced in April 201 2. (120188) Further details and registra- tion for the DesignSpark chip- KIT™ challenge are available at: chipkitchallenge.com. Ian Bromley is a Technical Marketing Engineer at RS Components and the Project Manager for the DesignSpark PCB software tool. Prior to working for RS, Ian worked for many years as a design support consultant with Texas Instruments, in addition to working as a field applications engineer immediately following his graduation in 1 994 with an honours degree in microelectronic engineering. M 03-2012 elektor DESIGNSPARK DesignSpark chipKIT" Challenge Get ready to win your share of $10,000 in cash prizes! It’s time to see if your hard work and superior engineering skills have paid off. The deadline for the DesignSpark chipKIT™ Challenge is just around the corner. It’s time to finalize your design and prep your entries for the judges! Will your design change the world? Reduce power consumption? Improve energy efficiency? There’s only one way to find out. Manage your project entry by clicking on the ‘My Project’ tab at www.designspark.com/chipkitchallenge-projects/latest. Be sure to upload, and clearly label, all materials necessary forjudging your entry including an abstract, complete documentation, and source code. For more information and tips on how to enter, visit www.designspark.com/chipkitchallenge/faq. ccnnuNicA PurvDlGJTrtL Wlax32™_ PQUIEP i - ■ i . analog In Don’t delay! The DesignSpark chipKIT™ Challenge ends on March 27, 2012 at 18.00 GMT (13.00 EST). r 'i L. A DesignSpark ChipKIT 1 * Challenge chipKIT™ is a registered trademark of Microchip Technology Inc. Max32™ is a registered trademark of Digilent, Inc. RADIO AVR Sof t wa re Den n ed Generating precision signals Atm el AVR microcontrollers are very popular, not least because of the free development tools that are available. In this series we shall show how these processors can be pressed into service for digital signal processing tasks. We shall cover the subject from the ground up, making the series suitable for beginners, and in true Elektor style the focus will be on practical experiments. You can build the hardware yourself or you can obtain boards from Elektor, and the software is as ever available for download as source code from our website. Let’s generate some signals! Ossmann 16 03-2012 elektor RADIO First a quick peek at what is in store in this series. The first board, which includes an ATtiny 231 3 , a 20 MHz oscillator and an R-2R DAC, will be used to make a signal generator. The second board will fish signals out of the ether. It contains all the hardware needed to make a digital software-defined radio (SDR), with an RS -232 interface, an LCD panel, and a 20 MHz VCXO (voltage-controlled crystal oscilla- tor), which can be locked to a reference signal. The third board pro- vides an active ferrite antenna. The software for all these projects is written using the WinAVR GCC compiler in AVR Studio and can be down oaded as C source code (plus fu|e settings) or as hex files. nts. We can look for- erferenc e more sensitive ains halo Signal geieratdr The signal generator clocked at 20 MHz and an R-2R lac Dpard board is based on an AVR nhicrocontroller rming a digital to analoi derf orming a digital to analogue converter to produce the output voltages. This is hardly a novel cir- cuit, but we will show how it can be used in a wide range of applica- tions. In particular we will use it to generate outputs useful for test- ing other circuits, such as frequency- and phase-modulated signals. Then, for even greater precision, we will connect the signal genera- tor to an external clock source which is in turn locked to a frequency Elektor Products and Support • Signal generator kit including printed circuit board and all components: #100180-71 • BOB-FT232R USB-to-TTL converter, ready built and tested: # 110553-91 • USB AVR programmer, printed circuit board with SMDs fitted, plus all other components: # 080083-71 • Free software download (hex files and source code): file # 100180-11.zip All products and downloads are available via the web pages for this article: www.elektor.com / 1 001 80 17 RADIO +5Vusb © Uj CO I i a. Vcc © JP1 6 O D1 BAT85 D2 R2 11 V( :c PAO(XTALI) |C1 PA1 (XTAL2) PA2(RESET) ATT | NY 2313 PB7(SCL/PCINT7) PDO(RXD) PB6(DO/PCINT6) PDI(TXD) PB5(DI/PCINT5) PD2(CKOUT/INTO) PB4(OC1B/PCINT4) PD3(INT1) PB3(OC1A/PCINT3) PD4(T0) PB2(OCOA/PCINT2) PD5(OCOB) PB1 (AIN1/PCINT1) PD6(ICP) PB0(AIN0/PCINT0) GND 10 R19 R13 19 18 R12 17 o — I 20k I — o 1 1 R11 16 15 14 13 12 H 20k I — (> I RIO R9 R8 OEH R7 R6 OEH R5 The processor is clocked at 20 MHz by oscillator XI . It is a good idea to choose a relatively high-precision component here (50 ppm or better). Using a socket makes it easier to try out different types of oscillator or oscillators of different fre- guencies. JumperJP2 allows the use of an external clock signal, which should be supplied at l<2 (EXT-CLK). The signal generator software programs allow a certain amount of external con- figuration using the microcontroller’s UART. The relevant pins are brought out to a connector on the board (which is available from Elektor in the form of a kit including all the components). The connector is suitable for directly attach- ing the BOB-FT232R USB-to-serial converter [1 ]. JP1 allows power to be obtained over the USB connection when the unit is used with a PC: in this case no additional AC power adaptor is needed. Populating the printed circuit board (Fig- ure 2) should present no particular diffi- culties: all the components are ordinary leaded types. It is worth using a socket for the processor in addition to the clock oscillator. Be sure to observe correct polarity on the programming connec- tors l<6 and l<7. Programming can be done using the Elektor AVRprog [2]. It is of course important to get the fuse con- figuration right: the source code gives this along with the compiler options in each case. Figure 1 . Circuit diagram of the signal generator. standard such as the German DCF77 signal on 77.5 kHz or French TDF signal on 1 62 kHz. The circuit of the signal generator is shown in Figure 1 . The central component is the ATtiny231 3 microcontroller, with the R-2R ladder connected to port B forming the digital-to-analogue converter. The analogue output signal appears on l<3 (SINE). Note, however, that the output impedance of the circuit is relatively high at 1 0 k El. PWM output OC1 A of the microcontroller is also available at l<4 (SQUARE). We will use this output to generate square waves with frequencies of up to a few hundred kilohertz, as well as to modulate other sig- nals. Another PWM output, OCOB, is brought out to l<5 (PWM-LF) via a low pass filter comprising R1 9 and C3: this is suitable for gen- erating low-frequency analogue signals. DDS sinewave generator Our first application is a simple sinewave generator programmed in C. The basic sample clock is produced by one of the timers built in to the microcontroller, arranged to trigger an inter- rupt. The interrupt routine is responsible for calculating the next sample value of the sinewave (Figure 3). Call the k th sample S[k], Writing p[l<] for the phase of this sample, we have 5[/c] = sin (p[k]). Between one sample and the next the phase advances by a constant value d (the ‘phase increment’): p[k+1] = p[fc] + cf. In a perfect sinewave generator these calculations must be carried out exactly, which of course is not practical. Instead, the direct digi- 18 03-2012 elektor RADIO COMPONENT LIST Resistors R1,R2,R19 = 1kn R5,R7,R9,R1 1 ,R1 3,R1 5,R1 7 = 1 0k£2 R3,R4,R6,R8,R1 0,R1 2,R1 4,R1 6,R1 8 = 20ka Capacitors C1,C2 = lOOnF 100V C3 = 10nF Semiconductors D1 = BAT 85 (Schottky diode) D2 = LED, green IC1 = ATtiny2313-20PU, programmed Miscellaneous SI = pushbutton K4,K5 = 2-pin pinheader, lead pitch 0.1 ” (2.54mm) JP3 = 2-pin pinheader, lead pitch 0.1 ” (2.54mm) with jumper JP1 ,JP2 = 3-pin pinheader, lead pitch 0.1 ” (2.54mm) with jumper K1 ,K2,I<3 = 2-way receptacle, right-angled BOB = 4-way receptacle, right-angled l<6 = 1 0-way ISP boxheader l<7 = 6-way ISP boxheader XI = 20MHz quartz crystal (with 4 receptacles Harwin type H31 53F01 ) BOB-FT232R-001 = Elektor ‘BOB’ USB/ TTL converter (ready assembled and tested,# 110553-91) Printed circuit board Alternatively Kit, including board and all parts: # 100180-71. Figure 2. The printed circuit board is available from Elektor as part of a kit including all the components. tal synthesiser (DDS) stores the current phase value DDSp to finite precision as an m-bit number in the so-called ‘phase accumulator’. One complete period of the sinewave corresponds to this value covering the range of values from 0 to 2 m -1 . The same precision is used for storage of the phase increment and for the phase addi- tion operation. The next step is to convert the phase value into the corresponding sinewave sample. This is done using a look-up table which stores a complete sinewave period. If we were to store a sample for each of the 2 m possible values in the phase accumulator the table would be unmanageably big: instead we use just the top n (where n>24 ) ) // set sample timing flag // fetch and output sine sample // advance DDS phase DDSp by DDSd // clear sample timing flag Listing 2 loop : add DDSphaseO , DDSdeltaO // 1 adc DDSphasel , DDSdeltal n 1 adc DDSphase2 , DDSdelta2 n 1 adc ZL ,DDSdelta3 n 1 1pm R0, Z n 3 out PORTB , R0 n 1 brtc loop n 2 n 10 LSB of 32 bit DDS adder MSB is in ZL as pointer access sine table out to R-2R DAC on PORTB 1) loop until T flag set by interrupt routine cycles in total for one loop 20 03-2012 elektor RADIO UM01522 (HW DxlGlMaCCL W 03 W) 2D12‘011? D906 AsitH-Trig / Run CHI LJOrtiV. AL SMSil 5oa^a Refresh C H J K tin ivs; j ■ ■ -1 1 1 N ..! 1 j ,J. 1 ■ J itiilLli 4 J LiLiIiL 1. * 1 J J L .iLfl j rim it lLjJiI.L iL 1 ' ,T 1 ■ ji.'il 1 ri rt'i -J["1 1 . ' HPT lIi iuil u r p ■. in ykkLL . 5pnn ?MU? Center 1MH 7 Avq #2 CHI lOOFUTi Figure 7. Spectrum of the generated signal. frequency followed by CR and LF. The maximum usable signal fre- quency is about 200 kHz. The theoretical frequency resolution is given by f D dsclk / 2" = 2 MHz / 232 = 0.00046... Hz. To take advantage of this resolution the software allows you to enter a frequency with up to three digits after the decimal point, for example as ‘1 000.045’ (followed by CR and LF). The internal calculations required to turn the entered frequency into a suitable parameter value for the DDS need to be carried out very accurately. To this end the author has written special-purpose arithmetic rou- tines, including one for fixed-point division. processor (paying attention to the fuse bit settings). The project is called EXP-SinusGenerator-DDS-ASM-C-VOI . To make the sinewave generator more flexible it includes the abil- ity to be configured over the UART interface (19200 baud, 8N1 data format). Using a terminal program, simply type in the desired Figure 7 shows the spectrum of the sinewave output signal at fre- quency f= 125.123 kHz over the range from 0 Hz to 2 MHz. As you can see, there are harmonics present, but all at more than 30 dB below the desired signal. A low level of wideband noise is also vis- ible: this is a by-product of the DDS technique. Advertisement Take out a free subscription to Elektor Weekly Do you want to stay up to date with electronics and information technology? Always looking for useful hints, tips and interesting offers? Subscribe now to Elektor Weekly, the free Elektor Newsletter. Your benefits: * The latest news on electronics in your own mailbox each friday * Free access to the News Archive on the Elektor website * You’re authorized to post replies and new topics in our forum e we La j. UL& jcJrMMxtic i r »p *rr *- v I! !j iB- Ehktor Aeadim* ipr«nrni>... in pS .1 Irwrmihifi wiEh *ni"*r 1 fl -4 niiy -or IiiiJiI yum mm kJ-uIkiI mi m bn KWL vwi hih —l - H iiH- C # b-a zOTfi *: 8 :'fccr :i : :: ^ch t--*- t-sa - *■ 'i n - w~ ■■■•> — * i x .jr-"rr*r w ■■ rw ”'» T-* -l 7* 5* i- ■ ■ •+.- -m-.n 7* ■■■?"■ ■ ■ J iu wii i_ j ir* w I iu**m s* i'i ■■ ■ » * . n a ■ ■ , ■ ■ ■ , Hiriil inut M '.i* -fiidrr-i P U inr L’lwluiln fm k'f J I'jigmro Jj 1123 F 1128 shield. We also describe how you can program your own Android app for this purpose and what (free) PC software you need for this. By Jos van Kempen (The Netherlands) Nearly all microcontroller circuits intended to control something have some form of user interface. This often involves several but- tons, knobs, LEDs and an LCD module. If you want something really nice, you might even use a touchscreen. A remote control can also be handy - preferably one that does not have to be aimed so precisely. However, ‘luxury’ interfaces of this sort usually cost more and are more difficult to implement. This doesn’t have to be the case. As you will see, an attractive user interface with remote control does not heed to be expensive, and the programming is reasonably easy. There’s a good chance that your have a smartphone with Bluetooth capability, which can be used as a fancy remote control unit. Some microcontroller boards have built-in Bluetooth capability, and with others you can buy adapters or shields to add this capability. In this article we use a small Arduino board with a Bluetooth shield (ITead, priced at around 1 5 pounds) augmented by a small I/O shield spe- cifically designed for this article. Articles about adding Bluetooth functionality to your own circuits have been published in previous issues of Elektor (September 2004 and February 201 0). Elektor also published an article about program- ming Android apps in the June 201 1 edition, and an Android control- ler using the audio output was described in December 2011. Many of you are familiar with microcontroller programming, although you may not have any experience with programming a 24 03-2012 elektor MICROCONTROLLERS mobile phone, so we devote only minimum attention to micro- controller programming in this article. However, we discuss smartphone programming in detail, from downloading and installing the software to programming the various compo- nents of the desired user interface. We hope this information will be sufficient to enable you to program a user interface yourself for your own application with your own microcon- troller. The source code of the application described here (for both the microcontroller and the smartphone) can of course be downloaded from the Elektor website [1 ]. Hardware and microcontroller software A Bluetooth shield is fitted on the Arduino board. It commu- nicates over the UART interface. In Bascom you can use the ‘input’ and ‘print’ instructions to receive commands and send data from and to the Arduino board. For this project we also developed a simple shield consisting of a pair of relays with LEDs (digital outputs), a PWM output with a FET (‘analogue’ output), a switch (digital input) and an NTC thermistor as an analogue sensor (analogue input). The schematic diagram is shown in Figure 1, and the PCB layout designed for this circuit is shown in Figure 2. This shield can be used to experiment with all of the options for communica- tion between the Android smartphone and the Arduino board using Bluetooth. All relay, switch and sensor lines are available on connector l<9. The microcontroller software (written in Bascom) works as fol- lows (see Listing 1). A loop checks whether a character has been received. If the Arduino receives an ‘R’, output D1 1 is activated (LED1 lights up and relay RE1 is energised). If it receives an ‘r’, LED1 and RE1 are a ‘P’ (short for ‘PWM’) is received, the routine ‘Input’ waits for a de-energised. Output D1 3 and the second LED and relay behave in value (the smartphone must send the character string ‘\r\n’ after a similar manner, but they respond to the characters ‘O’ and ‘o’. If the value), and this value is used to drive the PWM output. FET T3 AREF GND D13 D12 Dll DIO D9 D8 D7 D6 D5 D4 D3 D2 D1 DO Figure 1. Schematic diagram ofthe I/O shield consisting of a pairof LEDs and relays, an NTC thermistor, a pushbutton, and a PWM output with a FET and an indicator LED. COMPONENT LIST Resistors R1,R2,R3 = 560£1 R4 = 1 00£} R5,R6 = 4.7l<£2 R7 = 1 0ka R8,R9 = 1 k£2 Semiconductors D1 ,D2 = 1 N4148 LED1 ,LED2,LED3 = LED, red, 5 mm T1 ,T2= BC547 T3 = BS170 K7,l<8 = 8-way pinheader socket l<9 = 1 0-way pinheader socket RE1 ,RE2 = 5V miniature relay (e.g. TE Con- nectivity type MT2-C93401 orOMRON type G5V-2-H1 ) SI = pushbutton with make contact (e.g. B3F-1000) PCB #120075-1 (see [1 ]) Miscellaneous K1 ,l<2 = 6-pin pinheader K3,K4 = 8-pin pinheader K5,l<6 = 6-way pinheader socket Figure 2. The PCB layout is designed such that the connectors mate with a standard Arduino board. elektor 03-2012 25 MICROCONTROLLERS Listing i. The microcontroller program (written in Bascom). $baud = 9600 : UcsrOa = &H00 'Software under CC-BY-NC-SA licence by Jos van Kempen. Config Adc = Single , Prescaler = Auto , Reference = Avcc Start Adc Config Timerl = Pwm , Pwm = 8 , Compare A Pwm = Clear Down Config Pinb.l = Output Pwmla = 0 Dim Pwm_str As String * 5 Dim Pwm_b As Byte Dim Value As Integer D13 Alias Portb . 5 : Config D13 = Output Dll Alias Portb . 3 : Config Dll = Output D7 Alias Pind.7 : Config D7 = Input Declare Sub Set_pwm Dim B As Byte Do B = Ischarwaiting ( ) Print B If B = 1 Then B = WaitkeyO Select Case B "R" I! II Case Case Case Case Case End Select " 0 " "o" IT p IT Dll = 1 Dll = 0 D13 = 1 D13 = 0 Call Set_pwm End If Waitms 300 Pwm_b = Pwm_b + 3 Value = Getadc(0) Print "T" ; Value ; "t" Waitms 40 If D7 = 1 Then Print "G" Else Print "g" Waitms 30 Loop End Sub Set_pwm Input Pwm_str Noecho Pwm_b = Val (pwm_str) : Waitms 30 Pwmla = Pwm_b Print "*" ; Pwm_b : Waitms 30 End Sub 'Thanks to J.F. Theinert 'ADC (analog) input initialize 'PWM (analog) output initialize Prescale = 8 ' PB1 =digpin9=pwmla 'text 0-255 'Digl3 no resistance needed for LED ' Digll ' Initialize Diglnput Dig7 ' if incoming command 'A0 has a maximum rating of 60 V / 0.5 A. LED3 provides an indication of the PWM level. The measured value of the NTC thermistor sensor R9 is also printed with the format ‘T;adc(0);t\ and the signal level at input D7 to which pushbutton SI is connected is printed as ‘G’ if it is high (‘1 ’) or ‘g’ if its is low (‘0’). The interface is configured with standard data rate of 9600 baud, which means that a small waiting time (around 30 to 40 ms) is necessary after a value has been sent. Required software The following software that you need in order to program appsfor Android smartphones can be downloaded for free: 1 . The Java language is used for programming. The Java Develop- ment Kit (JDK) can be downloaded from the Oracle website [2J. 2. The Android Software Development Kit (SDK) is available at [3J. After installing the SDK, you should have a look at the rest of the site, where you can find a lot of information about program- ming, help files and USB drivers for your smartphone (which you will need later for downloading your app). The USB driver may already be installed on your PC if you use USB to exchange pho- tos, music and so on between your PC and your smartphone. 3. Download the ADT plugin for Eclipse from the same site, and make note of the folder it goes into. 4. We used Eclipse Classic 3.6.2 as the integrated development environment (IDE). It can be downloaded from [4] . (Note: the latest Android plugin at the time of writing was ADT1 2, which is not compatible with Eclipse 3.7.) 5. After installing Eclipse, you have to install the Android plugin (under Help \ Install new software | Archive). Select the ADT zip 26 03-2012 elektor MICROCONTROLLERS file and enter the name ‘Android’. Then go to Windows | Prefer- ences and look for the folder with the extracted Android SDK (in lower-level folders, including ‘Tools’). Go to Windows \ Android SDK andAVD Manager , select New (Vir- tual Device), and select Gingerbread for version 2.3.3 (or Sam- sung_GIO or something similar) so that you can simulate the program on the PC without a smartphone if necessary. 6. Download the folder containing the Bluetoothlnterface example project from [1 ], but do not put it in the Eclipse workspace. The Bluetoothlnterface project The software that allows a Bluetooth device to find other Bluetooth devices, establish contact and exchange messages is complicated, but fortunately an example is included with the Android SDK. Unfor- tunately, it apparently does not work properly with many Bluetooth devices. A replacement for one of the files (BluetoothRf com- mClient . j ava) can be found on the Internet. After the declara- tions are modified, it solves this problem (see [5] and [6]). Now you can use the project to make your own interface. After starting Eclipse, you can select File \ New \ Android project | to create a new project (perhaps based on an example), but in this case you already have a project that you want to import into the Eclipse workspace. To do this, select File \ Import. \ Existing Projects in Work- space. Be sure to tick Copy projects into workspace, as otherwise the original project will be overwritten. Browse to the folder where you placed the downloaded Bluetoothlnterface project. Various .java and .xml files are visible in the project file structure (Figure 3). You may have to click the relevant folder to see them. The ones we are interested in are BluetoothChat.java (main pro- gram), main.xml (smartphone screen interface) and strings.xml (declaration of the variables used in the interface). Lzj Bluetoothlnterface - iS src - (B www.etektor.BTInterface ■S 0 BtuetoothChaLjava + [Jj BtuetoothRfcommCiient.java + 0 DeviceLtet Activity . f ava ffi E& Android 2.3.3 + §5 gen [Generated Java Fi!e&] & assets Li- ifc? res + drawable + kz? drawabte-hdpi drawab!e4dpi drawaWe-mdpi - layout x custom Jitle. xml X device Jist xrnl x device_riame.xml x] main.xml x message. xml + menu ® (3- values ■ AndrotdManif est . xml El default. properties Figure 3. The file structure of the Bluethoothlnterface project. change) by two radio buttons labelled ‘On’ and ‘Off’ ( radioGroup orientation horizontal). The signal level on the analogue input is indicated by a horizontal progressBar (style: horizontal), a number in a textV/ew and a chart in an imageView. The PWM output with the FET is set by a slider on a seekBar. Interface implementation Double-click main.xml to display the smartphone screen interface (see Figure 4). The tabs below the screen layout can be used to switch between the graphical layout and the automatically gener- ated code. A horizontal layout is already defined on the interface, including a ListView for the detected Bluetooth devices, an EditText for the enter- ing the text you want to send during a chat session, and a button for sending the text. In many cases the easiest way to place a component is to drag it to the Outline pane. An error may occur when you drag the size on the screen if your PC is configured for a comma decimal marker. In this case you must replace the *,’ in the file main.xml with a 7. When you place a button or a radio button, you can define the pro- cedure that will be executed if it is clicked by entering the name of the procedure for the OnClick property. The LEDs and relays (digital outputs) on the shield are operated by a set of buttons or checkboxes. For this purpose, place a linear layout of checkboxes or (toggle) buttons on the screen or in the outline (which is often easier). The switch state (digital input) is indicated on the interface (for a rr.YiAirJ 72" ' > Via* tt. Libfxj Pjt P ' v AndadiMLJ 3 Jr, Vflttjfi v l - . i | her* v sm* ? □□ am y ini ■ I orm Widgets MM jrP ' I J Trat ftf-lik inrouti Cinii|Mj)iLe lm-iqe... K fedia Time & Dale T k.i [Kit I no i ArfvaiLBif [j-Olrtw |f| Tnd:LW - I - ' L^'eaiLflywJt. 1ZI rtCiiFl’.Vf' ■ - I j E iGKd&jO- tiMod-'-: L-r r.^'ed g ■■ i.YtntVniqi I ■SL .• D . new L apout - t/wiii .v.'fKr 1 HJ> ImitVhwl I “ , -i T ■ « la h.'j t E ir-J7e¥Kwl /ib m ■1 wtnfcRnr'1 ■7 I ] HiH-LiruJ. edMsxt b fTVl -WiH fustrwi... Vkrws FtnfwrtWrt M ; i ,i lMvnn | n-ata ■'inuioft Gr TfimrSr Figure 4. The interface screen layout. It’s often easiest to place the controls in the Outline pane. elektor 03-2012 27 MICROCONTROLLERS Figure 5. Select ‘Connect a device - Secure’ and then select one of the already paired devices or scan for devices that are configured as ‘discoverable’. You have to enter a code for (initial) pairing; ‘0000’ and ‘1234’ are common codes. you must first select the right COM port in the terminal emulator (e.g. Hyperterminal or Advanced Serial Port Terminal) and establish a connection. After the app has been downloaded and tested, establish a connec- tion by clicking the menu button at the lower left and choosing the desired Bluetooth device (select connect to device -secure). If every- thing goes right, you should see the message ‘connecting’ followed a short while later by ‘connected: ’ (Figure 5). The code in the BluetoothChatfile may look like this: private CheckBox chkD13, chkDll , chkDIM; (The variable must be declared if the checkbox properties are read (or written) in the program) You haven’t programmed anything yet, but you can already see what the interface will look like when it’s done. You can also run a simula- tion on the PC with a virtual smartphone displayed on the monitor, but it isn’t possible to simulate a Bluetooth device with this. Connect your smartphone to the PC with a USB cable and then select the associated project folder. Right-click the folder and select Run As.. | Android Application. The app will be compiled and down- loaded to your phone. If Bluetooth reception is enabled, you can now receive data and dis- play it on your phone. If you wish, you can also test the app by communicating with a Blue- tooth USB stick plugged into the PC, in combination with a termi- nal emulator program for sending and receiving data. Of course, iiQ a|t i O ill ■ 13144 1 1 Lie tooth- Interface ctnnrict?rd:iiCC'Od IteatJ- 0 V Screen Dimmer off Figure 6. The interface in use. The messages sent by Itead (the Bluetooth shield) or Me (the phone) are visible at the top. Commands to be sent can be entered manually at the bottom. These features are handy for troubleshooting, but you may want to remove them for other applications. chkD13 = (CheckBox) f indViewByld (R . id . chkD13 ) ; (The link between the name in main . xml (the screen layout) and the name in the program is created in the procedure ' onCreate ' ) public void chkD13Click (View view) { if (chkD13 . isChecked ( ) ==true) sendMessage ( "O" ) ; else sendMessage ( "o" ) ; } The procedure itself is very simple. Either an ‘O’ or an ‘o’ is sent, depending on whether the checkbox is ticked or cleared. These are the commands that cause the microcontroller to activate or deac- tivate LED 2 and relay 2. The code for sending a value determined by the position of the slider on the seek bar when it is released is a bit more complicated. However, if you start typing the ‘quick fix’ assistant will point out your mistakes and generate most of the code automatically. It also automatically adds implements OnSeekBarChangeListener in the class declaration. public void onProgressChanged (SeekBar seekBar, int progress, boolean fromUser) { // TODO Auto-generated method stub textView2 . set Text ( Integer . toString (progress ) ) ; } public void onStartTrackingTouch (SeekBar seekBar) { // TODO Auto-generated method stub textView2 . setTextColor (Color . rgb (255 , 48, 48)); } public void onStopTrackingTouch (SeekBar seekBar) { // TODO Auto-generated method stub textView2 . setTextColor (originalTextColor ) ; sendMessage ( "P" ) ; try{ Thread . sleep ( 1000 ) ; } catch ( InterruptedException e) { // TODO Auto-generated catch block e . printStackTrace ( ) ; 28 03-2012 elektor MICROCONTROLLERS } sendMessage ( seekBarl . get Progress ( ) + "\r\n" ) ; } The only things you have to add here are code to change the dis- played text value when the slider in the seek bar moves, code to change the colour of the text when you are moving the slider, and code to cause the phone to send a ‘P’ (which is the signal for the microcontroller to call a procedure in which the desired PWM value is read using Input Pwm_str) followed by the character string ‘\r\n’ to mark the end of the message. There is also already a procedure that receives messages from the microcontroller and places them in the text box. The following code is important for this: case MESSAGE_READ: byte [] readBuf = (byte [] ) msg.obj; // construct a string from the valid bytes in the buffer String readMessage = new String (readBuf , 0, msg . argl ) ; mConversationArrayAdapter . add (mConnectedDeviceName+ " + readMessage); break; Now all you have to do is to ‘capture’ the message and assign the right values to the radio buttons or the progress bar according to the message content. The radio buttons are controlled by the characters ‘G’ (on) and ‘g’ (off): if (readMessage . contains ( "G" ) ==true) G1 . setChecked ( true) ; if (readMessage . contains ( "g" ) ==true) GO . setChecked (true) ; For the progress bar, the code first checks whether the string ‘Txxxxt’ has been received. Here ‘xxxx’ is a number in the range of 0 to 1 023, which is the digitised value of the signal level on the ana- logue input. The entire string is evaluated because it sometimes arrives in two pieces, which should not lead to an incorrect value: if (readMessage . charAt ( 0 )==' T' ) if (readMessage . contains ( "t" ) ==true) { Tempoud=Temp ; Temp=readMessage . indexOf ("t") ; 01dMessage=readMessage . substring ( 1 , Temp) ; Temp=Integer . parselnt (OldMessage) ; The following code handles the value shown as text (the current temperature); for the progress bar and the chart it is sometimes necessary to recalculate and format the values due to the scale: RTemp=Temp ; RTemp=RTemp/6 ; // 0-255 naar grdC // nooit hoger dan maximum progressbar AO . setProgress (Temp*4 ) ; //schaal progressbar Temp=Temp/2; //schaal grafiek DecimalFormat formatter = new DecimalFormat ("#.#") ; textViewl . setText ( formatter . format (RTemp) ) ; } The measured value is also plotted on the chart. The chart is erased when the number of measured values reaches 1 50, after which the outline with scale lines is drawn again: xcoordoud=xcoord; xcoord+=l ; if (xcoord==l) { //tekenen kader en hulplijnen paint . set Col or (Color . BLUE) canvas . drawLine ( 0 , 105 , 150 , 105 , paint ) ;//10 grd canvas . drawLine ( 0 , 85 , 150 , 85 , paint ) ;//15 grd canvas . drawLine ( 0 , 65 , 150 , 65 , paint ) ;//20 grd canvas . drawLine ( 0 , 45 , 150 , 45 , paint ) ;//25 grd canvas . drawLine ( 0 , 25 , 150 , 25 , paint ) ;//30 grd paint . setColor (Color . YELLOW) ; canvas . drawRect ( 1 , 1, 149, 124, paint); } if (xcoord==150 ) {xcoord=0; canvas . drawColor ( Color . BLACK) ; } else { canvas . drawLine (xcoordoud, 125 -Tempoud, xcoord, 125 -Temp , paint ) ; } 01dMessage=readMessage ; To prevent the application from starting up with a keyboard, Androidmanifest \ Application \ Window soft input mode is set to state Hidden. This completes the discussion of the main points. Of course, you will want to tailor the application to your specific needs. We hope that you now have enough information to be able to do this yourself. The download on the Elektor website includes a complete application file (.apk) that you can copy directly to your smartphone and try out all of the features described here after installing it. (120075-I) Internet Links [1] www.elektor.com/ 1 20075 [2] http://www.oracle.com/technetwork/java/javase/downloads/ [3] http://developer.android.com/sdk/index.html [4] http://www.eclipse.org/downloads/ [5] http://projectproto.blogspot.com/201 0/09/android-bluetooth- oscilloscope.html [6] http://code.google.eom/p/android-bluetooth-oscilloscope/ elektor 03-2012 29 REVIEW EasyPIC vy APICMCU development board born underthesignof Connectivity When it comes to MCU development boards the Serbian manufacturer MikroElektronika (mE) has a reputation to keep up. Not only do they create and launch a wide range of such boards, they also keep improving them. Recently the seventh (!) generation of their EasyPIC development board for Microchip PIC microcontrollers was introduced. We tried it out for you. By Clemens Valens (Elektor UK/US Editorial) The EasyPIC board is a product within MikroElektronika’s ‘Easy’ line of development boards like EasyAVR, EasydsPIC, EasyPSoC, and so on. The EasyPIC targets, as you might expect, 8-bit PIC microcon- trollers from Microchip. My first contact with the EasyPIC series was a few years ago with the EasyPIC4. This was already a compre- hensive and useful board, so you might wonder how it could be improved to get as far as a seventh generation. The two boards look rather different, the ‘4’ is much smaller than the ‘7’ (26.5 x22 cm) and it was laid out quite differently, but when you look closely they appear highly similar. Both have eight sockets catering for all the different PIC DIP devices from 8-pin to 40-pin; they also have in common a 4-digit 7-segment LED display, space for a 2 x 1 6 alphanumerical LCD, space for a 1 28 x 64 graphical LCD, pushbuttons, LEDs, pullup & pulldown resistors on every I/O pin with an extension connector for every port, an on-board program- mer and in-circuit debugger, a power supply, RS-232 and USB ports and a few other things you might expect from a development board. Tracing the evolution of the EasyPIC, starting at generation 4, appar- ently the ‘5’ added mainly a touch panel controller. The ‘6’ took a bigger step by introducing SMD technology and DIP switches for pullup/down selection per GPIO, replacing the 7-segment display by a chip-on-glass (COG) LCD and adding a port expander, a 4 x 4 key- pad, a 6-key menu keypad and a connector compatible with Micro- chip’s ICD programmers/debuggers. Compared to the ‘6’, the ‘7’ seems to go back to its roots by replacing the COG display by the good old 7-segment LED display. The most obvious change however is the new component layout which I find much clearer. Where on previous generations all the GPIO LEDs, pushbuttons and pullup/ down resistors were grouped by component type (i.e. all the LEDs together), they are now grouped by port. The ‘theme’ of the ‘7’ is Connectivity, as printed in the lower right- hand corner of the board. All ports now have three extension con- nectors (instead of one, two on the right side of the board and EasyPIC v7 ($ 149 • supports over 250 8-bit PIC microcontrollers • on-board mikroProg programmer/in-circuit debugger • dual power supply (5 V & 3.3 V) • 3 extension connectors per port + row of holes • pushbutton, LED, pullup/down resistor per port pin • 2 mikroBus slots • RS-232 or serial-to-USB port • USB, ICD, buzzer, l 2 C EEPROM • 4-digit 7-segment display • optional 2x16 alphanumerical LCD • optional 128 x 64 graphical LCD with touch panel www.mikroe.com/eng/products/view/757/easypic-v7-development-system/ 30 02-2012 elektor REVIEW one on the left side) plus a row of extension holes. The connectivity theme is further illustrated by two slots (kind of) for add-on (‘Click’) boards compatible to MikroElektroni- ka’s mikroBus form factor (photo 1 ). Well over a dozen of these Click boards are cur- rently available offering functions like Ethernet, Bluetooth, GPS, MP3, SD-card, etc. The PS/2 port has finally been replaced by a USB-to-serial interface (FTDI based). Other changes can be found in the power supply which is now dual delivering 5 V and 3.3 V (one of which can be used for the board, selectable by a jumper), and in the mikrolCD programmer/ in-circuit debugger that’s now hidden by a metal cover. Remov- ing it is easy enough and reveals a completely redesigned circuit (photo 2; doing so will obviously void your warranty). How exactly the MCU voltage is derived from the board voltage is not clear from the schematic. Additions include a second thermometer connection — besides the traditional DS1 820 it is now also possible to easily connect an LM35 sensor—, a buzzer, a type 24C08 8 Kbit l 2 C EEPROM and, verging on the silly but highly essential as I see it: a 5 mm mounting hole in each (rounded) corner of the board. The build quality of the board is excellent. The PCB is extra thick (2.7 mm) so it will not easily bend and it has very clear component print on both sides. Super Duper mechanical supports for the LCDs are available and the variable resistors are spaced so wide apart that even thick fingers can adjust them comfortably. Photo 1 . A mikroBus EasyGPS ‘Click’ board positioned on slot #1 . circuit diagram of the board. Usually I do like the way mE draw their schematics with photographs of the components, but the verti- cally printed two-sided folded sheet supplied now is rather unpractical and I found it difficult to read. The board comes equipped with a PIC1 8F45K22, a 1 6 MIPS CPU with 32 KB of Flash memory and 1 .5 KB of RAM. The board supports more than 250 PIC MCUs, so if this one doesn’t suit you, just pick another. Note that the LCDs and temperature sensors have to be ordered separately. First power-on The board has three power connection options: a 6.3 mm barrel socket (centre is positive), a screw terminal and USB. Although there are three USB sockets on the board, it can only be powered from the mikroProg USB socket. Since the board comes with a USB cable it is easiest to power the board over USB. Make sure jumper J6 is on USB, connect the USB cable to the board and to the PC and put the power supply switch in the ON position. The 7-segment display now shows a simple animation with the text “EP7”, and then starts counting at a rate of about 20 Hz. The LEDs on port C scroll from right to left. on-board mikrolCD in- circuit debugger and the Photo 2. Inside the on-board mikroProg programmer/in-circuit debugger. Note that removing the hood will void you warranty. there may be an updated version available any- way. The installation is What’s in the box? One thing I like about mE’ their products come in sturdy cardboard boxes that allow for easy stor- age when you don’t use them, without kinder- garten puzzle solving to get everything back in the box. The EasyPIC v7 box is rather large. In it you will find the board in an antistatic bag, a (red) USB cable, a DVD with software and documen- tation, a printed User’s Guide, a manual for the mikroProg Suite for PIC, another manual for the Software installation Now that you know the board is working you can switch it off to install the software. Note that you can also use the board with non-mE compil- ers. Although a DVD is provided in the box you might as well download the latest version of the compiler of your choice from mE’s website as s products is their packaging. All of The board should also be detected by the PC’s operating system. In order for the board to be recognised as well, a driver is required that has to be installed first. Note that (certified!) drivers for Win- dows Vista, XP and 7 are available only. elektor 02-2012 3 i REVIEW straightforward and requires about 185 MB of hard disk space, two minutes and 1 6 mouse clicks. It creates two desktop icons, one for the compiler (mikroC Pro in my case) and one for the mikroProg suite for PIC. When you launch mikroC you can quickly navigate to the exam- ples using the Project menu and then Open Examples Folder. You can then select the Development Systems folder, which contains an EASYPIC7 folder, again containing example folders. From the LED Blinking folder load the project file LedBlinking.mcppi (sic), a sim- ple ‘Hello World’ project. One mouse click is enough to compile it and start programming the executable in the MCU. Or so it should, except that programming doesn’t start because you have to install the mikroProg driver first. The driver was copied to hard disk during installation, but it is not installed automatically for practical reasons and you have to do this manually. If, like me, you closed the Explorer window that opened up after the installation and you don’t know where the driver is, in Windows XP, go to C:\Program Files\Mil<- roelektronika\mikroC PRO for PIC\mikroProg Suite installer\Drivers (replacing “mikroC PRO for PIC” by the name of your compiler). In case you have no idea how to install a driver manually, you will also find a PDF document with clear instructions right there. With the drivers in place compiling and programming the LedBlink- ing example takes less than 1 5 seconds. All LEDs on port C and all segments of the 7-segment display should start blinking at a rate of 0.5 Hz. All in all the EasyPIC v7 with mikroC PRO for PIC scores a helloWorld benchmark! 1 ] value of 945, which is actually pretty good. When you got this far it’s time to start sampling the other exam- ples and of course begin developing your own applications (see the ‘MyFirstProgram’ inset). Note that some of the examples will not compile in the code-size-limited compiler demo versions, but precompiled versions are included for all examples, which is sure to meet with appreciation from newcomers. Photo 3. A DAC accessory board connected to port C. Conclusion The EasyPIC v7 is an attractive development board for 8-bit PIC microcontrollers offering all the peripherals you might expect from such a product. Many extension options allow you to easily add your own interface circuitry, and a choice of ready-made add-on mod- ules is available from mE that can be plugged either on the mik- roBus connectors or on the port extension connectors (photo 3). Build quality of the board is excellent and the mounting holes in the board allow for easy securing in out-of-lab situations. Its 3.3 V capability makes it compatible with low voltage parts and periph- erals so widely available nowadays. Using the board with program- ming tools from other manufacturers is within easy reach thanks to a Microchip-compatible ICD programming connector. If you are serious about PIC-based project creation and development, this board is a must-have. (120093) P] A Benchmark for Microcontroller Development Kits, Elektor February 201 2, www.elektor.com/ 1 20096 MvFirstProqram The review board came with an EasyGPS Click module (photo 1 ) so I decided to write a little program to use it. From mE’s website I down- loaded the EasyGPS demo code, but it turned out to be for their SmartGPS board as well as targeted at a PIC1 8F4520 on an EasyPIC6 board (issue corrected since). This meant that I had to change the target MCU (in the Project Settings window accessible from the View menu), enable the PLL x 4 fuse bit (Project -> Edit Project) and adapt the definitions of the graphical LCD interface (copied from another example). This made the program work on the EasyPIC v7 with graphical LCD (GLCD), except for the serial input. After some re- searching I discovered that you have to disable the analogue inputs of the PIC1 8F45K22 to enable the serial input (add ANSELC = 0 just before UART1 Jnit(9600)). Although the EasyGPS module runs from 3.3 V the program worked fine with the PIC1 8F45K22 running from either 5 V or 3.3 V. For those who use the demo version of the compiler or who do not have a GLCD I also added some code for a 2 x 1 6 alphanumerical LCD. You can download my program from www.elektor.com/ 1 20093; it in- cludes two precompiled executables, one for the 2x16 LCD and one for the GLCD. 32 02-2012 elektor Coming Soon! The RL78 2 - 0,000 Green Energy Challenge (P^l^ With an incredible ecosystem of hardware, software and third-party vendors, Renesas' family of RL78 MCUs are optimized for efficient power consumption and deliver up to 41 DMIPS at 32MHz. These versatile MCUs offer a true low-power platform for the most demanding 8- and 16-bit embedded applications. Renesas, along with Circuit Cellar and Elektor, invites you to experience true low power by developing a green energy application using the RL78 MCU and IAR tool chain. Succeed and win a share of $20,000 in cash prizes! In association with Elektor and Circuit Cellar Be the green you see in the world and get ready for the RL78 Green Energy Challenge. if .circuitcellar.com/RenesasRL78Challenge READERS’ PROJECTS Hard Disk Activity Monitor Aio-LED indicator to show how hard it’s working By Karsten Bohme (Germany) Almost every PC case is fitted with an LED on the front panel which flickers whenever the hard disk(s) is accessed. A single flickering light is better than nothing at all but a 10-LED linear scale showing hard disk loading as a percentage would be really handy! Features • A display using 10 LEDs indicates hard drive activity • Displays hard drive activity in 10 % steps • Crash proof operation (independent of PC software) • Neat compact module fits easily inside a PC case It can sometimes happen, even using the most up to date PC with super fast hard disks and a powerful processor, that while some complex application is running you find yourself staring at the monitor, not guite knowing why the machine is perform- ing slowly or has indeed decided to stop responding altogether. Sound familiar? You cannot be sure if the program has truly got itself into a pickle or intense hard disk activ- ity is responsible for the sluggish behaviour. In such situations it would be helpful if you had a piece of add-on independent ‘hard- ware’ which gave some insight into what was happening inside your PC. This design idea shows real-time hard disk activity in the form of a 10-bit linear display. One advantage of the design is that it runs independently of the PC software so it won’t place any additional load on the PC’s proces- sor. It is also unaffected by internet-borne bugs or viruses (assuming there are none in the microcontroller firmware to start off with) and will function even if an application running on the PC has crashed. Despite the market for PC case modding and customi- sation being relatively large there doesn’t appear to be any similar hard disk indicator available, but on second thoughts I guess that is what we have Elektor for! More LEDs! The average PC usually has just a single flickering LED giving you a rough indication that the hard disk(s) is being accessed. The modification described here shows hard disk activity in a much more informative linear display using ten LEDs (each step rep- resents 1 0 %). The display is refreshed five times per second, giving a good responsive indication. The question is how has the author man- aged to gain access to this information because it is not output from the hard disk controller in either analogue or digital form. His solution is to treat the on/off signal to the hard disk LED as a pulse-width modu- lated signal, simply measuring the on to off ratio of this signal gives an indication of how hard the disk is being used. This approach works surprisingly well. The wire from the motherboard normally connecting to the hard disk LED is instead connected to the input on the hard disk monitor board. A microcontroller then reads the state of this signal during 200 ms windows to determine the amount of time that this signal is high during each period. A high for the entire period will result in all ten LEDs lit while a low for the entire period will turn them all off. The photo of the author’s PC shows all ten LEDs lit. The first seven (the range from 1 to 70 %) uses green LEDs, the next two (71 to 90 %) are yellow and the final position is red (91 to 100 %). Decoder and LED driver From the functional description and circuit diagram you will be aware that the circuit uses a microcontroller. A low cost Atmel ATtiny23 1 3 microcontroller together with an optocoupler and LEDs are connected as shown in the diagram in Figure 1 . The wire which originally connected the moth- erboard to the hard disk indicator LED is instead connected to the monitor board input where it now drives an optocoupler. Its LED input stage forms a good substitute for the indicator LED and reduces the pos- sibility of any signal mismatch. The original hard disk indicator LED does not go unused because the circuit provides an output to drive it in the same way that the signal from the motherboard did originally. IC1 drives the indicator scale consisting of ten LEDs driven via 470 Q series resistors. Note. Readers’ Projects are reproduced based on information supplied by the author(s) only. The use of Elektor style schematics and other illustrations in this article or the availability of project (software) downloads from the Elektor website does not imply the project having passed Elektor Labs for replication to verify claimed operation. 34 03-2012 elektor READERS’ PROJECTS to HDD LED in PC case HDD LED Signal from Mainboard +5 V © C2 Cl □ lOOn 47u 25 V r 20 vcc RESET PDO(RXD) IC1 PDI(TXD) PB7(SCK) PD2(INT0) PB6(M ISO) PD3(INT1) PB5(M0SI) PD4(T0) PB4 PD5(T1) PB3(OC1) PD6(ICP) ATTiny2313 XTAL1 PBO(AINO) PBI(AINI) XTAL2 PB2 GND 10 11 12 13 14 K2 vcc GND O o POWER SUPPLY 5V ~70mA R1 470R R2 { 470R R4 { 470R R5 r~ [ 470R R6 "I — | 470R R7 { 470R R8 { 470R RIO { 470R 41 LD1 41 R3 -| 470R LD2 41 LD3 41 LD4 41 LD5 41 LD6 41 LD7 41 R9 -| 470R LD8 41 LD9 41 LD10 110628 - 11 o o Figure 1 . The hard disk monitor circuit diagram is quite simple. To increase the number of LEDs it would be necessary to use a larger controller with corresponding firmware. It is important to ensure that not only the maximum current output from each pin is within spec (10mA here) but also that the current drawn by the complete 1C (60 mA for this device) is not exceeded. If a brighter display is required (which many users find unnecessarily dis- tracting) more efficient low-current LEDs can be used. The complete circuit is powered from a 5 V voltage source (use the 5 V from a spare power connector in the PC normally used to power a hard or floppy drive). A 1 0-way pin header is included on the PCB to allow in- circuit programming of the microcontroller. Construction For this project the author has designed a PCB for mounting the entire circuit includ- ing display LEDs. The PCB layouts for the component side (file: PCB_top.jpg [1 ]) and the underside (file: PCB_bottom.jpg [1 ]) of the board show that despite the use of SMD components the layout is quite well spaced out. The author has specified 1 206 outline SMD resistors which are relatively easy to fit by hand. It is not anticipated that mounting any of the other components will present any great difficulty. All of the components except for the LEDs are fitted to the com- ponent side. The LEDs are mounted on the PCB underside at a suitable stand-off so that the LEDs fit snugly into the front panel holes when the PCB is fixed (on spacers) behind the front panel. A 1 :1 scale photocopy of the PCB layout can be cut out and used as a template to drill the ten LED holes in the PC front panel. The LEDs can also be arranged as in the author’s prototype board (see Pro- totype.jpg at [1 ]). It is important to specify that the microcon- troller is clocked by a 4 MHz internal clock when the firmware is flashed to memory. Without this step the controller runs notice- ably slower and affects the display refresh rate. The screen shot in Figure 2 shows how the clock fuses are configured in the Atmel AVR Studio 4 development environment. The author has written the software in C using the CodeVision compiler. The source code is well documented to allow simple modification should you be tempted to add your own improvements. For the less adventurous there is also a complete Hex file available which can simply be flashed to the microcontroller memory. Both files form part of the free downloads for this article [1 ] together with the PCB design files in Eagle format. To see the display in action click on the video in the link below. Internet Link [i] Video, software and author’s PCB art- work files: www.elektor.com / 1 1 0628 (110628) Wn A*** isAStt 1 HW Sittfli- 1 HW r/r ] Fib* vatut SELrPffi&J □ PW=N □ ESS AVI □ 5FIEN 14 WOTOH U WDLEVEL -■ RSTQi&L n CKErvfc CMCUT HjT_ciaa In RC0k. 4 HK+65 m W Figure 2. The fuse settings in AVR Studio 4 to give an internal 4 MHz clock. elektor 03-2012 35 MICROCONTROLLERS AndroPod (2) HTML and Java implement a tailored i-yj---- user ■ ■' fr^-f.njdrtUr# jfj, 1Arj f if ' -V ' ,V *■ tetftru#, pn j, f ■ ‘ ,V / #/ ,' fg <'Jtvn? *nr_r ?>3te{r JiTr* ■$>„ rj ^ '■ -C" " F '**"*«*" > / -- ' Z™^*afc*y 'V / av> ,■ / w/At ^-^L raef . // f^^-As- j ^ A *,Y> ' "'" ^ _ By Jens Nickel (Elektor Germany Editor) /J7- 1 * -> J Elektor Bus %"J|B COMPATIBLE ** :I in.# In the first article of this series we saw how easy it is to connect your own circuitry to an Android smartphone using the AndroPod interface. Our aim there was to make the software aspects as simple as possible for all users. Building a user interface for your own project with HTML is very easy if your use our free Android app. As always with Elektor, the app software can be downloaded free of charge, and you can modify it if necessary because everything is open source. To control your own circuitry, you basically need an Android app that includes a tailored user interface. The obvious approach is to use the powerful Android framework and the Java programming language to implement this user interface. However, program- ming in the Android environment has a very steep learning curve for beginners, although it may be worth the effort because more and more projects using Android are being published in Elektor. Bern- hard Worndl-Aichriedler [1 ], a student at the Hagenberg campus of the Upper Austria University of Applied Sciences and the developer of the AndroPod Interface, has put together a small Android tuto- rial in German and English (see [2] for download). A user guide in English is also available on the Android developers site [3J. Among otherthings, it explains howto install the Eclipse development envi- ronment [4] and howto extend it for Android programming. After starting a new Android project, the first task is to implement the basic functions (receiving and transmitting bytes over the serial interface). The AndroPod developers provide the Java class AndroPodConnection for this purpose (download at [5]). It can be linked into your own Android projects as described in the tutorial. The next task is to build the user interface, which consists of controls such as text boxes, buttons and so on. The structure of a complete AndroPod app is described in the inset. The source code for this app can be downloaded and used as a starting point for developing your own projects. Same control interface for smartphones and PCs There is also another option for generating the user interface: using HTML and Javascript. Even for beginners, it’s easy to learn how to build an HTML page with the necessary controls and program the control logic in Java. Furthermore, the result is fundamentally inde- pendent of the operating system that is used. You generate the user interface only once, after which you can use it on an Android smart- phone, a PC or another computer platform, as long as a suitable 36 03-2012 elektor MICROCONTROLLERS ANDROID-APP serial interface is available. For PCs, Elektor offers a USB to RS485 converter [6]. In theory the generated HTML pages can be displayed directly on the smartphone in the web browser present on every Android device. However, for security reasons it is not possible to persuade a normal Web browser to send data to the AndroPod or receive data from the AndroPod. For this we need our own Android app, which is a sort of special browser. It provides the HTML user interface and implements communication over the serial interface (Figure 1). The advantage of this is that this app can be provided ready for use and does not need to be modified by the AndroPod user. The Elektor- BusBrowserForAndroPod app is available on the Google Android Market site for free download. This makes downloading and instal- lation on the smartphone or tablet especially easy. The app is also available on the Elektor website in the form of an .apkfile (roughly equivalent to an .exe file in the PC world) and as source code [5]. If you have completed the hardware test described in the first article in this series, this app is already installed [7], but you should update it to the latest version. All you need to do after this is to download your HTML pages to the smartphone, which is not difficult. However, let’s first look at how these HTML pages should be put together. Simple messages Our Android app receives and sends 16-byte messages based on the Elektor Message Protocol [6]. The data rate is 9600 baud, which automatically makes it compatible with many upcoming Elektor projects. This protocol was developed for the ElektorBus [8], but it is by no means limited to ElektorBus hardware or the RS485 bus. The app works equally well if the data is received and transmitted over the mini DIN connector or the pin header. In this regard it is important to note that in this case the RS485 driver must always be disabled by removing the jumper at JP4. HTML/JS: USER INTERFACE o o H E 101 233 USB <3 C> ANDROPOD Smartphone 120097-13 Figure 1. Our Android app includes HTML pages that can be tailored by users for their own projects. BYTE 0 1 2 3 4 5 6 7 8 9 A B C D E F BIT 7 MODE 00 6 5 4 3 2 1 0 10 10 10 10 00000000 ADDRESS RECEIVER ADDRESS SENDER rHANNFI 0 wlIHIN INCLU rHANNFI 1 vnnlilNLL 1 rHANNFI 9 UnHININCLZ rHANNFI ? vnAININCLO rcr - 00 hex ID 0H 0L 1H 1L 2H 2L 3H 3L 120097 - 14 Figure 2. Structure of an ElektorBus message, which has a fixed length of 1 6 bytes. In the simplest case an ElektorBus message has the following struc- ture (see also Figure 2): Byte 0 Byte 1 Byte 2 Byte 3 Byte 4 Byte 5 Bytes 6-13 Bytes 14-15 170 - AA hex 0 0 Receiver address (1 -1 27) 0 Sender address (1-1 27) User data Optional; may be used for a checksum or CRC The default address of the Android smartphone is 1 0, but this can be changed in the Settings menu of the app. In the simplest case you communicate with just one other node, such as your own cir- cuitry, which is fitted with an AVR microcontroller or similar device. If you assign this microcontroller the address ‘1’, messages from the smartphone to the microcontroller have the sequence ‘170, 0, 0, 1 , 0, 1 0, ...’. In the other direction this is ‘170, 0, 0, 1 0, 0, 1 , ...’. The user data bytes are subject to the restriction that the value ‘170’ is not allowed because it is used as the start byte. If you are not happy with this (or something else, such as the fixed message length), you are free to develop your own protocol and modify the code of the Android app accordingly. Detailed Android expertise is not necessary for modifications such as changing the message length, as long as you do not alter the basic structure of the app (see inset). Receiving data After the Android app has received 1 6 bytes, it first parses the mes- sage into three parts: sender, recipient and user data (8 bytes). The user data is then passed to the HTML page of the AndroPod user. The application developer does not need to worry about the details because there is a Javascript library called ‘JSBus’ available for link- ing into your DIY HTML pages. It receives and decodes the 8-byte data packets (see Figure 3), under the assumption that the data is structured according to the Elektor Application Protocol. This pro- tocol is ideal for transmitting measurement values (in integer or elektor 03-2012 37 MICROCONTROLLERS JSBUS ANDROID-APP USER APPLICATION APPLICATION PROTOCOL REC SEND PART PART PART HYBRID MODE / SCHEDULER ELEKTOR MESSAGE PROTOCOL AA MODE REC SEND DATA CRC 120097 - 16 Figure 3. The Android app parses the messages, and Javascript decodes the user data. BIT 7 6 5 4 3 2 1 0 0 1 (2/4) SET/ CURRENT ACK / ORIGINAL + D9 D8 D7 xH 0 D6 D5 D4 D3 D2 D1 DO xL 120097 -15 Figure 4. Two bytes allow values in the range of-1 023 to +1 023 to be represented, which is sufficient for many applications. Interval DIRECTMODE < 3 - 2 2 120097 - 17 Figure 5. The simple Direct mode avoids collisions in one-to-one communication. floating point representation), changing the unit and scale factor (e.g. from volts to millivolts), configuring setpoint values, signal- ling alarms (values outside specified limits), and quite a few other things in ream of instrumentation and control. This protocol will also be used in future Elektor projects (one thing we have in mind is a multimeter), and it can of course be used to control ElektorBus hardware. For example, an AC power switch board will be described in the next edition. Various types of data can be transmitted in the messages. For exam- ple, up to four measurement values (range -1023 to +1 023) for four channels could be transmitted in a single message, using two bytes for each value (see Figure 4). When the Javascript library receives an 8-byte data packet, it splits it into four parts corresponding to four measurement values. For each received part it calls the Javas- cript routine ProcessPart {...}, which must be integrated in your own HTML pages. This is not as difficult as it sounds. Simply include the following lines in your HTML file: