Getting started with the chipKIT™ Max32 OnCE/JTAC Interface Program and debug Freescale DSPs Simple Bat Detector Inexpensive, sensitive and easy to build 770268 The industry’s brightest minds come here to shine. Every year one place brings together the innovators on technology’s cutting edge. And for those four days, Vegas glows brighter. Tuesday, January 1 0— Friday, January 1 3, 20 1 2 Las Vegas, Nevada | CESweb.org REGISTER NOW THE GLOBAL STAGE FOR INNOVATION f f mikro {Yl BUS 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! IN-CIRCUIT DEBUGGER Best selling PIC development board in the world enters it's 7th generation of development. It is state of the art in design, functionality and quality. With 4 connectors for each port EasyPIC v 7 has amazing POWERFUL ON-BOARD MIKROPROG PROGRAMMER AND IN-CIRCUIT DEBUGGER CAN PROGRAM ALL PICIO, PIC12, PIC16 AND PIC18 MICROCONTROLLERS. OUTSTANDING PERFORMANCE AND EASY OPERATION WILL BLOW YOUR MIND. YOU WILL NEED IT, WHETHER YOU ARE A PROFESSIONAL OR A BEGINNER. connectivity. Ports are logically grouped with their corresponding LEDs and Buttons. Powerful on-board mikroProg 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 support make this board an irreplaceable PIC development station. Mikrollektronika get it now DEVELOPMENTTOOLS I COMPILERS I BOOKS WWW.mikrOe.COm DUAL POWGR SUPPLY EASYPIC V7 IS THE ONLY DEVELOPMENT BOARD IN THE WORLD TO SUPPORT BOTH 3.3V AND 5V MICROCONTROLLERS. REVOLUTIONARY ENGINEERING ALLOWED US TO SUPPORT OVER 250 MICROCONTROLLERS IN A SINGLE BOARD. IT'S LIKE HAVING TWO BOARDS INSTEAD OF ONE! Great Expectations Some call it “disappointing”, others “prob- lematic to adapt to active marketing strategies” but I find it fascinating and a constant source of inspiration and amuse- ment: projects and articles that start out insignificant, then taking off in a grand way and eventually reaching blockbuster sta- tus, apparently “self-propelled”. Elektor’s Hexadoku, the Audio DSP Course , E-Weekly, The Chaos Machine, Pico C, Retronics and the ElektorBus are fine examples of Elektor readers determining the rate of success rather than us editors and publishers. Eightinstalmentsago,the ElektorBus wa s n o more than a vague idea loosely mentioned in an E-Labs Inside instalment. Since then it has gained momentum and thanks to many active thinking caps out there we’re now at the stage of describing an ElektorBus control centre running on a Smartphone. Likewise Retronics, kind of my own section in the magazine, started as a joke, but six years on it’s gathered a large group of loyal followers — and contributors! I’ve several ‘sensors’ available to gauge the success of published projects. Maga- zine and board sales reports are the obvi- ous monitors that come to mind, but as an editor I find my weekly website statistics quicker and more up to date, as well as telephone calls and just plain enthusiastic emails. In good engineering spirit I find all manner of feedback useful and rewarding. We kick off a global Challenge again, this time brought to you jointly by RS Compo- nents, Elektor and Circuit Cellar. It’s all about designing a project around the Digilent chipKIT™ Max32 hardware and software using RS’ DesignSpark PCB design tools, where ideally the three culminate in an add- on board that helps save or reduce energy any way you can think of. After the official launch of the Challenge on November 26 at the Elektor Live! event, a limited number of chipKIT™ boards will be given away to participants. Starting on page 16, Clemens Valens reports his initial findings with the chipKIT™ hardware and software compo- nents and you might find his story useful to be in pole position by the time the Challenge starts. I do expect your entry too! Enjoy reading this edition, Jan Buiting, Editor 6 Colophon Who’s who at Elektor. 8 News & New Products A monthly roundup of all the latest in electronics land. 16 SuperArduino This article should put you in pole position for the DesignSpark chipKIT™ Challenge organised by RS Components, Elektor and Circuit Cellar. 20 Improved Radiation Meter Gamma, beta and alpha radiation levels get measured with this instrument based on a cheap and cheerful PIN photodiode. 26 Simple Bat Detector Build this circuit over the winter period and next spring you’ll be able to listen to bats flying to and fro. 30 Audio DSP Course (5) This month we take a look at the important matter of structuring your DSP programs. OnCE/JTAG Interface This adapter was originally designed for the Elektor DSP courseware board but is compatible with other Freescale DSPs too. 42 Economical Voltage Monitor This circuit monitors the voltage output of a solar cell while consuming preciously little power itself. 44 E-Labs Inside: Working with Stencils A step by step guide to making perfect SMD boards as far as applying solder paste is concerned. 46 Here comes the Bus! (9) This month HTML and Javascript are used to make a control station running on a Smartphone. 4 11-2011 elektor CONTENTS 16 Super Arduino The chipKIT™ Max32 board offers 32-bit computing power and some 80 I/O pins while remaining compatible with the Arduino environment. It is the hard- ware component of the exciting design challenge brought to you by RS Com- ponents, Circuit Cellar and Elektor. In this article you’ll find a number of tips that should give you a head start in working with the hardware and software that go into making your entry for the challenge. 20 Improved Radiation Meter The basic instrument described in this article can be used with different sensors to measure gamma and alpha radiation. It is particularly suitable for long-term measurements and for examining weakly radioactive samples. The photodiode has a smaller sensitive area than a Geiger-Muller tube and so has a lower back- ground count rate, which in turn means that the radiation from a small sample is easier to detect against the background. 26 Simple Bat Detector Many species of bat produce sounds at frequencies in the 40 kHz range, which happens to be the operating range of most standard ultrasonic transducers. If you amplify the signals picked up by one of these transducers and feed them into a frequency divider, the output will be within your normal range of hearing. 58 Temperature Gradient Meter Measuring temperature is a fairly simple task, but doing so precisely takes rather more skill, particularly when it is desired to obtain readings to a resolu- tion of better than one tenth of a degree. The circuit presented here measures temperature to a resolution of one ten-thousandth of a degree, using just four active components and an optional display. Volume 37 November 2011 no. 419 54 Spice It Up! An introduction to LT’s renowned simulator — so easy to follow it will get you hooked on Spice! 58 Temperature Gradient Meter This instrument reports and records the tiniest temperature changes with a resolution of i/ioooth of a degree centigrade. 62 Resistive Bolometer An innovative use of two electric bulbs you were about to trash. 64 RGB - YPbPr (or YUV) Converter This circuit proves that analogue video is not dead; in fact it’s wide open to making your own converter projects. 68 Lifelike Lighthouse A ring of LED chaser lights successfully mimic a rotating light beam. 70 Flashing Light for Model Cars Blue LEDs and a handful of parts make a nice flashing light for your model ambulance. 72 Dual Linear PSU for Model Aircraft Here’s how to double the power supply in a remote controlled model. 74 Gerard’s Columns: Teaching Yourself From our monthly columnist Gerard Fonte. 75 Hexadoku Elektor’s monthly puzzle with an electronics touch. 76 Retronics: Exotic Tubes Facebook Old friends hail from this month’s Retronics pages. Series Editor: Jan Buiting 84 Coming Attractions Next month in Elektor magazine. elektor 11-2011 5 elektor international media bv Elektor International Media provides a multimedia and interactive platform for everyone interested in electronics. From professionals passionate about their work to enthusiasts with professional ambitions. From beginner to diehard, from student to lecturer. Information, education, inspiration and entertainment. Analogue and digital; practical and theoretical; software and hardware. m ^Cut-rate Radiation S»*\Meter et#andc t ‘K i ANALOGUE • DIGITAL MICROCONTROLLERS & EMBEDDED AUDIO • TEST & MEASUREMENT ektor rate h,r M _ I . -•! ‘ I" Super Ardui Getting started with the ehlpKIT 1 Max32 OnCE|JTAG Interface Plutfi am and debug FrwvLdlEf DSh> Simple Bat Detector inexpensive, sensitive ind easy to build Volume 37, Number 418, October 2011 ISSN 1757-0875 Elektor aims at inspiring people to master electronics at any personal level by presenting construction projects and spotting developments in electronics and information technology. 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. Elektor is also published in French, Spanish, American English, German and Dutch. Together with franchised editions the magazine is on circulation in more than 50 countries. International Editor: Wisse Hettinga (w.hettinga@elektor.nl) Editor: Jan Buiting (editor@elektor.com) International editorial stafl Harry Baggen, Thijs Beckers, Eduardo Corral, Ernst Krempelsauer, Jens Nickel, Clemens Valens. Design stafl Christian Vossen (Head), Thijs Beckers, Ton Ciesberts, Luc Lemmens, Raymond Vermeulen, Jan Visser. Editorial secretariat: Hedwig Hennekens (secretariat@elektor.com) Graphic design / DTP: Giel Dols, Mart Schroijen Managing Director / Publisher: Don Akkermans Marketing: Carlo van Nistelrooy 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 6 11-2011 elektor Elektor eC-reflow-mate Professional SMT reflow oven with unique features r The eC-reflow-mate is ideal for assembling prototypes and small production batches of PCBs with SMD components. This SMT oven has a very large heating compartment, which provides plenty of space for several PCBs. The accompanying PC software allows you to monitor the temperature curves of all sensors precisely during the soldering process, and it enables you to modify existing temperature/time profiles or create new ones. Special features: • Optimal temperature distribution thanks to special IR lamps • Drawer opens automatically at end of soldering process • Glass front for easy viewing Technical specifications: • Supply voltage: 230 V/ 50 Hz only • Power: 3500 W • Weight: approx, 29 kg • Dimensions: 620 x 245 x 520 mm (W x H x D) • Heating method: Combined IR radiation and hotair • Operation: Directly using menu buttons and LCD on oven • Remotely using PC software and USB connection • Temperature range: 25 to 300 °C • Maximum PCB size: 400x285 mm • Temperature sensors: 2 internal and 1 external (included) V. Price: £21 70.00 / € 2495.00 / US$3495.00 (plus VAT and Shipping) Further information and ordering at www.elektor.com/reflow-mate Email: subscriptions@elektor.com Rates and terms are given on the Subscription Order Form. Head Office: Elektor International Media b.v. P.O.Box ii NL-6114-ZC 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 Telephone: (+31) 46 4389444, Fax: (+31) 46 4370161 Email: t.vanhoesel@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 an 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 Publisher 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. 2010 Printed in the Netherlands elektor 11-2011 7 NEWS & NEW PRODUCTS Compact, high-Efficiency RF Power amplifier for 5 GHz Wi-Fi® applications Microchip Technology Inc., recently announced the new SST1 1 CPI 5 RF power amplifier for 5 GHz IEE 802.1 1 a/n WLAN embedded applications. The device operates on the 4.9 to 5.9 GHz band, and offers a wide operating voltage of 3.3 V to 5 V. The SST1 1 CPI 5 features a high linear output power of 1 8 dBm at 2.5 percent EVM, using 802.1 1 a OFDM 54 Mbps at 3.3 V, and 20 dBm at 5.0 V, and offers an output power of 23 dBm at mask compliance of 6 Mbps, at 3.3V. The device is offered in a compact, 2 x 2 x .55 mm, 1 2-pin QFN package. It is ideal for 5 GHz WLAN applications where small size and high-efficiency operation are required, such as in wireless multimedia and MIMO applications for broadband gateway and consumer-electronics equipment. The SST1 1 CPI 5 meets the needs of designers who must reduce DC current consumption in their portable multimedia and MIMO applications. With its high power-added efficiency, the device reduces battery current drain and extends battery operation. Its 4.9 to 5.9 GHz linear operation enables 802.1 1 a/n operation and increases data rates, while its small size is ideal for space- constrained applications. Developers can begin designing today with the SST1 1 CPI 5 Evalu- ation Board (part # 1 1 CPI 5-QUBE-K), which is available now, via any Microchip sales representative. The SST1 1 CPI 5 RF power amplifier is available in a 2 x 2 x 0.55 mm, 1 2-pin QFN package. Samples are available today, at www. microchip.com/get/TNQ6. Volume-production quantities can be ordered today at www.microchip.com/get/9JD6. For addi- tional information, contact any Microchip sales representative or authorized worldwide distributor, or visit Microchip’s website. www.microchip.com (110604-VI) New multi-function ASB DAQ modules ADLINK Technology, Inc. announces the release of its USB-1 900 Series and USB-2401 USB DAQ modules. Equipped with built-in signal conditioning, the USB-powered Plug and Play USB DAQ modules deliver easy connection and accurate results for both portable measurement and machine auto- mation applications. Featuring built-in sig- nal conditioning, ADLINK USB DAQ mod- ules enable direct measurement of most frequently applied signal sources, which reduces manpower requirements and asso- ciated development costs while increasing overall accuracy. All of ADLINK’s USB DAQ modules feature USB power and removable screw-down ter- minals for simplified device connectivity, and a multi-functional stand for fast and easy desktop, rail, or wall mounting. Addi- tionally, a lockable USB cable secures con- nectivity. The USB DAQ modules also pro- vide device ID setting by a rotary control for convenient identification of the active mod- ule in multiple-connection configurations. ADLINK’s USB DAQ collection offers the USB-1 900 series, consisting of USB-1 901 and USB-1 902 models of 16-bit 250 kS/s DAQ modules. Also in the series is the USB- 1 903, with additional built-in precision cur- rent-to-voltage resistors allowing direct measurement of current signals from 0 to 20 mA. Rounding out the USB DAQ cate- gory is the USB-2401 , a 24-bit four-channel simultaneous-sampling universal DAQ mod- ule supporting sampling rates up to 1 .6 kS/s and a more flexible signal conditioning cir- cuit such as voltage, current, strain, load cell, thermocouple, and RTD measurement. The USB DAQ line is ideally suited for eas- ily accomplished deployment and superior accuracy when measuring temperature, stress, strain, and other factors in diverse applications. The USB DAQ modules include ADLINK’s free U-Test utility, allowing direct operation and testing of all functions with no require- ment for coding or programming. Driver support is provided for Windows 7/Vista/ XP, in both 32-bit and 64-bit versions, and 3rd party software support accommodates LabVIEW & MATLAB. www.adlinktech.com/USBDAQ (110675-II) Power controllers for next-generation server, desktop and computing applications International Rectifier has introduced a new digital power platform that dramati- cally improves energy efficiency in a wide variety of applications, including high per- formance server, desktop and computing applications. The new family of digital controllers is based on CHiL’s proven digital platform offering full telemetry and programmability, provid- ing system designers a chance to differenti- ate their products with custom features. The family offers a fully compliant high speed serial bus to meet new industrial require- ments. These 5, 6 and 8-phase dual output PWM controllers, in which phases are flex- 8 11-2011 elektor NEWS & NEW PRODUCTS ibly assigned between loops 1 and 2, can be easily configured for Intel® VR1 2, AMD® SVI / PVI/G34, and feature switching frequency between 200 kHz to 1 .2 MHz per phase. The family of digital controllers offers effi- ciency improvements with features such as variable gate drive and dynamic phase con- trol for best-in-class efficiency and program- mable 1 -phase or 2-phases for light loads. When used in conjunction with IR’s Pow- IRstage® devices this family offers an opti- mized end-to-end solution delivering high- est efficiency for next-generation servers. Other key features of the new digital con- trollers include adaptive transient algo- rithm (ATA) on both loops to minimize out- put bulk capacitors and system cost, auto- phase detection with auto-compensation and per-loop protection features. In addi- tion, the digital ICs offer l 2 C, SMBus and PMBus system interface for full telemetry and programmability. Non-volatile mem- ory for custom configuration, 3.3 V tri- state driver compatible, +3.3 V supply volt- age and 0 9 C to 85 9 C ambient operation are also featured. All CHiL digital power solutions are fully supported by IR’s Digital Power Design Cen- ter (DPDC) GUI at www.irf.com which facili- tates design, development and deployment of the company’s digital solutions. Addi- tionally, hardware support using IR’s pro- prietary SVID emulator system enables cus- tomers to emulate and monitor either Intel or AMD serial interface protocols, as well as high speed l 2 C communication. www.irf.com (110675-V) Digital differential pressure sensors with very low measurement ranges Sensirion has recently launched two new versions of its differential pressure sensors with-in the SDP600 series. The new sen- sors SDP6xO-1 25Pa and SDP6xO-25Pa fea- ture particularly low measurement ranges of -125 to +125 Pa and -25 to +25 Pa, respectively. Due to their better resolution, the new products have improved zero point accuracy of 0.1 Pa. In addition, zero point repeatability reaches a remarkable 0.05 Pa for the 125 Pa ver-sion and 0.03 Pa for the 25 Pa version. The new differential pressure sensors are excel-lent solutions for many applications in medical and HVAC mar- kets where high accuracy measurements of particularly low differential pressure are required. The two versions complement the compre- hensive product range of Sensirion’s digital differential pressure sensors in the SDP600 series. Along with the other products of this series, they offer a digital PC output and are fully calibrated and tem-perature New series of free schematic symbols and PCB footprints for DesignSpark PCB design tool RS Components’ (RS) and Accelerated Designs’ new series of component libraries provides customers with schematic symbols and Printed Circuit Board (PCB) foot- prints for an extensive range of products from STMicroelectronics and Microchip Technology. Thousands of PCB footprints and schematic symbols are available for free download in a vendor-neutral format from RS’ online DesignSpark electronics design community and resource centre, and can be exported to virtually any EDA and CAD/CAE system using Accelerated Designs’ Ultra Librarian (UL) translator software, thus saving the design engineer valuable time and effort in the CAD design process. The UL Reader also supports RS’ free DesignSpark PCB design tool that offers powerful schematic capture and PCB layout software. The free Ultra Librarian software, including footprints and symbols, is available now for download from the Designspark website. Bill of Materials (BOM) reports can be generated and prices quoted using RS’ free Online Quotes tool. www.designspark.com (110604-VII) elektor 11-2011 9 NEWS & NEW PRODUCTS compensated. Thanks to the principle of calorimetric flow measurement, the CMO- Sens® differential pressure sensors achieve outstanding sensitivity and accuracy, espe- cially around the zero point. Furthermore, the sensors exhibit very high long-term sta- bility and freedom from zero-point drift. www.sensirion.com/sdp6xo www.sensirion.com/ differential-pressure-sensor-sdp6xo-datasheet (110675-III) Wireless QWERTY keypad-equipped DUAL IR/RF remote control Ultra low power (ULP) RF specialist Nor- dic Semiconductor ASA announced that Philips Home Control, Singapore, is using Nordic wireless technology in its advanced QWERTY keypad-equipped DUAL infrared (IR)/RF remote control. DUAL is designed for use by consumer elec- tronics (CE) manufacturers of emerging ‘connected’ products such as Smart TV, Over The Top (Internet) boxes, and Hybrid set-top boxes (STB). The DUAL platform comprises everything required for CE man- ufacturers to develop a customized IR/RF remote control with minimum design over- head, and includes controller handset, com- pact USB dongle, and demonstration soft- ware that runs on a PC. DUAL is equipped with a full QWERTY-key- pad on one side, and on the other, touchpad or optical sensor controls for alternate input methods allowing manufacturers to imple- ment free cursor, gesturing, and moving highlight mechanisms. Philips Home Con- trol says this makes browsing a better expe- rience than traditional RF remote controls with directional keys. iPad, iPod touch, and iPhone turned into spectrum analyzer or dynamic power meter.. .or both Oscium’s breakthrough product line for the iOS Test industry enables iPad, iPod touch, and iPhone to now become either a spectrum analyzer or a dynamic power meter.. .or both. Oscium’s first-to- market product, iMSO-104, successfully merged a mixed sig- nal oscilloscope and the iOS family of products using the 30-pin dock connector. The contribution was so significant that Cypress Semiconductor Corp heralded the prod- uct as ‘revolutionary’. Oscium’s new product line, called WiPry, is the next installment in modular test equipment. This new category of test equipment has the potential to change the benchtop dominated landscape by establishing the touchscreen-based iPad (or iPhone, iPod touch) as the new user interface. This platform presses the refresh button on the anti- quated buttons and knobs of benchtop instruments while at the same time offering mobility that PC- based instruments cannot match. Three distinct prod- ucts fit under the WiPry brand: WiPry-Spectrum, WiPry-Power, and WiPry- Combo (which com- bines the functionality of both WiPry-Spectrum and WiPry-Power). WiPry-Spectrum leverages the colorful potential of the OpenGL inter- face on the iOS platform for stunning real-time views of RF activity in the 2.4 GHz ISM band. WiPry-Power crosses the chasm of this new platform by not only graphically displaying RF data from 1 00 MHz - 2.7GHz but also adding the ability to capture, trig- ger and record the actual power output of RF amplitude. An optional accessory kit is also available that boosts the products ability by giving the user the ability to make conducted measurements. The final product combines all the features of both WiPry- Spectrum and WiPry-Power into one product called WiPry-Combo. By merging a spectrum analyzer and a dynamic power meter into the iOS Test industry, Oscium is opening the door for a more productive and useful mobile platform. WiPry-Spectrum costs $99.97, WiPry-Power $149.97, and WiPry-Combo $199.97. WiPry is compatible with all generations of iPod touch, iPhone, and iPad devices run- ning iOS version 3.1.3 or higher. It is made for: iPod touch (1 st, 2nd, 3rd, and 4th gen- eration), iPhone 4, iPhone 3GS, iPhone 3G, iPhone, iPad 2, and iPad. www.oscium.com (110675-I) Traditional remote controls struggle to meet the demands of modern consumers due to limited bandwidth and ‘one-button- one-operation’ interfaces. RF provides suf- ficient bandwidth for advanced navigation interfaces — such as scroll wheels, touch screens, and track balls — and bi-directional communication required when negotiating the complex user interfaces and menus typ- ical of modern media devices. In addition, the QWERTY keypad is useful for brows- ing the Internet on the latest generation of Smart TVs and other connected products. 10 11-2011 elektor NEWS & NEW PRODUCTS PHILIPS DUAL, I-OIKM V RF eliminates the need for IR’s line-of-sight access, allowing devices to be controlled in the presence of obstacles and even interior walls (up to a range of 1 5m and assuming wall construction materials do not exces- sively attenuate the RF signals). DUAL remote control also incorporates IR remote control functionality so that users can oper- ate legacy entertainment devices. In operation, the DUAL remote handset uti- lizes a Nordic nRF24LE1 System-on-Chip (SoC) 2.4 GHz ULP transceiver running a modified version of Nordic Gazell RF pro- tocol software. An nRF24LU1+ System- on-Chip (SoC) 2.4GHz ULP transceiver and USB 2.0 compliant device controller, incor- porated into a compact USB dongle, plugs into the host device (the product to be con- trolled) to form the other node of the wire- less link. The Nordic RF technology enables a bi-directional communication link with sufficient bandwidth for rapid screen refresh and seamless navigation. The nRF24LE1 integrates a proven nRF24L01+ transceiver core, enhanced 8051 microcontroller, 16 Kbytes of on-chip flash and 1 Kbytes of SRAM into a single- chip solution. The chip boasts a 2 Mbps on-air data rate combined with ultra low power (ULP) operation and advanced power management. The nRF24LU1 + inte- grates a USB 2.0 compliant device control- ler, 8-bit application microcontroller, and nRF24L01+ compatible 2.4 GHz RF trans- ceiver. Gazell RF protocol soft- ware provides features for advanced navigation, remote data transfers, and advanced pairing schemes while handling up to five remote devices at the same time. In addition, Gazell is a frequency agile protocol that is highly immune to interfer- ence from other 2.4 GHz radio sources. DUAL from Philips Home Control is now ready for commercialization. www.nordicsemi.no (110675-VI) 16-Channel 50mA buck LED driver with dot correction & gray scale dimming Linear Technology announces the LT3745, a 1 6-channel LED driver integrated with a 55V step-down controller. The LED driver powers up to 75mA of LED current for each channel, which can drive up to 36V of LEDs in series, making it ideal for applications such as large LED billboards. Each channel has individual 6-bit dot correction current adjustment and 1 2-bit gray scale PWM dim- ming. Combined with a 0.5 ps minimum LED on-time, the LT3745 offers very wide dynamic contrast ratios. Both dot correc- tion and gray scale dimming are accessible via a serial interface in TTL/CMOS logic. The LT3745’s 6 V to 55 V input voltage range is well suited for a wide range of input sources found in commercial and industrial designs, typically between 1 2 V and 48 V. The com- bination of minimal externals and a 6 mm x 6 mm QFN package provide a highly com- pact solution footprint for multichannel LED applications. The LT3745’s internal buck controller gener- ates an adaptive bus voltage slightly higher than the parallel LED strings to deliver effi- ciencies over 90%. Sixteen individual linear current sinks regulate and modulate indi- vidual LED strings, offering a wide range of functionality in a compact solution foot- print. The LT3745 performs full diagnos- tics and protection against open/short LED and overtemperature faults, with the fault status sent via the serial data interface. The 30 MHz fully buffered, skew-balanced, cas- cadable serial interface makes the LT3745 ideal for large screen LCD dynamic back- lighting as well as full color LED displays. www.linear.com/product/LT3745 (110675-IX) X f.MMril QQ[i (t — f //I =r --*7*:: * f t ; : 1 : * * * ’ ■ ■ Tl. TNClS [ al te TIL" xt i m Advertisement PCBs Muuuuch Cheape f. No-frills policy 16.94 EURO" 5 pcbs, 100 mm x 100 mm *per piece, incl. DAT (21%) + shipping costs e. g. Germang 1 0.71 EURO * Jadaltac LULum.jackaltac.com elektor 11-2011 11 NEWS & NEW PRODUCTS New general purpose programmable power supply product line Keithley Instruments, Inc., intorduces five new general-purpose programmable DC power supplies designed to comple- ment the company’s existing line of spe- cialty power supplies and source measure- ment instruments for component, module, and device characterization and test appli- cations. The Series 2200 family combines superior voltage and current output accu- racy at a cost-effective price, flexible opera- tion, and features designed to enhance ease of use in a variety of device characterization or test applications. More information on the Series 2200 is available on Keithley’s website. The five models in the Series 2200 line offer maximum voltage, current, and power out- put levels designed to address a wide range of sourcing requirements for characterizing components, circuits, modules, and com- plete devices: Model 2200-20-5: 20V, 5A, 100W Model 2200-30-5: 30V, 5A, 1 50W Model 2200-32-3: 32 V, 3A, 96W Model 2200-60-2: 60V, 2.5A, 1 50W Model 2200-72-1 : 72V, 1 .2A, 86W The voltage output accuracy of Series 2200 power supplies is specified at 0.03%; their current output accuracy is 0.05%. Both specifications are significantly better than those of competitive general-purpose sup- plies. In addition, their high output (1 mV) and measurement (0.1mA) resolution makes them well-suited for characterizing low power circuits and devices in applica- tions such as measuring idle mode and sleep mode currents to confirm devices can meet today’s ever-more-challenging goals for energy efficiency. Remote sense terminals on the back panel and less than 5 mV pp noise help ensure that the voltage programmed is the voltage that the supply actually outputs. A dual-line display shows both the programmed values and actual outputs for a continuous indication of the status of the power delivered to the load. Series 2200 supplies include a variety of fea- tures designed to enhance operating versa- tility. For example, each model provides 40 onboard memory locations for storing fre- quently used test setups for later recall and reuse. In addition, a built-in list mode func- tion supports the programming and stor- age of up to seven custom test sequences of up to 80 steps. Once saved, a sequence can be triggered to run manually using the instrument’s front panel keys, automatically via an external trigger, or by using program- mable interface commands. Competitive general-purpose power supplies don’t pro- vide these capabilities. Several Series 2200 fea- tures help protect DUTs from damage during test- ing, including a program- mable voltage limit value that prevents the supply from outputting exces- sive voltage (even if a volt- age higher than the limit is entered into the instru- ment) and a programma- ble over-voltage function that causes the output to drop to less than 1 V if the over-voltage limit is reached. These limits are in addition to the current limit setting function, which controls the level of current that can flow into the DUT. Also, a programmable timer can be used to turn off the output after a [continued on p.14] GALEP-5 programmer has 60k device output GALEP-5 is a new, diminutive, palm-sized programmer with a massive device output. Its high speed allows it to double as a fast production programmer in ganged arrays, while its JTAG debugging capabilities enable GALEP-5 to be used for microcon- troller development. GALEP-5 is a universal programmer for a wide range of device types: EPROM, EEPROM, FLASH mem- ory, serial EEPROM, NV-RAM, LPC, FPGA, PLD, EPLD, GAL, PALCE, PIC, Microcontroller (MCU). More than 60,000 device algorithms are currently supported. Additionally, GALEP’s JTAG player can program SVF/JAM data into all existing and future devices that have a JTAG port. Ultra-compact, USB-powered GALEP-5 Device Programmer fits into a jacket pocket and weighs less than 200g, tiny compared with the 3-4 lbs of most other programmers. Ver- satile GALEP-5 is normally powered via USB from a PC, but it has two additional power options — rechargeable internal batteries, or conventional line power plug — useful when it needs more than 500 mA for older NMOS devices. GALEP-5 has been designed for speed. An internal 200 MIPS ARM-9 processor handles the data transfer, while a 50,000 gate FPGA controls the pin drivers and accelerates programming algorithms by setting up device-dependent state machines and UARTs. A custom-designed pin-driver 1C implemented to all pins on the socket guarantees optimal signal quality at the output pins. This design innovation permits an extremely small size and very low power consumption. This level of hardware acceleration makes GALEP-5 one of the fastest device program- mers available. For instance, a MB91 F467 Fujitsu Microcontroller (8MB) requires only 1 9 seconds for a serial program/verify cycle; a 256 MB NOR Flash (28F256P30) is pro- grammed and verified in 1 70 seconds. Internal 64 MB of RAM provides data storage, permitting transfer of data once only in order to program multiple devices. The GALEP-5 Programmer is available now at only $597.95 from Saelig Company. Inc. Pittsford NY, USA. www.saelig.com (110675-IV) 12 11-2011 elektor QUASAR Quasar Electronics Limited PO Box 6935, Bishops Stortford CM23 4WP, United Kingdom Tel: 01279 467799 Fax: 01279 267799 E-mail: sales@quasarelectronics.com Web: www.quasarelectronics.com 01279 All prices INCLUDE 20.0% VAT. Postage & Packing Options (Up to IKg gross weight): UK Standard 3-7 Day Delivery - £4.95; UK Mainland Next Day Delivery - £1 1 .95; Europe (EU) - £1 0 95; Rest of World - £1 2.95 (up to 0 5Kg). Order online for reduced price UK Postage Payment We accept all major credit/debit cards. Make cheques/PO’s payable to Quasar Electronics. Please v sit our online shop now for full details of over 500 kits, projects, modules and publications. Discounts for bulk quantities. VISA ViSA Electron Credit Card 467799 SWITCH Board menu and to set the serial port properly (Tools -> Serial Port). Once done the BlinkWithout- Delay example (File -> Examples -> Digital) should work without modification, just click the Upload button to see the green LED LD4 start to flash at a rate of 0.5 Hz. If you got this far without problems you’re all set to develop real applications for the Max32. So read on, because there will be some hur- dles that you may want to know of... Porting a shield Flashing an LED is nice, but not very satisfy- ing, that’s why I ventured on to try out my Arduino Ethernet shield on the Max32 (a shield is an extension card for an Arduino board). This shield is based on Microchip’s ENC28J60 stand-alone Ethernet control- ler with SPI interface. I know, the PIC32 has an Ethernet MAC inside, but I didn’t have a shield handy with an Ethernet PHY and RJ45 connector. Digilent proposes such a shield (that offers other things besides), but I didn’t have time to order one and wait for it to arrive. Besides, now I had a good opportunity to see just how Arduino com- patible the Max32 is. As you will see below, not entirely... My old Ethernet shield — I will call it etherShield from now on to distinguish it from the new official Arduino W51 00-based Ethernet shield — is supported by a library and some examples. This shield and code works just fine on my Seeeduino. The first step was therefore to install this library in the Max32 IDE (in the folder libraries\) and see if it would compile. The answer was, as you may have expected: No(pe). The reason was not so much the code itself, but the fact that the compiler apparently was unable to find anything to compile. According to the Digilent website, where a few things about porting Arduino code are explained, librar- ies are supposed to be handled in the same way as Arduino does, but clearly not in my case. When I put the library in the folder hardware\pic32\libraries\ (where you find the same items as in the folder libraries]) the compiler did find the code, but produced many errors and a warning saying that the code contained AVR specific code (Arduino boards are based on Atmel’s AVR proces- sors). Great! Now I had clue. The first thing you have to do when port- ing Arduino libraries is to get rid of the ref- erences to program memory. With an AVR some special compiler directives are needed for accessing constants (strings, tables) located in program space. This is unneces- sary for the PIC32 and these directives have to be removed. To keep your code Arduino compatible it may be better to #def i ne them away, you can use the macro _ BOARD_|VEGA_ (see Figure 1) defined by the Max32 IDE to do this (confusing; you’d have expected something like _BOARD_ W\X32_). Do the same for any AVR-specific #i ncl ude directives. This may not be sufficient (in my case it wasn’t) because the library may also refer to AVR registers that the PIC32 doesn’t have. The SPI driver for the ENC28J60 Eth- ernet chip did this, probably because it is relatively old and the SPI library that’s now part of the Arduino IDE simply did not exist when at the time it was written (it did not appear before version 0019 from Septem- ber 2010). I therefore modified the old etherShield library to use the new Arduino SPI library instead and tested this first in the real Arduino IDE before trying it in the Max32 IDE. This introduced new problems because the SPI library references pin functions that the Max32 compiler did not like. As it turned out, the hitch was caused by my library being written in C and compiled as such, whereas the pin functions and the SPI library are written in C++. Files with the extension .c are compiled as C, files with the exten- sion .cpp are compiled as C++. So, back to the Arduino IDE it was for porting the com- plete etherShield library to C++ and testing it. This was not particularly difficult to do, but you may have to watch out for com- piler directives like #ext er n “C" { ... } hidden in unexpected places. After this last modification my etherShield library com- piled without errors in the Max32 IDE and for the Max32 board. But did it work? No — of course not! This did not really come 18 11-2011 elektor MICROCONTROLLERS 4- + | wtp /,;!*?. ies. i-i5.i " C la- / * “■~" r Welcome to chipKTT Ethernet Shield VI. 0 — Put vour chipKlT online — Control digital uiiLpiits Read digital analog inputs HERE VI. 0 ww^ckkser.cQHi -a Figure 3. The modifications I made to the etherShield. Figure 4. The result of a successful port: I can now connect to a tiny web server running on the Max32. as a surprise as I had already spotted SPI- problem posts on Digilent’s website, but the optimist in me kept hoping. The main problem is incompatibility of Max32 I/O pins with AVR I/O pins. Arduino digital pins 1 0 through 1 3 have SPI capabil- ity and pins 1 0 and 1 1 can do PWM also. The reason for this combination is simply the way the AVR I/O pins were laid out byAtmel. The PIC32 combines functions in a different way on its I/O pins and there are no exact equivalents for these AVR pins. Digilent has chosen to give priority to the PWM func- tions as they are used by Arduino’s analog- Write functions, meaning that they could only connect part of SPI port 2 to these pins. However they did find a way to connect SPI port 1 in an Arduino compatible manner by using the Arduino ICSP connector (Figure 2) that’s connected to the same signals as pins 1 0 through 1 3. 1 had never considered this connector as part of a compatible shield, and I am in good company, but Seeedstu- dio, the maker of my etherShield, had put an ICSP pin header on the shield in the right place. Replacing it with a female (socket style) connector on the solder side only took a few minutes and restored SPI com- patibility with the Max32. To prevent con- flicts on pins 11,12 and 13 (MOSI, MISO & SCK) I simply removed these pins from my shield (Figure 3). Now it should work, right? Wrong. At this point I fired up the oscillo- scope because I suspected compatibility issues between the SPI protocol as pro- duced by the PIC32 and the one accepted by the ENC28J60. Notably the clock speed was worrying me slightly. The scope proved me right, because where the Arduino managed to reach a clock speed of about 61 0 kHz, the PIC32 was blasting away at 20 MHz. Accord- ing to the datasheet of the ENC28J60 this should be OK, but experimenting later when all was finally working showed me that 2.5 MHz was a more realistic value. For now I just reduced the PIC32’s clock speed to an Arduino-like value: 625 kHz. With this change the shield still didn’t work, but I felt I was getting close. Nowadays even the lowest budget digital oscilloscopes can record traces, including my 240-euros (shipping included) 25 MHz Atten ADS1 022C, and this very useful func- tion showed me that there was a polar- ity/phase issue between the SPI clock and data lines. By carefully comparing transi- tions I discovered that the shield needed SPI mode 1 on the Max32 whereas it used mode 0 on the Arduino. Did that mean that the shield was now finally working? It did (Figure 4). Phew. Final remarks Digilent have made a decent job of port- ing the PIC32 to the Arduino IDE. Although they did not achieve 100% compatibility, they definitely tried hard and managed to get pretty close. It’s safe to assume that simple Arduino shields with simple libraries respecting Arduino coding rules and style will be easily portable, although you may run into some of the problems I encoun- tered. The more complex shields exploit- ing AVR subtleties will definitely be more difficult and may require solid PIC32 knowl- edge. To keep your life easy, try to use the functions available in Arduino libraries as much as possible, and let Digilent do the hard work for you. Digilent has started keeping a list of known- to-work shields, so first look there before starting a project yourself. Updates to the Max32 IDE correcting some of the issues mentioned in this article may be expected, so make sure you always use the latest version. The only thing that I haven’t completely cleared up yet is the issue of where to put your own libraries. After thinking hard and experimenting a bit I settled on the assump- tion that all files that contain PIC32 spe- cific code, like low-level drivers, must be placed in the folder hardware\pic32\librar- ies\ including the files that need these files. All other files including the examples that use the library must be placed in the folder libraries \ to ensure they are recognized by the IDE as examples. The source code files for the tests and experiments described in this article can be downloaded from [4]. (110661) Internet Links and Resources [1] http://chipkit.cc [2] www.digilentinc.com [3] http://arduino.ee [4] www.elektor.com/ 1 10661 elektor 11-2011 19 TEST & MEASUREMENT Improved Radiation Meter Counter for alpha, beta and gamma radiation By Burkhard Kainka (Germany) All that’s required to measure radiation is a simple PIN photodiode and a suitable preamplifier circuit. We present here an optimised preamplifier and a microcontroller-based counter. The microcontroller takes care of measuring time and pulse rate, displaying the result in counts per minute. The device we describe can be used with different sensors to measure gamma and alpha radiation. It is particularly suitable for long-term measurements and for examin- ing weakly radioactive samples. The pho- todiode has a smaller sensitive area than a Geiger-Mullertube and so has a lower back- ground count rate, which in turn means that the radiation from a small sample is easier to detect against the background. A further advantage of a semiconduc- tor sensor is that is offers the possibility of measuring the energy of each particle, allowing a more detailed investigation of the characteristics of a sample. The optional PC-based software displays the energy spec- trum, permitting a very detailed analysis to be carried out. Preamplifier In the June 2011 issue of Elektor we described experiments using a BPW 34 photodiode as a detector for gamma radia- tion [1 ]. Only simple experiments could be carried out as the pulses from the detector are very short. Here we look at an improved preamplifier design, which avoids the use of a comparator, and which generates output pulses that can be heard directly or pro- cessed further. The amplifier uses a BF 245 B JFET at its input followed by an opamp cir- cuit, providing an overall voltage gain of 30 000 . At the output it delivers pulses with an amplitude of up to 200 mV with a pulse width of around 0.5 ms, which can be ren- dered audible without further processing or which can be used to drive a counter. The circuit (see Figure 1) can use sev- eral photodiodes in parallel at its input. On the one hand, this increases the pulse rate; unfortunately, this advantage is on Elektor products and services • Printed circuit board: #110538-1 • Kit (components and circuit board): # 110538-71 • PDF layout: free download at [2] • FT232R USB/Serial Bridge: #110553-91 • Software and firmware: free download at [2] (file # 110538-11) 20 11-2011 elektor TEST & MEASUREMENT Features Measures alpha, beta and gamma radiation Simple construction using standard components PC connection using Elektor FT232R USB/Serial bridge Threshold configurable in software from the PC Two different types of sensor can be used the other hand offset by I the reduced amplitude of the sensor’s output due to its increased total capacitance. The JFET input offers good signal-to-noise ratio and a high input impedance. A DC level of about 2 V or 3 V appears across the BF245B’s source resistor, more or less inde- pendent of the supply voltage. If a BF245C is used, this voltage will be higher; in the case of a BF245A, lower. This voltage level is a suitable operating pointforthe opamp. The capacitance of the photodiode drops as the voltage across it increases, and so it is operated at the full supply voltage, with the gate of the JFET being pulled to ground through a 20 resistance. The counter The pulse counter is constructed using an ATmega88 and a two-line LCD. The power supply voltage of 9 V to 12 Vis taken via D1 (for reverse polarity protection) to voltage R1 R2 Rll 45V 1 20 VCC AVCC AREF IC4 PCflRESET/PCINTTA) PC5(ADC5ySCL/PCINn3) PC4(ADC4/SDA/PCINT12) PC3(ADC3/PCirmi) PC2(ADC2/PCINT10) PCKADC1/PCINT9) PC0(ADCCyPCINT8) ATMEGA88 PB5(SCK/PCINT5) PB4(MSO/PCII\ir4) PB3(MOSI/OC2A/PCINO) PB2(SS/0C1B/PCIWT2) PBKOC1A/PCINT1) PBOflCPl/CLKO/PCINTO) GND XTAL1 XTAL2 AGND PD0(RXiyPCINn6) PDXCrXD/PCIMn7) PD2(iNnypciNns) PD3(INn/OC2B/PCINn9) PD4fnyXCK/PCINTT20) PD5(n/OCOB/PCINT21) PD6(AINO/OCOA/PCINT22) PD7(AIN1/PCI MT23) 8 10 22 X 11 12 13 LCD1 in u _ > oinrsirorfinior' ^^l.SS!S8!S 8 8 8 0 d = RE ADBYTE ( ) D = Get a d c ( 0) bi n( d) = bi n ( d ) + 1 L 0 op Unt i 1 D > UO We nd Po r t b . 0 = 1 Fo r n = 1 To 255 Po r t b . 1 = 1 xl = 2 * n 1 f D > Ma x Th e n Me \ x = D x 2 = 2 * r 1 + 2 Do y 1 = 2 0 0 - b i n ( n > D = Get a d c ( 0) y2 = 2 0 0 - b i n ( n + 1) 1 f D > Ma x Th e n CD X II If y 1 > 21 i 5 Then y 1 = L 0 op Unt i 1 D < UO If y IX) V IX) 1 n i 5 Then y2 = N = N + 1 Pi ct u r e 1 . L i n e ( x 1 , yi) Ma x = Ma x - U m ( X 2 , y 2 ) 1 f Ma x > 255 Th e n Max = Ne xt n 255 End S u b Pr i nt Ch r ( ma x ) ; Po r t b . 0 = 0 Po r t b . 1 = 0 Listing 5: 255 255 Loop Listing 3: Timer processing and LCD output Ti ml _ i s r : T i me r 1 = - 7 8 1 2 S = S + 1 If S = 60 Then S = 0 Setting the trigger threshold Private Sub C 0 mma n d 2 _ C I i ck( ) I = HScr ol I 1. Val ue SENDBYTE I End Sub Private Sub C 0 mma n d 4 _ C I i ck( ) I = 100 + HScrolll. Value SENDBYTE I End Sub extremely carefully as any damage to the diode itself or to its bonding wires spells doom for the device. A lidded tin makes a good screened enclosure (Figure 8). The metal must be connected to signal ground so that it provides electrical shielding as well as screening from ambient light. The lid must of course be fitted before any readings can be taken. The oscilloscope shows high-amplitude peaks, up to 2 V, corresponding to alpha particles. Smaller peaks can also be seen: the BPX61 is, like the BPW34, sensitive to gamma rays too. Hence we can discriminate between the two types of radiation on the basis of the pulse amplitude. Firmware The firmware is available for free download at [2]. It is written in BASCOM-AVR and is Figure 8. Screening. reasonably easy to understand. The output voltage from the preamplifier in the qui- escent state is about 2 V, on top of which we see the sensor pulses. In order to count these pulses we need to use some kind of comparator, and the AT mega is fast enough to do this job in software. At start-up the unit computes an average background sig- nal level by averaging 1000 readings (see Listing 1). The averaged value U is then increased by a trigger threshold increment L to produce a threshold U 0 which gives adequate margin over background noise for reliable counting. During the measurement itself (Listing 2) the output of the software comparator is also used to drive digital output ports PortB.O and PortB.1 . An LED is connected to pin B.O to give a brief flash of light for every pulse detected. An small loudspeaker can be connected to B. 1 with a resistor ora vol- ume control potentiometer in series. The maximum level achieved by each pulse is also measured and output as a single byte over the serial interface, to which a PC can be connected. This single-byte format is chosen so that no extra time is wasted in data transmission. As a consequence the maximum pulse height that can be reported is 1 .25 V, which corresponds to a byte value of 255. Pulses of greater amplitude than this are clipped to the maximum value. The display continuously shows the current counter value, updated once per second (Listing 3). Accompanying this on the lower 24 11-2011 elektor TEST & MEASUREMENT Figure 9. The alpha spectrum of a sample of pitchblende. Figure 10. Gamma radiation: pitchblende behind a piece of aluminium foil. Figure 1 1 . Beta particle measurements from a potassium chloride sample. line of the display is the total time elapsed since the beginning of the measurement, shown in minutes and seconds. At the end of each full minute the program calculates the count rate in pulses per minute. The sensitivity of the unit depends chiefly on the threshold setting for the compara- tor. This is initially set at ten A/D conversion steps above the quiescent level, but the value can be modified if desired using the ure 9). The higher energy values are due to alpha particles: because of the relatively thick sample used these tend to lose a lot of their energy on their way to the sensor, and so no sharp energy lines are seen with this sample. When looking only at gamma rays using the BPW34 the higher energy levels are empty; when alpha particles are detected they usually have an energy beyond the range of the display, which readings over a long period using the BPX61 and a small sample of potassium chloride. Ordinary potassium chloride contains a small percentage of radioactive potas- sium-40. Some 90 % of the disintegrations produce beta particles with energies of up to 1 .3 MeV; the other 1 0 % produce gamma quanta with energies of 1 .5 MeV. The beta spectrum shows a characteristic falling-off in energy up to a clearly-visible maximum Measuring background radiation serial interface. A threshold of three steps has proved a good compromise, giving reli- able pulse counting while still being above the background noise level. To change the threshold simply send a single byte to the unit over the serial port. Values of up to 100 are used immediately as the new threshold value. If you wish to store the new threshold as the default value in the microcontroller’s EEPROM, add 1 00 to the value before send- ing it. In this case the new setting does not take immediate effect. So, for exam- ple, sending the byte value 1 03 will set the threshold after the next reset to three. PC software The Visual Basic program AlphaGamma (available for free download at [2]) receives incoming bytes over the serial port and counts them in 255 bins. After a while col- lecting these values it becomes apparent which energy levels are particularly com- mon in the incident radiation. The energy spectrum is plotted in a simple graph (Fig- accounts for the sharp peak seen at the maximum energy value. Listing 4 shows the main timer routine. In this routine all the bytes found in the input buffer are read in and processed. For each byte one element of the array ‘bin’ is incre- mented and then the results are displayed graphically. The program also allows the trigger thresh- old to be set to any value from 2 to 100. The value can be used immediately or stored in EEPROM (Listing 5). Alpha particles can easily be filtered out, for example by placing a piece of aluminium foil in front of the ‘naked’ BPX61. Doing this considerably reduces the energy spectrum obtained from a sample of pitchblende (Figure 10). Beta particles also produce measurable sig- nals. The pulse amplitude they produce is generally similar to that which results from gamma radiation, and it is therefore difficult to distinguish between the two. To test for beta particle sensitivity it is possible to take value, while the gamma spectrum takes the form of a sharp line. The result is the full spectrum shown in Figure 1 1 , demon- strating that the photodiode is capable of detecting alpha, beta and gamma radiation. (110538) Internet Links [ 7 ] www. elektor. com/ 110372 [2] www. elektor. com/ 1 1 0538 Kit of parts A kit of parts is available for this project, containing the printed circuit board and all components including a pre-pro- grammed microcontroller. A suitable display can also be purchased. Prices and further information can be obtained from the web pages accompanying this article at [2] and in the ‘Shop’ pages at the back of this issue. elektor 11-2011 25 HOME & GARDEN Simple Bat Detector Inexpensive, sensitive and easy to build By Jan van Eck (The Netherlands) (j.vaneck@fontys.nl) Various animal welfare associations everywhere in Europe have designated 2011 as the Year of the Bat. Their aim is to enhance public awareness of these flying mammals, which are unfamiliar and surrounded by mystery for many people. Bats hibernate at this time of year, but this gives you time to build this simple bat detector so that you will be prepared to go on safari for bat sounds in the spring. In order to hear the sounds made by bats, we have to make use of a few electronic techniques. This is because bats use sounds in the ultrasonic range to detect objects while they are flying, and these sounds are well outside the range of human hear- ing. Many species of bats produce sounds at frequencies in the 40 kHz range, which happens to be the operating range of most standard ultrasonic transducers. If you amplify the signals picked up by one of these transducers and feed them into a frequency divider, the output will be within your normal range of hearing. The circuit A type 400SR1 60 ultrasonic receiver was selected for the sensor, since most bats in our part of the world produce sounds in a range around 40 kHz. The author opted for the inexpensive plastic version of this trans- ducer, which can easily be protected with a piece of aluminium foil or metallised adhe- sive tape. The signal picked up by the transducer is amplified by a factor of approximately 200 by IC1 , an LM386 (Figure 1 ). Although the LM386 is designed as a power amplifier 1C, its low price makes it perfectly suitable for use as a ‘normal’ gain stage. The main advantage here is that aside from a few decoupling components, no external com- ponents are necessary. The gain can be boosted from the minimum value of 26 dB to 46 dB by connecting a capacitor across the internal feedback path of the LM386 (between pins 1 and 8). A 10-pF electro- lytic capacitor is used for this purpose in the standard application circuit, but this is only necessary if you want to amplify vir- tually the entire audio band with the same gain. That is not necessary for this applica- tion, so the value of capacitor Cl can be reduced to 220 nF, which places the corner frequency at approximately 4 kHz. This means that in theory the capacitance could be made even smaller, which would reduce the risk of problems with low-fre- LSl UM4148 110550-11 Figure 1 . Schematic diagram of the simple bat detector. 26 11-2011 elektor HOME & GARDEN COMPONENT LIST 43 -tf) -3 C j Op) -O Q -12 -15 -18 -21 -24 -27 -30 -33 -ib -42 20k 30k 40k 50k 60k 70k 80k 100k 110550-12 Figure 2. Frequency response at the output of IC2b (top) and the output of IC1 (bottom). from the amplifier passes through a fairly steep high-pass filter built around IC2a and IC2b. This is a Chebychev filter with pass bandwidth of approximately 1 5 kHz and a gain of around 50 (see the blue curve in Figure 2). It strongly suppresses undesir- able signals, such as (mechani- cally coupled) feedback from the loudspeaker. The filter was dimen- sioned using the free program Fil- terPro Desktop from Texas Instru- ments [1 ]. The gain of the filter stage is approximately 35 dB, as can easily be seen from Figure 2 (0 dB r is relative to the output), where the bottom curve represents the out- put signal from IC1. The bandwidth is further limited by adjustable-gain amplifier IC2c after the filter to suppress high- frequency noise. Capacitor Cl 2 limits the bandwidth to 1 60 kHz. If necessary, you can reduce the bandwidth a bit more. The final opamp in the circuit (TL074) is used in conjunction with a voltage divider (R1 1 /R1 2, each 47 k£l) to generate an arti- ficial ground reference for the other opamps at half the supply voltage level. The output signal from IC2c is fed to the Resistors R1 =10£1 R2 = 1.3I<£1 R3 = 1 50l<^ R4,R7,R9 = 1 k£2 R5 = 560I<£1 R6 = 1 0ka R8 = 470l<^ R^0 = ^00a R1 1 ,R1 2 = Alka PI = 22k a preset, vertical mounting Capacitors Cl = 220nF MKT, lead pitch 5mm C2,C3 = 47nF MKT, lead pitch 5mm C4 = 220 jiF 16V radial, lead pitch 2.5mm C5 = 2.2nF MKT, lead pitch 5mm C6 = 1 .5nF MKT, lead pitch 5mm C7,C1 2 = 1 0OpF ceramic, lead pitch 5mm C8 = 1 nF MKT, lead pitch 5mm C9,C1 0 = 470pF ceramic, lead pitch 5mm Cl 1 = 1 0OnF MKT, lead pitch 5mm Cl 3 = 33nF MKT, lead pitch 5mm C14,C1 5, Cl 6 = 1 0OptF 25V radial, lead pitch 2.5mm Semiconductors D1 ,D2 = 1 N4148 T1 = BC337-40 IC1 = LM386N-3 IC2 = TL074CN IC3 = 4024 Miscellaneous REC1 = 40kHz ultrasonic sensor (receiver) (e.g. Prowave 400SR1 6P, diam. 1 6 mm) LSI ,S1 ,BT1 = 2-pin pinheader, lead pitch 0.1 inch (2.54mm) 3 pcs 2-pin connector (for loudspeakers, switch and battery) LSI = loudspeaker 8^/0. 3W, diam. 20mm (e.g. Kingstate KDMG20008) SI = slide switch, 1 make contact BT1 = 9V battery with clip-on lead PCB # 1 1 0550-1 (see www.elektor. com/1 10550) Figure 3. The PCB for the circuit is long and thin to enable it to fit in a length of PVC pipe. elektor 11-2011 27 HOME & GARDEN clock input of a type 4024 seven-stage binary counter. The signal on the CT3 out- put (pin 1 6) is the clock input divided by 1 6. It consists of pulses in the audible range (2 to 3 kHz), which are fed via T1 to the loud- speaker to generate an acoustic output. Diode D1 is included for protection against negative voltages on base of the transis- tor. Resistor R7 limits the drive current that IC3 supplies to T1 . A free-wheeling diode is connected in parallel with the loudspeaker (LSI) to protect transistor T1 from volt- age spikes generated by the inductance of the speaker coil. You can also use a small piezoelectric buzzer for LSI . Resistor R9 is included to ensure proper operation of a piezoelectric buzzer, as otherwise the out- put would be mute because piezoelectric buzzers are highly capacitive. Decoupling network (R1 0/C1 4) in the speaker supply line suppresses noise on the supply voltage rail, which is necessary because the input stage is very sensitive. The quiescent current consumption of the entire circuit is around 14 mA, rising to a maximum of 90 mA when it receives ultra- sonic signals. The circuit works well with a supply voltage as low as approximately 4.5 V. Mini PCB The PCB layout designed for the bat detec- tor is shown in Figure 3. The 9 V battery can be fitted on the bottom of the board. The PCB has a ground plane on the top side to provide screening, which is necessary due to the relatively high input sensitivity. The board is dimensioned to fit in a length of standard PVC pipe with an inside diame- ter of 33 to 35 mm, which can be purchased in any home improvement shop. Matching end caps are also available, and a small loud- speaker and switch can be fitted on an end capas illustrated in Figure 4. If you fit three self-adhesive rubber feet on the bottom, you can stand the pipe upright on a garden table, and whenever any bats fly overhead you will hear them right away. The sensitivity can be adjusted with the trimpot. It should be set to minimise or eliminate any ticking sounds from the speaker. When making the adjustment, take care to avoid undesirable sources of ultra- sonic energy in the immediate vicinity, such as fluorescent lamps, television sets, com- puter monitors, switch-mode power sup- plies and so on. They can be detected at distances of 1 0 to 20 feet ( 3 to 6 metres). Simply rubbing your thumb and forefinger together, zipping a plastic bag (such as a sandwich bag) or shaking a bunch of keys will generate enough ultrasonic energy to be detected by the circuit at a distance of several metres. Bats are rather loud and can be detected at distances of 1 00 feet (30 metres) or more with this circuit. The various sounds pro- duced by bats can also be clearly recognised with this detector. ( 110550 -I) Internet Link [i] www.ti.com/tool/filterpro Figure 4. The on/off switch and a speaker are fitted in the end cap. 28 11-2011 elektor Elektor OSPV I S Open Source Personal Vehicle Last year we launched the Elektor Wheelie, a self-balancing personal transport device. Our new Elektor OSPV is based on the same concept, but with the difference that it’s for indoors, it’s easy to steer, it’s light and foldable and... it’s open source. You can configure or modify it to suit your wishes! The OSPV is primarily intended for moving people, but it doesn’t have to be limited to that. A variety of other uses are conceivable, ranging from an electric wheelbarrow to a handy motorised shopping cart. This is where the advantages of the open source approach come to the fore! ^ektor Important specifications: • Size: 1 20x47x47 cm / 47.2x1 8.5x1 8.5 inch (HxWxD) Weight: 25 kg (25lbs) Maximum load: 90 kg (200 lbs) Motors: DC 2 x 200 W Wheels: Polyurethane, 1 4 cm dia. (5.5 inch) Drive train: HDT toothed belt Max. speed: 1 5 km/h (9.3 mph) Range: 8 km (5 miles) The kit comprises two 200-watt DC drive motors, two 1 2-V lead-acid AGM batteries, battery charger, two wheels Polyurethane 14 cm wheels, casing, control lever and fully assembled and tested control board with sensor board. Art.# 11 0320-91 .£975 / €0095-/ US$T576 £787/ €885 /US $1280 *lnd. VAT, excl. shipping costs Further information and ordering at www.elektor.com/ospv LOW NCQA2G15 AUK A sviin Class D Audio Amplifiers High y ii a lily, High KFTcc fancy DC/DC Converters lli^h Kited ?nc>. No IE cut Sink FM Audio Transmitters JIiJ L Sound Qujlih Evaluation Boards Low Cost. Ready-to-Use Applications c A integrated tlesigr £> Ultra cornea cl ® Atmoat no eternal ptsrl^ c Sol ri a my SMT oi h-y nano c Lew cost * High Reliability £" Many ready- to-user EVB c Consumer 0 Auto accessories c Instruments c Industry 0 Toys c Communication Equipments 0 And many mart! Dealer Wanted! THE ORIGINAL SINCE 1994 PCB-pnQL 8 FITS-OR-NOT! 3D PCBs: Hands-on collision check assembly service! Even one component possible 0 5mil track 8mil drill 1 free! A Free Stencil <5! Free Phone UK: 0800 389 8560 sales@pcb-pool.com p-cirpxm |SJ WTIMJIDKAi W RS-274-X www.beta-layout.com m\Y.l OwNGKhs Q Pu ™; H E..SV PC 3. elektor 11-2011 29 DSP COURSE In this article we describe the basic structure used for the DSP application programs developed in this course. We have decided to divide application programs into two parts: the first, the same for all applications, provides the high-level structure, while the second, unique to each application, carries out the actual processing. This division makes it easier for beginners to get to grips with the applications we describe and get started with DSP programming. The article concludes with some handy hints and tips on using the assembler and on programming the DSP. Audio DSP Course (5) DSP program structure By Alexander Potchinkov (Germany) The first of the two parts of the software we shall call the ‘framework’, and is the same for all applications. The second part, the ‘audio loop’, is concerned with the audio signal pro- cessing proper, and has to be developed anew for each project within this course and for any application you might design. Both these terms were introduced in the second article in this series. We will now look at how they are applied in the context of the DSP board and of the applications developed in this course. Framework tasks The first job of the framework code is to initialise the DSP itself. This involves con- figuring the processor clock frequency and the interrupt system, setting up a software stack and various other tasks. The next job is to establish connections to the peripheral devices on the DSP board so that audio and control data can be passed to and fro. This requires writing to various registers in the DSP to configure the processor’s interface hardware to suit the peripherals. In effect the task of the framework is to initialise all the hardware on the board and put it into a state where it can be used without further ado. In our case we have to take account of the needs of five peripheral components: ADC, DAC, SRC, SEEPROM and SPI port. Figure 1 illustrates this array of peripherals connected to the central DSP. The solid lines show paths where data transfer takes place and the dotted lines show control paths. The control paths are used by the DSP to configure the peripherals and to request status information from them. • A clock signal is made available to the ADC, from which the sample rate and data transfer timings are derived. The ADC is capable of determining the ratio between the master clock frequency and sample rate by itself and this value therefore does not need to be configured. In our case the ratio is 512. • The DAC is also provided with a clock signal, and, as with the ADC, it is able to determine the master clock to sample rate ratio autonomously and configure itself accordingly. • The SRC is not capable of such inde- pendent operation as the ADC or DAC, and requires some configuration. We gave the byte sequence necessary to configure the l 2 S and digital audio interfaces in the SRC in the third article in this series. The DSP con- figures the SRC over its SPI port as part of the framework code, and in order to do this the DSP must first configure its SPI port to be compatible with the communications protocol used by the SRC. Then the DSP can reset the SRC and send the necessary 54-byte configuration sequence. The SEEPROM can be used for general-pur- pose non-volatile storage. If the DSP board is to be used in a stand-alone application (that is, without the use of the debugger) with fixed application code then it is pos- sible to arrange matters so that the DSP boots from the SEEPROM, taking advantage of the bootloader code stored in the DSP’s on-board ROM. The SPI port can be used to transfer data to and from devices external to the DSP board. For the digital signal level meter application in this course we use the SPI port to drive an LED bargraph display. We could also use the SPI port to connect to an external microcon- troller with keypad, digital potentiometer (rotary encoder) and LCD to allow the par- ameters of a program running on the DSP to be adjusted interactively, for example alter- ing the frequency of the sine wave output in our signal generator application. Structure of the framework code The framework can be divided into four parts. 1 . General declarations • Defining the memory map: fixed areas 30 11-2011 elektor are provided for program vari- ables and parameters. • Assigning values to constants required by the program. o Setting up the entries in the interrupt vector table as given in the file i v t . asm. 2. DSP setup Setting up the DSP itself, which includes configuring the processor core and the peripheral interfaces, is done by program- ming the 24-bit registers that lie at the top of the processor’s address space from $FFFF80 to $FFFFFF. This range covers a total of 128 locations of which we use up to 1 8. The processor manufacturer refers to this address range as ‘internal I/O memory’. In the 52-pin DSP56374 device that we use only the X-RAM locations are used. The locations are written to using the special instruc- tion mo v e p (move peripheral data) which allows values to be written directly to the register without the overhead incurred by the normal move instruction of transferring the value via a CPU register. For example, the instruction mo v e p #$D17D0 0, x: RCR writes the specified value directly to RCR (Receive Control Register), which controls the characteristics of the receiver part of the audio interface. DSP COURSE proper begins. • All interrupts are disabled while the pro- cessor configuration is changed. This avoids the possibility of the processor crashing or other unexpected operations if an interrupt should be generated before the core and peripheral registers are properly initialised. • The hardware stack pointer (s p ) is reset and the software stack is set up in ascend- ing locations in X-RAM starting at address $40. Setting up the DSP and its peripheral inter- faces is a tedious task, which is a reflection audio sample rate of 48 kHz. When config- uring the PLL multiplier and divider values it is important to bear in mind that the VCO only operates reliably between 300 MHz and 600 MHz; we operate the VCO at a fre- quency of 589.824 MHz. The manual pro- vides tables that give advice on suitable settings for common audio sample rates. If non-standard frequencies are to be used the calculations must be done manually. Based on the fact that the board is populated with a 24.576 MHz crystal oscillator module the correct PLL configuration is obtained by set- ting PCTL=#$01E006 which results in an Figure 1 . An array of peripherals connected to the DSP. Here RCR is a handy and easy-to-remem- ber abbreviation (much like the mnemon- ics used for assembler instructions) for the address $FFFFBF. To make the job of the programmer easier all our programs make use of the auxiliary file mi o e q u . a s m, which contains (among other things) similar abbreviations for all the I/O register addresses. A suitable ‘include’ directive to the assembler makes the abbreviations in the file available to our program. • The program starts at address $000000, which is the value of the DSP’s program counter immediately after reset. The first instruction is a branch to program address $000100, thus skipping over the interrupt vector table and other paraphernalia asso- ciated with the DSP core. Then the program of the flexibility of the device and its range of possible applications. There is no deny- ing that setting up the processor properly demands extensive study of the manuals and can be a significant hurdle to the begin- ner. Fortunately, however, the processor is logically designed and Freescale’s manuals are well written. A complete step-by-step description of what is required would far exceed the space we have available, and so we discuss below only the most important aspects of the set-up process. • Processor clock PLL configuration. The processor clock frequency is set to 147.456 MHz, which is six times the audio master clock frequency and 3072 times the overall clock multiplication factor of 6. o The instruction sequence mo v e c #0 , s p , move #$40, r 6 and move #- 1 , m6 resets the hardware stack pointer and initialises the software stack. o Setting I PRP=#$000003 allows the interrupt system to respond to interrupts from the audio interface at priority level 2. We do not use the core interrupts in the programs in this course. • The audio interface is configured for operation in master mode with a mas- ter clock frequency of 24.576 MHz, in l 2 S network mode with two channels car- rying 24 bit left-aligned data in 32 bit elektor 11-2011 3 i DSP COURSE frames. Interrupts are set up for recep- tion and transmission, error handling and ‘last slot’ (right channel). The receive and transmit control registers are set to the same values: R C C R =T C C R = $ F DD 3 0 2 and RCR=TCR = $D17D00. The registers R S M A , T S MB , RS MA and T S MB allow the network- mode channels (up to 32 of them) to be individually enabled or disabled for trans- mission or reception. By setting all these registers to the value $ 0 0 F F F F we enable all possible channels, of which we use just two. Setting PCRC = PRRC = #$000FFF con- figures Port C as an audio port. It is also pos- sible to configure individual pins on port C as GPIOs that can be accessed via the audio connector. • The SHI interface is configured in mas- ter SPI mode with a clock frequency of 0.9216 MHz. Interrupts are not used, C POL and C P H A are both set to zero, and the nar- row spike filter and the FIFO are disabled. For programming the SRC: 8-bit data, with HC K R = #$ 0 0 2 0 4 8 and HCSR = #$ 0 0 0 0 4 0 . For controlling the LED bargraph display: 1 6-bit data, with HCKR = #$002048 and HCS R = #$ 0 0 0 0 4 4 . • Port H is used for the SRC and the SEEPROM and for setting the boot mode. PH4: GPIO input, lock signal from SRC4392. PH3: GPIO output, reset signal to SRC4392. PH2: used as MODC to select the boot mode of the DSP. PHI: GPIO output, chip select to the SRC4392. PHO: GPIO output, chip select to the M95M01 SEEPROM. This configuration is obtained by setting PCRH = #$000014 and PRRH = #$00000F . 3. Final set-up before entering the audio loop o Interrupts (and in particular the audio interrupts) are enabled so that the audio buffer is read and written and the flag syn- chronisation system for received audio data is initialised. o The SRC is configured over the SHI in SPI mode. 4. Interrupt service routine o The interrupt service routine code forms the final part of the framework program. The code is in the source file e s a i 4 R 2 T . a s m. The audio loop The audio loop contains the digital signal processing code and is embedded within the framework code. We will adopt the principle of reflecting the block structure of the processing to be done through the use of subroutines, where each processing block is embodied in one subroutine. The representation of a processing chain as a series of blocks will be familiar to analogue designers. Each of our subroutines therefore has ‘input signals’ and ‘output signals’. In the example below we shall deal with four signals, called S i g n a I I n L / R and Si gnal OutL/R. Note that not all subrou- tines will have input signals: for example a signal generator will only have outputs. In our projects signals are represented by samples with 24 bits of precision, each occupying one location in memory within a dedicated area in the DSP’s RAM. A sub- routine may also have one or more par- ameters or settings that affect its oper- ation. An example of such a parameter might be the time constant of a filter. Fig- ure 2 shows an example of how subrou- tines can be connected together. There are four subroutines in the exam- ple, labelled from ‘A’ to ‘D’, each repre- senting a signal processing block. The small rectangular boxes in the middle of the figure are the subroutines, connected together via signal paths. The boxes with rounded corners symbolise parameters of the subroutines. Some subroutines do not require any parameters: this is the case for subroutine C in the illustration. The pointed boxes contain the signals passed between the subroutines. These signals have a dedicated storage area in the DSP’s memory which makes it possi- ble to observe their values at any point in time. We have constructed the block dia- gram so that it is possible to examine the function of the system in more detail by observing the signal at these monitoring points. For example, we can copy any one of these signals to the audio buffer at the end of the audio loop and then observe it as if we were using a digital audio oscillo- scope. This is a great help when it comes to tracking down bugs in the signal pro- cessing code. To capture the output the author uses a simple low-cost USB sound card (available for considerably less than £100) in conjunction with a waveform edi- tor program. Commercial waveform edi- tors are available, or there are several free editors and analysers available for down- load on the internet. The software allows one or more signals to be inspected in the time domain or converted to the fre- quency domain to allow a spectrum to be viewed, and thus can be used as a pow- erful replacement for an ordinary oscil- loscope. Spectral analysis is particularly useful for analysing distortion, for exam- ple in the output of a sinewave generator. It is also possible to use a waveform editor to create sound files and carry out various kinds of processing on them. These files can then be loaded into a numer- ical computing package such as MATLAB after which the sky is the limit! Such a set- up could be used to test the characteristics of a dynamics processor using signal bursts of varying duration, frequency and ampli- tude. Since the DSP board includes a DAC, we could equally observe the signals using an ordinary analogue oscilloscope, although this approach is better suited to giving an overview of a circuit’s performance than a precise and detailed analysis. The ADC is connected to SDI1 (SD04) and the SRC to SDI2 (SD03). The receive buffer, which occupies four locations in memory, is laid out as follows. x : Rx Buf f Ba s x : Rx Buf f Ba s x : Rx Buf f Ba s x : Rx Buf f Ba s e ADC e +1 SRC, RX e+2 ADC, e +3 SRC. RX, left channel left channel right channel right channel The DAC and the AES3 encoder, whose 32 11-2011 elektor DSP COURSE Figure 2. Example subroutines in an audio loop. transmitter circuit is in the SRC, are con- nected to SDOO. The transmit buffer occu- pies two memory locations with the follow- ing layout. x: TxBuff Base DAC and SRC. TX, left channel x: TxBuff Base + 1 DAC and SRC. T X , right channel At the beginning and at the end of the audio loop there are two small sections of code. The first synchronises with the audio clock and reads from the audio receive buffers; the second writes to the audio transmit buffers. Audi oLoop j c 1 r #Ri g ht Rx , x : L RF 1 a g , * be 1 r #Ri g ht Rx , x : L RF 1 a g move x: RxBuf f Base, a move ; ADC CS5340, 1 eft x : Rx Buf f Ba s e +2 , b ; ADC CS5340, right b r s et #Lock_SRC4392, x: PDRH, NoSRC ; use ADC if SRC does not lock move x : Rx Buf f Ba s e +1 , a move ; SRC. RX SRC4392, 1 eft x : Rx Buf f Ba s e +3 , b NoSRC move ; SRC. RX SRC4 3 9 2, right a , y : 1 n L move b, y : 1 n R The first two lines are responsible for syn- chronisation, as described in the second instalment in this series. The third and fourth lines read the values received from the ADC and store them in accumulator reg- isters a and b . The fifth line checks the lock flag of the SRC. If this indicates that a valid audio signal is available , then the values in accumulators a and b are overwritten with the values read from the SRC; if no valid sig- nal is available the overwriting is skipped. In lines 8 and 9 the accumulator contents are written to memory locations I n L and I n R from where they can be read by the first sig- nal processing subroutine. This approach guarantees that we will always have a valid audio signal to use: if a digital signal is con- nected to the board then it will take priority, but if no valid digital signal is available then the system will fall back to using the signal at the ADC input. The second section of code, at the end of the audio loop, is responsible for writing the contents of accumulators a andb to the transmit buffer, the samples to be transmit- ted having been fetched from memory loca- tions Ou t L and Ou t R . Finally the program jumps back to the start of the audio loop. move y : Out L , a move y : Out R, b move a, x: TxBuff Base ; - > DAC and SRC. TX, left move b, x: TxBuff Base+1 ; - > DAC and SRC. TX, right j m P Audi oLoop Memory map Table 1 shows the memory map used by the programs in this course. We have not expended much effort in ensuring that there are no gaps in the layout, preferring to adopt a common layout for all the programs to make them easier to compare with one another. Not all memory locations indicated here are used by every program. Address registers, software stack and sample counter Two of the eight address registers RO to R7 are used in the framework code for dedi- cated purposes and should not therefore be used as general-purpose registers by an application program. Register R6 is used to point to the software stack in X-RAM. The software stack is an extension to the hardware stack provided by the proces- sor and occupies RAM addresses from $40 upwards. We make a total of 32 locations, from $40 to $5F, available to programs. The framework code uses the software stack in the audio interrupt service routine (ISR) to store registers R 0 and MO for the duration of the routine and restore them afterwards: it is important that the ISR does not alter any of the registers used by the main pro- gram. The software stack can also be used by application programs for temporary stor- age of processor registers, both those in the datapath and, more significantly, those in the address generation unit (AGU). Address register R 7 , which we refer to as the ‘sam- ple counter’, is used to count modulo 192 at the audio sample rate. It is used in two of our example applications. In the test pro- grams it is used to index into the two 1 92- entry sinewave look-up tables Si n e wa v e , f =1 kHz, x : $ 8 0 0 to x : 8 B F Si n e wa v e , f =2 kHz, y : $ 8 0 0 to y : 8 B F from which sample values are fetched and fed to the DAC or to the digital output. The second use is in the digital signal level meter where it is used to trigger the regular writ- ing of data to the LED bargraph. The display is updated at a frequency of 48 kHz/ 1 92 = 250 Hz: in other words, every 4 ms. Regis- ter R 7 can be used for other purposes in an application program as long as it is saved on elektor 11-2011 33 DSP COURSE the stack and restored after use. Subroutines A signal processing subroutine has the fol- lowing structure. NameOf Subrout i ne move y: Si gnal 1 n L , xO move y: Si gnal 1 n R, yo move x 0 , y : S i g n a 1 Out L move y 0 , y : S i g n a 1 Out R rt s The subroutine is called using the instruction j s r Na me Of Su b r o ut i n e .Thej s r (jump to subroutine) instruction tells the DSP to push the program counter and processor status register onto the hardware stack and branch to the subroutine. The subroutine terminates with an r t s (return from subrou- tine) instruction which causes the processor to restore the program counter and status register from the hardware stack, thus allow- ing execution of the calling code to continue. Parameters may be passed to the subroutine using the software stack. Macros The DSP assembler has a text macro facility. The contents of a macro are inserted into the program code at each point where it is called. A macro is declared as follows. NameOfMacro macro p a r a ml p a r a m2 . . . para mN e n d m A macro is called by simply giving its name followed by any parameters. The use of macros can make programs easier to read, especially when parameters are used. How- ever, they do not result in a reduction in code size. This is in contrast to subroutines, which can help both to make code more readable and to make it smaller. On the other hand, subroutines consume processor clock cycles in the stack operations involved in calling them and returning from them. Initialisation of the signal processing code Two subroutines are called immediately before the audio loop is entered. The first is the routine Z e r o S t a t e , which sets the memory storing the state of the signal processing routines to zero. The second is called Set Def aul tParams and sets up the default values of the signal processing parameters. The values used in this routine can be changed to adapt the system for a particular application; alternatively, param- eter values can be modified using an input device connected to the SPI port. Loading and executing the program Once a DSP program has been written it must be assembled and checked for errors. This can be done in the command window using the following command. as m5 6 3 0 0 -a -b -I my program, asm The - 1 option tells the assembler to gener- ate a listing file, which is often useful when trying to locate errors. Assuming there are no errors, the assembled code in the file my p r o g r a m. cl d can be loaded into the debugger to which the DSP board is con- nected. From there, using an adapter, the code can be transferred to the DSP itself and executed. Handy hints Using the assembler o The assembler interprets text starting in the first column of a line as a label. A label must being with a letter, and reserved words such as mo v e or a 0 are not allowed as labels. o The assembler is of the ‘two pass’ variety. A two-pass assembler first looks through the code building a ‘symbol table’, which is a list of the locations of all labels used. In the second pass it assembles the code itself, using the values stored in the symbol table to resolve ‘forward references’, where a label is defined after it is first referred to in the assembler source file. Without the sym- bol table from the first pass it would not be possible to resolve these labels as their val- ues would not be known. o Labels starting with an underscore (*_*) are useful when writing macros: their scope is local to the macro itself. • Labels, unlike keywords, are case sensitive. • DSP instructions can appear from the sec- ond text column onwards. • The file mi o e q u . asm can be included in a DSP program using an i n c I u d e directive. This file defines a large number of abbrevi- ated names for the interface registers in the DSP. • The first usable address for program code is p:$ 1 00: below this address are the inter- rupt vector table and other reserved areas. • The o r g directive can be used to specify the use of X, Y, P or L memory. • The processor has an instruction pipe- line which greatly speeds up code execu- tion as long as it is not disturbed by pro- gram branches or long interrupts. Because of this pipeline, the assembler is sometimes obliged to introduce additional nop instruc- tions into the code. When this happens it reports a warning to the programmer that there may be an opportunity to improve the efficiency of the code by reordering it so that the nop instructions can be replaced by instructions that do useful work. At the end of the processor manual there is a number of so-called ‘programming sheets’ which greatly simplify program- ming the processor’s registers. We would recommend any programmer to take advantage of these sheets: they can easily be printed off from the PDF manual, used during the development of a program, and then finally attached to the other program documentation. Programming the DSP • It is not possible to move immedi- ate data directly to memory: instruc- tions like move #$123456, x: $000100 do not exist. Instead, a register must be used as a staging-post, for example using move #$123456, xO followed by mo v e xO, x: $000100. There are, however, spe- 34 11-2011 elektor Table 1 . Memory map used by the software in the course X-RAM use Y-RAM use Region P-RAM use Audio RX buffer Signals $00 to $0F Audio TX buffer Signals $ 1 0 to $ 1 F Audio flags and pointers Pointers, coefficients, status storage $20 to $2F Program parameters $30 to $3F Interrupt vector table and reserved areas Software stack Free for application use $40 to $4F Software stack Free for application use $50 to $5F Free for application use $60 to $9F Auxiliary variables $A0to$BF SRC boot sequence Free for application use $C0 to $CF Free for application use $D0to $FF Filter and polynomial coefficients $100 to $5FF Application program Circular buffer, left Circular buffer, right $600 to $7FF Sinewave, 1 kHz Sinewave, 2 kHz $800 to $8BF Free for application use $8C0 to $1 7FF cial instructions for moving values directly to addresses in the peripheral register area at the top of the memory map, such as movep #$123456, x: $FFFFE0. © A register must again be used for interme- diate storage when moving data from one memory location to another, for example move x: $000010, xO followed by mo v e xO, y: $000010. However, memory-to- memory transfers within the peripheral register area are possible. © The instruction move #$ F , x 0 does not result in the perhaps expected outcome x0=$00000F, but rather inx0=$0F0000. The instruction move #>$F,x0 gives the right-aligned result. The DSP is designed to work with fractional values, which means that numbers are in general left-aligned. • Nested ‘do’ loops must use distinct labels. Furthermore, there must be at least a n o p instruction between the two labels if other- wise no code would appear there. • P-RAM should not normally be used for data storage as accessing it incurs an extra penalty in processor cycles. • When integer values are multiplied, for example in address calculations, it is neces- sary to halve the result by arithmetic-shift- ing it right one place using an a s r instruc- tion. This again is because the DSP’s multi- plier is designed for left-aligned fractions, not right-aligned integer values. • The three-operand instructions ma c and mp y do not allow all sixteen possible com- binations of source operand registers to be used. This is because there are only three bits available in the instruction encod- ing to specify them rather than the four that would be required. So for example mp y x 0 , x 0 , a and mac x 0 , y 1 , b both exist, but neither mp y x 1 , x 1 , a nor mp y y 1 , x 0 , b is possible. • Fast interrupts should not be terminated byanrti instruction. • We have reserved address register R 6 for use as a pointer to the software stack, which starts at address X:$40. The software stack is particularly useful when manipulating the AGU registers in a subroutine. It is a com- mon schoolboy error to set up an address register for modulo addressing inside a sub- routine and forget to reset its mode before leaving the routine, giving rise to unex- pected operation elsewhere in the code. • The hardware stack pointer s p should be reset to zero during initialisation. • In particularly time-critical applications it is best to try to avoid the use of instruc- tion extensions. An instruction extension is an second word added to an instruc- tion, for example containing an address or an immediate value. The instruction mp y i #0. 3, xl, a requires an extension word to store the immediate value 0.3 and so the instruction occupies a total of two words in program memory. In contrast, the instruc- tion mp y x 0 , x 1 , a only occupies one word of program memory. It is normally preferable to store constants in the DSP’s RAM during program initialisation and load them into a processor register (in this case the operand register x 0 ) shortly before they are required: this can often be done using a parallel move instruction. • Looking at a program for the DSP it is clear that a very large number of mo v e instructions are used. One of the reasons for this is that the CPU is register-based. This in turn means that it is important to take full advantage of the DSP’s capabil- ity to do parallel moves. In general this means that a value is loaded into a regis- ter in advance of (sometimes considerably in advance of) its use, whenever there is a suitable arithmetic operation available to which the move can be attached. Unfortu- nately this kind of optimisation makes pro- gram code rather hard to follow, since dif- ferent parts of what might be considered a single operation are separated from one another in the source file. • A few years of experience of programming DSPs has taught us that the commonest pro- gramming error is inadvertently using the same memory location for more than one pur- pose. We therefore recommend that program- mers draw up a detailed and exhaustive mem- ory map for each program they write. Also, our preferred approach of allocating dedicated memory areas to groups of variables, while not exactly economical in memory use, neverthe- less can help avoid many simple errors. For later programs it will prove useful to write two routines to push and pop the ten datapath registers (xO, yO, xl, y 1 , aO, bO, elektor 11-2011 35 DSP COURSE Table 2. Two’s complement integer and fractional representations Integer Decimal Integer Decimal Fractional Decimal Fractional Decimal 0000 0 1000 -8 0.000 0 1.000 - 1.0 0001 1 1001 -7 0.001 0.125 1.001 - 0.875 0010 2 1010 -6 0.010 0.25 1.010 - 0.75 0011 3 1011 -5 0.011 0.375 1.011 - 0.625 0100 4 1100 -4 0.100 0.5 1.100 - 0.5 0101 5 1101 -3 0.101 0.625 1.101 - 0.375 0110 6 1110 -2 0.110 0.75 1.110 - 0.25 0111 7 1111 -1 0.111 0.875 1.111 - 0.125 al, bl, a 2, and b 2 )to and from the soft- ware stack. These routines can then be used in subroutines to avoid unwanted side effects on these registers should they be used by the call- ing program. How samples are represented in the DSP Signal samples in the DSP are represented using a special numeric format. The binary point is immediately after the top bit, which is used as the sign bit. The only difference between this format and the usual represen- tation of integers is that with normal integers there is no binary point (or you can imag- ine a binary point immediately to the right of the integer value). The DSP’s format is called ‘two’s complement fractional’, or just ‘fractional’, representation. The difference between two’s complement representation of integers and the fractional format can be illustrated simply using four-bit values. There are sixteen different four-bit values, of which seven represent positive numbers and eight represent negative numbers, leaving one representation of zero: see Table 2. For clarity we have marked the sign bit in the table and included the binary point in the fractional representations. The values represented differ only in the significance of each bit. From left to right, the bits after the sign bit in the integer representation have significances of 4, 2 and 1 while in the fractional representation the bits after the binary point have significances of 1 / 2, 1 / 4 and 1 /8. In the integer format values are naturally right-aligned while in the frac- tional format they are naturally left-aligned. This means that we can extend an integer without changing its value by adding zero bits to the left (if it is positive) or one bits to the left (if it is negative); we can extend a fraction without changing its value by add- ing zero bits to the right, whether the value is positive or negative. Observant readers will have noticed that the extreme positive and negative representable values have dif- ferent magnitudes. This sometimes causes difficulties as the clipping level depends on the sign of the signal. In the case of our 24-bit DSP the difference in magnitude is just 2~ 23 = 1.1 921x1 O' 7 , which is in many cases small enough to be ignored. Now let us look at how the fractional repre- sentation is used. We will imagine a DSP-lite working with four-bit values (single preci- sion) and eight-bit values (double preci- sion). We will interpret the values in exactly the same way as the full-fat 24-bit DSP: the only difference will be in the resolution (that is, the difference between consecutive rep- resentable values). One common job the DSP has to do is ‘requantisation’. In our example this means converting an eight-bit value to a four-bit value. Suppose the eight- bit value is 0.1 00 01 00, representing a value of 1 / 2+1 / 32 = 0.531 25. One way to requan- tise this value is simply to drop the last four digits, leaving the value 0.1 00, which rep- resents 1 / 2 = 0.5. That might not seem too impressive, but readers are invited to con- sider how a similar task would be done with integer values. Back to the real DSP: in single precision it calculates to 24 bits of accuracy and in dou- ble precision to 48 bits. We know that the preferred basic word length for digital audio processing is 24 bits, corresponding to sin- gle precision on the DSP. But what happens when we multiply together two signal sam- ple values or if we want to implement a sim- ple 20 dB attenuator? In both cases the mul- tiplication produces a result in double preci- sion with a word length of 48 bits. Compare with multiplying two numbers on the four- bit DSP: 0.010 * 0.001 representing 0.2 5 * 0.1 2 5 = 0.0 3 1 2 5 0. 000 0100 representing 0.03125 The result has eight digits. With this in mind we can revisit one of the hints given earlier. If we want to multiply two integer values together, for example in a memory address calculation, the result from the DSP’s multiplier has to be shifted to obtain the correct answer. Looking again at the example above, thinking of the values as integers: 0010 * 0001 representing 2 * 1 = 2 0000 0100 representing 4, the result produced by the fractional mu I t i p I i e r 0000 0010 representing 2, the correct result obtained by arith me tic-shifting the multiplier's output right by one place Coming soon... Now that we have described the structure of DSP programs, we will move on in the next instalment to make the DSP board into an audio signal generator. (110005) 36 11-2011 elektor Elektor Academy Webinars in partnership with element14 Elektor Academy and elements have teamed up to bring you a series of exclusive webinars covering blockbuster projects from recent editions of Elektor magazine. Participation in these webinars is COMPLETELY FREE! All you need to do is register at www.elektor.com/webinars . Webinar programme: E-Blocks, Twitter and the Sailing Club Date: Thursday November 17, 2011 Time: 15:00 GMT (16:00 CET) Presenters: Ben Rowland and John Dobson (Matrix Multimedia) E-blocks are small circuit boards containing a block of electronics that you would typically find in an electronic or embedded system. In this webinar Ben and John demonstrate rapid prototyping of an E-Blocks configuration capable of automatically sending Twitter messages to members of a sailing club. Let’s Build a Chaos Generator Date: Thursday December 15, 2011 Time: 15:00 GMT (16:00 CET) Presenters: Maarten Ambaum and R. Giles Harrison (Reading University) Join us in this webinar to look at the making of the Chaos Generator project published in the September and October 201 1 editions of Elektor. Get out your opamps, wipe your monitor and glasses and turn up the volume loud! Here comes The Elektor Bus Date: Thursday January 19, 2012 Time: 15:00 GMT (16:00 CET) Presenter: Jens Nickel (Elektor) Many Elektor readers have actively participated in designing what’s now known as the Elektor Bus. Elektor editor Jens not only tells the story of how it all came about, but also delve into protocols, bus conflicts and hardware considerations. Now available to view on demand at www.element14.com: Platino - an ultra-versatile platform for AVR microcontroller circuits Presenter: Clemens Valens (Elektor) Many microcontroller applications share a common architecture: an LCD, a few pushbut- tons and some interface circuitry to talk to the real world. Platino offers a flexible through- hole design for such systems based on the popular AVR microcontrollers from Atmel. Platino supports all 28 and 40 pin AVR devices, several types of LCD and has a flexible pushbutton and/or rotary encoder configuration. e I e k ACADEMY ths school of electrunirs elementiu www. element 1 4. com Places are limited. REGISTER NOW at www.elektor.com/webinat s! MICROCONTROLLERS To help with the programming and debugging of the DSP board used in our DSP course, Elektor Labs designed a small adapter that can be used to connect the board to a PC via a modern, fast USB connection. This adapter can also be used in combination with other Freescale DSPs from the DSP56K series. By Ton Giesberts (Elektor Labs) OnCE/JTAG Interface Program and debug Freescale DSPs For the DSP course we developed a circuit based around a DSP from the Symphony series from Freescale, the DSP56374. The programming and debugging of the DSP happens via a JTAG interface, for which Freescale uses their own 14-pin connec- tor, known as OnCE (an abbreviation of On- Chip Emulation). To keep the DSP board as compact as possible, no direct interface for connection to a PC was added to the board. Freescale does have several pro- gramming adapters for sale, but they tend to be rather expensive. Those of you who have already used an evaluation kit from Freescale will probably have a suitable pro- gramming adapter as well. Furthermore, there are several simple (home-built) pro- grammers for these Freescale DSPs to be found on the Internet. Most of these, how- ever, work via a parallel port and there aren’t that many (new) computers that still come provided with such a port. The OnCE/JTAG interface described here is an addition to the DSP board, and provides a fast and modern USB connection between the DSP board and a PC. The circuit For the USB interface we’ve used a Hi-Speed Dual USB UART/FIFO 1C from FTDI, the FT2232H (IC1 , see Figure 1 ). This 1C comes from the latest generation from FTDI (refer to the datasheet in [1 ]). With the help of Figure 1 . The circuit diagram of the programming adapter, this 1C the interface can communicate with with an FT2232H made by FTDI at its heart. +3V3 O f ^C9 JcD 1 CIO 4u7 llOOn +1V8 I K1 ■ m 0n^l00t^l00t^ u3 14 50 49 in USBB D1 R1 7 ■—I 10R I -| R2 8 1— 1 10R I D2 > 2x PGB1010603 +3V3Q f I C15 ^100n IC2oo u cs CLK 8 VSS Dl 1 ( 63 2 62 3 61 J93LC46B R8 60 36 13 R4 PI fn 3 a JciiJceJcb^c: ^MOnpOO^jOan^M 8 l i RESET VREGN VREGOUT DM DP a a a goo u u u a a a EECS EECLK EEDATA PWREN SUSPEND REF TEST S D H 8 O 8 o UADBUSO ^ADBUSl ADBUS2 ADBUS3 ADBUS4 ADBUS5 ADBUS6 ADBUS7 ACBUSO ACBUS1 ACBUS2 ACBUS3 ACBUS4 ACBUS5 ACBUS6 ACBUS7 BDBUSO BDBUS1 BDBUS2 BDBUS3 BDBUS4 BDBUS5 BDBUS6 BDBUS7 BCBUSO BCBUS1 BCBUS2 BCBUS3 BCBUS4 BCBUS5 BCBUS6 BCBUS7 iiiiiiii kj7^100n H ! 15 I 13 11 16 8 17 6 18 4 19 2 IC1 FT2232H 27p fM rol ■ 4 [ Cl 12NHZ |c: a 12NHz|c2 _^27p_ a a 5 s IC3 21 22 1 TAG /OnCE 23 24 26 27 28 Rll 29 30 32 33 34 S 39 40 n 43 44 45 46 48 H B 54 B 57 58 59 D3 -f3V3 1D1 EN2 EN1 74AC244 RIO R9 -0+3V3 04 R12 ' IC3 -0+3V3 C16 lOOn TDI K2 TDO 3 TCK 5 _7 RESET 9 TMS r OnCE 6 -f3V3 110534-11 38 11-2011 elektor MICROCONTROLLERS the PC at the high data rate of USB2.0. The supply for the circuit comes from the DSP board itself, which makes the interface Self Powered. This makes the circuit a bit simpler, since the supply voltage for the I/O interface is 3.3 V and this is already present on the DSP board. The core of the FT2232H operates at an even lower voltage, which is 1.8 V. This is obtained from an on-chip voltage regulator, which is a welcome feature. The connection to the USB bus requires nothing more than two resistors and a USB Type B connector (K1 ). Two ESD suppressors (D1 en D2) have been added next to the USB connector, which protect against static charges. The reaction speed of these diodes is less than 1 ns. Because of their extremely low capaci- tance (just 0.055 pF) they don’t affect the USB signals. The active-low reset line of the 1C isn’t used and is pulled up via R3 to the supply voltage. The external EEPROM (IC2) is connected according to the standard application note (R5 to R8) to the FT2232H. The EEPROM should be one with a word size of 1 6 bits and which operates from a sup- ply voltage of 3.3 V. There is no need for it to have a selectable memory configuration input (usually called ORG). The 93LC46B made by Microchip is a suitable candidate for this application. The supply voltage for the FT2232H has been decoupled extremely well, as can be seen from the 1 2 capacitors and two inductors used (C3-C1 4 & LI / L2). We decided to buffer all the output signals, with the exception of the reset signal. When the adapter hasn’t yet been activated in the development environment the buffered outputs will be in the off state and will have high-impedance outputs. The fast 74AC244 (IC3, an octal buffer/line-driver with tri- state outputs) is suit- able for use with pi supply voltages between 1 .5 Vto 5.5 V and will therefore work perfectly well at 3.3 V. As a precaution, we’ve added a pull- up resistor (R9) to the reset output, which means that the interface should be able to be used with other projects without any problems. The DSP board already has this pull-up resistor on-board. If the adapter is going to be used exclusively with the DSP board then R9 may be left out. In Figure 2 you can see the PCB that was designed for the adapter. Its size has been kept small by using SMD components. The 2x7 pin header is mounted on the under- side of the board, which makes it easy to plug the adapter into connector l<8 of the COMPONENT LIST Resistors (SMD 0805, 0.1W) R1,R2 = 10£1 5% R3 = 1 ka 5% R4 = 12.0kni% R5,R6,R7 = 10k£l 5% R8 = 2.2k£2 5% R9,R10 = 4.7kn5% R11 =270^5% R12 = 56(to 5% Capacitors (SMD 0805) Cl ,C2 = 27pF 50V 5%, NPO C3 = 3.3jlxF 1 0V 1 0%, X5R C4,C5,C6,C8,C1 0-C1 6 = 1 0OnF 50V 1 0%, X7R C7,C9 = 4.7jiF 6.3V 1 0%, X5R Spoelen (SMD 0805) LI ,L2 = 600fl@ 100MHz, 200mA/0.35Cl (e.g. Murata BLM21 BD601SN1 D) Semiconductors D1 ,D2 = PGB1 01 0603, V clamping = 1 50V (Littelfuse, SMD 0603) D3 = LED, green (Kingbright KPHCM- 201 2CGCK, SMD 0805) D4 = LED, red (Kingbright KPHCM- 2012SURCK, SMD 0805) IC1 =FT2232HL-R(FTDI, SMD 64-pin LQFP) IC2 = 93LC46B/SN (Microchip, SMDSO-8) DSP board. Apart from the bare PCB, Elektor also supplies a fully populated and tested version of this adapter [2]. Software for Symphony Studio When the circuit was designed we assumed that the adaptor would be used in combi- nation with the development environment from Freescale, Symphony Studio. With the help of a template from Freescale the FT2232H can be programmed such that it will be recognised as a Symphony Sound- Bite. This will have been done for you in the fully populated board supplied by Elektor so that you can plug the adapter into the DSP board straight away. For those of you who want to program the FT2232H them- selves, FTDI provides a utility called Mprog that will let you do this. The template from Freescale is meant to be used with this pro- gram. (There is a more recent program IC3 = CD74AC244M (Texas Instruments, SMDSO-20) Miscellaneous K1 = USB-B connector, right angled, PCB mount l<2 = 14-pin (2x7) IDC socket, lead pitch 0.1 in. XI = 12MHz, C, oad 18pF±30 ppm, HC-49S PCB# 110534-1 Assembled, programmed and tested board: #110534-91 C15T IC2|_I R6dJ L * cu- ll |R5 P"| HC12 I 1 (D ‘ l_l o;d- SPa cn R 8 J° Cl/ ^. R fifeD=l gpii r~1ro R12 ^ ci] deceit = ' * ‘ • ni ■ : oClO^Cff CO IC1 O inm s m 1 m i s Figure 2. The PCB for the circuit has been designed such that it can be plugged in directly into connector l<8 on the DSP board. elektor 11-2011 39 MICROCONTROLLERS Figure 3. Screenshot of the program used to program the FT2232H. from FTDI, FT_Prog, but the template from Freescale can’t be used with this.) The most recent version of Mprog (3.5) can still be downloaded from the FTDI website [3]. One problem is that this program doesn’t sup- port the Single Channel version of the USB interface, the FT232H. In order to make it easier to program the interface, and avoid problems with setting up a template, we decided to use the (unfortunately more expensive) dual-channel version. We have already adapted the original SoundBite tem- plate in a few places (see Figure 3) and this can be used directly. If you first carry out a Scan (under Device ) you can check in the status window if the program recognises the interface. You can also verify that it has not yet been programmed and if any other devices have been found. If the interface is found it can be programmed, as long as it’s still in the unprogrammed state, otherwise it needs an Erase first. When you want to build the interface yourself and/or program the FT2232H you should do the following: From the File menu select ‘Open’ and search for the template 1 1 0534-1 .ept, which can be downloaded from our website (1 1 0534- 1 1 .zip, see [2]). If you want to make changes to the template you should select Edit from the File menu after the template has been opened. The following changes have been made by us in the original tem- plate from FreeScale: We used an FT2232H instead of an FT2232D as the Device Type. For the USB Power Options we selected Self Powered. When the FT2232H has been selected a tab automatically appears on the right with a range of settings for the I/O pins. The choice for Hardware (Side A) should be ‘245 FIFO’ instead of the stand- ard ‘RS232 UART’. The driver is already set correctly to D2XX Direct. Make sure that the driver has already been installed [4]. In the datasheet for the FT2232H are two exam- ples of applications that are Self Powered. In both of these a voltage divider is used to detect the 5 V bus voltage. In the text, it is mentioned that the option ‘suspend on DBUS7 low’ in MProg should be selected. However, this only works if this voltage divider is present. If you were to select this option with our circuit you’d find that the PC couldn’t detect the circuit any more. To get round this it seems that connecting pin 46 (BDBUS7) to the 3.3 V supply is a solu- tion, rather than pin 59 as mentioned in the datasheet. For the connection you could use a piece of 0.1 mm enamelled copper wire, if necessary. Make sure that you don’t cause any shorts since the pins of the 1C are only 0.5 mm apart. All I/O pins are set to work at their highest current rating, 1 6 mA. This Figure 4. Here you can see how the adapter is selected in Symphony Studio. 40 11-2011 elektor E CD 4 — • i — CD > "O < Current consumption Several measurements were carried out on the prototype to determine its current consumption. When the DSP board without the interface is connected to 5 V (digital 5 V and ana- logue 5 Von the DSP board are connected together via a small choke), the current consumption was found to be about 84 mA. With the programming interface connected this rose to about 87 mA when power was applied to the board. At that stage the FT2232H is still in Suspend mode and uses only a few hundred pA. Once the interface is connected to the PC, the total current consumption depends on the USB speed: 1 35 mA (Full Speed) or 1 55 mA (High Speed). Once the interface has been configured in Symphony Studio the latter value rises to about 1 60 mA. The ex- tra 5 mA is caused by the green LED that indicates that the OnCE output is active. When, for example, one of the test programs is tried out, such as tst_src2.asm, the total current consumption rises to about 272 mA (with the SRC activated and optical digital audio signals). way the green LED (D3) is driven better. The current through the LED is typically 4.7 mA. The current through the red LED (D4) is less, about 2.7 mA, which makes the brightness of both LEDs appear equal to the eye. If you want to program a modified template you should first save it. It’s best if you never overwrite the original tem- plate, so choose a new name for it (select Save As... under File). After opening a template it can be programmed immediately. In the configuration for Symphony Studio we have to select ‘soundbite’ as our interface. From the C/C++ Perspective choose Run , External Tools , and External Tools again, OpenOCD CDB Server (double-click the very first selection). In the Main tab you have to select ‘56300’ forthe Device and ‘soundbite’ forthe Dongle in the OpenOCD Configuration File section (see Figure 4). To make the use of the circuit as simple as possible it was decided to design the board as a plug-in module. The connector to the DSP board (l<2) is a socket (female connector) and is mounted on the underside of the board. The USB connector is a standard Type B ver- sion for PCB mounting. For the connection it’s best to use a USB2 cable; this will be specifically stated on the cable. (110534) Internet Links [1] www.ftdichip.com/Products/ICs/FT2232H.htm [2] www.elektor.com/ 1 1 0534 [3] www. ftdichip.com/Support/Utilities/MProg3. 5.zip [4] www. ftdichip.com/Drivers/CDM/CDM2081 4_Setup.exe YEARS -{tCHJS/o r E 1 1 YEAR WARRANTY l ej j ^CELEBRATE OUR 20TH YEAR, TECHNOLOGY ANNOUNCE... THE 500 MHz PICOSCOPE 6404 500 MHz BANDWIDTH 5 GS/s SAMPLING 1 GS MEMORY BUILT-IN AWG XI 00,000,000 ZOOM ADVANCED TRIGGERS NO NEED FOR EXPENSIVE OPTIONAL EXTRAS. INCLUDES: SERIAL DECODING • MASK LIMIT TESTING • SEGMENTED MEMORY... Technology www.picotech.com/scope31 1 3 elektor 11-2011 4i POWER SUPPLIES Economical Voltage Monitor By Rolf Blijleven (Netherlands) Powering stand-alone circuits from solar cells is perfectly possible as long as continuous operation is not required. You can also accumulate the relatively low energy output of solar cells until you have enough to power a circuit for a short while. How do you know when you have enough? You use a voltage monitor. The hitch is that the monitor itself consumes power, but it shouldn’t drain the accumulated energy — or at least it should use as little as possible. Even a few microamperes make a difference. We discussed the principle of energy har- vesting in the January 201 1 edition. The idea is to operate a circuit entirely from a small source of energy, without using an external power supply or batteries. In the present case the energy source is a small solar cell (costing 5 pounds or so) with a maximum output of 1 V at 1 00 mA. This level is only possible on a cloudless day with the cell facing directly towards the sun. On a cloudy day the cell products only a few hundred millivolts at a few dozen microam- peres. Nevertheless, you can do something useful with this small amount of energy — not continuously, but for brief periods a few times a day. Design Figure 1 shows the block diagram. The out- put of the solar cell is connected to a volt- age multiplier, which charges the storage capacitor C s . A number of voltage multi- plier designs were discussed in detail in this year’s January issue of Elektor, so here the multiplier is shown as a functional block. The opamp in the block diagram is a com- parator that is powered from the storage capacitor. In practice there are also a few resistors around the comparator. When the plus input reaches the threshold volt- age, the output of the comparator goes high (to the level of supply voltage V s ) and the transistor is driven into conduction. Cur- rent supplied by C t and R t keeps the transis- tor conducting for a while after the compar- ator output changes back to the low level. As a result the load continues to operate as long as energy is available in C s . This design is called a ‘solar engine’. You can find infor- mation on solar engines on the Web (e.g. [i])- On a cloudy morning the charging cur- rent is only some 20 to 30 pA, so the stor- age capacitor charges very slowly. Nev- ertheless, we need to continuously check whether enough energy has been stored. We can’t use a timer because we don’t have a battery. Experiments using a Maxi- mum MAX8282 voltage monitor [2, 3] as a comparator yielded results that were V cc=Vs Vs LOAD Vc Vs Figure 1. Basic block diagram Figure 2. Schematic diagram of the energy-efficient voltage of the energy harvesting circuit. monitor. All semiconductor components are available as SMD and through-hole types. 42 11-2011 elektor POWER SUPPLIES Figure 3. The chime sounds when enough energy has been harvested. This saves watching the meter all the time. usable but not entirely satisfactory. This 1C together with its configuration resistors draws around 6 pA - more than 25% of the charging current on a cloudy morning. Practical solution Figure 2 shows a better solution. The TC54VC27 is a voltage detector. This little three-terminal 1C consumes less than 1 pA as long as the supply voltage is below the built-in threshold voltage (2.7 V), which is the situation during the vast majority of the charging cycle. Above the threshold level the TC54 passes the input voltage to the output. The tran- sition must occur under controlled condi- tions, since the output of the TC54 also sup- plies power to the comparator — a Maxim MAX931 with a quiescent operating cur- rent of 4 pA. The comparator output may go high right away if the supply voltage is applied abruptly, causing the transistor to conduct briefly and pull down V s . If this hap- pens the voltage on Cs will never rise to the desired level, which is not what we want, so we use an RC network (220 £1 / 2.2 pF) to prevent this sort of behaviour. The MAX931 remains off until the threshold voltage V th+ is reached. This voltage is determined by R1 , R2 and R3 and is approximately 3.1 V with the specified component values. The dif- ference between this and 2.7 V may appear small, but it is significant. You notice the difference if the load is a motor. Calculating the values of R1 and R2 is described in detail in the MAX931 data sheet [4]. At voltages between 2.7 V and the threshold voltage, the monitor 1C draws a total of 5 pA. TC54 devices are available with various built-in threshold voltages in the range of 1 .4 to 7.7 V (see the data sheet [5]). In fact, we could have used one with a threshold voltage closer to our V th+ . You may won- der whether the comparator is really nec- essary. The answer is yes, because the tran- sistor must have a clearly defined switching point. Here the TC54 starts conducting at around 2.76 V. If the MOSFET were con- nected directly to the TC54, it would start to conduct a little bit, the voltage on C s would drop and the TC54 would stop con- ducting — and that would get us nowhere. A feedback resistor between the input and the output of the TC54 is not a solution because it would also draw current from Cs. The time constant of C t /R t determines how long the transistor continues to conduct. Cs should not be discharged any more than is necessary to allow the load to do its job. Suppose the load resistance plus R^son of the MOSFET amounts to 25 Q and C s con- sists of three 4700-pF capacitors for a total capacitance of 14.1 mF. This means that C s would be fully discharged in 0.35 s. If 0.2 s is sufficient, one-third of the charge can be retained in Cs, which reduces the time necessary for it to recharge. If we make C t 2.2 pF, then R t can be 100 k£2. The value of voltage V s versus time is shown in the diagram. Although the differences may seem small, they are clearly noticeable. The author was not keen to keep his eyes glued on a meter while testing the circuit, so he put together a chime with an electric motor so he could hear how often the energy supply was topped up (or what the weather was like outside). With the design described here the chime sounds several times a day even during rainy weather, while with less energy-efficient designs it remains still under these conditions. ( 110662 -I) Internet Links [1 ] http://library.solarbotics.net/circuits/ se.html [ 2 ] www.maxim-ic.com/datasheet/index. mvp/id/1273 [3] www.iamwhen.com/archives/53-Her- bert-1 701 -Species-B-Generation-1 .html [4] www.maxim-ic.com/datasheet/index. mvp/id/1219 [5] http://ww1 .microchip.com/downloads/ en/DeviceDoc/21 434h.pdf elektor 11-2011 43 E-LABs INSIDE Working with Stencils By Thijs Beckers (Netherlands Editorial / Elektor Labs) and Figure 2 Antoine Authier (Elektor Labs) The PCB and the stencil are held in the proper position using these specially shaped pins. Most electronics professionals know all the ins and outs of making PCBs, but we want to show you a technique that is probably not familiar to many electronics hobbyists: using Figure 3 stencils to apply solder paste. First we press the cone-shaped parts onto the strip of board When you order a PCB (or a panel) designed for predominantly material, and then place it on the holder PCB. SMD components, some manufacturers offer you the option of ordering a stencil at the same time. The purpose of the stencil is to considerably simplify, improve and accelerate the process of Figure 4 applying solder paste. The PCB panel for the Elektor BOB project Next, we fit the board holder pins on the holder board, provides an excellent example for demonstrating this. Figure 1 These are the components that you receive in a stencil kit: the PCB (front), the stencil (right) and the holder with the clamps (left). Figure 5 Now we can fit the PCB on the holder board. It’s important to ensure that the board is nice and clean. Fingerprints or other dirt on the pads are taboo. 44 11-2011 elektor Figure 6 We must ensure that the stencil can be laid on the PCB properly, without any curled corners. To achieve this, we tape the top edge of the stencil to a piece of board material with the same thickness as the PCB. Figure 7 Now we lay the stencil on top of the PCB. Figure 8 The cone-shaped pins hold the stencil exactly in place. As you can see, the solder pads are exposed. Figure 9 Now we can apply the solder paste. Here we only intend to apply paste to the first row of PCBs, so we don’t want to put too much paste on the stencil. Figure 10 The next step is to use a squeegee to spread the solder paste over the stencil in a single motion. Pulling the squeegee towards you yields the best results. Figure 11 If everything went right, we now have a board with perfectly applied solder paste after the stencil is removed. Figure 12 In this close-up you can see that even on the small pads for the 1C, exactly the right amount of solder paste has been applied in the right place (note that the 1C pin spacing here is only 0.5 mm). Now the board is ready for the components. After they have been placed, we can put the assembly in the reflow oven — but that’s a different story. (110514-1) MICROCONTROLLERS Here comes the Bus! (9) Rapid application development The ElektorBus browser running on an Android smartphone. Any reader wanting to create their own application for the ElektorBus has so far had to be content either with making small modifications to the demonstration software we have given, or has had to start from scratch, guided by our examples. Here we change all that: we show how you can rapidly develop an application with a custom user interface, and modify it instantly as needed. The concept is based on HTML and Javascript, and so the central control station can run on a wide range of platforms, including PCs and smartphones. By Jens Nickel (Elektor Germany Editorial) Home automation and similar measure- ment and control applications need a cen- tral control unit with a display, allowing the user to view readings and adjust settings. The unit might take the form of a PC, pro- grammed, for example, in Visual Basic. Alternatively a smartphone or tablet com- puter, running the Android open-source operating system, makes an ideal control- ler. In this case the application code has to be developed in the Java programming lan- guage within the powerful Android frame- work, which presents a steep learning curve to the beginner. Of course, if you are already familiar with Java, the Android framework and the vari- ous development tools, there is nothing to stop you using them to implement the Ele- ktorBus protocol and your own application. If the code for the protocol and the applica- tion proper are mixed within the program (as is the case in the demonstration soft- ware that we have given previously), then modifications and extensions can be hard to implement. And if you switch from one plat- form to another, the code must be rewritten from scratch. Hence we would ideally like to have a library which • implements the ElektorBus protocol, freeing the developer to concentrate on the application proper; • provides a clear separation between the application code and protocol code; • makes it easy for an electronics engineer to design and program a user interface; and • is platform-independent, so that the same application can run equally well on a PC and on a smartphone. Sounds like a tall order? Let’s see... HTML spoken here Before we look at how the library is used we will take a step back and describe how Elektor Products and Support • Experimental nodes: printed circuit board 110258-1 or set of three boards #iio258-iC3 • USB-to-RS485 converter (ready built and tested): # 110258-91 • Free software download (microcontroller firmware plus PC software) All products and downloads are available via the web pages accom- panying this article: http://www.elektor.eom/1 10517 46 11-2011 elektor the whole set-up works. At first the concept might seem overcomplicated and elabo- rate. However, the advantages of our cho- sen approach over more conventional pro- gramming methods turn out in practice to be significant, and the ideas can be used in other Elektor projects that reguire con- trol from a PC. Also, a similar approach is adopted with success in modern software development, for example of mobile ‘apps’. And so we recommend even beginners to work through the following description. First, platform-independence: we achieve this by writing the application code itself, including the user interface, in HTML and Javascript. This combination is astonishingly versatile, allowing our user interfaces to run within a browser on Windows PCs, Macs, Linux machines and all kinds of mobile device. A further benefit is that HTML pages can be transmitted over the internet, which opens up a world of remote control possibil- ities. HTML’s star is decidedly in the ascend- ant: the new HTML5 standard brings in new features such as local database storage, 3D graphics and much more. A dedicated browser The HTML front-end interface to our bus will run in a normal browser such as Firefox or Internet Explorer, but for security reasons these browsers are very limited (compared to fully-fledged applications) in what they allow an HTML page to do. For example, a normal browser cannot receive or send data over the serial port of the PC on which it is running. We therefore need a dedicated browser, still capable of displaying HTML pages, but with the extra features we need for ElektorBus applications. Since the ‘Ele- ktorBus browser’ accesses USB and other device functions, it must be specially built for each platform. Fortunately this does not present any great obstacle, as normally the source code does not need to be changed for each new application. For simplicity we make the ElektorBus browser available as an executable file for various platforms: in the case of a PC, as an ‘exe’ file. When switch- ing to a different machine, you simply need to install the appropriate version of the Ele- ktorBus browser, put the HTML/Javascript files in the right directory, and off you go! The screenshot in Figure 1 shows the first version of the ElektorBus browser. As in a normal browser, the window that displays the application’s HTML occupies the major- ity of the display. The HTML and Javascript code form the core of the application, wrapped within the browser which itself is written in a more conventional program- ming language such as Visual Basic .NET or Java (see Figure 2). We can think of the Ele- ktorBus browser the ‘host’ in our system. Protocol library The host receives an ElektorBus message over the serial port of the device on which it is running. The message is then pro- cessed according to the protocol we have described previously, and the payload is passed on to the application program (the part written in HTML and Javascript). When the user presses a button in the HTML user interface, the Javascript code generates a corresponding payload for the message to be sent: an example of this is the set- ting of a threshold value in a sensor node as described in the previous instalment. The message is then passed out to the Elektor- Bus browser, which is responsible for actu- ally transmitting it. In principle it would be possible to imple- ment all three bus protocols (the ‘Elektor Message Protocol’, ‘Hybrid Mode’ (which is optional) and the ‘Application Protocol’) within the host. On the other hand, it would be possible to make the host transparent, passing the 1 6 raw bytes in a received mes- sage packet directly through to the Javas- cript code, where the details of the protocol could be implemented. We choose a mid- dle road: the simple Elektor Message Pro- tocol and the rather timing-sensitive Hybrid Mode and scheduler are implemented within the host, while the Application Pro- tocol, which requires rather more code and which some readers will perhaps want to extend, is implemented with the help of a small Javascript library: see Figure 3. In more detail, the process runs as follows. The host receives the sixteen bytes of the message sent over the bus using the start byte synchronisation system described in [1]. The message is ‘unpacked’ into a Figure 1 . Screenshot of the first version of the ElektorBus browser with example application running. HOST: ELEKTOR BUS BROKER HTIMjJS: BUS-APPLICATION ' "j [M] 0 • _ HE our IN USB CONVERTER ELEKTOR BUS PC, Smartphone ikku n Figure 2. The platform-dependent host is only responsible for the lowest-level functions such as driving the serial port and synchronisation. The application proper is written in HTML and Javascript. data structure that contains (among other things) the transmitter address, the receiver address and the eight payload bytes. These parts are then encoded into a string (called ‘InCommand’) and passed in to the Javas- cript code (see Figure 4). The InCom- mand string is formatted as plain ASCII (see the text box) which ensures that it will be treated compatibly across different platforms. The Javascript code accepts the InCom- mand string and converts it to a simple data structure called ‘Message’, which can elektor 11-2011 47 MICROCONTROLLERS JSBUS HOST USER APPLICATION APPLICATION PROTOCOL REC SEND PART PART PART HYBRID MODE/ SCHEDULER ELEKTOR MESSAGE PROTOCOL AA MODE REC SEN) DATA CRC 110517 -12A USER APPLICATION REC SEND PART REC SEND PART JSBUS APPLICATION PROTOCOL 1 REC SEN) PART PART PART HOST J t inT REC SEND DATA ^OUT HYBRID MODE/ SCHEDULER ELEKTOR MESSAGE PROTOCOL AA MODE REC SEN) DATA CRC 110517 -12B BYTE 0 1 2 3 4 5 6 7 8 9 A B C D E F BTT 7 6 5 4 3 2 1 0 10101010 00000000 ADDRESS RECEIVER ADDRESS SENDER PART PART PART CRC MODE ID 110517-13 Figure 3. The standard ElektorBus protocol stack (Hybrid Mode and the Scheduler are optional). The host is responsible for the Message Protocol layer, the JSBus Javascript library for the Application Protocol layer. Figure 4. The host and JSBus library communicate with one another by exchanging, in plain text form, the contents of messages that are received or that are to be transmitted. Figure 5. The Application Protocol allows several numeric values or other items of information such as alarm thresholds to be conveyed in one message. The diagram shows an example of three of these so- called ‘parts’: two consisting of two bytes and one consisting of four bytes. then be further decoded. In accordance with the Application Protocol the message is divided into so-called ‘Parts’, which cor- respond to individual units of information: see the text box ‘Messages and Parts’. One unit might for example comprise a single transmitted two-byte value (from -1 023 to +1 023), or be a message such as ‘read- ing below threshold on sensor 2’. Just as one message can convey several such morsels of information (see Figure 5), so the Javascript library can create an array of several parts from a message. The received parts are then passed to a Javascript function into which the developer can put code particular to the application. For example, this applica- tion code could copy a numerical value con- tained within a part into an HTML text box. Command types When the application wants to transmit data, the process operates in reverse. A click on an HTML button calls a Javascript func- tion specially written for the application, InCommand and OutCommand The ElektorBus application, written in Javascript, and the ElektorBus browser, written (for example) in Visual Basic .NET, communicate with one another using simple text strings. The JSON syntax is used to encode the necessary information in a data structure within the string to be passed outwards from the Javascript application to the host or inwards from host to Javascript application. The data struc- tures for InCommand and OutCommand are very similar. OutCommand: Command command type (‘Send’, ‘Url’ or ‘ Scheduler ’) Url file name for HTML page to be loaded ( only for ‘UrT commands) Options reserved for future use Mode mode byte for the message to be sent (needed as part of the acknowledge mechanism) Receiver receiver address Sender transmitter address Data array of eight data bytes, or addresses of up to eight sched- uled nodes InCommand: Command command type (‘ Rec ’ or ‘Status’) Mode mode byte of the received message (status 2 = OK; - 1 = error) Valid checksum OK? (not yet implemented) Receiver receiver address Sender transmitter address Data array of eight data bytes In JSON syntax an InCommand appears as in following example: {"Co mma n d " : "Rec", "Mode": 0 , " V a I i d " : 0 , "Sender": 2, " Recei ver " : 10, " Dat a" : [ 0, 0, 64, 1, 0, 0, 0, 0] } In the first version of the ElektorBus browser the In- and OutCom- mands are displayed to aid debugging: see the bottom of Figure 1 . 48 11-2011 elektor MICROCONTROLLERS Messages and Parts which in turn generates one or more parts. Parts which are ultimately destined for the same receiver can be encoded into a single message. The message object is then trans- ferred from the Javascript code out to the ElektorBus browser as an ‘OutCommand’, again in the form of plain text. The browser then generates a set of sixteen bytes and sends them out over the bus. Once this is done it returns a success message to the Javascript code. This message also takes the form of an InCommand, this time of type ‘Status’. There are also other types of OutCommand (see the text box) used in various ways to allow the HTML and Javascript to con- trol the actions of the host. The OutCom- mand ‘Url’ causes the host to load a new HTML page. This makes it possible to con- struct an application over several different pages, selected, for example, using some kind of menu. The OutCommand ‘Sched- uler’ switches the scheduler on and off. In this case the data array contains a list of addresses of up to eight nodes that are to be polled. Example application The easiest way to see how the Javascript library and the ElektorBus browser fit together is through an example. We will use exactly the same hardware as we did in the previous instalment in this series, with just minor changes to the firmware run- ning on the two nodes: the BASCOM file is available at [2]. Figure 6 shows once more the hardware involved: node 2, equipped with a light-dependent resistor, continu- ously sends readings to the master node. The master can instruct the sensor node to change its units of measurement and to set a lower threshold value. If the reading goes below this threshold value the sensor pro- duces an alarm message. In response to this the master sends a message to node 1 to instruct it to pull in its attached relay, and acknowledges the alarm message from the sensor. A first version of the ElektorBus browser to run on a PC can be downloaded from the web pages accompanying this article [2], along with the Javascript library ‘JSBus.txt’ The javascript library works internally with two data structures to describe messages and parts (items of payload information such as two-byte values, alarm reports, quantity settings and so on) that are being transmitted and received. The Message object basically consists of the familiar components of an ElektorBus message. Mode mode byte Receiver receiver address Sender transmitter address Data array of eight data bytes Valid checksum OK? (not yet implemented) Within the eight data bytes we can convey up to four parts in accordance with the Applica- tion Protocol. Each Part is characterised by the following properties. Valid check sum OK? ( not yet implemented) Sender transmitter address Receiver receiver address Channel channel number Numvalue Setflag desired setting or current value? Acl | I I < S C R I PT Language='j avascri pt 1 > function ProcessPart(part) { i if ((( pa r t . Sender == 1 ) | | ( p a r t . Se n d e r == 2)) && ( pa r t . Pa r 1 1 y pe == PARTTYPE_VALUE2) ) { ; if (part. Channel == 1) {Radi oButtonSetval ue(' LED 1 + part. Sender, part. Numval ue) ; }; } j if (( pa r t . Sender == 2) && ( pa r t . Pa r 1 1 y pe == PARTTYPE_VALUE2) ) ] { | if (part. Channel == 0) {TextboxSetval ue( 1 ADC' , part. Numval ue);}; } i } functi on SetSensorScal e ( quant i ty) { var parts = I ni tParts( ) ; parts = Set Sc a I e ( pa r t s , 10, 2, 0, 0, quantity, 0, 0); SendParts( parts, true); if ( quant i ty= = RESI STANCE) {TextSetval ue( ' uni t 1 , 1 Ohm 1 ) ; }; if ( quant i t y= = RA WV A L U E ) {TextSetval ue( 1 uni t 1 , 1 ADC-Val ue 1 ) ; }; } < F O R M Name=' Bus 1 > < D I V I D = 1 head 1 >EI ekt or Bus Br ows er
Sc hed u I e r o n of f LED Node 1 LED Node 2
<1 N P UT Ty pe =' text 1 I D = ' ADC 1 Valued' /> S e t - Li mi t-Page
elektor 11-2011 5i MICROCONTROLLERS Main functions in the ISBus lavascript librar f unct ion I ni t Par t s( ) Returns an empty array of parts. Called as follows: va r parts = Initpartsf); f u n c t i o n Set L i mi t ( pa r t s , sender, r ec ei ver , channel , mode, 1 i mi t , n u mv a 1 u e ) f u n c t i o n Set Seal e( par t s, sender, r ecei ver , channel , mode, quant i t y , unit, scale) f u n c t i o n SetVal ue( parts, sender, r ec ei ver , channel , mode, setval u e ) These functions append a new part to an existing array parts, respectively representing a threshold, a quantity, unit and scaling value, and a set-point for a given sensor or actuator. The return value is the extended array. function SendParts( parts, overri deQueue) Encodes and sends all parts in the array in one or more messages: see the text for more details, function PartText(part) Returns a textual representation of a part, for example for debugging purposes. function Radi oButtonSetval ue(i d, setvalue) Sets or resets a radio button s e t v a I u e = 0 or 1 ). function TextboxSetval ue(id, setvalue) function TextSetval ue( i d, setvalue) Sets the text in a text box or text element. function Got o Ur I ( u r I ) Causes the host to load a new HTML page (u r I = file name without trailing ‘.htm’ extension), function SetSchedul er(status, schedul ednodel, ... , schedul ednode8) Switches the scheduler in the host on or off (status =SCHEDULER_ON orSCHEDULEROFF) and provides the scheduler with a new list of nodes that should be regularly requested to send a message. A zero value terminates the list. RESI STANCE is defined as the constant 1 8. BASIC aficionados should beware of the doubled equals sign in comparison opera- tions and pay particular attention to consist- ency in the use of upper and lower case in Javascript code. Now we turn to the HTML section. This consists of a series of elements, each introduced by a tag such as ‘
’ or ‘\ The tags of particular inter- est to us are those enclosing ‘’ and ‘