September 2012 AUS$ 14.90 - NZ$17.90 - SAR 105.95 " NOK102 + Arduino on Course 1 -bit Sound Generation ... What?!? + Model Train Interface with USB connection and Windows script editor + PICoPROto Minimalist prototyping tool for PIC1 6 or 1 8 770268 451 7 lektor Brought to you by Eurocircuits rvice The European reference for PCB prototypes and small series Speed up your design cycle and keep costs down using our fast, easy-access online PCB pooling services. We deliver: • Top quality PCBs at low pooling prices • Fast deliveries to suit your requirements • Comprehensive technology support • No set-up or tooling charges • No minimum order charge - order from 1 PCB • Online ordering without pre-payment • Stencil service PCB proto - dedicated engineering prototype service , fast and low-cost • 1 or 2 PCBs in 2, 3, 5 or 7 working days • DRC-checked and fully finished with 2 soldermasks and 1 legend, 150pm technology • 1 x 100 x 80mm in 7WD - 2 layer 47,02 € - 4 layer 95,52 € • 2 x 100 x 80mm in 7WD - 2 layer 36,89 € each - 4 layer 74,76 € each Prices quoted include 2 1 % Belgian VAT but exclude transport costs STANDARD pool - widest choice of Eurocircuits pooling options • 1-8 layers 150pm technology PCBs • from 2 working days TECH pool - all the benefits of pooling for high-density PCBs • 2-8 layers 100pm technology PCBs • from 4 working days IMS pool - aluminium-backed PCBs for high heat-dissipation (LED) applications • Single layer Insulated Metal Substrate PCBs • 1.5mm aluminium base with 75|jm thermally conductive dielectric and 35pm Cu foil • from 3 working days On demand - multi-option non-pooling service for specialist needs • 1-16 layers down to 90pm technology • RF and high Tg materials • from 2 working days www.elektorPCBservice.com ELEKT0R-09-2012 PIC18FJ, dsPIC33, PIC24 or PIC32? workstation v7 supports all mikromedia boards with Microchip® microcontrollers. Easily switch to the one you need. workstation v 7 is perfect for multimedia development. It features on-board debugger, mikromedia socket button, LED and three headers for each pin group. Four mikroBUS host sockets provide an elegant way for adding desired Click boards. Use large breadboard area to assemble your custom electronics. This miracle board is fantastic for education as well. We made sure to provide a rich set of libraries and examples for our mikroC, mikroBasic and mikroPascal compilers which facilitate development. At the end of Checkout page enter the code above to GET FREE Shipping! *ALL ORDERS INCLUDED * //cf u ntil 14th Septet * FREE GIFT > for all readers of Elektor Magazine! Mikroilektronika DEVELOPMENT TOOLS I COMPILERS I BOOKS GET IT NOW www.libstock.com www.mikroe.com * Main picture includes: mikromedia workstation i /7, mikromedia for PIC3Z, WiFi PLUS click, THERMO click, RTCZ click and SHT11 click. ** mikromedia and click boards are sold separately! 6 Colophon Who’s who at Elektor. Do try this at home I believe one our first articles linking DIY elec- tronics to ‘kiddie’ electronics was the Game- boy Digital Oscilloscope (GBDSO) from 2000. Basically, you plugged a module into a Nin- tendo Gameboy game console and hey presto there’s a simple portable oscilloscope. Initially we staged a Dutch-ish auction on the web to ‘test the market’, that is, check what price our customers were willing to pay for the product. Eventually the Elektor GBDSO reached sales volumes in the thousands across a period of more than ten years. If that GBDSO were an Olympic athlete, it would be in the company of Crescendo, EEDTs, Junior Computer, Film- net Decoder, ATM18, SDR and Pico-C. Resonating widely across the e-commu- nity, it is not surprising to see a product like GBDSO attracting strange questions from law-abiding readers (mostly from Germany), like “Where do I get hold of a known-good Gameboy, with full warranty, mint condition, at the lowest price?” to which we replied “Promise your kid(s) the new Advance model”, or “Dig around in the sandpit at the local playground”. Like- wise, Q: “Did you get Nintendo’s lawyers to approve that module?” A: “Hardly. Nin- tendo’s techies subscribe to Elektor.” Twelve years on, I would unhesitatingly rec- ommend to all you electronics designers out there to hack, fry, disembowel, blend, explore, rebuild or repurpose the tons of kid’s electronics out there. It’s cheap, often free and in plentiful supply. By rescu- ing stuff from skips and dumpsters filled by the throwaway generation, the elec- tronics inside provides a mental link to the clever people who designed and build it all. Reverse engineering is good engineering. Do it creatively and with respect. Like we did with the Nunchuk on page 18. Happy reading and nunchuking, Jan Buiting, Managing Editor 10 M£2/ mm) that provides a highly stable behavior (better than ±3%) over a wide temperature range (-40 g C to 1 25 Q C). The new TP0702UCAP, is particularly suitable for applications such as TPMS (Tire Pressure Monitoring Systems) which requires an excellent performance under extreme conditions, according to AEC-Q200 and additional requirements as EU regulations. PREMO offers four standard values, 2.38 mH, 4.91 mH, 7.2 mH and 9 mH at 125 kHz. Other inductance values and frequencies, from 340 pH to 1 8.5mH, are available upon request. A surface mount (SMT) device, the new antenna allows easy use in the automated process of mounting circuit boards, thus eliminating any manual handling. www.grupopremo.com (120487-IV) 8 og-2012 elektor NEWS & NEW PRODUCTS iPad transformed into portable logic analyzer Oscium’s new LogiScope is a logic analyzer with the real time data analysis capabilities of an oscilloscope. Oscium’s test and measurement equipment is ultra-portable and designed specifically for the iOS family of products like the iPhone, iPad and iPod touch. The LogiScope is a powerful tool that transforms an iPad into a 100 MHz, 16 channel logic analyzer for only $389.99. Traditionally, a logic analyzer records a buffer which has to be downloaded and searched. Now with LogiScope’s advanced triggering, decoded data can be viewed live, eliminating the need to capture, pause, and then view. There is no need to settle for pictures when it’s possible to analyze live data. The touchscreen-based iOS platform is truly a superior solution making the display simple and intuitive. For example, changing the timescale is as easy as zooming into a picture on a smartphone, and adjusting the delay is as simple as a swipe across the top of the screen. LogiScope’s intuitive interface also provides immediate feedback for signals that are too fast for the timescale by changing the waveform to red. No need to wait for the reading to be complete. Save precious time and receive instant feedback with LogiScope. “ The user interface on LogiScope is extremely well executed,” said Bryan Lee, President of Oscium. “It's our best interface yet. ” New 4-channel, compact, USB-powered oscilloscopes The PicoScope 3000 Series of high-performance oscilloscopes has been expanded to include six new 4-channel models. The new oscilloscopes offer a maximum sampling rate of 1 GS/s (up to 1 0 GS/s effective for repetitive signals), a range of input bandwidths from 60 MHz to 200 MHz, and buffer memory depths from 4 M to 1 28 M samples. The new FlexiPower™ system allows the scopes to run on either USB or AC power. With an option of either a built-in function generator or a built-in arbitrary waveform generator, and a new, slim case design, these scopes are perfect for engineers and technicians needing a complete, portable test bench in a single unit. The PicoScope oscilloscope software includes as standard all the oscilloscope and spectrum analyzer functions you would expect, as well as serial decoding, mask limit testing, segmented memory and advanced triggers: features that often cost extra on other manufacturers’ scopes. Running on your Windows PC, PicoScope shows waveforms on a large, clear display and allows easy zooming and panning under keyboard or mouse control. Other built-in features include persistence displays with fast waveform update rates, math channels, automatic measurements with statistics, programmable alarms, and decoding of l 2 C, UART/RS232, SPI, CAN bus, LIN and FlexRay signals. Updates to the software are released regularly, free of charge. The advanced triggering modes include pulse width, interval, window, window pulse width, level dropout, window dropout, runt pulse, variable hysteresis, and logic. All triggering is digital, ensuring lower jitter, greater accuracy and higher voltage resolution than the analog triggering found on many competing scopes. A free Software Development Kit (SDK) allows you to control the new scopes from your own custom applications. The SDK includes example programs in C, C++, Excel and LabVIEW, and can be used with any language that supports C calling conventions. The PicoScope software and SDK are compatible with Microsoft Windows XP, Windows Vista and Windows 7. The PicoScope 3000 Series 4-channel oscilloscopes are available now from Pico distributors worldwide and from www.picotech.com. Prices range from only £599 for the 60 MHz PicoScope 3404A with function generator to only £1349 for the 200 MHz PicoScope 3406B with AWG, including four probes and a 5-year warranty. www.picotech.com (120487-VIII) LogiScope version 1.0.12 is available for download free in the Apple App Store. The LogiScope app is made for: iPod touch (3 rd , and 4 th generation), iPhone 4S, iPhone 4, iPhone 3GS, iPad 3, iPad 2, and iPad. LogiScope hardware can be purchased for $389.99 from Oscium directly or from one of their partners. www.oscium.com (120487-MI) Advertisement PCBs Muuuuch Cheape No-frills policy 17.22 EURO 5 pcbs, 1 00 mm x 1 00 mm ♦per piece, incl. UflT (23%) + shipping costs e. g. Germang 1 0.89 EURO * JaCCaltac ujLULU.jackaltac.com elektor og-2012 9 NEWS & NEW PRODUCTS Cloud-ready HMI extension for industrial panel PC family Input device specialist Hoffmann + Krippner has further extended its flexx- IPC™ customizable panel PC concept with the launch of a software platform that will reduce the time and cost of human machine interface (HMI) development and deployment. Using flexx-HMI OEMs can rapidly create optimized HMIs that seamlessly integrate with industrial automation, process control and other deterministic PLC- and controller-based applications. The new flexx-HMI® technology allows OEMs to quickly and easily develop advanced and intuitive HMIs that harness the power of Hoffman + Krippner’s Microsoft Windows Compact 7-based flexx-IPC panel PCs. These PCs use the company’s innovative membrane input technology to support cost-effective front panel customization in order volumes as low as just 20 units. A selection of flexx- HMI drivers supports more than 1 00 PLCs and controllers, while the HMI software provides comprehensive ‘cloud-based’ support for secure, remote access via any web-enabled device. OEMs looking to create advanced user interfaces for the platform can purchase a comprehensive development environment from Hoffmann & Krippner. Using project wizards this development environment dramatically simplifies the building of HMI applications including data source creation, screen design, testing and deployment. Once the HMI has been created it is possible to provide users with access to a cloud- based service that supports monitoring and control access from any browser on any hardware. www.flexx-ipc.co.uk (120487-VI) UV cure adhesive for optoelectronic and circuit assembly applications Engineered Material Systems, introduces 535-1 0M-1 UV Cured Adhesive formulated for disk drives, camera modules, optoelectronic and circuit assembly applications. 535-1 0M-1 is an ultra low Advertisement Fascinated by technology’s impact on the future? TrtimitFmijiK ►I*!--!! Mi..,,#, It* cl U'uirr rrli L* 1+Jy.iyir.i it*,!,- Check out Tech the Future! Computing power and global interconnectivity are pushing tech innovation into overdrive. Pioneering technologies and creative workarounds affect even the couch potato 24/7. Tech the Future reports on technology strides that shape the future — yours included. www.techthefuture.com jfl 1 kuiiui P i M .iifci c ,■ Follow Tech the Future 10 og-2012 elektor Low Cost. High Performance. PC-based measurements from only £69 Multifunction DAQ Nl USB-6008 12-Bit, 10 kS/s, Multifunction DAQ ■ 8 analogue inputs; 2 analogue outputs; 12 digital I/O; 32-bit counter ■ Bus-powered for high mobility; built-in signal connectivity ■ NI-DAQmx driver software and LabVIEW SignalExpress LE interactive data-logging software ■ £99 ALSO AVAILABLE: Nl USB-6009 14-Bit, 48 kS/s, Multifunction DAQ - £179 Nl USB-6210 16-Bit, 250 kS/s, Multifunction DAQ - £399 Nl USB-9201 12-Bit, 8 Channels, 500 kS/s - £549 Sensor-based measurements Nl USB-TC01 Thermocouple Measurement Device - £79 ALSO AVAILABLE: Nl USB-9211A 24-Bit, 4 Channels, Thermocouple Input - £529 Nl USB-9219 4 Channels, Universal Analogue Input - £1049 Instruments Nl USB-5132 50 MS/s Bus-Powered Digitiser/Oscilloscope - £499 ALSO AVAILABLE: Nl USB-5133 100 MS/s Bus-Powered Digitiser/Oscilloscope - £699 Nl USB-4065 6V 2 -Digit USB Digital Multimeter - £1049 Digital I/O Nl USB-6501 24 Channel, 8.5 mA, USB Digital I/O - £69 ALSO AVAILABLE: Nl USB-6525 8 Solid-State Relays, 8 Dl, Counter, Channel-to-Channel Isolated - £249 Nl USB-9421 8 Channels, 1 1-30V Digital Input - £339 Nl USB-9472 8 Channels, 6-30V Digital Output - £339 Instrument Control Nl GPIB-USB-HS GPIB Controller for Hi-Speed USB 2.0 - £ 349 ALSO AVAILABLE: Nl USB-232 Single-Port RS232 Interface for USB Nl USB-485 Single-Port RS485 Interface for USB Nl USB-8451 I2C/SPI Interface - £339 - £129 -£129 At lower cost than you might think, National Instruments provides an intuitive platform that can connect to thousands of sensors and instruments to acquire, analyse and process signals, and present results graphically. Whether programming in C, Basic or LabVIEW on Windows, Mac or Linux, get the latest in PC-based data acquisition, instrumentation and instrument control, starting at less than £70. »Buy online and explore the range at uk.ni.com/lowcost Join us to improve your product skills, knowledge and productivity using Nl LabVIEW software, 9 UK & Ireland locations in September and October: uk.ni.com/devdays JOIN THE CONVERSATION: Follow us on Search niukie 01635 517300 uk.ni.com info.uk@ni.com v NATIONAL ^INSTRUMENTS ©2012 National Instruments Corporation. All rights reserved. National Instruments, Nl, and ni.com are trademarks of National Instruments. Other product and company names listed are trademarks or trade names of their respective companies. Prices subject to change. For latest prices, check online at ni.com/products. NEWS & NEW PRODUCTS Xylobands™ LED wristbands get crowds rocking at Coldplay concerts Nothing lights up a rock arena quite like a Coldplay audience with tens of thousands of flashing Xylobands(™) LED wristbands powered by embedded technology from Silicon Laboratories Inc. Created by UK-based RB Concepts Ltd., Xylobands use wireless ICs and ultra-low-power microcontrollers (MCUs) from Silicon Labs to receive and process wireless signals that trigger each wristband’s LEDs to light up in sync with the music and stage lightshow. The Xylobands are the unique, patented creation of inventor and Coldplay fan Jason Regler, a co-owner of RB Concepts. Coldplay’s high-energy music and lyrics inspired Regler’s bright idea to create a wireless LED wristband that could be controlled remotely through proprietary software and a laptop connected to a radio transmitter to enable fans to be part of the lightshow. Recognizing the brilliance of Regler’s invention, the Brit Awards- and Grammy-winning rock band has used Xylobands to light up arenas and stadiums all around the world. “Taking the LED wristband from concept to finished product required best-in-class embedded control and wireless technology,” said Jason Regler, director of technology and innovation at RB Concepts. “Silicon Labs was the ideal choice for wireless technology, enabling us to achieve both FCC and Industry Canada Certification and deliver more than 30,000 Xylobands just in time for a recent Coldplay concert in Edmonton, Alberta, Canada.” “RB Concepts and Silicon Labs have been outstanding,” added Phil Harvey, Coldplay’s creative director. “They’ve delivered hundreds of thousands of units whenever and wherever we’ve needed them. The wireless LED wristbands have broken down that invisible wall between band and audience and put the audience right at the heart of the show. The mass feeling of joy and wonder when they all light up at the top of the show is hard to put into words.” Xylobands have a very broad appeal. In addition to lighting up rock concerts, Xylobands can generate interactive audience participation at a wide variety of sporting events, theme parks, festivals, parties and corporate activities. “Xylobands and the low-power, long-range wireless technology behind the product is a game changer for how audiences can interact with performers and become an integral part of the concert experience,” said Diwakar Vishakhadatta, vice president and general manager of Wireless Embedded Systems at Silicon Labs. “RB Concepts’ wireless wristbands are also a versatile innovation that can be applied to a wide range of events and activities.” Seeing is believing. Visit www.coldplay.com to see Xylobands flashing on and off to Coldplay’s hit song, “Charlie Brown,” performed at Rexall Place in Edmonton. Silicon Labs’ EZRadioPRO transmitters enable Xylobands base stations to transmit wireless signals in the sub-GHz frequency bands. These transmitters offer industry-leading RF performance resulting in exceptional wireless range and compliance with stringent wireless regulatory standards. Xylobands LED wristbands include EZRadio receiver ICs designed for low-power sub-GHz radio applications. These receivers offload many RF-related activities from the system MCU, allowing extended MCU sleep periods and resulting in lower power consumption. The EZRadio products work in concert with Silicon Labs’ ultra-low-power C8051 F98x MCUs, offering the industry’s lowest active mode current consumption, which saves power when the application is running, as well as the industry’s lowest current consumption in sleep mode, making it an ideal choice for battery-powered wireless applications. www.silabs.com (120487-VII stress, lower glass transition temperature version of the 535-1 OM UV Cure Adhesive. The material is designed to eliminate any “crowning” (warpage) of sliders in head gimbal assemblies and can be used in other bonding applications in the head stack assembly. The material also can be used for lens bonding in camera modules, chip encapsulation in smart cards and a variety of general bonding applications in photonics assembly. This new nonconductive UV cured adhesive cures rapidly when exposed to high-intensity UV light. 535-1 OM-1 is a low outgassing, extremely flexible, high-strength epoxy adhesive that does not contain antimony. The 535-1 OM-1 was developed to pass the rigorous reliability requirements in disk drive, camera module, photonics and circuit assembly applications. 535-1 OM-1 is the latest addition to Engineered Material Systems extensive line of electronic materials. www.conductives.com (120487-V) 12 og-2012 elektor Elektor RF & Microwave Toolbox <=> for Android ■lipp * 41 LJ-Cl- 1 :-? Cl C2 7 Synch ro=1 Start l 2 C vy I2C(0) MI2C_Start 0xA5 I2C(0) MI2C_Trans... buf 0 I2C(0) NUN_BUF[0]... bufl ... buf 4 Synchro=0 Calculation of 3 axes Figure 4. Reading the data from the Nunchuk controller. elektor og-2012 21 HOBBY & GAMES in the operating systems, so the interface is compatible with Win- dows, Linux, MacOS, etc. with no installation needed. Software All the programs provided have been produced using Flowcode v4. This software is ideal for programming the 1 8F2550, as even a beginner in computing will be able to handle the HID (human interface device) drivers for the USB link and for the l 2 C bus. Those used to using C will have more difficulty porting the programs, but will have to remember to tell the compiler to start the program from the address $800 in order not to delete the bootloader if they want to go on using the USB program (Table 7). Table 7 Using the bootloader At power-up... To program a Flowcode hex file, all you have to do is hold the ‘boot’ button pressed as you apply power to the board. The LED D1 flashes Figure 5. The Nunchuk connector, showing the keyway (hollow), which must be oriented towards the solder side of the board. Figure 6. The two slots made with a min disc-cutter are vital so as to be able to plug the controller cable in. Table 7. Address Flash memory user program Flowcode $0800 $07FF bootloader (do not delete) $0000 Figure 7. Running the PDFSUSB.exe programming software that lets you access the contents of the 1 8F2550’s Flash ROM. to indicate that the drivers must be installed. The various files are contained in the ‘USB Framework’ pack from Microchip [3]. We strongly recommend you opt to install it in the default directory. You’ll find the drivers in the \Microchip Solutions v201 0-1 0-1 9MJSB ToolsXMCHPUSB Custom DriverX MCHPUSB DriverXRelease directory. They can be downloaded from the Elektor website [1]. After installing the driver, run the programming application PDFSUSB.exe which is located in the XMicrochip Solutions v2010- 10-19XUSB ToolsXPdfsusb directory. Select the PICDEM FSUSB 0 (Boot) driver. Load a hex file, click on ‘program device’, then ‘run’ (Figure 7). Example programs I’m providing four examples of applications [1] which will be easy to modify so you can use them elsewhere or in a different way. hid_davier_trame.fcf (basic program included in the firmware) This program lets you test that everything is working properly. 22 og-2012 elektor NUNCHUK USB INTERFACE When you press button Z on the Nunchuk, the digital values for all three axes are sent over the USB link. They will be displayed in Notepad, then the interface board emulates a PC keyboard. When button SI is held down, only the digital value for the X axis is sent to the PC. You can then analyse these data in a spreadsheet, as shown in Figure 8. hidjoytick.fcf The Nunchuk turns into a joystick on the X and Y axes. The joystick calibration can be accessed in the Windows ‘Settings’ (‘Games controllers’). Warning: if you don’t calibrate it, the joystick operation will not be optimum. hid_souris_accel.fcf (‘souris’ = mouse) Turns the Nunchuk controller into a computer mouse: X axis = left/right movement and Y axis = up/down movement. Z & C buttons: left/right click You’re likely to be a bit disconcerted at first by the sensitivity of the controller. Figure 8. The ‘boot’ button also lets you send the accelerometer X-axis values, which you can then analyse in a spreadsheet. Advertisement Create complex electronic systems in minutes using Flowcode 5 flowcode Design - Simulate -Download Flowcode is one of the World’s most advanced graphical programming languages for micro- controllers (PIC, AVR, ARM and dsPIC/PIC24). The great advantage of Flowcode is that it allows those with little experience to create complex elec- tronic systems in minutes. Flowcode’s graphical development interface allows users to construct a complete electronic system on-screen, develop a program based on standard flow charts, simulate the system and then produce hex code for PIC AVR, ARM and dsPIC/PIC24 microcontrollers. Convince yourself. Demo version, further information and ordering at www.elektor.com/flowcode elektor og-2012 23 HOBBY & GAMES COMPONENT LIST Resistors R1,R2 = 10kn R3,R4 = 22 ft R5-R9 = 1 k£l Capacitors Cl = 470nF C2 = 1 OjlxF 1 6V radial C3 = lOOnF C4 = 220nF C5 = 2.2pF 16V radial C6,C7 = 22pF Semiconductors D1 -D5 = LED, 3mm, low current IC1 = PIC1 8F2550-I/P, DIP, 28- pin, programmed, Elektor# 100594-41 IC2 = LP2950ACZ-3.3 Miscellaneous SI, S2 = pushbutton l<2 = USB-B connector, PCB mount l<3 = 4-pin pinheader l<4, l<5 = 9-way sub-D socket, right-angled pins, PCB mount XI = 20MHz quartz crystal PCB #100594-1 nunchuck_dmx.fcf The Nunchuk turns into a ‘moving head’ stage spot controller using the DMX protocol on the serial connector l<3 (RC6: TXD). Warning! You will need to modify the program depending on the spot being used, and add an RS485 bus 1C: 75176. ( 100594 ) Internet Links [1] www.elektor.com/ 1 00594 [2] http://wiibrew. 0 rg/wiki/Wiim 0 te/Extensi 0 n_C 0 ntr 0 llers#Nunchuk [3] Microchip USB FrameWork: http://ww1 .microchip.com/down- loads/en/DeviceDoc/MCHP_App_Lib_v201 0_1 0_1 9Jnstaller.zip Update list: www.microchip.com/stellent/ idcplg?ldcService=SS_GET_PAGE&nodeld=2896 [4] www.microchip.com/wwwproducts/Devices. aspx?dDocName=en01 0280 Figure 9. Initially, there are no slots in the PCB either side of K1 for the Nunchuk plug. The serial interface (l<3) is used only by the nunchuck_dmx.fcf program and any personal applications you may think of. At the time of building the prototype, the 3.3 V regulator drawer was empty, which explains why there are two diodes in place of IC2. 24 09-2012 elektor •:::c355‘* '3::a:cc atccecec ccceecec :ccc:ccf reeccccc ;::ccct ‘C8CCCC 3f 8098CC JCfl8C3CC CCCC3t3s 1 16 3 C C 3 C C 3' Read Elektor with the cut-rate PLUS membership! Join now or upgrade: www.elektor.com/member HOBBY & MODELLING Model Train Interface With USB connection and Windows script editor By Willem Tak (The Netherlands) How many people have a model railway tucked away in the attic or somewhere, which they bought at one time for themselves or the children? After going around and around for a while the fun usually starts to wear off and there are very few who will continue to expand and automate their railway. With this small circuit your model railway will have a few additional features and more intelligence, without the need to buy intelligent trains and other expensive model railway equipment. Every year, during the month of December, the lady next door builds a beautiful Christ- mas landscape. To add some life to the scen- ery a train runs through it. However, this train going around forever and ever in cir- cles gets to be a little boring after a while, so something had to be done about this. Could this little train not change direction or speed every once in a while? And is it pos- sible to stop at the station sometimes? There are obviously countless methods to realise this, such as the excellent EEDTS (EDiTS) from Elektor, but this simple appli- cation begs for an equally simple solution. The idea is to write a script which contains a sequence of instructions (drive forwards or backwards at a particular speed, stop for a number of seconds, drive to the station, etc.) and to have this script executed by a circuit specifically designed for this purpose. Hardware This circuit has been designed for use with model trains that operate on DC. It has been tested with a Fleischmann 9336. At the heart of the circuit is a Microchip PIC 1 8F4550 (see Figure 1 ). This micro was selected because of its built-in USB inter- face, which we can use nicely to communi- cate with the script editor running on the PC. This is very easy: you write a script using Windows and then send it to the interface. Because of the USB functionality, using a 24-MHz crystal is absolutely necessary. To operate the circuit, a two-line LCD was chosen, together with a rotary encoder with pushbutton. The LCD is controlled directly by the PIC. Data line RD7 is fitted with a pull- 26 og-2012 elektor MODEL TRAIN INTERFACE ■ down resistor (R14) because the software makes use of the Busy flag. The power supply design with relay Rel appears a little strange at first, but this has to do with the cir- a pulse-width modulated signal with a fre- quency of 1 00 Hz. The train goes slow with narrow pulses and with wide pulses it ‘flies’ along the tracks. The 5-V pulses from the controller are ‘enlarged’ byTI to 15 V, after which Schmitt-trigger gates IC3.Ato IC3.C age on the tracks. You will have to experi- ment which way around the wires have to be connected to the tracks. If the program indicates that the train should travel for- wards but it actually goes in the opposite direction then you have to swap the wires. 1 2 3 4 5 120351 - 11 Figure 1 . The controller generates a pulsewidth modulated signal, which drives the train via MOSFET T3. cuit really having two functions: it is a USB interface and a train controller. When the power supply relay is in the non-energised state, the 5-V power supply voltage of the USB interface is used to power the circuit. This then functions as a HID-USB device and in this state scripts can be read and loaded. When an external power supply of 1 5 V is switched on, the relay is energised and the controller gets powered via a 7805 regulator (IC2). The pulses that drive the train are availa- ble at output RB4 of the controller. This is are used to enhance the edges. The pulses are subsequently sent to an N-channel MOS- FET type FQP1 2N60. This FET can cope with quite a lot, but the author is no model rail- way expert. I assume however that there are model trains requiring much more cur- rent than the one with which the circuit was tested. The type selected here can carry quite a bit of current (about 1 0 A), but usu- ally no more than about 1 A is required. For- wards and backwards driving directions are accomplished with the driving relay (Re2). This simply reverses the polarity of the volt- Since the little motor in the train (a sub- stantial inductance!) can generate sizeable noise spikes, there is a suppression net- work (Cl 2/Cl 3/Ll / L2) between the relay contacts and connector l<2. Its purpose is to prevent these spikes from upsetting the control electronics. Capacitor C3 between the CD401 06 and the MOSFET contributes to this as well; the edges of the control sig- nal are a little less steep as a result. Via opamp IC4 there is a feedback signal for the controller (pin 1 5), so that the control- elektor 09-2012 27 HOBBY & MODELLING LED indications Internal LEDs (D3/D4): • Yellow (D4) • Green (D3) on when USB is in use on in Train mode with external power supply Front-panel LEDs (D5/D6/D7), USB Mode: • Blue(D7) flashes during initialisation of the USB Mode • Blue(D7) on when the program trein.exe is running • Blue (D7) can be controlled by the program trein.exe Front-panel LEDs (D5/D6/D7), Train mode: Red (D5) Red (D5) + Green (D6) Green (D6) Blue (D7) on in Train mode when the train is moving on when the train is stationary during the command ‘wait’ on when the train is stationary at the station on when the train is stationary when the station has not been found • Red + Green + Blue • Red + Blue • Running lights on when there is an LCD error on when there is an EEPROM error train is not moving according to the script ler can check that the instructions from the script are actually being carried out; when the train is moving, IC 4 receives pulses at its + input. Station detection is achieved with the aid of a light barrier (separate schematic in Fig- ure 2). This is a simple U-shaped construc- tion consisting of two upright wooden posts, one on each side of the rails. An LED is mounted in one post and an LDR on the Figure 2 . These parts are mounted near the light trap and are connected to l <3 on the circuit board. other. When the train passes through the barrier it interrupts the light from the LED that shines on the LDR. The trigger level can be adjusted with a 10-l<£2 potentiometer, which is connected to K 3 . The various LEDs on the board indicate the different power supply and communica- tions states. When the circuit is powered via the USB cable the yellow LED D 4 is on. When the USB connection has been established the blue front panel LED D 7 will flash. Once the program Trein.exe is running on the PC, the blue front panel LED is on continuously. When an external 1 5 -V power supply volt- age is connected the green LED D 3 is on and the red front-panel LED D 5 flashes briefly to indicate initialisation. For a complete over- view see the sidebar ‘LED indications’. Software The software for the 1 8 F 4550 was written entirely in assembler, the PC program to make the scripts is written in Visual Basic. The assembler code consists of two parts: the USB-HID interface and the control of the train. USB code The USB code is a standard HID interface for the PIC 1 8 F 4550 . It has a VID/PID of 0 D 59/5275 built in. After a successful enu- meration, the standard UDB loop is started, set to 6 ms. The USB interface communi- cates with the PC via a buffer that is 64 bytes in size. Via this buffer the scripts from the VB environment are loaded into the 4550 . The task of the USB program is to store and Bvte composition The script supplies two bytes per step. They are coded as follows • High byte bit 7: 1 when driving forwards • High byte bit 6: 1 when driving backwards • High byte bit 5: 1 when searching for the station • High byte bit 4: 1 during a wait action • High byte bit 3: service bit • High byte bit 2-0: train speed (1-7) • Low byte: time (1-255 s ) The service bit (bit 3) has multiple functions. depending on the byte in which it is used. • In byte 0: Toggle bit for EEPROM Write action • In byte 2: A ‘1’ indicates scripti • In byte 4: A ‘1’ indicates script2 • In byte 6: A ‘1’ indicates script3 • In byte 8: Status of blue USB front panel LED 28 og-2012 elektor MODEL TRAIN INTERFACE Figure 3. With the aid of the corresponding Windows program it is easy to enter the movement pattern of the model train. read the scripts from the EEPROM. Three scripts can be used. The instructions as well as the data come from the VB program. A format was selected comprising of 32 instructions per script (which turns out to be sufficient in practice), because this fits nicely in the 64-byte buffer of the HID. There is also still some space for a few control bits, because the instruction byte for a command is only seven bits in length. The sidebar ‘Byte com- position’ details the layout of the bytes. As usual the USB program takes care of the timing with the USB connection to the PC. To prevent the program from getting into trouble with the slow write times of the EEPROM (4 ms according to Microchip), only one byte is written to the EEPROM for each USB loop. The entire write operation is initiated by a Toggle byte in the VB environment and a few flags in the USB code. One byte is then written for each of the next 64 consecutive cycles. During this period the PC indicates it’s waiting and no data can be entered. The USB program never reads directly from the EEPROM (except when starting up), but ensures that the USB-in-buffer is always provided with the latest state of the actual script via separate buffers in the PIC. Train code The second initial operating mode for the PIC is the Train mode; this selection is made via an input (AO) on the PIC. The train interface communicates with the user via a two-line LCD (contrast adjustment using PI ). Using the rotary encoder it is pos- sible to scroll through the various instruc- tions. The pushbutton on the encoder is used to confirm a command. The assembly code for the train controller is quite simple. A line from the script needs to be retrieved and then needs to be carried out. In most cases the routine that supplies the pulsewidth modulated signals is called. This is controlled via a timer which deter- mines how long the action should last. The progress of these steps is always visible on the LC display. In Train mode the menu program is started first. This can start up one of the three scripts or allow the train to be controlled manually. The settings can be reached using the reset button. The heart of the program is the DRIVE rou- tine. This runs at 1 00 Hz via normal timing loops (i.e. not using an interrupt) and con- trols the train with a variable pulsewidth with a frequency of 100 Hz. The on- and off-times of the pulsewidth timing come from tables and depend on the minimum pulsewidth that has been set. The routine also supplies a seconds pulse for the timing of various actions. The rotary encoder can be read by two dif- ferent routines with different sensitivities (fast and secure). The pushbutton for start- ing/interrupting is part of the encoder. Putting scripts together The purpose of the Windows program Trein. exe (Figure 3) is to compose the scripts which are then carried out by the train interface. The order of connecting things is important when working with this pro- gram. First the USB cable (of a running PC) needs to be connected. (The very first time that this is done it is possible that Windows generates an error message, but usually the device is nevertheless correctly installed. Each subsequent time will then be with- out problems.) Subsequently the program Trein.exe is started. The blue front-panel LED D7 will light up and the program shows in the box ‘USB HID interface’ the message ‘Treininterface’. The correct operation of the USB-interface can be tested with the button ‘TestLED’. Ticking and un-ticking of this checkbox activates or extinguishes elektor og-2012 29 HOBBY & MODELLING the blue front-panel LED. The program can be used to compose or modify scripts, read from the memory in the train interface and put them back into the memory. There are three scripts, each of which can be up to 32 lines long. Each line can be used to program one of the following actions: drive forward, drive backward, find station and wait. The program is operated entirely using the mouse (and therefore not always entirely logical). Each of the four actions mentioned has a corresponding time variable which has to be set with a slider between 1 and 255 seconds. This time determines the duration of the action. With the exception of ‘wait- ing’ the actions also have a speed setting. This can be set with a second slider between 1 and 7. This number indicates the speed of the train during that action, where 1 is the slowest and 7 is the fastest. The operation is simple: choose a script, select a line, select an action or time which will then appear on that line. The end of the script is indicated with a blank line. If all 32 lines have a function defined then the program will continue on line 1 after completing line 32. The exception to this is script 1. If all 32 lines are used then the program will continue with the first line of script 2. Should script 2 also contain 32 lines then execution continues with line 1 of script 3. It is therefore possible to make a script with a maximum of 96 steps. The program has buttons to retrieve the scripts from the memory (Read Script) and to write the current script to the memory of the controller (Write Script). Note that these write oper- ations do not require any further confirma- tion but are carried out immediately. Dur- ing the Read- and Write operations the program cannot be used for a short time; this is indicated by a ‘wait’ window. The program also shows a few windows that are greyed out. These contain the val- ues which will be written into memory and are only of interest to the programmer. Construction The Elektor lab designed a printed circuit board for the train interface, containing the entire control including the power stage (Figure 4). The construction is not difficult, only leaded components have been used. Voltage regulator IC2 is fitted with a small heatsink. The MOSFET is fitted near the edge of the board so, if necessary, it can also be bolted to a (small) heatsink. Once the board has been fully assembled and has once more been visually checked, you can fit the programmed microcon- troller (available from Elektor, if you are unable to program it yourself) in its socket and then the display can be mounted on the top of the board using four 20-mm long stand-offs. You can make the connections between the display and the board using short pieces of wire or a 2x8-pin PCB connector and correspond- ing header with extra-long pins. •ft 1 1 1 The board can now be connected to the PC with a USB-cable and you can start to write a script. You can then load it into the EEPROM of the controller. Usage Connecting the train interface to the model railway is simple. Connect to l<1 an AC power supply with an output voltage of 1 5 V and capable of supplying a current of one or more amps (depending on the train used) and connect K2 with the tracks of the model railway. Using the coils listed for LI and L2 in the parts list, the circuit can sup- ply a current of up to 1 A. This is more than enough for the average model train. The parts shown in Figure 2 you will need to mount yourself to make the light barrier. After switching on the 1 5-V power supply the circuit starts in Train mode. The red front-panel LED will turn on and the operation is now via the rotary/pushbutton below the LCD. After the welcome message, the rotary switch can be used to select one of five options. These are scriptl , script2, script3, manual control and test scripts. When the pushbutton is pushed the selected option is activated. The three script options start the corre- sponding script. The LCD shows on the top line the current instruction from the script and at the same time the sequence number of this instruc- tion. The bottom line indicates the actual action (including direction of travel) and the time (in seconds) remaining forthis action. Driving forwards, backwards as well as wait- ing are unambiguous; the station search action requires a little explanation (for more information: see the additional description on the Elektor website). This really consists 30 og-2012 elektor MODEL TRAIN INTERFACE COMPONENT LIST y y y Figure 4. The dimensions of the PCB are such that the display can be mounted above it using four stand-offs. Resistors R1,R2,R18,R19,R20 = 330£1 R3,R4 = 27£1 R5,R10,R12,R13,R14 = 10k£l R6,R7,R1 1 ,R21 -R24 = 4.7k£2 R8 = 1 OCto R15 = 27^1W R16 = 3.9£2 5W R17 = 1k^ PI = 1 0k^l preset Capacitors Cl -C4.C7-C1 1 ,C1 3 = 1 OOnF C5,C6 = 22pF Cl 2 = 3.3 jlcF MKT, lead pitch 1 5mm Inductors LI ,L2 = choke, 330|iFI, 0.9A, 0.32C1 (e.g. Pana- sonic ELC1 0D331 E, Farnell # 1 749073) Semiconductors D1 ,D2,D8 = 1 N4004 D3,D6 = LED, green, 5 mm D4 = LED, yellow, 5 mm D5 = LED, red, 5 mm D7 = LED, blue, 5 mm T1 = BC547 T2 = BC557 T3 = FQP1 2N60 IC1 = PIC1 8F4455-I/P (programmed, Elektor# 120351-41) IC2 = 7805 IC3 = 401 06 IC4JC5 = LM31 1 Miscellaneous RE1 ,RE2 = PCB relay, 5V(e.g. V23 1 06-A5401 -A201 ) LCD1 = LCD 2x20 characters with backlight (e.g. Midas MC22005A6W-SPTLY) ENC1 = rotary encoder w. pushbutton (e.g. Bourns PEC1 1 -4230F-S0024) K1 ,l<2 = 2-way PCB screw terminal block, pitch 5mm l<3 = 5-pin SIL pinheader l<4 = USB-B connector, right angled, PCB mount SI = pushbutton (e.g. Omron B3F-3100) XI = 24MFIz quartz crystal PCB # 1 20351-1 (see www.elektor.com/ 1 20351 ) of two instructions: firstly the train has to pass through the light barrier that marks the station. During this action the maxi- mum time is indicated. That is because the actual travel time is not known, since it depends on the location of the train and its speed. Once the station has been found the waiting time assigned to the station line commences. A script can be interrupted at any time using the pushbutton. In addition to the PC-software and the firm- ware for the microcontroller the Elektor website at www.elektor.com/ 1 20351 also supplies supplementary information about the train interface. ( 120351 -I) elektor og -2012 3i MICROCONTROLLERS Embedded Linux Made Easy (3) Software development By BenediktSauter [i] It takes the right software to bring a microcontroller to life. Beyond the usual firmware, in an embedded GNU/Linux system we have to deal with building the components of the operating system. In this article we show how it all works, and even write our first program in C! It is easiest to develop for an embedded Linux system with the help of a conventional Linux system, normally running on a PC. We will base our experiments on version 1 2.04 of the ‘Ubuntu’ [2] distribu- tion. What do we need to install such a system? Not a lot: a little free space on the hard disk and, ideally, a network connection. The first thing to do is download the image of the installation CD from the internet [2]. We can use either the 32-bit or the 64-bit desktop variants: if in doubt, select the 32-bit variant. Once the CD image is downloaded it has to be burned onto a CD using a suitable program. It is important to burn the file to the disk as an ‘image’ rather than copying it as a simple file. Now insert your newly-burned CD into the PC and boot from it (which may require some adjustments to your BIOS settings). Ubuntu starts up with the splash screen shown in Figure 1. To make the system more convenient to use will we install it to the hard disk, by selecting the second menu option (see Figure 2). You will now be guided step-by-step through the installation process. First choose your language (Figure 3). We do not need to install any third-party software (Figure 4). The next window, shown in Figure 5, lets you choose to let Linux occupy the whole hard disk (which would be suitable for a machine that does not already have another operat- ing system installed); alternatively, you can install Linux to a second hard disk, or parti- tion the main hard disk into two areas, one area retaining the already-installed operat- ing system and the other dedicated to the new installation. In Figure 6 you select the drive or partition that will be used, and then proceed as shown in Figure 7 and Figure 8. We will explain more about the password that you are asked to set (Figure 9) later. If all goes well, you should reach the point shown in Figure 10. An alternative (and potentially more convenient) approach is to run the operat- ing system in a virtual machine. The author has prepared an image of a Linux computer set up for development especially for Elektor readers, and it can be downloaded from the Elektor website [3]. The virtualisation program ‘VirtualBox’ is needed to run the image: it can be downloaded free of charge at [4]. When VirtualBox has been installed, the image is loaded by simply selecting ‘File > Import Appliance’ from the main menu; it can then be run immediately. Toolchain on CD With the new operating system running the next step is to install the toolchain. If you are using the VirtualBox image this has all already been done for you, and you can skip the next two sections. The quickest way to do things in Linux is usually to use the console. Simply open up a new terminal window on the PC by pressing Con- ubuntu® ubuntu® Try Ubuntu without Installing Try irmtitwi thnut installing install Mhuntu Tristan Ubuntu check Cite for defects Check disc for defects Test mamnry Test memnryi EcuT from first hard disk Boot from first hard disk Figure 1 . Use down-arrow to select the second menu item. Figure 2. Select ‘Install Ubuntu’ and press Enter. 32 og-2012 elektor EMBEDDED LINUX MADE EASY Welcome i- Figure 3. Choosing your language. Figure 4. Preparing for installation. trol-Alt-T. In the terminal, switch to the directory ‘/tmp’ cd /tmp and then download the ARM toolchain CD directly using the ‘wget’ command thus: wget ftp: //ftp.denx. de/pub/eldk/5 . 0/ iso/a rmv5te-qte-5 . 0. iso This will download a CD image. The image can be opened directly using Linux: there is no need actually to burn the file to a CD. However, the file does need to be ‘mounted’, which makes it visible as a set of files to the operating system. First switch the the directory media’: Figure 5. Choosing where the operating system will be installed. Figure 6. Selecting the hard disk. cd /media In theory you can mount the contents of the CD image wherever you like in the file system, but there are certain conventions in the Linux world that make it easier for people to find their way around a new system. We will look in more detail later at the standard arrange- ment of the file system. We now want to create a new empty directory called ‘eldk-iso’, where we will subsequently mount the CD image. Although this might seem odd to someone familiar with Windows, we are not going to copy the files from the CD image to the new directory: instead, the new directory just marks the place in the file system from which the contents of the CD are made accessible. In Linux, everything is handled through files and directories. Here is the command to create the new directory: sudo mkdir eldk-iso The machine will prompt you for a password, as creating the directory requires you Figure 7. Selecting the time zone. I«ul BJi Welcome to U buntu 1 2,04 LTS 1 jni j"d 'jjt.me packed Jbunh. “ij* yc-T rt j -i*; '.=■ A-d «iLh llw u.E'.: Ywruan d !h# LnLy .-Enl 1 I'inosi p iitp- * "_L" -r.T r H.r jrrj fn ito if esd rww l J sr*7‘: In ball <=Jt ‘nr Figure 8. Selecting the keyboard layout. Figure 9. Entering a user name and password. Figure 10. The installation process begins. elektor og -2012 33 MICROCONTROLLERS Permissions and orivileaes A Linux system always has a user called ‘root’. This user has the highest level of privileges on the system: other users typi- cally only have ordinary privilege levels. Full access to system files, devices and so on requires ‘root privileges’. One approach is simply to execute all commands as the user ‘root’ but this is not advisable. One of the reasons Linux is so secure is that the restrictions on what ordinary users can do prevent a lot of potential damage. Users are normally only given permission to run the programs they need, not to access system files or other important information. The Linux programmer can, however, grant any application a higher level of privileges as needed, and so there is no need to execute all commands as the user ‘root’. We will also create a new user account on our Linux board for carrying out ordinary tasks and running the programs we write. If a user briefly requires root privileges, for example to create a directory within a system directory, then we can use the com- mand sudo provided in most modern Linux distributions (including the version of Ubun- tu we are using) as a prefix to the command proper. This indicates that the command is to be run as if by the root user. You will be prompted for a password. If you have installed the Linux system on the PC yourself, you will have set up this password as part of the installation process; if you are using the VirtualBox image, the password is ‘elektor’, entirely in lower-case. (briefly) to have ‘root privileges’: see the text box ‘Permissions and privileges’. To make this happen, we have prefixed the normal com- mand with ‘sudo’, which asks the user for the password that was configured when the system was installed. If you are using the Vir- tualBox image, the password is ‘elektor’, entirely in lower-case. The CD image can now be mounted in the file system to allow us to access its contents: sudo mount -o loop /tmp/armv5te-qte-5 . 0 . iso /media/ eldk-iso From our current position in the file system we can change directory into the CD image by typing: cd eldk-iso Installing the toolchain In the directory you will find a small script that you can use to install the toolchain. Again, you need root privileges to install new programs: sudo . /install. sh -s -i qte armv5te The following message should appear: *** Installing . /targets/armv5te/eldk-eglibc-i686- arm-toolchain-qte-5. 0. tar . bz2 When installation is complete you can leave the CD directory: cd . . This step is important, as the next thing we will do is unmount the CD image. This will not work if you are currently in a directory within the image: the operating system will refuse to execute the com- mand and an error message will be printed. sudo umount /media/eldk-iso The directory you created for the toolchain CD can now be deleted. sudo rmdir eldk-iso/ When installation is complete the toolchain will be located in the directory ‘/opt/eldk-5.0/’. So that we can access the programs in the toolchain using the command line from whichever directory you happen to be in, we have to add this directory to the PATH vari- able. This is a Linux ‘environment variable’ which contains a list of directories in which the system will automatically look for programs to execute. The best approach is to write a small script file (call it ‘set.ch’) which you can run from the console before using the toolchain. Create a new file using the editor: gedit set.sh and add the following lines to it: #! /bin/bash PI =/opt/eldk-5 . 0/armv5te/sysroots/i686-oesdk-linux/ usr/bin/armv5te-linux-gnueabi/ P2=/opt/eldk-5 . 0/armv5te/sysroots/i686-oesdk-linux/ bin/armv5te-linux-gnueabi/ 34 og-2012 elektor EMBEDDED LINUX MADE EASY export ARCH=arm export CROSS_COMPILE=arm-linux-gnueabi- export PATH=$P1 : $P2 : $PATH The last command here adds the path mentioned above to the PATH variable. Then write the new file to your start-up directory (called the ‘home directory’). For the commands in the file to take effect, you have to cause the shell (the Linux command line interpreter) to read them in (or ‘source’ them). One way to do this is with the following command: . ./set.sh Type this carefully: the line starts full stop, space, full stop! If you would prefer not to have to type this command every time you bring up a new console you can include it in the file ‘.bashrc’, which is automatically executed whenever the shell starts up. The file is located in your home directory, which you can switch to using the command cd without any arguments. You can edit the file using the command: gedit .bashrc The compiler in action The toolchain programs that we will use to build the Linux ker- nel and the bootloader all have names that begin with ‘armv5te-’. For example, the GCC compiler is called ‘armv5te-gcc’. Typing the command armv5te-gcc — version will give the version number of the compiler (note that there are two dashes before ‘version’). If this command works, it means that you have successfully set up the path to the toolchain programs. To compile application programs for Linux we need to use the tool- chain commands that start ‘arm-linux-gnueabi-’ rather than ‘arm- v5te-’. So how do we compile a simple ‘hello world’ program? First create a source file gedit hello. c with contents as follows: #include int main(void) { printf (“Hello world! \r\n”) ; return 0; } ■ F , webimrl O* Vursdav In < I W ^ P n, cerJ tF ^,T m * wS*, lv (fwt *1 Save it and leave the editor. Now we are back in the console. To compile the program, type: arm-linux-gnueabi-gcc -o hello hello. c To test whether the above process has been successful, we can copy the file ‘hello’ that the compiler has created to the Elektor Linux board’s SD card. Make sure the board is off and remove the card. Insert it into the PC’s card reader, and plug the reader into the PC. Wait a few seconds for the machine to detect the card. Normally Ubuntu will automatically pop up a window when this happens: since we will be copying to the card using the console, we can close this window. Full-scale operating systems such as Ubuntu automatically mount external storage devices when they are plugged in. We therefore need to find where Ubuntu has decided to mount the SD card. It is easiest to switch to the directory ‘/media’: cd /media and then type Is (for ‘list’) to display a list of files and directories within this directory. If there is more than one subdirectory, you can type cd directory-name to switch to a given directory, look inside using Is, and then cd . . to move back up one directory level into ‘/media’. The name of the directory where the SD card is mounted will typically consist of a long string of digits. The directory will contain the complete file system of the Linux board, including files with names such as ‘zlm- age’ and ‘swapfilel ’. If you get lost in the file system, you can always return to your home directory using the command cd without any arguments. Another elektor og-2012 35 MICROCONTROLLERS First aid for a sick SD card If a system that has been booted from an SD card is not powered down properly, using the halt or poweroff commands, it is possi- ble that the file system on the card will be corrupted. This typically results in ‘EXT2-fs errors’: Filesystem “EXT2-fs (mmcblkOpI): error: ext2_lookup: deleted inode referenced: 694962”: e2f sck 1,42 (29-Ngv-2011) /dev/sdhl was not cleanly unmounted, check forced. Pass 1: Checking inodes, blocks t and sizes Pass 2: Checking directory structure Pass 3: Checking directory connectivity Pass 4: Checking reference counts Pass 5: Checking group summary information /dev/sdhl: 66/24576 files non- contiguous) , 8294/97988 blocks Fortunately we can usually rescue the file system using a Linux PC from the console. First put the SD card into the card reader and use dmesgto determine what name it has been assigned. For example, if you see the following [ 1549.424156] [ 1549.425624] [ 1549.427527] [ 1549.427533] [ 1549.730223] sd 7:0:0:2: [sdh] Assuming drive cache: write through sdh: sdhl sdh 2 sd 7:0:0:2: [sdh] Assuming drive cache: write through sd 7: 0:0: 2: [sdh] Attached SCSI removable disk EXT2-fs (sdhl): warning: mounting unchecked fs, running e2fsck is recommended it means that the first partition, which is the one we are interested in, has been given the name ‘sdhl ’. This contains a file system in ext2 for- mat, which it is possible to repair. We have to unmount the file system umount /dev/sdhl before we can use the tool e 2 f sek (or equivalently f sek . ext 2 ) to attempt the repair: sudo e 2 fsck /dev/sdhl The result should be as shown in the screenshot. From time to time the program will ask if certain actions should be carried out: you should normally answer ‘y’. The result should be an error-free SD card! handy command is pwd, which will tell you the path to your cur- rent directory. Hello world! To test the ‘hello world’ program, switch to the directory where the SD card is mounted and copy the file across: cp -/hello ./ Then we have to unmount the directory manually so that the oper- ating system is forced to finish writing all the data to the card. cd sudo umount /media/directory-name Here again ‘directory-name’ should be replaced by the name of the directory that the operating system chose when the SD card was mounted. We can now move the SD card back to the Linux board and start it up. Connect to the board using a terminal emulator on the PC, as described in the previous instalment in this series [5]. Now, on the board, we switch to the top-level directory in the file system using the terminal emulator: cd / and run the program: ./hello The result should be that ‘Hello World!’ appears in the terminal win- 36 og -2012 elektor EMBEDDED LINUX MADE EASY dow (see Figure 11). If the system is booted from the SD card, it is important to shut the system down in an orderly fashion when you have finished. For this we need the command halt It is then necessary to wait until the message System halted appears before it is safe to remove power: otherwise it is possible that not all files will be updated properly on the SD card. This can in turn result in ‘EXT2-fs errors’. It is normally possible to recover the situation using a Linux PC: see the text box. Bootloader and kernel We shall now look at how we can build the two main components of the operating system, the bootloader and the kernel. The source code we need (290 MB for the current version) is avail- able from the Elektor website [3]. The simplest approach is to down- load the files using a browser: on a Linux machine the files will nor- mally end up in the ‘Downloads’ directory. When the download is complete, switch to the directory ‘Down- loads’ and find the file called ‘120026-1 1 .zip’. Move the file into your home directory using the command mv ~/Downloads/1 20026-1 1 . zip ~/ To unpack the file, switch back to your home directory using cd and enter the command unzip 1 20026-1 1 . zip Figure 1 2 shows what you should see on the console. Building the bootloader The bootloader is a program which is copied from the SD card to the internal SRAM of the LPC3131 on system reset (assuming the jump- ers are set correctly: see [5]). The following sequence of commands shows how we can compile the bootloader for ourselves and copy it to the SD card, to allow us to boot from the card. Before starting we need to install a couple of packages on the Ubuntu system: sudo apt-get install patch libncurses5-dev Now switch to the source code directory cd ElektorLinuxBoardDownload_201 20509 unpack the tar file that contains the bootloader tar xvzf bootloader . tar . gz root@gnublin:~# cd / root@gnublin:/# ./hello Hello World! root@gnublin:/# | Figure 1 1 . ‘Hello world’ running on the board. then switch to the new ‘bootloader’ directory cd bootloader and unpack the source code proper: tar xvzf apex-1 . 6. 8. tar. gz Now comes an important step if we want to be able to distribute any changes we make to the bootloader. We create a so-called ‘work- ing copy’ of the source code and make changes only on that copy. Later it will be easy to create and publish a ‘patch’ that represents the changes we have made. mv apex-1.6.8 work_1.6.8 cd work_1 .6.8 In the source code tree we need to apply a couple of patches that are required to make the bootloader work with the Elektor Linux board. patch -pi < .. /apex-1 . 6. 8_lpc31 3x. patch patch -pi < . . /gnublin-apex-1 . 6. 8. patch The build process for the bootloader is controlled by what is called a ‘configuration file’. We have to copy the master version of this file into our directory, with the new name ‘.config’. Note that here the full stop before the word ‘config’ is very important: it marks the file as ‘hidden’ to the operating system. cp . . /gnublin-apex-1 . 6 . 8 . config .config At this point, if you installed the toolchain manually and did not arrange for the environment variables to be set in your .bashrc file, you will need to set them by running the script . -/set . sh . The build process can now be initiated: make apex.bin Normally at this point we would need to copy the bootloader firm- ware into flash memory on the microcontroller using a suitable pro- grammer. Here, however, we can copy the firmware to the SD card using ordinary Linux commands. With the SD card once again in the PC’s card reader, run the elektor og-2012 37 MICROCONTROLLERS command dmesg to see the messages output by the kernel running on the PC. The results obtained on the author’s PC are shown in Figure 1 3. As you can see, the SD card has been recognised as ‘/dev/sdh’ and contains two partitions, called ‘/dev/sdhl ’ and ‘/dev/sdh2\ For safety it is best to unmount these partitions, as we will be copying the boot- loader across by accessing the blocks on the SD card directly rather than via a file system: sudo umount /dev/sdhl sudo umount /dev/sdh2 The following command (where the ‘sdh2’ will need to be modified to reflect the results from the dmesg command above) will copy the file ‘apex.bin’ to the SD card in such a way that the LPC31 3 1 can find it when booting: sudo dd if=src/arch-arm/ rom/apex . bin of=/dev/sdh2 bs=51 2 The command copies the bootloader code to the beginning of the second partition of ‘/dev/sdh’ using a block size of 512 bytes. The Linux operating system does not guarantee exactly when the new blocks of data are actually written to the NAND storage on the SD card. The command sync is therefore needed to force the operating system to ensure that all pending blocks are written out and that the new bootloader code is safely stored on the SD card. We can now try to boot the Linux board from the SD card. Building the kernel Building the kernel is a similar process to building the bootloader. First we switch to the home directory using the command cd, and then into the source code directory. cd ElektorLinuxBoardDownload_201 20509 We unpack the kernel source code tar xvzf linux-2.6.33-lpc313x-gnublin-032012.tar.gz switch to the kernel source directory cd linux-2 . 6 . 33-lpc31 31 x and start the build process that will result in a bootable kernel. make zlmage We also need to compile the loadable kernel modules. The is simply done using the command: make modules With everything built we need to copy the kernel and the modules to the SD card. In our case the kernel ‘zlmage’ happens to be there already, but it is worth practising the process for replacing the ker- nel. We need to copy the file ‘arch/arm/boot/zlmage’ in the kernel source tree directly to the first partition on the SD card: the proce- dure is much the same as for the bootloader above, with the appro- priate changes. Don’t forget to unmount the partition! A look at the possibilities Now we are in the happy position of being able to rebuild the boot- loader and kernel at will, we can look at the possibilities for making modifications to them, in particular to the kernel. Of course, we only have space here to look at this in general terms. You can take a first look at the Linux kernel configuration by typing make menuconfig from the directory ‘linux-2. 6. 33-lpc31 31 x’. The result is shown in Figure 14. If, for example, you want to use a particular USB device with the Linux board, you have to enable to corresponding driver here. You can navigate around the blue window using the arrow keys. The ‘Enter’ key opens and closes the menu. With a bit of hunting around you will be able to find drivers for various devices you rec- ognise. In the next article in this series we will go into this subject in more detail. Restoring the boot image Since we are now beginning to get down to the nitty-gritty of how the Elektor Linux board works, it is a good idea to make an exact copy of the SD card for backup purposes. Put the card in the PC’s card reader and then check, using dmesg, what device name the operating system has chosen for it. Again, for safety, unmount the partitions: umount /dev/sdletterl umount /dev/sdletter2 (where you should insert the appropriate character for ‘letter’, for example giving ‘/dev/sdbl ’ and ‘/dev/sdb2’ or ‘/dev/sdhl ’ and */ dev/sdh2’). You can now take an exact copy of the card’s contents: sudo dd if=/dev/sdletter of=Image_SD_card_backup_ copy. img 38 og-2012 elektor EMBEDDED LINUX MADE EASY This will take some time. You should now find a file in your current directory whose size is exactly equal to the capacity of the SD card: Is -lh You now need to put another SD card, exactly the same size as the original, in the PC’s card reader. Again, find out the device name using dmesg. The following command will copy the card image you have just created onto the new card: sudo dd if=Image_SD_card_backup_copy . img of=/dev/ sdletter This will take even longer than reading the original card. Assuming the command is successful you can now issue the sync command to ensure all blocks are actually written out to the card, and then try the new card in the Elektor Linux board. There is no need to umount the card as the file system on the card was never mounted in the first place: we wrote blocks directly to the card. The above process is fairly straightforward, but unfortunately it does not work if the sizes of the two cards are not identical. Also, we sometimes want to create a new card with different partitions or with a different file system from those of the original card. These cases are handled by a graphical installer, which we shall look at briefly in the next article in this series. What the future holds In this instalment we have made good progress on the route to understanding our embedded GNU/Linux system. We have a devel- opment environment in place, we can now build our own boot- loader and kernel, and we have compiled and run a small program. In the next article we will take a quick look at the structure of the source code for Linux so that we can be in a position to write our own driver for a particular piece of hardware. We will also see how easy it is to write programs using scripting languages. ( 120180 ) A r l luve : E Lck Itn L Lfhj s Boo r dlJo^ri Loo<) ?0126!1 69 . t ip creating, tlckior Liruxboarouoin.C'.id cil 1 oc 1 1 ng : El c-k. Lo r Li nuiBod r dDowii 1 add 261 20500 / boo 1 jdu r . Ijt . g 1 i nf \ a c i ng . t lekta rL i nuxHaa rdUGwn 1 bad Jtti n ■ 1 n l liUi r- 1 , i - be : a - tu n , t . gi inflating: ElektarLinujrBoaniDpwnlisad 20120503/gnublin installer 1.3 beta' J.3S4. deb i nf la ting, t lekt a rL 1 nuxbaa r dDown 1 Dad / 1 i nu* - £ . b . J i ■ l pc J 1 J k - gn-.i bl i n - 0 12 61^ . tar . g 1 inflating: clcktorLinuxBoardDowsiload 26I20iflVrpptf5.tar.gz Figure 1 2. Messages that appear when unpacking the software download. [ 1148,953337] sd 5:6:9:2: [sdh] Assuming drive cache: write through i 1148.955001] sdh: sdhl sdh2 [ 1148.958583] sd 5:0:Qi3: [sdi] Attached SCSI removable disk [ 1148.959252] sd 5:0:0 r 2 : [sdh] Assuming drive cache: write through Figure 1 3. The messages from the kernel show that the SD card has been assigned to ‘/dev/sdh*. Figure 14. Configuring the Linux kernel. Internet links [1 ] sauter@embedded-projects.net [2] http://www.ubuntu.com [3] http://www.elektor.eom/1 20180 [4] http://www.virtualbox.org [5] http://www.elektor.eom/1 20146 elektor og -2012 39 HOBBY Motorbike Alarm electronic sentry The principle is a very simple one: once the bike has been set on its stand, three carefully-positioned mercury switches give position information to a microcontroller, which it then memorizes when it is powered up. The surveillance starts right away; any change in the bike’s position will upset the configuration of the three switches and set off the alarm. My circuit fits into a tiny case, barely bigger than a matchbox. I’ve already fitted this alarm to two bikes, a Kawasaki 650 and an Aprilia SX50. Elektor in turn has fitted it to a vintage Honda Gold- wing GL1 200 that you can see in the pho- tos. For environmental reasons, the Elektor lab has preferred to replace my mercury switches with roll-ball tilt switches, cheap and less polluting. When power is applied, a very brief audible signal indicates the start of a 30 s delay dur- ing which you can still move the bike; once this delay has elapsed, the bike’s position is memorized. This is indicated by a sec- ond, very brief audible signal. As soon as the microcontroller detects a change in the position of the switches, after a final delay of 30 s (to allow for accidental jolts), the alarm is set off for 30 s. If at the end of this 30 s period the bike is still not in its original position, the alarm will continue to sound. The pC in my prototype is an ATtiny13 in a DIP package, mounted on prototyping board. To program it, I used a small con- nector from TE CONNECTIVITY / AMP, part number 7-21 5079-6, which is smaller than an HE1 0. 1 also fitted the same connectors to my AVR-ISP probes. Their pinout follows the Atmel standard for the AVR family. If you really want to go for miniaturization, you can also program the microcontroller then solder it in directly, which saves some space. As shown in the photo, two of the three 90° switches (SI to S3) are arranged head- to-tail in a sideways direction, and slightly inclined in opposing directions, so as to obtain reliable detection of any movement of the bike when it is up on its side stand. 40 og-2012 elektor MOTORBIKE ALARM The third switch is arranged longitudinally, at right-angles to the other two; this one will be more likely to detect the jolts caused by taking the bike down off a main stand. The three switches that form the tilt detec- tor are connected to ports PB2, PB3, and PB4 on the pC. To prevent these inputs from floating, their internal pull-ups are enabled in the ATtiny13. The switches are fitted in sockets so they can be easily removed while programming the pC, in order to avoid any possible con- flict between internal and external logic levels; in any event, the switch connected to PB2 must be open during programming, otherwise the SCK line will be at 0 and pro- gramming will be impossible. If you want to, port PB1 will let you connect +5V 120106 - 11 an LED (D2), which will flash to show the alarm is in service. COMPONENT LIST The PBO output drives the ‘siren’ via T1 . The sounder is not a passive piezo resonator, but an active type with built-in oscillator, powered from 1 2 V, which emits a piercing sound. When it is operating, it consumes around 1 50 mA. In stand-by, the consumption of the alarm is of the order of 1 .5 mA. As the circuit in its present state does not have a self-contained power supply, the bike power needs to be present during stand-by. Resistors R1 =22ka R2 = 1 ka Capacitors C1,C2 = 10pF 16V, radial Semiconductors D1 = 1 N4148 T1 = BC547C IC1 = ATTINY13-20PU (Atmel), DIP-8, Elektor# 120106-41 IC2 = 78L05 You’ll need to find a place to hide the alarm unit that is discreet and relatively difficult to get at. The aim of my system is first and Miscellaneous SI ,S2,S3 = tilt switch, 90 degrees, e.g. RBS04020 elektor og -2012 4i HOBBY foremost dissuasion, and I’m well aware of the fact that on certain models of bike, like the SX50, a determined thief will very quickly lift the saddle and cut the battery cables! To conclude, all that remains is to find a dis- creet location to hide the reset switch (to be connected between pins 5 and 6 on K1 ) that will enable the protected bike’s legitimate owner to disable the alarm. Software The very simple program [1 ] has been writ- ten in C using the CodeVisionAVRtool (pub- lished by HP Infotech) and consists of just a single C file (main.c). Once compiled, it occupies less than 50 % of the Tiny13’s flash memory. In order to minimize power consumption, the Tinyl 3 uses its own inter- nal 1 28 kHz oscillator. For what it has to do, there’s no point clocking it like mad at 8 MHz! The description of the FUSE BITS is given as a comment within the main.c file. At the start of the file, we find the type definitions ( typedef ), a few defines , and the global variables, whose names I have made always start with G_ in order to differen- tiate them from the local variables. The global variables are the ones that are shared between the background task and the timer 0 interrupt. The latter has been configured in CTC mode so as to generate an interrupt every 1 00 ms. This 1 00 ms timebase is used both for the countdown for the ‘anti-jolt’ delay and for handling the flashing of the LED. This gives a 1 00 ms flash every 500 ms during the power-on delay period, then one flash every 5 s in stand-by mode. Divided by 1 0, this 1 00 ms timebase is also used to obtain seconds and handle the delays that use an increment of 1 s. The interrupt [TIM0_COMPA] void timer0_compa_isr (void) function is the timer 0 interrupt routine, and like any inter- rupt function, neither receives any param- eters nor returns anything. It makes use of two static variables that are retained from one interrupt to the next. We come next to the void main(void) function. Naturally, this is the main pro- gram, which cannot receive any parameters nor return any values either! The main uses a single variable memo_sw for memorizing the state of the switches. Here we find the initialization of the micro- controller, the interrupt enabling, the power-on beep, and then the infinite loop that makes up the background task. It’s here that we test the delays being counted down in the timer 0 interrupt and verify the state of the switches. My comments [1 ] will help you understand how it works. (120106) Internet Links [i] www.elektor.com/ 1 201 06 Source code excerpt; full: program available for free downloading [1] I Fonction : main I Action : main program I In Param : nada I Return : nada I */ void main(void) { byte memo_sw; // tilt status check // Crystal Oscillator division factor: 1 #pragma optsize- CLKPR=0x80; CLKPR=0x00; #ifdef _0PTIMIZE_SIZE_ #pragma optsize+ #endif // Input/Output Ports initialization // Port B initialization // Func5=In Func4=In Func3=In Func2=In Func1=In Func0=Out // State5=P State4=P State3=P State2=P State1=P State0=0 PORTB=0x3E ; DDRB=0x01 ; // Timer/Counter 0 initialization // Clock source: System Clock // Clock value: 0,500 kHz // Mode: CTC top=OCR0A // OC0A output: Disconnected // OC0B output: Disconnected TCCR0A=0x02 ; TCCR0B=0x04; TCNT0=0x00 ; OCR0A=0x31 ; OCR0B=0x00; 42 og-2012 elektor By Thijs Beckers (Elektor Editorial & Labs) Soldering SMD ICs seems to scare off many inexperienced elec- tronics fans, despite efforts by ‘old hands’ and other experts to lift the jinx. “It’s just too small”, “I don’t have the right tools”, “They’re all in mum’s hoover” et cetera. I refute those argu- ments. Here’s another ‘trick’ to solder small pitch ICs. As you can see in the photographs, this particular 1C doesn’t come in the smallest of packages — it’s an SN20086APF chip from Sonix in an 48-pin LQFP package on a rather ancient mem- ory stick with 128 MB of storage. However with its 0.5 mm pitch (distance between pins) it’s perfect for demonstrating another way of soldering this type of component. Here, I am hoping to introduce you to a method of soldering an LFQP 1C using a relatively large solder tip. First of all, make sure the 1C is positioned correctly and secured in its place, for exam- ple by soldering two opposite pins. Next, apply a little solder flux along the pins. Now use a chisel type solder tip — a ‘spoon’ tip — with a little solder in its ‘bowl’ and slowly move the tip along the pins to be soldered — bowl up, and angled at about 30 degrees, see the photographs. Enjoy watching the surplus solder in the bowl at the tip flowing to the pins and solder pads, joining them ever so neatly. Sure, some practicing will be needed, but it’s not too diffi- cult. After a few try-outs you quickly arrive at the right speed of movement and amount of solder to apply and you’ll be off looking for more small ICs waiting to be by secured on a board ‘spoon-feed’ soldering. Ah, you’re not into SMT soldering at all and think 0.5 mm pitch is too ambitious as a first attempt? Try our simple electrosmog detector kit, the TAPIR, with a few SMDs only. It’s a fun pro- ject with lots of documentation available on line: www.elektor. com/120354. (120234) USB: current unlimited!? By Raymond Vermeulen (Elektor Labs) After working on a number of USB-related projects it occurred to me something odd was happening with the power supplied to a connected USB device. I started to doubt the consensus that a USB host device limits the supplied maximum current to 100 mA and only after a connected device identifies itself as being a high- power device, this limit would be upped to 500 mA. Using the recently published USB power meter (‘I’ve got the USB Power’, July & August 201 2) and a simple dummy load con- sisting of two 22 ohm/10 watt resistors in parallel I ran some measurements on several USB connections available on PCs in the Elektor Labs. All measurements led to the same conclusion: apparently there is no power limiting — at least not to 1 00 mA! Let’s assume that no current limit is applied in the case of USB con- nections not featuring data communication — after all, resistors aren’t terribly ‘communicative’. To disprove the assumption, I con- nected a device (project with an ATmega32U4, to be published soon) that negotiates specifically being a low power device, need- ing only 1 00 mA and connecting a load (resistor) in parallel on the USB bus power lines. Again, the full 500 mA were still available!? From these observations I can only conclude that modern PCs and laptops always offer the full 500 mA current capacity on their USB buses. I suspect the 1 00 mA limit originates from the early USB days in the nineties, and that recently there is no rea- son for limiting the maximum available current anymore, pos- sibly due to the general availability of more potent components. If anyone has information on this or a better explanation of the phenomenon, please write to us (preferred e-mail: r.vermeulen@elektor.nl) so we can enlighten ourselves and the community with unlimited knowledge. (120436) elektor og-2012 43 E-LABs INSIDE E-LABs INSIDE GPIO access on Elektor Linux board By Fran^ois-Xavier Maurille (Elektor Labs Intern) At some point during the development of a musical project based on the Elektor Linux board I found that an SPI DAC was called for. It turned out I needed to work with 24-bit words, but the SPI hardware interface inside the chip wasn’t capable of processing data in that format. Consequently the chip select (CS) output had to be realised with a GPIO pin, which proved to be tough to implement in the operating system: the response time after a command was given was far from insignificant due to the complex and busy exchange between the application and the hardware. The illustration shows the results of my attempts of speeding up the CS sequence ‘101 O’. In my first attempts I used the Linux file system and its fprintf C function. CH2 shows the results of the command fprintf (“/sys/class/gpio/gpiol 1 /value” , “%d”, state). A minimum response time of 90 ps was feasible, which was far too slow for my application. Next I tried to access the GPIO pin using the echo system command. CHI shows the output signal after the command system(“echo 1 > /sys/class/gpio/gpiol 1 /value”) was given. This didn’t speed things up either. In fact, it was even slower than my first attempt: about 200 ms elapsed before the CS output changed state. Then I tried to access the microcontroller’s GPIO registers directly. This is much more difficult than using the file system, but it sure proved a lot faster. Thanks to guidance on http:// forum.gnublin.org I was able to implement a few functions to set and reset GPIO pins using a pointer and offsets on the IOCONFIG register address (given by mmap()) to access the MODEx registers. Signal CH3 describes the output after the command ^(unsigned int *)(ptr + GPI0_0FFSET + GPIO_MODE0) = 1 << nGPIO; . This command resulted in a response time of (about) 700 ns, which was more to my liking. Some observations: - Pay attention: The 4 th MODEx bit is used for GPI04, while the 5 th MODEx bit defines GPIO1 1 (CS) as set/reset pin (and notGPIOS). - With your Linux Board you’ll be able to ‘work in the future’, when the internal date of the board is not in sync with your PC’s internal date. I received the following warning while working with the board: "make: Warning: File ‘ CPIO.c ’ has modification time 52 s in the future ”. (120457) SD Card Correction Script By Francois-Xavier Maurille (Elektor Labs Intern) The popular Elektor Linux Board (article series started in the May 201 2 edition) provides an easy way for starters to engage in a Linux environment. Albeit the hardware is working fine, there might be a complication with the software. Those of you already using the Elektor Linux board may have experienced the odd problem with an SD Card appearing to be corrupted. The notice “EXT2-fs (mmcblkOpI): error: ext2_lookup: deleted inode referenced: 694962” might pop up. An easy instruction is given in this month’s edition explaining how to fix this error. But if you’re too lazy to copy-paste the instructions, or if you are not sure how to proceed, you may download a little piece of software that does it all for you. It’s a small bash script I wrote, meant to be run on a Linux PC. It runs exactly the same commands as described in the article inset. With one exception: they are run automatically. The script looks for the corrupted device name using the grep and sed commands, unmounts the device and runs the e2fsck command. This script is able to correct your SD Card in a very straightforward manner. You just need to follow the on-screen instructions, and answering by pressing ‘Enter’ or ‘y’. These are the concise instructions: After downloading the bash script from [1 ], browse to the directory where you stored the file, and unpack it (right-click on it and select Extract Here). Before the first run, the script has to be made executable. Start a terminal session, browse to the script’s directory and enter the following line in the terminal window: sudo chmod 777 correctSD.sh. Now you should be able to execute the bash script from within the terminal (enter ./ correctSD.sh) and let it take care of the corrupted SD card. A small additional README text file provides some extra information on the correct procedure. This is of course not a n excuse to press the RESET button on the board all the time... (120443) Internet Link [1 ] www.elektor.com/ 1 20026 44 09-2012 elektor Elektor-projects.com 4U2 Home News Proposals In Progress Finished Home News PfQj>osals In Progress Finished Home riom-e Project Proposals This oae* I -sis- all tie new project proposals and project ideas that have not deem promoted to In Progress yet, Promotion oFa project depends on its popularity, originality or usefulness.. Create a new project or submit, an Idea now! Get help, feedback & votes from other visitors, and maybe ybur project will be promoted too! Before you know it you too are Efektorized / Vote for the projects you like! The more votes a project collects the: higher the chances that it gets promoted to In Progress. Elektor Labs has been expanded and now you too can get involved in the development of your favourite magazine’s pro- jects. In fact we encourage you to join the international Elektor community — show and discuss your own ideas and develop- ments out there and see what Elektor Labs is working on. If your project is worth its salt it may get elected for developing into a real Elektor Project! Fresh project ideas, circuit sketches and other e-doodling gets entered in the Proposals section. The most interesting or appeal- ing ones are picked up by our lab team and developed into a project (and matching article) of the kind Elektor is famous for. And the fame is yours too. Take a look at the Switched 7905 Replacement in the In Progress section. Publication of this project is due in the October 201 2 edition of Elektor; on our Projects website you can get a sneak preview of the project and actually follow some of the design- er’s steps as he progresses with the design. The section called Finished contains wrapped up projects, like Platino and the Improved Radiation Meter. Of course this doesn’t mean the end of a project... (120484) Please note: Read-only access to our Elektor Projects website is free for everyone, but only Elektor Plus members can actively par- ticipate. If you are an Elektor Plus member, use your Elektor Plus credentials to enter Elektor Projects. If you don’t remember your password, you can request a reminder using the email address you registered for your Plus membership. Projects in Progress This page lists all projects currently under active development and not yet (completely) finished. Projects on this list may get suppor from the Elektor team and even make It to print in Elektor Ma-gaKine anchor become a ready-made product n the shop That's right, you can make money from your project! Home News Proposals ^ In Progress m Finished Home » Projects Switched 7905 replacement «t + i I Shun* 1 tw«i I'hvraton Pra;fct s-atuv l.n Progress I 0 canrrlbucdrs 2 members 0 cximflierts _j_ _ After having designed a swlbened 7305 replacement, jily editor suggested that I should make a matching negative variant, a switched T3DS replacement. I knew that converting a positive DC voltage to a negative DC was possible, but 1 had never heard ora switched negative to negative DC convertor, So after a bit of research I Found a topology called "Negative Buck Convertor' in an old National Semiconductor application note. It abuses an asynchronous boost convenor to convert a low negative DC voltage to a higher negative DC voltage, lust like an 7905. And I did manage to keep the PCS dimensions In chock, os can be seen n the photo, It is all a bit experimental', so what the final specs will be is will unknown. But I aim for an input Is low as -IflV which pan still output 0,$A at -$V. Update; | assembled it and tested it with a light load and ft works! !F -IJV in, -SVout- I've Still get some tests to dp- I wilt keep you posted- Updotel: I did some tests with different input votages, -17V till -BV works but higher than that gives incorrect output voltages,. Home News Proposals Finished Projects The projects- on th s page are no ranger acti vely developed beta use they a re either finished or have reached a dead-end, Finished projects may still be updated on occasions when □ bug is found, a component has turned obsolete or an Improvement was added, Some of these projects have been published in Elektor Hagai ine, some have products for sale In the on Ine Elektor Shop. Home News Proposals Finished Home r Projects Platino - Versatile Board for AVR Microcontrollers 2 [QlJsiw* p Trail t.vvird Ik n • PraVert storm: fun lifted i 0 CDntrbLfJqm ! 1 me^rlien I 0 comments Behind every great circuit there's a great. PCS Tho me PUtireo ii a playful ■‘cfcrence tp tita French ar*d German word ’Platino' meaning 'circuit board 1 , with a slight wink at 'Artfui no", TFw goal of th s project was to design a PCS tnat would be useful fer many MCU applications that may need an LCD and/or push-buttons and that can bo easily programmed us«ng WlnAVA, AVR studio, BA5C0M, Mikno-C or Arduino. TFw dimensions of the board fl _ c adapted to a standard Bopla enclosure so i; Is easy to finalise a project properly, Plating supports most 20-pin and 40-pin DIP B-bit AVR microcontrollers (ATmega0 r 1-6, 32, *0 r 53 r 1W, 160, 3Z* r 644 6 126*3- It has extension wnnectbrs compatible with Arduino shields and when equiped vj th the right AVR (ATmegaJ.60 nr A‘”mega320 for insFanco] it if fUIy cwrpahbic wiEh Arduino pro] rains (sKrttTes) Ego. It nlsn ha* qxtmiEion fflnrHhftflrR, rnmnirit hlf* with nmitrtvw hflflrdifi elektor 09-2012 45 E-LABs INSIDE By Thijs Beckers (Elektor Editorial & Labs) In this year’s March edition you got a glimpse of an unsys- tematic selection of old connectors from Managing Editor Jan Buiting’s private collection of vintage electronics. The page triggered numerous responses from our readers, which were gratefully appreciated. Many readers managed to provide descriptions and images of their oldest and most peculiar con- nectors, many of which we think are worth showing. So here’s a random selection of pictures received, with their descriptions. The first collection shows Dr. Klaus Rohwer’s set of Hirschmann plugs, some of which prob- ably date back to the 1950s. The first four are power plugs, the big one is des- ignated as ‘UPO’ — Unidentified Plug Object. We suspect it’s for a telex machine; one of my fellow lab workers thinks he’s seen something simi- lar on an old telephone switchboard in a former military com- mand centre. This little collection was pictured by W. Haas. We start with an ‘LMK’ radio antenna connector in the upper left corner, which has one horizontal and one vertical oriented prong. Next to it is a 240-ohm VHF antenna connector for balanced-feeder cable. Then two white symmetrical VHF Band III 240-ohm plugs with horizontal prongs. Next to those are two red, symmetrical 240- ohm connectors for UHF band IV/V with vertical prongs. The bottom right connector is a plug with cubed prongs, suitable for VHF and UHF. The rest of the connectors pictured are various adapter plugs, from banana to single pin; the blue one suited with a wire insert and fastening screw. This second set of connectors shows various audio plugs once used at the Westdeutscher Rundfunk Koln. Elektor reader W. P. van de Meerendonk from The Netherlands sent us, among others, this picture of another ‘UPO’. It looks like a tube socket, but it’s not. As far as we could see, it is some sort of octal-style plug made from Bakelite. Application unknown. We received many more photographs and even some descrip- tions of older connectors (without photographs). We even trig- gered some remarks on our descriptions. General consensus on connector #1 0 in the original Plug-o-(d)rama article is a bal- anced 240-ohm antenna connector for radio, suitable for 3 and 4 mm holes; 3 mm supposedly used for VHF and UHF fre- quencies, 4 mm for VHF FM radio. Connector #11 would be the chron- ological successor of #1 0. This polar- ized connector offers connections for an AM ‘antenna’ (vertical) and ‘ground’ (horizontal). Suggestions came in that plugs #6 weren’t used for loud- speaker connections unless they where the Bakelite version; high impedance loudspeakers were often directly connected to the anode, which could lead to dangerously high voltages on the cables and connectors. (120303) Richter used to play around with these starting from the 1950s. Various adapter plugs were also constructed to be able to link different connector plugs. Says Mr. Richter: “the only adapter we didn’t construct was from Lemosa to Gardena.” This plug and socket belong to a ‘Pansanitor’ machine, which dates back to 1928 (see also this month’s Retronics article). According to proud owner, Mr. Butte from Germany, these original con- nectors are made of glazed porcelain. They are probably the oldest plugs of which we have received photo- graphs so far. 46 og-2012 elektor TEST & MEASUREMENT Low-cost 60 MHz Sig Gen With PWM mode and incremental control By Peter de Bruijn (Netherlands) This low-cost signal generator has an impressive frequency range from 250 Hz to 60 MHz. It can generate PWM signals from 250 Hz to 60 kHz, which are suitable for testing devices such as LED dim- mers, ultrasonic transducers, voltage converters and drive systems for electric bicycle motors. It can also be operated in oscillator mode with a frequency range of 1 kHz to 60 MHz. This is useful for applica- tions such as testing a DCF aerial at 77.5 kHz, generating an adjust- able 20 MHz clock signal for a processor, or testing resonant circuits. The signal generator is controlled by four capacitive touch keys. enclosure equipped with a well defined front panel. The CPS sensors can be made from small pieces of copper PCB material measuring 1 x 1 cm, attached to the enclosure by hot-melt glue. The source code and hex code for the PIC microcontroller can be downloaded from the web page for this project [1 ]. A brief user guide (1201 1 1 -W.doc) is also available on the web page. (120111-I) Internet Link [i] www.elektor.com/ 1 201 1 1 low-cost generator with an impressive frequency range Specifications • Initial frequency: 10 kHz / 5 V OSC mode • Model: PWM 250 Hz to 60 kHz Drift: 1 % Accuracy: 1 % • Mode 2 : OSC 1 kHz to 60 MHz Drift: 0 . 05 % Accuracy: 0 . 75 % The main components of the circuit are a PIC microcontroller and a programmer oscillator module (type LTC6904). The oscillator module is controlled by pins RA4 and RA5 of the PIC device. The touch keys are connected to inputs RC0-RC3. The PIC device used here allows sensor keys to be connected directly to several inputs, eliminating the need for extra hardware. Output RC4 drives a piezo- electric beeper that generates a tone when a key is touched. LED1 also provides a visual indication. Two paralleled XOR gates are con- nected to the output of the LTC6904 to provide sufficient current at the signal generator output. PIC output RC5 is responsible for PWM signal generation. IC3 provides a stabilised supply voltage. The combination of R3, Cl and C 8 provides good supply decoupling. A 5.6 V Zener diode is included as extra protection for the LTC6904 in the event that an excessive voltage is accidentally applied to the output connector. The signal generator can be powered from a standard AC power adapter with an output voltage in the range of 9 to 1 6 V. The PCB layout must provide screening between the capacitive touch sensors and the oscillator output. This can be achieved by placing a ground plane between the oscillator and the CPS 1C. The relatively few components can easily be assembled on a piece of prototyping board. The author fitted the circuit board in a tiny m PWM LU A FRQ V +5V I ♦ elektor 05-2012 47 FUNDAMENTALS Electronics for Starters (7) Blinkers and oscillators In the previous instalment we worked with static flip-flops and Schmitt triggers. Now things get a bit more dynamic, with capacitors providing the necessary feedback. You will see LEDs blinking and flashing against an audio backdrop provided by signal generators. After all, making things blink and beep is one of the main functions of electronics. By Burkhard Kainka (Germany) A bistable circuit that automatically and continually switches states without any out- side influence is called a multivibrator or an astable multivibrator. Figure 1 shows an example of an astable multivibrator circuit, and as you can see right away, in this cir- cuit the feedback is provided capacitors. If you use electrolytic capacitors for this, you must pay attention to the polarity because the voltage on the associated collector is (on average) higher than the voltage on the opposite base. The circuit remains in a stable state only as long as it takes for the capacitors to be charged or discharged. After this the circuit flips to the opposite state and the process starts again. A practical experiment with two 10 pF capacitors yielded a fairly low LED blinking rate with a period of around 1 second. You can adjust the toggle rate of the multivi- brator over a wide range by changing the capacitor values. Experiments using rela- tively small capacitors and capacitors with differing values are also worthwhile. With a pair of capacitors having values of 1 00 pF and 100 nF, the circuit generates short flashes of light from one of the two LEDs. With a pair of 1 00 nF capacitors it produces rapidly flickering light. Simplified multivibrator The multivibrator circuit can be modified to operate with just one capacitor. The circuit basically needs two transistors operating in common-emitter mode, each acting as an inverter that changes the phase of its input signal by 1 80 degrees. These two stages can be directly coupled to eliminate one of the capacitors, as shown in Figure 2. To ensure reliable oscillation, this circuit must be dimensioned to have an operat- ing point in the middle of the character- istic range in the absence of feedback. Otherwise the output transistor would be either completely cut off or driven fully on. The overall circuit would therefore not have enough gain to start oscillating. In this example, strong negative feedback on the first transistor (provided by the 1 0 k £1 resistor between the collector and the base) yields an operating point in the middle of the range. However, the feedback via the RC network is stronger than the negative feed- back, with the end result that the output transistor is alternately cut off and driven into saturation. It’s a good idea to first put together the cir- cuit without the feedback capacitor. The LED should light up dimly because the out- put transistor is not fully switched on. With the capacitor fitted, the LED will alternately be full on or full off. With a 22 pF capaci- tor, the LED blinks approximately once per second. The circuit also works with smaller capacitors, down to a value of 1 0 nF. As you reduce the capacitor value, the blinking gradually changes to rapid flickering. If you connect an acoustic transducer to the out- put, you will hear a clacking sound. Figure 1. Multivibrator circuit. LED voltage converter Red LEDs need 1.5 to 2 V, while blue or white LEDs need as much as 3 to 4 V. This is usually handled by connecting three batter- ies in series to provide 4.5 V. A series resistor is then used to reduce the supply voltage to the operating voltage. It would be better to be able to manage with just 1 .5 V, which means we need a voltage converter. The key component here is a small fixed inductor rated at 1 .5 mH. This component looks like resistor, but it has a small fer- rite core and a wire coil under the protec- tive lacquer. If you wish, you can also make your own inductor for this purpose. Around 200 turns on a ferrite rod will do the job. The circuit shown in Figure 3 is another sim- ple multivibrator. The current through the inductor is switched on and off at a high rate. Here the inductor acts as a magnetic energy storage device. Each time it is switched off, it generates an induced voltage that adds to the battery voltage. The magnitude of this voltage depends on the connected load. It adapts automatically to the load, so a white LED receives a higher voltage than a red LED. Most voltage converters of this type Figure 2. Simplified blinker circuit. 48 06-2012 elektor ELECTRONICS FOR STARTERS NPN sawtooth siqnal generator A sawtooth generator can also be built with a single transistor oper- ated in a highly unusual manner. Here the NPN transistor is wired the wrong way round in the circuit, with a positive voltage on the emit- ter, and the base lead is left open. The voltage on the capacitor grad- ually rises to approximately 9 V. At this point the transistor suddenly starts conducting and discharges the capacitor to approximately 7 V. The data sheet for the transistor doesn’t say anything about this, and each transistor behaves somewhat differently. It’s worth trying a variety of transistors in this circuit. The discharge current pulse is strong enough to drive an LED. This requires a supply voltage greater than 1 2 V. The circuit works very nicely with a pair of nearly exhausted 9 V batteries. The LED keeps blinking for a long time as it sucks the batteries dry, with a gradually decreasing blink rate. When operated this way with an ‘inverted’ voltage between the emitter and the collector, the transistor has a characteristic curve with a negative slope, which can easily be measured. The base-emit- ter junction exhibits the well-known avalanche breakdown effect at approximately 9 V. At this voltage the high electric field strength in the thin reverse-biased junction region causes the charge carriers to move so fast that they dislodge other charge carried from the crystal lattice. As result the number of charge carriers, and with it the cur- +12V rent, rises very quickly. This is the same as what happens in a 9 V Ze- ner diode, but a Zener diode has a positive internal resistance. There’s another factor involved with an inverted transistor. Here the emitter and collector switch roles, but due to the essentially symmetrical structure the transistor also operates in this inverted condition. The operating principle of a transistor is that some of the charge carriers that enter the base layer pass through the reverse- biased junction on the other side. In this case avalanche breakdown is occurring in the reverse-biased junction region, so there are even more charge carriers available to dislodge additional charge carries from the lattice. This results in a self-reinforcing avalanche effect. also have a rectifier and a smoothing capaci- tor. Here they are not necessary because the LED acts as its own rectifier. A pulsating DC current flows through the LED. The average value of this current is somewhat less than the battery current because the voltage is higher. The overall efficiency of this circuit is higher than with the usual approach of using a higher battery voltage and a series resistor. Audio generator If we fit our simple multivibrator with a rel- atively small-value capacitor, it will gener- ate a signal in the audio frequency range. A piezoelectric transducer (buzzer or beeper) connected to this circuit with produce an audible tone (Figure 4). A piezoelectric transducer has some of the characteris- tics of a capacitor and therefore affects the audio frequency. As a diversion, you can try a little experiment with this circuit. If you touch the transducer with your finger or with a hard object, the tone (frequency) and the sound level both change. The vibrating piezoelectric disc generates an AC voltage that affects the signal generator. To a lesser II lOn 0 c c i" s f i 9V H 27k H L-€ — < 0 (5 % )i BC547 < — BC547 < — Figure 4. Driving a piezoelectric buzzer. extent, acoustic echoes can also affect the signal generator. The frequency can also be modified by adjusting the value of the resistor in the feedback path. You could use a potenti- ometer for this, or you could use a light- dependent resistor (LDR). In the latter case the audio tone depends on the amount of light striking the LDR. With the circuit shown in Figure 5, you can distinguish not only the brightness of the light, but also different types of light. Rap- idly fluctuating artificial light modulates the ui II 1 10n E 3 LDR L c C z> -S C \ 9V ( H 10k H L-€ — < 0 ) )i BC547 < — BC547 < — Figure 5. An adjustable audio signal generator. elektor 06-2012 49 FUNDAMENTALS I Figure 6. Using a multivibrator as a VCO. Figure 7. A blinker circuit using complementary transistors. frequency of the audio signal. Light from a fluorescent lamp produces a raspy tome. Light from a PC monitor also affects the sound, due to modulation of the audio sig- nal at the frame rate. Voltage to frequency converter You can use a multivibrator to build a volt- age-controlled oscillator (VCO) as illustrated in Figure 6. Here both base resistors are connected to a common voltage input. The capacitor charging current, and therefore the oscillator frequency, is directly depend- ent on the voltage applied to this input. An adjustable voltage divider can be used to set the input voltage to any desired value in order to set the frequency. This circuit can also be used as an acoustic voltmeter with a measuring range of 1 V to 9 V. Among other things, this is handy for quickly checking various batteries. NPN/PNP flip-flop circuit You don’t necessarily have to use a pair of NPN transistors. Figure 7 shows a blinker with complementary transistors. As in the previously described circuit, negative feed- back from the collector to the base of the NPN transistor establishes a stable oper- ating point. The PNP transistor acts as an emitter follower. A signal with the right phase for the feedback can be taken from the resistor in series with its collector. The impedance of the feedback path of this circuit is very high. As a result, it has a period of around 1 second with a feedback capacitance of just 1 pF. Energy-saving LED flasher In shops you sometimes see advertising signs with a blinking LED that seems to work forever from a single battery. The circuit £ 9V s & • 1) • • BC547 BC547 ^ BC557 _ ♦ • Figure 8. Low-power LED flasher. Figure 9. Sawtooth generator. 50 06-2012 elektor ELECTRONICS FOR STARTERS A voltaqe to frequency converter with the Tinvl 3 The voltage to frequen- cy converter described here is really handy because it can be used as an acoustic volt- meter. For instance, a concert A could mean that the battery volt- age is OK. Your ears are also good at detecting slow changes. With the microcontroller you can implement a converter with a linear relationship between frequency and input voltage. Here the ATtinyl 3 microcontroller operates with a 5 V supply voltage, which means that the measuring range of the A/D converter extends to 5 V. The range is enlarged to 1 0 V by a high-impedance voltage divider. A piezoelectric acoustic transducer is connected to port B4. The software implements a simple direct digital synthesis (DDS) function with square-wave output. An accumulator A is iteratively incremented by the input sample value until the most significant bit flips, at which point the state of the output signal is toggled. Flere the accumulator has a width of 1 2 bits. At the highest input voltage the output state changes every four measurement intervals, which yields a frequency of just under 600 Hz. The source code can be downloaded from www.elektor.com/ 1 20007. ‘U/f Converter 0...5 V 0...6O0 Hz $regfile = “attinyl 3 . dat” $crystal = 1200000 $hwstack = 8 $swstack = 4 $framesize = 4 Dim U As Word Dim A As Word Config Adc = Single , Prescaler = Auto Start Adc Ddrb.4 = 1 Do U = Getadc(3) A = A + U A = A And &H0FFF If A >= &H0800 Then Portb.4 = 1 Else Portb.4 = 0 End If Loop End +5V ©■ n i — i t n O-QHh — f 0V...5V -U vcc PB2 PB1 PBO 3 ATtinyl 3 RES PB3 PB4 GND a IT rr I shown in Figure 8 is an astable multivibra- tor with special properties. The 1 00 jiF elec- trolytic capacitor is charged relatively slowly by a small current and discharged quickly by a short current pulse through the LED. This also generates the necessary voltage boost, since 1.5 V isn’t enough for the LED. This circuit is optimised for low-power operation, which is why the multivibrator circuit is built with a pair of complemen- tary transistors (NPN and PNP). This avoids power losses from control currents. Both transistors conduct only briefly when the LED flashes. To ensure stable operating conditions and reliable oscillation, there is an additional stage with direct-coupled negative feedback. Here again the circuit is designed to work with very high resistance values to minimise power consumption. The PNP transistor only conducts during the very short pulses occurring every couple of seconds. The output capacitor is charged to nearly 1 .5 V between pulses. When the tran- sistor is switched on, the voltage across the capacitor adds to the battery voltage. This produces an open-circuit voltage of nearly 3 V. A red or green LED with a forward volt- age of 1 .8 V to 2 V connected to the output will flash brightly. You can use the charging current of the electrolytic capacitor to estimate the cur- rent consumption. The average voltage across the pair of charging resistors, each with a value of 10 k Q, is 1 V. This means that the average charging current is 50 jiA. Exactly the same amount of charge is addi- tionally drawn from the battery during the LED pulse, so the average current is around 1 00 |iA. If you assume a battery capacity of 2,000 mAh, the battery should last approxi- mately 20,000 hours, which is over 2 years. Sawtooth generator Sawtooth signals, with their characteris- tic jagged waveforms, can be generated by periodically charging a capacitor to a spe- cific voltage and then discharging it sud- denly. This is illustrated in Figure 9. While the capacitor is being charged, the PNP transis- tor is cut off and no base current flows to the two NPN transistors. The discharge level is set to around 5.1 V (4.5 V + 0.6 V) by a volt- age divider consisting of two 10 k Q resis- tors; above this level the voltage on the base is 0.6 V lower than the voltage on the emit- ter. This means that the transistor starts to conduct when the voltage rises above 5. 1 V, and this current is amplified to obtain a hefty discharge current. This causes the voltage elektor 06-2012 5i FUNDAMENTALS You want to use a simple voltage-controlled multivibrator as an acoustic voltmeter with an 8 -ohm loudspeaker. With a supply volt- age of 9 V and a corresponding measuring range of 9 V, you use an oscilloscope to check out the circuit. At the moment when one of the transistors of the multivibrator starts to conduct, the base voltage of the other transistor drops to -9 V. After this the 10 nF capacitor is charged by the current through the 1 00 to resistor to around +0.6 V in approximately 0.65 ms, at which point the circuit switches states. 1 ) What is the output frequency with a measured voltage of +9 V? A Approximately 3.3 kHz B Approximately 330 Hz C Approximately 770 Hz 2 How does the frequency change when the supply voltage drops but the measured voltage remains the same? D The frequency drops. E The frequency remains the same. F The frequency rises. 3 If you want to increase the volume, what can you change? G Reduce the value of the 4.7 to emitter resistor of the right-hand transistor. H Increase the resistor value. I Replace the emitter resistor by a 1 00 jllF electrolytic capacitor. If you send us the correct answers, you have a chance of winning a Minty Geek Electronics 101 Kit. Send you answer code (composed of a series of three letters corre- sponding to your selected answers) by e-mail to basics@elektor . com. Please enter only the answer code in the Subject line. The deadline for submitting answers is 30 September 2012. All decisions are final. Employees of the publishing companies forming part of the Elelctor Inter- national Media group of companies and their family member are not eligible to participate. The correct solution code for the quiz in the May 2012 issue is 1 ADH Here are the explanations: Answer i: The BF245 provides a constant current of approximately 1 0 mA, so choice A is correct Answer 2: With a higher input voltage the current will rise quickly with a series resistor ; leading to high heat dissipation. By contrast, the FET holds the current constant, so the dissipation is less. Choice D is correct Answers: The electrolytic capacitor buffers the voltage under conditions of rapidly changing load current and improves regulation at high frequencies. For example, at i kHz the capacitor has an impedance of 1.6 El, which reduces the internal impedance of the voltage stabiliser. It makes a no- ticeable contribution to maintaining the voltage for 1 ms, but not much longer. Choice H is correct. to drop to 0.6 V, at which point the transis- tors are cut off and the next charging cycle begins. The circuit shown in Figure 9 has three transistors and is designed for very slow charging. It produces a sort of metro- nome signal: tick, tick, tick, ... This circuit can be simplified somewhat by omitting the left-hand transistor. In many cases the resulting circuit still works prop- erly, but sometimes there are difficulties with switching off this ‘DIY SCR’ (see the previous instalment for more informa- tion). If the charging current is low, the circuit may get stuck in the on state. This doesn’t happen with the three-transistor version, which works reliably over a wide range of charging currents. Another simplification is also possible. As the piezoelectric transducer is effectively a capacitor, you can omit the electrolytic capacitor. This converts the otherwise slow clock generator into a fast audio generator. ( 120007 -I) 52 06-2012 elektor Buy it today! www.cc-webshop.com CIRCUIT CELLAR ADuC841 Microcontroller Design Manual: From Microcontroller Theory to Design Projects If you’ve ever wanted to design and program with the ADuC841 microcontroller, or other microcontrollers in the 8051 family, this is the book for you. With introductory and advanced labs, you’ll soon master the many ways to use a microcontroller. Perfect for academics! q ADuC841 MICROPROCESSORS Arduino on Course (ib) Part ib: an Arduino By David Cuartielles (Spain) 1 -bit Sound Generation ... What?!? Up to this point, you have been experimenting with code that can be generated directly out of the Arduino language. Now we pro- ceed with methods of hacking the processor on the Arduino Uno (the AT mega 328) at a low level, aiming to create a block of code that will use sound data coming from a WAV file for storage inside program memory — and playing back of course. The method used is not trivial. A good way to start is to look at sound based in terms of its spectrum rather than from any sort of representation in time. Figure 1 . Recording of human speech saying “ta-te-ti-to-tu”. Figure 2. Spectrum of human speech saying “ta-te-ti-to-tu”. sound player Sound spectrum The sound spectrum is a representation of the energy transmitted by, say, a loudspeaker as a function of frequency. Looking at the spectrum of sound, you do not nor- mally get a clear view of the sound itself as in Figure 1. Rather, the graph represents the amount of energy for different discrete fre- quencies within a certain amount of time. Typically we represent the spectrum for a whole song (see Figure 2). Alternatively, we can look at the spectrum of just 0.5 seconds of a song. The smaller the time frame we’re watching, the better the spectral representation of the sound generated at that very instant. The shape of the wave generating that spectrum can be anything. As a matter of fact, two different sound signals can generate very similar spectra. Thus, the size of the time frame determines the similarity of that signal is to the original one. The human ear is stimulated by the energy content of the sound, therefore two signals having identi- cal spectra will be perceived as the same, but only if the time reso- lution is small enough. This is key to the whole science of sound compression: the ability of getting signals that are ‘good enough’ for us to understand the sound, even if the sound is very different from the original one. This is also the way 1 -bit sound generation works [1 ]. We can gener- ate sound by having a pulse width modulated (PWM) signal whose average energy level is similar enough to the one of the original signal. This mathematical trick allows generating medium-quality sound by a microcontroller. The following paragraphs show how to take advantage of this. We will start from a WAV file that can be recorded with your computer. Next, we’ll filter it, and transform it into an array of numbers for storing inside Arduino. Optimal digitalisation and filtering Many different tools exist for recording sounds. I can only recom- mend the use of Audacity [2], an open source and free software tool that provides most of the options needed to reproduce sound with microcontrollers (Figures 1 and 2 are screenshots from Audacity). Before you move on, you should filter the sound. I use a low-pass fil- ter with a 4 kHz roll-off frequency. The Arduino sound player shown here uses a sampling frequency of 8 kHz (i.e. 8000 samples per sec- ond), which means that if there were sound components above 4 kHz in your original file, you would hear artefacts in the sound. With microcontrollers it is possible to reproduce reasonable quality sound, however these chips are limited in terms of memory space. Consequently you need to use sound formats of lower quality that will allow generating several seconds of sound without the use of external memory chips. A sound format that can be of great use is the 8-bit PCM WAVE (also called Microsoft unsigned 8 bit). This sound format is of sufficient quality to reproduce, for instance, recorded human voice. Thus, the file you’ll need in the following step of the process should be 54 og-2012 elektor ARDUINO ON COURSE exported as: mono (1-channel), 8-bit, PCM WAVE. Converting sound to text Let’s look at importing your sound file as a header file that you can add to your Arduino sketch. Since the ATmega 328 microcontroller has 32 KB of Flash memory space, you can use part of that space to store the sound file. You can store large chunks of data into memory arrays by using the Progmem library from Atmel’s toolchain. 8-bit const unsigned char sounddata_data[] PROGMEM = {128, 128, 128, [...] 69, 62, 59, 57, 52, 50, 56, 65, 74, 86, 96, 109, 116, }; sound is nothing but a stream of numbers between 0 and 255. It can be declared like: I have created a tool for Arduino’s IDE that enables you to open WAV files and import them directly as part of your code. You can down- load it from the link mentioned in the reference list, and add it to your sketchbook folder. Place the file into your Arduino sketchbook folder and uncompress it there. It will add the following folder to your sketchbook: tools/SoundData After rebooting the IDE, you will see a new item under the Tools menu called SoundData. Clicking on it produces a dialog window enabling you to select a WAV file (see Figure 3). The second but- ton, titled Generate Code will open the WAV file, check whether it is properly encoded, and add a new tab to your code titled // soundData for your Arduino sound project // automatically generated data // - original sound file: /development/tmp/matis. wav // - sampleRate: 8000 // - encoding: 8 bits // - channels: 1 const int sounddata_length = 7969; const signed char sounddata_data[] PROGMEM = {127, 127, 127, 127, 127, 127, [...] 69, 62, 59, 57, 52, 50, 56, 65, 74, 86, 96, 109, 116, }; sounddata . h. This new file contains everything you need to play your WAV file as a 1 -bit sound. The file will look like this: But keep on reading before pressing the Generate Code button on the dialog window, because there is more to it! The Sound Player inilLi.i5-playercB.de Generate Code Figure 3. Dialog Window to import WAV files into your Arduino sketches as header files. Playing back a sampled sound is not obvious, since it requires changing some of the features of the Arduino core works. There exist libraries for Arduino Uno that hide all of the complexity of mak- ing this type of sound player. However, I want you to take a chance and see how this is done at low level, like in Figure 4. The trick that can get Arduino to play a sound sample is the so- called Fast PWM, a feature of Atmel’s Atmega family (other brands have it as well, but Arduino Uno runs on Atmel chips). There is a reg- ister that allows running PWM attheamazing rate of upto half the clock speed. This allows nice things to be done like playing sound with 1 -bit outputs. The only limitation of Fast PWM is that it oper- ates at a resolution of 8 bits only. That’s why you should encode your sound files at 8 bits. To get it all to work, you use two out of the three internal timer reg- istries inside the processor: soundclata.h // sound Data for your Arduino sound project ff automatically generated data // - original sound f iles /document s/Ri Trab // - sampled ate j 300 Q // - encoding :6 bits // - channels ;1 const int sounddata_length |= BOSS; const signed char sounddata_data[) PROGMEM , 127, 127, 126 r 127, 127, 127, 127, 126 , 1 , 127, 12S, 127. 127, 128. 127, 123. 127, 1 r 127, 127, 127 r 127, 127, 127, 125, 127 , 1 , 127. 127. 127. 127, 127, 127. 127, 127. 1 , 12B, 127, 126 , 127, 128, 127, 123, 127, 1 Binary vhaLi.ii hie &2S' 1 UyluT. Ce 1 d 32256 bfle ■d.xjrjBl e fijdrJ/io Uno on HQ Figure 4. View of the “ta-te-ti-to-tu” sound file within the Arduino IDE after importing it with the SoundData tool. elektor og-2012 55 MICROPROCESSORS " & O Sound Data Tool For Arduino Tile Cdn Sketch 7ao3s I ielp FjE Wm EketchmayDds // a bunch of includes #incl ude #inc 1 ude #include // this is the sound converted to a C strea #inc 1 ude 11 so und data , h " // if you transform SAMPLG_RATE into a vari ff it will possible ta e.g. use a potentiom! // control the sample rate #def ine SAMP LEjR ATE 3 GQ 0 // configure the pins we will use in the ex „ £j i id i y vhcLi.li ai£E $284 u ?• I u l- r= sounddata_length) { if (sample == sounddata_length + lastSample) { // this is the condition of reaching the last sample stopPlayback() ; } else { // Ramp down to zero to reduce the click at the end of playback. 0CR2A = sounddata_length + lastSample - sample; } } else { // 0CR2A is the register in memory that will push // PWM at high frequency to pin 11 // pgm_read_byte reads data out arrays stored in program memory 0CR2A = pgm_read_byte(&sounddata_data [sample]) ; } // increase the sample count ++sample; low level commands in order to override the timers. I will describe the functions one by one. Let’s start with TIMER1 : ISR is the name for the interrupt handling function inside the micro- controller. An interrupt is an event that will tell the chip to stop doing anything it is into at the time and attend a certain event. Pro- cessors can have both internal and external interrupts. The internal ones are timers, while the external ones happen when certain pins change from HIGH to LOW or vice versa. This one instance of the ISR function is taking care of the arrival of internal TIMER1 events. Every time TIMER1 ticks, this function will do the following: • increase the counter used to address the sound data; • check whether the end of the sound data array is reached; • if not at the end, load the next sample from the array; • if at the end, fade the sound to zero. void startPlayback() { pinMode(speakerPin, OUTPUT); // Set up Timer 2 to do pulse width modulation on the speaker // pin. // Use internal clock (datasheet p . 1 60) ASSR &= ~(_BV(EXCLK) | _BV(AS2)); 56 og-2012 elektor c: QJ E QJ QJ > TD < r r PicoScope Technology // Set fast PWM mode (p . 1 57) TCCR2A |= _BV(WGM21 ) | _BV(WGM20); TCCR2B &= ~_BV(WGM22) ; // Do non-inverting PWM on pin 0C2A (p . 1 55) // On the Arduino this is pin 11. TCCR2A = (TCCR2A | _BV(C0M2A1)) & ~_BV(COM2A0) ; TCCR2A &= ~(_BV(C0M2B1 ) | _BV(COM2B0)) ; // No prescaler (p.158) TCCR2B = (TCCR2B & ~(_BV(CS1 2) | _BV(CS1 1 ))) | _BV(CS1 0) ; // Set initial pulse width to the first sample. 0CR2A = pgm_read_byte(&sounddata_data[0]) ; // Set up Timer 1 to send a sample every interrupt, cli () ; // Set CTC mode (Clear Timer on Compare Match) (p.133) // Have to set 0CR1A *after*, otherwise it gets reset to 0! TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12); TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10)); // No prescaler (p . 1 34) TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS1 1 ))) | _BV(CS1 0) ; // Set the compare register (0CR1A). // 0CR1A is a 16-bit register, so we have to do this with // interrupts disabled to be safe. 0CR1A = F_CPU / SAMPLE_RATE ; // 16e6 / 8000 = 2000 // Enable interrupt when TCNT1 == 0CR1A (p . 1 36) TIMSK1 |= _BV(0CIE1 A) ; lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1 ]) ; sample = 0; sei () ; Both tinners TIMER1 and TIMER2 are initialized as part of the startPlay- back function. Let’s see how what looks like: Although the sequence of low level commands is explained in the code, a summary of it may be useful for the non-expert: • turn the pin for the speaker into an output; • configure the board to use the internal clock for this; • initialise Fast PWM mode; 4-CHANNEL PC Oscilloscope 60 - 200 MHz bandwidth 128 MS deep memory 1 GS/s real-time sampling Advanced digital triggering 200 MHz spectrum analyzer Function generator or AWG i m T ! i | I* ^ ' ' 'J Spectrum analyzer. Full SDK and advanced triggers or. — .. ! r - mm LimiiijjiMurJir Serial decoding (CAN, FlexRay, Lin, SPI, I2C, UART) Mask limit testing, Colour persistence modes, measurements and math channels all as standard and free updates ALL MODELS INCLUDE PROBES, FULL SOFTWARE AND 5 YEAR WARRANTY. www.picotech.com/PS164 elektor og-2012 57 MICROPROCESSORS Made with D FTim rn^.or^ Figure 6. Arduino Uno is perfectly capable of driving a small loudspeaker directly. • configure TIMER2 to run the PWM that will play the sound, the way to set the duty cycle to the PWM is by changing the value of the register called 0CR2A; • load the first sound sample into 0CR2A; • stop the interrupts for a second - cli ()- so that we can config- ure the TIMER1 without breaks; • configure TIMER1 to tick for picking up the next sample; • load the last sound sample; • restart the interrupts - sei() . void stopPlayback() { // Disable playback per-sample interrupt. TIMSK1 &= ~_BV(0CIE1 A) ; // Disable the per-sample timer completely. TCCR1B &= ~_BV(CS1 0) ; // Disable the PWM timer. TCCR2B &= ~_BV(CS1 0) ; digitalWrite(speakerPin, LOW); } In a similar fashion, you need to have a function that will stop the timers of counting this way once the end of the sound is reached. This leaves you with a series of functions you can call anywhere void setup() { startPlaybackO ; } void loop() { // do nothing } from a program to play sound this way. In this case, the example by default will call startPlaybackO within setup. In this way the sound will be played just once. Closing words This article is an introduction to different ways of producing sound using Arduino. You have seen how to play tones by means of basic Arduino functions. Libraries have been described that simplify the way basic melodies can be played using inexpensive piezo buzzers. Finally you got a sneak peek at the programming behind Fast PWM to generate 1 -bit sound. All code chunks and tools discussed here are packed into a ZIP file [4], including properly formatted sound files for you to try all the examples. I also created a new tool for the Arduino IDE that will help you with the importing of short WAVE files into Arduino’s pro- gram memory. The tool enables you to load sounds and play them back, change their sample rate, play them backwards or scratch the sound. In terms of hardware, you connect your loudspeaker as shown in Figure 6. But don’t stop here! There is a lot to explore — for instance using pin 3 in parallel with pin 1 1 to produce stereo sound. Or create 8-bit synthesizers with the ability of mixing four sound lines on a single channel. What about transforming your Arduino board into a MIDI activated soundcard? Happy hacking. See you in a month. (120427) References [1] 1-bit Sigma Delta DA Converters: www.digitalsignallabs.com/presentation.pdf [2] Audacity, the free and open source sound studio: audacity.sourceforge.net [3] Various references from the example by Michael Smith: Arduino reference on the use of the tone library: arduino. cc/en/Reference/Tone Original article on the Arduino Playground: arduino. cc/playground/Code/PCMAudio www.uchobby.com/index.php/2007/1 1 /1 1 /arduino-sound- part-1 / www.atmel.com/dyn/resources/prod_documents/doc2542.pdf www.evilmadscientist.com/article.php/avrdac http://gonium.net/md/2006/12/27/i-will-think-before-i-code/ http://fly.cc.fer.hr/GDM/articles/sndmus/speaker2.html www.gamedev.net/reference/articles/article442.asp [4] Example files for this article: www.elektor.com/ 1 20427 58 og -2012 elektor COMPONENT TIPS AS3935 Lightning Sensor By Raymond Vermeulen (Elektor Labs) austriamicrosystems’ new lightning sensor 1C measuring just 4x4 mm landed on my desk like a stroke of lightning, thanks to a suggestion from my colleague Luc Lemmens. If a suitable antenna is connected to the 1C, a microcontroller linked to the device via SPI or l 2 C can calculate the distance to the edge of a thunderstorm. That’s right - not the distance to the lightning, but instead the distance to the storm front. The range is 5 to 40 km (approx. 3 to 25 miles). ( 120405 ) AS3935 The microcontroller connected to the AS3935 can also configure a lot of settings in the 1C. One of the really remarkable features of the algorithm used in this 1C is that it can determine whether the received signals are man-made or naturally occurring. This means that you can also use it indoors. What’s more, the noise floor level can be adjusted in a register to allow the device to be used in a noisy environment. An interrupt is sent to the microcontroller when the received noise level rises above the configured noise floor, which al- lows the microcontroller to raise the noise floor level if necessary. The gain of the integrated amplifier also has a separate mode for indoor use. Artificially generated noise can adversely affect the light- ning detector, so the detection level can also be adjusted in a regis- ter, although this reduces the detection sensitivity. The recommended antenna is a loop antenna consisting of a par- allel-resonant LC circuit with a Q factor of approximately 1 5 and a resonant frequency of 500 kHz. As it is rather difficult to make an antenna that perfectly meets these specifications, the 1C has provi- sions for tuning the antenna. There are register settings that allow the microcontroller to read out the resonant frequency of the con- nected antenna using a signal on the IRQ pin with a configurable division ratio. The microcontroller can tune the antenna circuit by adding 0 to 1 20 pF of capacitance in steps of 8 pF. Once the antenna is properly tuned, the rest of the internal oscillators in the 1C can be calibrated. All interrupts are signalled by setting the IRQ pin high, and the microcontroller can read a register to determine the specific cause of each interrupt. It is also possible to configure the 1C to sense a minimum number of discharges in a 15-minute interval if you are not interested in detecting individual sporadic discharges. As our readers are generally interested in weather-related projects, it wouldn’t surprise me to see a circuit based on this device appear in a future issue of Elektor. I2CL/ I2CD/ CS SCL MISO MOSI SINT ADDO ADD1 VDD VREG EN_VREG Description Condition Value Supply voltage range EN_VREG = VDD 2,4 -5,5V Supply voltage range EN_VREG = GND 2,4 -3,6V Current in power-down mode VREG = OFF 1 pA Current in listening mode VREG = OFF 8 jllA Current in signal verification mode 350 pA Austriamicrosystems AS3935 data sheet: wwwl .futureelectronics.com/doc/AUSTRIAMICROSYSTEMS/AS3935. pdf Evaluation kit application note: http://media.digikey.com/pdf/Data%20Sheets/Austriamicrosystems%20PDFs/AS3935_EvalManual_AN.pdf elektor og -2012 59 RADIO AVR Software Defined Radio (5) Part 5: Decoding DCF77, MSF and TDF162 using MR and matched filters By Martin Ossmann (Germany) The aim of this series of articles is to show that the popular AVR microcontrollers are also suitable for digital signal processing. In this instalment we use a variety of decoding methods and filters to convert the signals from various VLF time signal transmitters into digital data. In the previous instalment [4] we devoted our attention to the reception of digital radio signals. Using the digital receiver described in that instalment, we received signals from time signal transmitters such as German DCF77 and from weather ser- vices and decoded the received signals. Now it’s time to examine a variety of decoding methods. Along with transmit- ting and receiving RTTY signals, we dis- cuss the reception and decoding of signals from DCF77 in Germany, MSF in the UK and TDF1 62 in France. Finally, we describe how to use a matched filter for bit decoding. Sadly the author can’t even dream of ever receiving WWVB at his location, but the information supplied in this article should enable Elektor USA readers to develop suita- ble decoding and demodulation algorithms. WWVB transmits at 60 kHz. Wireless data transmission at 125 kHz If the level of the DDH signal at your receiver location (see the previous instalment in this series) is too weak or absent altogether, you can build your own test transmitter. The hardware is exactly the same as for the DCF test transmitter described in the third instalment [3]. A simple ferrite antenna and a variable capacitor form a series-resonant circuit that is fed from the square-wave out- put of the signal generator. This arrange- ment is shown in the photo at start of the article. The software for the transmitter is con- tained in the EXP-SQTX-FM-RTTY- V0 1. c file. After configuring the reception software in EXP-1 25kHz-RTTY-RX-V01.c for operation at 1 25 kHz, you can start your signal trans- mission and reception experiments. The author obtained a range of over 5 m (15 ft) (even through walls) with this simple sys- tem. Among otherthings, this arrangement could form the basis for a wireless remote control system. With the same software, you can also decode conventional RTTY (‘telex’) signals in the amateur radio bands. All that is necessary for this is to adjust the filters and the timing to match the transmission parameters. For testing, you can generate RTTY signals with suitable PC software such as MMtty (down- load from [6]) and a sound card. Decoding DCF77 An oscillogram of the received and demod- ulated DCF77 signal was shown in Figure 3 of the third instalment of this series. Now let’s see how you can recover the data from the keying pulses. As the amplitude of the received signal can vary widely depend- ing on reception conditions, the first thing you need to do is to define a threshold level (as automatically as possible) for decid- ing whether the instantaneous amplitude is high or low. For the sake of simplicity, you could set the threshold level at half the average signal level. However, this requires determining the long-term average value. If we wanted to use a CIC filter to average the signal, we would need a very large interim buffer. This is why we use an HR filter [7] instead. MR filtering The abbreviation MR stands for ‘infinite impulse response’. This long impulse 60 og-2012 elektor AVR SOFTWARE DEFINED RADIO Carrier on 0.5 s Carrier off Bit Bit A B Os 0.1 s 0.2 s 0.3 s Figure 1 . Carrier keying of the Rugby MSF signal. Figure 2. Signal paths in an FIR filter. response (which corresponds to the averag- ing interval) is obtained by using a recursive filter. The computation formula for a simple MR filter is: y k+1 =ox k + (1 -o)y k Herey k is the output sample series, x k is the input sample series, and a is a number less than 1 but close to 1 . The new sample y k+1 is the averaged sum of the previous sample and the new input sample. In this formula the factors a and (1 - a) are normally numbers less than 1 . This makes it tempting to use floating-point operations to compute the filter, but that would be much to complicated. In our implementa- tion (see Listing 1 ) the filter coefficients are represented as fractions, with the denomi- nator (65,536) being a power of 2. Here a = (65536 - 50) / 65536 = 0.999237 ..., and (1 - o) is accordingly 0.000763... The computations are performed using 32-bit integer numbers. The compiler cov- erts division by 65,526 into simply selecting the most significant 1 6 bits, which consider- ably speeds up the computation. The result is a highly efficient HR filter. The output of the MR filter is the signal in binary form, and the time of day can be obtained by evaluat- ing the pulse lengths. In central Europe and the south-east of the UK, DCF77 reception with decoding requires the simple front-end or the uni- versal receiver, along with the active ferrite antenna tuned to 77.5 kHz. With the EXP- DCFdecode-RX- V0 1. c software loaded in the receiver microcontroller, you obtain a sec- onds timer and the signal is output by the PWM DAC. The signal strength and time of day are also shown on the LCD module, and the decoded data is output on the RS232 or USB port. Decoding MSF There are several time signal and stand- ard frequency transmitters in Europe. One of them is MSF [8] in Rugby, Great Britain, which broadcasts at 60 kHz (coinciding with WWVB in Fort Collins, Colorado, USA). Its signal is relatively weak at the author’s place of residence, so a bit more effort is necessary. The amplitude of the MSF car- rier wave is keyed at 1 -second intervals (see Figure 1 ). The carrier is keyed to a low level for 0.5 s at the start of each minute. At the start of each subsequent second, the carrier is initially keyed low for 0.1 s. The next 0.5 s is the time slot for the A bit. The A bit is high if the carrier amplitude is low in this time slot. The following 0.1 s is the time slot for the B bit. The B bit is also high if the carrier amplitude is low in this interval. The A and B bits are used to trans- mit time data, additional synchronisation data and error detection codes. Our first attempts to receive the signal yielded a severely distorted signal, which could not be adequately filtered by a simple CIC filter. We therefore needed a better fil- ter with a cutoff frequency at a round 10 kHz and fairly strong attenuation. Another requirement for the filter was that it should not affect the waveform too much. These characteristics can be achieved with a FIR filter [9] of sufficient order. For MSF reception you need the receiver, the active antenna tuned to 60 kHz, and the software EXP-RX-MSF60decode-V01 .c. With this arrangement, the signal strength and time of day are shown on the LCD mod- ule and the date and time are output on the serial port. The structure of the fifth-order FIR filter is shown in Figure 2. The input elektor og-2012 61 RADIO Listing 2 : FIR summation #define FIRLength 60 prog_int16_t FIRCoeffs []={ 112, 3, -17, -52, 112 } ; FIRSum=0 ; j=FIRPointer ; for (k=0 ; k 07:09 08.03.10 MONDAY P=1 P=1 P=1 P=1 <20000000000000000001 00000001 1 001 000001 0001 1 1 001 000001 11 131 03> 07:10 08.03.10 MONDAY P=1 P=1 P=1 P=1 <20000000000000000001 00000001 1 001 000001 0001 1 1 001 0001 0111111 03> 07:11 08.03.10 MONDAY P=1 P=1 P=1 P=1 this signal is coded in the same way as the DCF77 signal. However, we encoun- ter a new problem with the decoding. The time code bit is transmitted at the start of each second, but this is followed by a lot of phase-modulated data that is used for internal purposes. This means that the receiver must first determine the exact position of the seconds pulse. There is a long modulation gap before the seconds pulse for the null second, since the pulse for the 59 th second is mission. Once the receiver has detected this gap, it looks for the next peak in the phase waveform (see Figure 6). This peak marks the exact position of the desired seconds pulse. At exactly one-second intervals from this point onward, the receiver checks whether the received signal indicates a 1 or a 0. A matched filter with CIC If you want to evaluate the phase directly, you don’t want to have any phase drift. Con- sequently, you need to use a PLL to stabi- lise the phase of the signal. However, this is a bit complicated and control loops are not always stable, so a different approach is better. Instead of evaluating the phase, we evaluate the frequency. The frequency can be obtained from the phase by differ- entiating successive samples and filtering the resulting samples with a CIC low-pass filter to clean up the waveform. To deter- mine whether a 0 or a 1 has been transmit- ted, we check whether the waveform cor- responding to a 1 has been received at the right time. If it has not, we conclude that a 0 has been received. This leaves us with the question of how to determine whether the signal waveform we are looking for has actually been received. A matched filter is often used for this pur- pose in telecom engineering. The impulse response of such a filter exactly matches the desired waveform (although it is mir- rored in time). Our 0 waveform consists of a combination of three rectangular pulses. This makes it fairly easy to implement a matched filter in the form of a CIC filter, since the impulse response of such a filter — the response to a single 1 at the input — is naturally a single rectangular pulse, as described in [4]. The filter is shown schematically in Fig- ure 7. Here the signal is sampled at a rate of 500 samples per second. The first pulse has a length of 25 ms and therefore cor- responds to twelve samples. The second pulse has a length of 50 ms and corre- sponds to 25 samples. The final pulse, like the first one, has a length of 25 ms. These pulse lengths translate directly into the required delay stages. This filter is ideal for detecting the 0 waveform. As the 1 wave- form is similar to the 0 waveform (consist- ing of two successive 0 waveforms), we can use the same filter and simply check the output 50 ms later. This is exactly the strategy that is used in the receiver. The oscillograms (Figures 8 and 9) show the corresponding waveforms. The yel- low trace shows the state of the timer that Figure 7. A matched filter implemented as a CIC filter. elektor og-2012 63 RADIO Figure 8. The output signal of the matched filter when a 0 is received. Figure 9 . The output signal of the matched filter when a 1 is received. After the final bit is received, the data in this array is decoded and displayed on the LCD module. It is also output at the same time on the serial port at 1 9,200 baud. Listing 4 shows an example of the received data. The final instalment of this series will appear in the next edition. In that instalment we will look at bit clock synchronisation and describe the ‘early late gate synchroniser’, among other things. Finally, we will decode the signal from the BBC 198 Droitwich transmitter and get acquainted with several other decoding methods. detects the gap for the 59 th second. The input signal is sampled at the points where there is a sudden change in the yellow sig- nal, which is exactly where the peaks occur in the received signal. The zeros and ones are stored in an array. (120089-I) Listing 4 : Example data from TDF 162 TDF 162 0001 1 1 0000000000001 01 1 001 1 001 0001 001 111 01 01 1 001 00000001 00000 08:19 17.02 WEDNESDAY 2010 p 000 00001 1 0000000000001 01 000001 01 0001 001 111 01 01 1 001 00000001 00000 08:20 17.02 WEDNESDAY 2010 p 000 00001 1 0000000000001 01 1 00001 000001 001111 01 01 1 001 00000001 00000 08:21 17.02 WEDNESDAY 2010 p 000 00001 1 0000000000001 01 01 0001 000001 001 111 01 01 1 001 00000001 00000 08:22 17.02 WEDNESDAY 2010 p 000 0001 1 1 0000000000001 01 1 1 0001 01 0001 001 111 01 01 1 001 00000001 00000 08:23 17.02 WEDNESDAY 2010 p 000 Internet Links [1] www.elektor.com / 1 001 80 [6] [2] www.elektor.com / 1 001 81 [ 7 ] [ 3 ] www.elektor.com /1 001 82 [8] [ 4 ] www.elektor.com /1 20088 [ 5 ] www.elektor.com /1 20089 [ 9 ] http://hamsoft.ca/pages/mmtty.php www.dspguru.com/dsp/faqs/iir/basics www.npl.co.uk/science-technology/time-frequency/time/ products-and-services/msf-radio-time-signal www.dspguru.com/dsp/faqs/fir/basics Elektor Products & Support • Signal generator (kit with PCB and all components, 100180-71) • Universal Receiver (kit with PCB and all components, 100181-71) • Active ferrite antenna (kit with PCB and all components, 100182-71) • Combo kit with all three component kits plus BOB FT232 USB to TTL converter: 100182-72 • BOB FT232 USB to TTL converter, fully assembled and tested: 110553-91 • Free software download (hex files and source code) All products and downloads are available on the web page for this article: www.elektor.com / 1 20089 64 09-2012 elektor ELEKTOR Preferred Suppliers Coast Electronics • CS Technology • Easysync * Elnec • FTDI Chip • Robot Electronics Surf to www.elektor.com 365 days per year preferred suppliers online with up to date and relevant information. To become a preferred supplier contact Johan Dijk byj.dijk@elektor.com ELNEC www.elnec.com Europe’s leading device ^ programmers manufacturer: • reliable HW: 3 years warranty for most programmers • support over 69.000 devices • free SW updates • SW release: few times a week • excellent technical support: Algorithms On Request, On Demand SW • all products at stock / fast delivery FIRST TECHNOLOGY TRANSFER LTD. first © Technology Transfer Ltd. http://www.ftt.co.uk • Training and Consulting for IT, Embedded and Real Time Systems • Assembler, C, C++ (all levels) • 8, 16 and 32 bit microcontrollers • Microchip, ARM, Renesas,TI, Freescale • CMX, uCOSII, FreeRTOS, Linux operating systems • Ethernet, CAN, USB, TCP/IP, Zigbee, Bluetooth programming FLEXIPANEL LTD www.flexipanel.com TEAclippers - the smallest PIC programmers in the world, from £20 each: • Per-copy firmware sales • Firmware programming & archiving • In-the-field firmware updates • Protection from design theft by subcontractors HEXWAX LTD www.hexwax.com World leaders in Driver-Free USB ICs: • USB-UART/SPI/I2C bridges • TEAleaf-USB authentication dongles • expandlO-USB I/O USB expander • USB-FileSys flash drive with SPI interface • USB-DAQ data logging flash drive THE NEXT GENERATION OF MAXSONAR * ■* « i + The HRLV - MaxSonar Sensors •Amazing One-Millimeter Resolution •Simultaneous Multiple Sensor Operation •Superior Noise Rejection •Target Size Compensation for Accuracy •Temperature Compensation ($4.95) •Outputs now include TTL Serial $3495 (msrp) f| www.MaxBotix.com TYDER http://www.tyder.com • ONEoverT Digital Filter Design Software (Full version for only £30) • Design FIRs, NRs, NCOs, FFTs for DSPs and FPGAs • VHDL Code Generators • Makes DSP design simple • Download demos from website SCOPES and more Instruments A Rohde&Schwarz Company www.hameg.com Great Value in TEST & MEASUREMENT ROBOT ELECTRONICS http://www.robot-electronics.co.uk Advanced Sensors and Electronics for Robotics • Ultrasonic Range Finders • Compass modules • Infra-Red Thermal sensors • Motor Controllers • Vision Systems • Wireless Telemetry Links • Embedded Controllers ROBOTIQ h ttp ://www. ro boti q . co . u k Build your own Robot! Fun for the whole family! Now, available in time for X-mas • Arduino Starter Kits *NEW!!* • Lego NXT Mindstorms • Affordable Embedded Linux Boards • Vex Robotics (kits and components) • POB Robots (kits and components) email: sales@robotiq.co.uk Tel: 020 8669 0769 www. elektor. com elektor 09-2012 65 INFO & MARKET BasicCard goes contactless A discreet alternative By Patrick Gueulle (France) The only chip card that you can program in BASIC has now been on the market for more than ten years. It remains under continuous development: in a new twist, this well-known card with an open operating system is now available in an RFID version. As well as the new facilities for contactless operation, very powerful (and free!) development tools are now available to provide an easy way to get to grips with this fascinating technology. The philosophy behind the product has not changed since the first ‘Compact’ BasicCard appeared in 1998: put into the hands of devel- opers (which includes interested enthusiasts) the means to develop their own applications independently of the mass-market chip card manufacturers. The result is a complete range of asynchro- nous cards using Flash technology, with products available in small quantities and even individually. With the help of a (reprogram- mable virtual machine, which in some versions was even capable of supporting several applications simultaneously, there is support for a high-level language simpler, but no less powerful, than Java: ZCBasic (Figure 1). A complete development environment (compiler, simulator and double-debugger, along with a manual running to some 250 pages) is available for free download at [1 ]. With just a couple of lines of source code it is possible to make a BasicCard compatible with just about any terminal, including for example a mobile phone. This existing know-how can now be trans- ferred to contactless applications using the ZC7.5 RFID version of the card. The transition is also simplified by the use of the ZC7.5 Combi card, which offers two interfaces: one over contacts (trans- port layer protocol T=0 orT=1) and one contactless (ISO 14443 type A T=CL). An ACR1 22 or Omnikey 5321 makes a suitable RFID reader for the contactless interface. Card applications Twenty or so lines of code (RFIDspy.BAS [2]) suffice to demonstrate the flexibility oftheZC7.5 Combi card. At under 400 bytes of P-code the program occupies just a tiny fraction of the 32 kbyte EEPROM space in the powerful 1C. This short program is a T=CL version of the logger that we presented for the first T=0 BasicCard with contacts in the May 2002 issue of Elektor [3] (for card version ZC4.1). The pro- gram can store and subsequently dump the commands used by a reader as part of its dialogue with a card presented to it. Depending on the reader, this ‘impostor’ will either be rejected almost instantly or be accepted (for a while at least) by the reader as a genuine card intended for use with it. The underlying idea, of course, is to use this code as a basis for incre- mental extension: as more and more of the commands emitted by the reading device are understood, code can be written to deal more precisely with them, thus better emulating a genuine card. There is a certain amount of detective work to be done in unmask- ing the security mechanisms used in the design and in determining their strengths and weaknesses. In summary, we have a very handy experimental tool. Skipping over the first three lines of the source code, which are just preparatory declarations, we come to a series of ‘#Pragma’ directives, of which the first two are specific to operation in con- 66 og-2012 elektor BASICCARD GOES CONTACTLESS tactless mode. The first thing to know is that most contactless objects (cards and tags) have a unique number (or UID), several bytes long, which is written into ROM during manufacture. This is occasionally used as part of a defence against cloning, but its main use is during the anti-collision process used by the reader to com- municate with a single specific card when more than one is within its range. The details of this process are relatively complex, but with luck card and reader will handle it all themselves: unless you really want to get his hands dirty, as an applications programmer you need not get involved. However, you can specify the number of bytes that will be used to form the UID in order to match the characteristics of another card as closely as possible. The ZC7.5 supports three standard variants: ‘single’ (four bytes, like MIFARE Classic), ‘double’ (seven bytes, like MIFARE Ultralight), and ‘triple’ (ten bytes). It is also possible to replace the fixed UID in the chip with a random value to help the owner of a card to avoid being tracked. In our example the UID is sent out as a group of four ran- dom bytes when a reader starts polling: #Pragma UID(Random, Single) At the beginning of communication begins between reader and card, the reader selects it and waits for its reply (ATS for ‘answer to select’), which is comparable to ATR (‘answer to reset’) in the case of a card with contacts. #Pragma ATS (TA1 =0 , FWI=7 , TCI =0 , HB=”EMVA”) This second command allows the default communications param- eters to be modified, either partially or completely, in order to optimise compatibility with a particular reader. In this example we choose compatibility with the ‘EMV Contactless Specifications’ (which are publicly available: [4]). These specifications ensure com- patibility for electronic payments between chip cards and termi- nals that bear a special logo indicating that they comply with them (Figure 2). In a similar way we can modify the ‘ATR’ parameters of the card, which affect its communications over the contact interface when it is connected to a suitable reader: #Pragma ATR(Direct ,T=1 , HB=”RFIDspy”) In this case we specify use of the T=1 protocol and select ‘direct con- vention’ for communications; we could equally well have used the T=0 protocol and/or ‘inverse convention’. We will now look at what happens in the card when it is selected by the reader. The BasicCard has an internal file system, similarto MS-DOS. Opening a file called, for example, ‘Card. Log’, can be done as follows: Open “Card. Log” For Append As #1 To allow this file to be deleted using an external instruction, it is convenient to define a special command for the purpose. Here we Figure 1 . The ZeitControl BasicCard development environment in action. Figure 2. The EMV contactless logo is found on an increasing number of point-of-sale terminals. have called the command ‘FLUSH’: Command &HC8 &HA2 FLUSH() Close Kill “Card. Log” End Command Now, if we send the byte sequence C8 A2 00 00 00 to the card it will delete the file. The main part of the program is found in the next seven lines: Command Else SAVE(S$) Call SuspendSWI SW2Processing() C$=CHR$(CLA)+CHR$(INS)+CHR$(P1 )+CHR$(P2)+Chr$(Lc)+Chr$(L e)+S$ S$=String$(Le, &HFF) Write#1 , C$ SW1 SW2=&H9000 End Command elektor og-2012 67 INFO & MARKET That is all that is needed to trap any unrecognised command (hence the ‘Else’) received by the card and store it in the file Card. Log along with the parameters CLA, INS, Pi , P2, Lc, Le and any data received from the terminal (‘incoming’ commands). For the outgoing message the card delivers by default a number of FFh bytes equal to the value of Le (the expected data length). A dif- ferent reply can be constructed if required by changing the contents of S$ as required. The status bytes SW1 and SW2 can also be changed from their default values of 90 00 depending on the desired effect on the reader. Terminal application Having collected some information in the file Card. Log we will want to read it from the card for further analysis. The file is normally left open so that data from several consecutive sessions can be logged, and so the first thing the program RFIDutil.BAS has to do is send the command C8 04 00 00 00, which closes the file as follows: Command &HC8 &H04 COP(Lc=0,S$) Close#1 S$=” (c)2009 Patrick GUEULLE” End Command Just two corresponding lines are required in the source code for the terminal: Declare Command &HC8 &H04 C0P(S$, Le=&H1 7) Call C0P(S$) Recovering the contents of the file is equally straightforward. In the terminal code we add the prefix ‘@:’ to the filename, and read the file as normal. The operating system generates all the necessary commands automatically: Open”®: card. log” For Input As #1 The following instruction is then used to extract one by one the commands for which the file contains the reply information: Input#1 , Z$ The rest of the terminal code is concerned with converting the con- tents of the data file into readable text, storing it on the hard disk and displaying it on the screen. A practical example Once you have had a look at the manual you can decide whether you prefer to use the development environment, which is well suited to organising projects, or to drive the ZCMBasic compiler from the command line. The result of compilation is a file RFIDutil.EXE, which can be run directly from the Windows command line, and a file RFIDspy.lMG (or RFIDspy.DBG), which has to be loaded into the memory on the card. With the card thus prepared, all you need to do is bring it within range of the terminal whose characteristics you are investigating. The author tested the card at the point-of-sale terminal at the checkout in a French supermarket. The supermarket accepts pay- ments of up to 20 Euro using contactless EMV cards such as Master- Card PayPass or Visa payWave. The BasicCard was brought within range of the terminal immediately before the real payment was car- ried out using a conventional bank card. Subsequent analysis of the file Card. Log revealed a sequence of select commands resembling the following: 00 A4 04 00 0E 32 50 41 59 2E 53 59 53 2E 44 44 46 30 31 00 A4 04 00 07 A0 00 00 00 04 30 60 00 A4 04 00 07 A0 00 00 00 04 10 10 00 A4 04 00 07 A0 00 00 00 04 99 99 00 A4 04 00 07 A0 00 00 00 03 20 10 00 A4 04 00 07 A0 00 00 00 03 10 10 00 A4 04 00 07 A0 00 00 00 43 10 10 00 A4 04 00 07 A0 00 00 00 42 10 10 The initial 00 stands for the ISO class (CLA) of the command, and A4 for the opcode (INS). Then 04 00 give the parameters Pi P2, fol- lowed by a length indicator byte (Lc) and the application identifier (AID). We have discarded the null byte at the end of each line as it is not of any interest for analysis and only serves to indicate that the command does not expect a reply (Le = 0). The first line represents an attempt to select the ‘PPSE’ (Proxim- ity Payment System Environment) with the identifier, transmitted in ASCII, 2 PAY . SYS . DDF01 . This is exactly analogous to PSE in the case of EMV cards with contacts, which use the identifier 1 PAY. SYS . DDF01 [5]. Our card replies with invalid data and so the termi- nal deduces that the PPSE, which at this point would normally sup- ply a list of applications supported by the card, is not available. The terminal then proceeds to attempt to select in turn all the applica- tions which it supports in the hope of finding one which also rec- ognised by the card. The next two lines show the terminal attempting to select two MasterCard applications, with priority given to Maestro (A0 00 00 00 04 30 60), a card which requires systematic (on- line) authorisation. Before the terminal goes on to attempt to select the Visa Electron (A0 00 00 00 03 20 1 0) and Visa credit/debit (A0 00 00 00 03 10 10) applications, there is an attempt to select the mysterious application A0 00 00 00 04 99 99. This might correspond to a supermarket loyalty card: the contactless reader is apparently capable of dealing with these as well as with bank cards. The final selection attempt is for the French Carte Bleue credit card (A0 00 00 00 42 10 10). 68 og-2012 elektor BASICCARD GOES CONTACTLESS What’s in the kit? The BasicCard is developed by ZeitControl, a small business based in Germany that evolved from being a vendor of time tracking systems into a specialist in chip cards. The first BasicCard was pro- duced in 1996. Compared to earlier BasicCard kits the ‘dual interface’ version features the addition of an RFID pro- totyping board carrying the TagTracer 14443 with a USB connection, buzzer, LED indicators and a printed antenna. These make developing applications much easier. In the author’s opinion this de- velopment kit is a distinctive product, and is considerably more flexible than other similar units on the market. • Omnikey 5321 USB - dual interface PC/SC smart card reader/writer • Pocket card reader (balance checker) • Development PCB for contactless IS 0 14443 USB reader/writer • Software development kit (SDK) for Windows • Documentation on CD-ROM • Printed technical manual (250 pages) • 4 off BasicCard ZC7.5 Combi (32 kbyte EEPROM) Further information is available at www.basiccard.com On the other hand, a terminal that only accepts cards with contacts (such as a public telephone or petrol pump) might attempt to select applications in the following sequence: 00 A4 04 00 07 A0 00 00 00 42 10 10 00 A4 04 00 07 A0 00 00 00 42 20 10 00 A4 04 00 0E 31 50 41 59 2E 53 59 53 2E 44 44 46 30 31 00 A4 04 00 07 A0 00 00 00 03 10 10 00 A4 04 00 07 A0 00 00 00 03 20 10 00 A4 04 00 07 A0 00 00 00 04 10 10 00 A4 04 00 07 A0 00 00 00 04 30 60 Here we see that the terminal attempts to select French bank cards before the PSE. Only after that does it attempt to select interna- tional applications. In both cases the terminal’s strategy is designed to make the transaction as quick as possible, which is especially criti- cal in contactless applications. One will sometimes encounter an attempt to select the Moneo application (00 A4 04 00 06 A0 00 00 00 69 00): this is an elec- tronic wallet that is available in versions with and without contacts. Identifiers more than ten bytes long betray the existence of a card ‘co-branded’ with one or more commercial suppliers. The author’s next step is to experiment with contactless bank cards outside his home country. Contactless payment systems are being rolled out in many European countries including the UK, and it is expected that the system will be in widespread use for small pay- ments within the next few years. ( 090378 ) Internet Links [1] www.basiccard.com [ 2 ] www.elektor.com/090378 [3] www.elektor. com/01 01 38 [4] www.emvco.com £■5 Ciyptn |ij‘.rnni Sr Ei® irtef onim# Oif WM(I w* —r— iRMfcirtMW Base Card Vmi'l • 1 111 1 ■: i-j ii'M ih'iijj ^Yilvrii ZeitControl ^ .1 1 cd w - aaiiCjCaftf Port ■' ! "I *eiri raft- ^ara- elektor 09-2012 69 MICROCONTROLLERS PICo PROto Minimalist prototyping tool for PIC16 or 18 By Michel Kuenemann (France) How can you set about quickly testing a new detector or evaluating a new idea without having to modify or wire up a complex, expensive development board? I ask myself this question at least twice a day in busy periods — how about you? Working on the principle that the simplest things are the ones we use the most, I had the idea for the PICo PROto, a minimalist prototyping tool. Main technical specifications • accepts SO28 and SSOP28 packages • minimal size and cost • maximum flexibility • lightning-fast implementation Bulimic for new technologies, I like above all to evaluate new devices for myself, espe- cially in the area of MEMS (microelectrome- chanical systems) detectors. Usually pow- these ‘break-out boards’ (BOB), they are fit- ted with a 0.1 in. (2.54 mm) pitch connector connected wire-for-wire to the main device. I also regularly use several types of micro- controllers from the Microchip PIC1 8 fam- ily in 28-pin packages. As Microchip has had the very good idea of standardizing the pinout for these devices, it’s easy to go from one type of device to another. What’s more, as these devices also exist in traditional through-hole DIP packages, it’s perfectly on the cards to build test set-ups on experi- mentation boards without any soldering at You’d be right to point out that Microchip does offer many inexpensive evaluation boards that are just waiting to be adapted to my ideas, but here again, for most of my tests, the wealth of connectors on these boards, their size, and the resulting price are out of all proportion to my actual needs. So I’ve designed a minimalist double-sided board for a PIC1 6 or 1 8, in an S028 pack- age on one side or an SSOP28 on the other, along with a few additional SMD compo- nents. Around the part occupied by the SMD components, there’s an area with This pinout is suitable for all PIC16 or 18 devices in a 28-pin package ered from 3.3 V, they deliver their data on analogue outputs or via an l 2 C bus, or less commonly on an SPI bus. Many of these modern detectors are encapsulated in tiny packages that are impossible to solder manually. Fortunately, the manufacturers of these marvels do think about the devel- opers who have to implement them, and often offer a small evaluation board with the detector soldered onto it. They call all. However, these spring-contact boards do have three major drawbacks: firstly, their size and weight are not compatible with my onboard applications in the field of model aircraft. Secondly, their electromechanical contacts are pretty random, not to say cha- otic; and thirdly, you can’t keep these set- ups for long, as we need to free up the pre- cious board in double quick time for a new experiment. square pads on a 2.54 mm pitch that can take through-hole components, and the inevitable pin headers for connecting the prototype to the outside world. It’s small size - only 28 x 42 mm - means it can be built just as well into a scale model air- craft or a small mobile robot as into a more roomy project. The good thing about the small size constraint is that it forces the constructor to stay focused on the objective 70 og-2012 elektor PI Co PROTo 120137 - 11 Figure 1. This is not a circuit diagram in the usual sense, but more of a phantom, as it doesn’t show the components, just their footprints. The PICo PROto is compatible with all 8-bit PICs in 28-pin packages. of their operation, without giving in to the temptation to “weigh down the donkey” with superfluous components. Circuit No surprise here, it’s transparency itself; besides, we can hardly call it a circuit (Fig- ure 1 ) as there are no components. So we can move straight on to the practical side. In addition to the S028 and SSOP28 foot- prints for the controller (only fit one at a time, please!), I have allowed for S08 and MSOP8 footprints too. This can be seen more clearly still in the enlarged repro- duction of the double-sided PCB (Figure 2). The photos show the top and under- side of two of my PICo PROtos (Figure 3). Their layout is slightly different from the final version. On the left, without com- ponents, on the right the top side with a TSSOP28 (the quality of the soldering is far from exemplary). How to use PICo PROto? Start by soldering the microcontroller you’ve chosen onto the top or underside, depending on the type of package. Then at the edge of the board solder in a 5-pin header (2.54 mm pitch) - using a right- angle type if necessary. This will let you elektor og-2012 7i MICROCONTROLLERS Figure 2. The through-hole plated double- sided PICo PROto PCB at a scale of 1 50%. connect the vital PICkit or ICD programmer for flashing and debugging your programs. Connect the header to the microcontroller as shown in the diagram (Figure 3), but don’t go any further for the moment. Check that your MPLAB development environment sees and recognizes the device. To do this, connect your programmer to the board and to your development PC. Run MPLAB, then in the ‘Programmer’ menu, select your tool and check that it connects correctly. Let’s assume you are using a PICkit3. At this point, MPLAB will return the following error: “You must connect to a target device to use PICkit”. This error is due to the fact that your microcontroller is not yet pow- ered up. Go into Programmer -> Settings -> Power, check that the cursor is on the volt- age suitable for your application and check the “Power target circuit from PICkit3” box. In Configure -> Select device, select the exact type of microcontroller you are using, and everything should then be OK. The least exciting part of the adventure is now behind you! If you want to communicate with your microcontroller using the USB interface, make use of a BOB FT232 module [2]. After K1 a a c> ICSP VDD © R1 2 W 3 4 28 5 27 K2 TX RX VDD GND a a a 2 _ 3_ 4_ 5_ 6 _ 7_ 1 0_ 9 20 VDD MCLR RBO RBI RB2 RB7/PGD RB3 RB6/PGC RB4 RB5 PIC16F/18F RAO RCO RA1 RC1 RA2 RC2 RA3 RC3 RA4 RC4 RA5 RC5 OSC2 RC6/TX OSC1 RC7/RX GND GND 21 22 23 24 25 26 11 JS ^^0 12 |R2 QL 19 T K2 X P/Co Proto O O O K2 BOB FT232 VCCIO TX RX GND CTS BOB FT232 120137 - 12 Figure 3. Wiring up the PICo PROto. soldering in and wiring up connector l<2, BOB FT232 will also take care of power- you’ll be able to make the connection; the ing your board (see the PICo PROto / BOB Figure4a. Application using the BOB for evaluating a barometric sensor. 72 og-2012 elektor PI Co PROTo interconnection diagram at the bottom of Figure 4). In this case, before connecting up the BOB, don’t forget to uncheck the “Power target circuit from PICkit3” box in the MPLAB. On the BOB, you will also have taken care to select the right supply voltage for your circuit using jumper JP1 . If you find it reassuring to see a red LED flashing to tell you the current program is running OK, don’t be afraid to fit a red LED as shown in the diagram. A seasoned experimenter will need less than an hour to get to this point in the project. The free space is now available for your boldest testing. To end with, here are two more examples (Figure 4) of the PICo PROto in use: Figure 4b. Underside: PIC1 8F27J1 3 in an SSOP28 package. Evaluating a barometric sensor, using the BOB Evaluating a voice synthesis process with a PIC1 8F27J1 3 in an SSOP28 package on the underside and an SSM2301 Class D ampli- fier on the top. 120137 -I Figure 4c. Top side, an SSM2301 Class D amplifier being tested forthe lengths counter for swimmers published in the Summer 2012 issue. Internet Links [1] www.elektor.com/ 1 20137 [2] BOB-FT232R USB/serial Bridge, Elektor September 201 1 , www.elektor.com/ 1 1 0553 Advertisement ’ 1 r r With dual ^ interface PC-linked reader/writer t . -'£ I fm Card Basic www.basiccard.com elektor og-2012 73 HOBBY Model Aircraft Lighting This design should gladden the heart of any model aircraft enthusiasts: it is a circuit to control the navigation lights, landing light, anti collision beacon and wing tip strobes from a spare channel of a model remote controller. The lights are switched remotely using any spare servo channel on the remote control receiver. By Werner Ludwig (Germany) Model servos are controlled by a PWM sig- nal. The pulse width determines the posi- tion of the servo output arm. A 1 ms pulse will drive the arm to one end of its travel (viewed from above servo fully anticlock- wise) and a 2 ms pulse drives it to the other end (fully clockwise). The servo control pulse output signal from the receiver plugs into connector K1 . The circuit consists of a pulse-width discrimina- tor circuit which controls the lights depend- ing on the length of the pulses from the transmitter. The pulse-width discriminator is constructed using four NOR gates. IC1 .A and IC1 .B are configured to form a mono- stable flip flop which produces an output ‘reference’ pulse width of 1 .5 ms. This pulse width corresponds to the servo neutral posi- tion. When the input pulse width is either longer or shorter than this reference pulse it will cause an output pulse from either IC1 .C (input pulse longer than reference pulse turns on landing light plus all other lights) or from IC1 .D (input pulse shorter than the reference pulse turns on all lights except landing light). In the quiescent condition IC1 .C and IC1 .D will both have a zero out- put state. The resistor/capacitor networks on the outputs of IC1 .C and IC1 .D smooth out the positive pulses to produce a stable high level which switches either transistor T1 or T2 on. These driver transistors will then switch the load. The transistors used in the author’s prototype version are capable of switching 2 A, making them suitable for driving low voltage filament lamps as well as LEDs. T1 switches the aircraft landing light, which is a high efficient white power LED. Diode D1 at the output of IC1 .C per- forms a logic ‘OR’ function ensuring that when the landing light is on all of the other navigation lights will also be on. These are shown in the first circuit as the navigation lights (left = red, right = green and tail light = white) the white wing tip strobes and the anti-collision light (ACL beacon). The navi- gation lights are switched by transistor T2 and the other branch from T2 switches an earth return to the pulse generator stage to flash the strobe and ACL beacon. The pulse generator consists of IC2 (4060) which is a 14-stage binary counter with built-in clock generator. The circuitry on the output of 74 og-2012 elektor MODEL AIRCRAFT LIGHTING this chip provides a four flash output for the strobe light and a double flash output for the ACL beacon. An alternative version of the aircraft light controller is also included here. This one uses a 1 0-stage decimal counter type 401 7 to provide control signals to switch the lights. This type of 1C does not have an inter- nal oscillator so a NE555 timer is included to provide the clock signal. The counter out- puts uses transistor logic to gate the correct pulses to the LEDs. In contrast to the first circuit this one provides separate signals for wing tip rear and forward strobes and tail ACL beacon. One final tip: LEDs are ideal for this sort of application, compared to filament lamps they are physically smaller and much more robust, using little energy and have a long life expectancy. They also have quite a nar- row beam width which in this application is a disadvantage. This can however be rem- edied by lightly abrading the LED front sur- face and then painting with clear varnish to give a more even light dispersion. (090144) Table 1: Circuit diagram lamp designation 1 Landing light 2 Navigation lights 3 Rear wing tip strobes 4 Forward wing tip strobes 5 ACL beacon 6 Tail strobe elektor 09-2012 75 3jetxatu£& The ‘Pansanitor’ (1928) By Dipl-lnf Karl-Ludwig Butte (Germany) Electrical muscle stimulation machines offer relief from aches and pains, muscle tension, neuralgia and lots of other miscellaneous ailments, using either low- or high-frequency alternating currents. Generating these currents is bread-and-butter stuff using modern semiconductor technology, but how was it done eighty years ago, in a time when transistors, let alone integrated circuits and micro- controllers, were not exactly off-the-shelf components? In this ‘Ret- ronics’ article we take a rare opportunity to examine the practically forgotten know-how from that period, with the help of an original example of the ‘Pansanitor’, a muscle stimulation device dating from 1928. Muscle stimulation machines: use and operation “The radiation from high-voltage and high-frequency currents is, like the high voltages delivered by the electrophorus, believed to have a soothing effect on the nervous system in general and on sore nerves in particular.” These words appear in the book High frequen- cies for the sick and the healthy: a medical companion [1 ], quoting Prof Dr Opitz from his Gynaecology Handbook [2]. However, that was not the only application of electrotherapy. Whether machines like the Pansanitor were used to treat the metabolism, respiratory organs, or skin and hair, the patient was soon restored to health (or at least that is what the books’ publish- ers would have you believe). Muscle stimulation machines are still used in medicine today, for example in cases of myaesthenia and circulatory disorders, and in general pain management. Thermal radiation is used in such cases, which has a deeper penetration than for example infra-red light. The historical context The device we are examining dates from 1 928, the year in which Amelia Earhart becomes the first woman to cross the Atlantic, Alex- ander Fleming discovers penicillin, and Coca-Cola becomes the first commercial sponsor of an Olympic Games. Just three years earlier the physicist Julius Edgar Lilienfeld had filed the first patent covering the principle of operation of the transistor [3]. The basic technology that paved the way for the boom in muscle stimulation devices was developed by Nicola Tesla in the last years of the nineteenth century. In 1 898 he published his research results in The Electrical Engineer under the title ‘High frequency oscillators for electro-therapeutic and other purposes’ [4]. Starting from an ordinary spark coil, he described, more from the point of view of an electrical engineer than that of a doctor, how his experimental devices were constructed and then refined. A spark coil consists sim- ply of a transformer, a capacitor, a ‘hammer’ interrupter and a spark gap. For reasons of economy Tesla wired two capacitors in paral- lel to reduce the potential difference between the secondary-side connections and so save on materials. This had the disadvantage of reducing the frequency of the alternating current, which he com- pensated for by adding a so-called Tesla coil (see figure 4 in [4]). For electrodes Tesla used evacuated glass bulbs, subsequently filled with a gas that glowed violet while the machine was in operation. From this the device came to be known as the ‘violet wand’. The shape of the glass bulbs was modified to adapt the device to the particular complaint or bodily part being treated: a selection can be seen in Figure 1. Retronics is a monthly section in Elektor magazine covering vintage electronics including legendary Elektor projects. Contributions, suggestions and requests are welcomed; please send an email to Jan Buiting (editor@elektor.com). 76 06-2012 elektor fRefrcanics XL Electrical muscle stimulation from the olden days Description of the Pansanitor The Pansanitor unit, along with all its accessories including cables, electrode holders and its wide array of glass electrodes, came in a handy carrying-case with a plush violet lining (Figure 1 ). The con- trol unit for generating the stimulation currents was built into a black wooden housing, with a plastic ivory-coloured top panel car- rying the legends for the two rotary controls and for the connection sockets (Figure 2). The device’s logo also appears in large letters, of course, along with the model number. It is interesting to note that there is no indication as to the manufacturer of the device: I have searched the internet for such information, but so far without success. On the left-hand side are four pins in a T-shaped arrangement, which were used to connect the device to the mains. The middle pin on the left is the neutral connection, while the other three allow for operation from 1 1 0 VAC, 1 50 VAC or 220 VAC. We therefore know that the manufacturer had an eye to the export market, intending the unit to be used with different line voltages. It behoved the cus- tomer to select the right pin for his AC voltage as there was no over- voltage protection! Indeed, the unit is not even fused. Black plastic caps were fitted over the unused pins. The AC power cable on this example has been replaced by the pre- vious owner, but the original porcelain plugs are still present and in good condition (Figure 3). Of the two large black rotary controls the one on the left functions as an on-off switch while the one on the right controls the intensity of the device’s output. The glass electrodes are connected to the two central sockets on the device using the cables on the electrode holder, which also acts as a handle (see Figure 4). However, out of concern for my own safety I have not dared to switch the machine on! Circuit of the Pansanitor Figure 5 shows the circuit diagram of the Pansanitor and Figure 6, the insides of the machine. Coil LI has two extra taps, to allow for the various supply voltage options. This means that the whole device is at mains potential! LI , together with the mechanical con- tact WH1 , forms the hammer interrupter; in conjunction with a cam on the On-Off switch, this also controls overall power to the unit (Figure 7). When the main switch is turned and power is applied, a magnetic field builds up in LI which attracts the switching contact WH1 . As a result the electrical circuit is broken and the large back EMF from the coil begins to charge Cl. Cl has a capacitance of 25 nF and is rated (or perhaps it would be better to say ‘was rated’) for operation at up to 2 kV. Given the antiquity of the component it is probably best not to rely on that figure anymore! With the supply voltage interrupted the switching contact WH1 returns to its original position, causing current to flow and the whole process to start again from the beginning. I10V- * ISO V- 22 0 V- ov~ L2 L3 elektor 06-2012 77 3jetxatu£& The high voltage thus produced is then converted to an even higher voltage by the Tesla transformer comprising a primary coil L2 and a secondary coil L3. L2 consists of two series-connected windings mounted one above the other (Figure 8). A pair of sprung contacts between the two windings, which can be moved using the inten- sity control knob, gives a certain amount of control over the final voltage produced: the contacts simply act as adjustable taps on the windings, much like a wirewound potentiometer. called the ‘Tesla tower’) [5], which was sadly demolished in 191 7. Pictures of enormous electrical discharges can easily be found [6]. The chief fascination of the Tesla transformer, however, is the fact that it is not just the turns ratio between the primary and secondary windings that is responsible for determining the magnitude of the voltage produced, but that resonance between the two coils also plays an important role [7]. (120177) The secondary coil L3 (Figure 4) is located in the handheld part of the device into which the various glass electrodes are fitted, and is connected to the main unit using a plug-and-socket arrangement. L3 has just ten turns using doubled-up conductors (Figure 9). The whole circuit is mounted on the back of the lid of the unit. In terms of simplicity and elegance it is hard to beat. Tesla transformer included! Just as the microcontroller is the most interesting component in the modern version of the circuit, so the Tesla coil commands centre stage in the 1 928 Pansanitor. Microcontrollers are now part of eve- ryday life, and many Elektor readers will be on friendly terms with them. The Tesla coil, on the other hand, now holds a certain mys- tique that will attract any electronics fan. That must originate not just from the charismatic personality of its inventor, Nikola Tesla, but also from its best-known incarnation, Wardenclyffe Tower (also References [1 ] Thuringer Verlagsanstalt und Druckerei GmbH: Jena, 1930; www.electrotherapymuseum.com/2005/HF/index.htm [2] Bergmann: Munich, 1 922; page 354 [3] http://en.wikipedia.org/wiki/Transistor [4] The Electrical Engineer, volume XXVI, number 550, November 17 1898; www.tfcbooks.com/tesla/ 1 898-1 1-1 7.htm [5] http://en.wikipedia.org/wiki/Wardenclyffe_Tower [6] http://en.wikipedia.org/wiki/ File:Lightning_simulator_questacon02.jpg [7] http://en.wikipedia.org/wiki/Tesla_coil 78 06-2012 elektor INFOTAINMENT Hexadoku Puzzle with an electronics touch If you have the odd minute to spare after reading and doing all that electronics wizardry in this edition, try solving this Hexadoku served fresh for your amusement. Enter the right numbers or letters A-F in the open boxes, find the solution in the grey boxes, send it to us and you automatically enter the prize draw for one of four Elektor Shop vouchers. The instructions for this puzzle are straightforward. Fully geared to electronics fans and programmers, the Hexadoku puzzle employs the hexadecimal range 0 through F. In the diagram composed of 16x16 boxes, enter numbers such that all hexadecimal numbers 0 through F (that’s 0-9 and A-F) occur once only in each row, once Solve Hexadoku and win! Correct solutions received from the entire Elektor readership automati- cally enter a prize draw for one Elektor Shop voucher worth £80.00 and three Elektor Shop Vouchers worth £40.00 each, which should encour- age all Elektor readers to participate. in each column and in each of the 4x4 boxes (marked by the thicker black lines). A number of clues are given in the puzzle and these determine the start situation. Correct entries received enter a draw for a main prize and three lesser prizes. All you need to do is send us the numbers in the grey boxes. Participate! Before October 1 , 201 2, send your solution (the numbers in the grey boxes) by email to: hexadoku@elektor.com Prize winners The solution of the June 201 2 Hexadoku is: 7924A. The Elektor £80.00 voucher has been awarded to Thomas Raith (Germany). The Elektor £40.00 vouchers have been awarded to Reino Anttila (Finland), Michael Evans (UK), and Nuno Tavares (Portugal. Congratulations everyone! 7 8 C 5 B F 0 1 E 9 3 6 2 D 4 A 3 A E 0 7 9 2 8 C D B 4 5 6 F 1 4 D 9 B 5 6 C E A 2 F 1 0 3 7 8 1 F 2 6 A D 3 4 0 5 7 8 E C 9 B 5 C 6 1 F A D 0 2 7 8 9 3 4 B E 8 0 D 4 C B 1 5 3 E 6 F 9 A 2 7 9 2 A 7 E 3 4 6 B C 1 5 F 0 8 D B E F 3 8 7 9 2 4 A D 0 C 1 6 5 E 4 0 8 2 C F A 5 B 9 D 6 7 1 3 A 3 5 2 D E 6 B F 1 0 7 4 8 C 9 C 7 1 F 0 4 8 9 6 3 A E D B 5 2 D 6 B 9 1 5 7 3 8 4 C 2 A E 0 F F 5 8 C 9 0 A D 7 6 E B 1 2 3 4 2 1 4 E 3 8 B C 9 0 5 A 7 F D 6 6 B 3 A 4 1 5 7 D F 2 C 8 9 E 0 0 9 7 D 6 2 E F 1 8 4 3 B 5 A C C 9 E 6 7 B C 0 A F 3 5 A 6 4 0 7 C E F 2 8 3 D A B 3 B 2 F 4 E 1 A F 3 4 0 6 B A E 2 5 D 7 A 9 0 8 B 4 A 9 8 0 F 2 9 A C B 8 1 6 E D E 5 8 2 A 4 0 F 5 F 1 6 9 D C 2 5 C 8 6 F 4 2 E B ° 1 3 2 8 1 8 2 A E 5 7 C 0 4 7 8 5 The competition is not open to employees of Elektor International Media, its business partners and/or associated publishing houses. elektor og -2012 79 ELEKTOR STORE Technology Viriceni Himpu LabWorX 2 ■v LabWorX 2 Mastering Surface Mounted Technology This book takes you on a crash course in techniques , tips and know-how to successfully introduce Surface Mounted Technology in your workflow. Even if you are on a budget you too can jumpstart your designs with advanced fine pitch parts. Besides explaining metho- dology and equipment, attention is given to parts technology and soldering technique. Several projects introduce you step by step to handling surface moun- ted parts and the required technique to successfully build SMT assemblies. Many practical tips and tricks are disclosed that bring surface mounted technology into everyone's reach without breaking the bank. Approx. 260 pages • ISBN 978-1-907920-12-7 • £29.50 • US $47.60 A whole year of Elektor magazine onto a single disk DVD Elektor 2011 The year volume DVD/CD-ROMs are among the most popular items in Elektor's product range. This DVD- ROM contains all editorial articles published in Vol- ume 2011 of the English, American, Spanish, Dutch, French and German editions of Elektor. Using the sup- plied Adobe Reader program, articles are presented in the same layout as originally found in the magazine. An extensive search machine is available to locate key- words in any article. With this DVD you can also pro- duce hard copy of PCB layouts at printer resolution, adapt PCB layouts using your favourite graphics pro- gram, zoom in / out on selected PCB areas and export circuit diagrams and illustrations to other programs. ISBN 978-90-5381-276-1 • £23.50 • US $37.90 More than 70,000 components CD Elektor's Components Database 6 This CD-ROM gives you easy access to design data for over 7,800 ICs, more than 35,600 transistors, FETs, thyristors and triacs, just under 25,000 diodes and 1,800 optocouplers. The program package con- sists of eight databanks covering ICs, transistors, di- odes and optocouplers. A further eleven applications cover the calculation of, for example, zener diode series resistors, voltage regulators, voltage dividers and AMV's. All databank applications are fully inter- active, allowing the user to add, edit and complete component data. ISBN 978-90-5381-258-7 • £24.90 • US $40.20 Elektor Linux Board Embedded Linux Made Easy Today Linux can be found running on all sorts of de- vices, even coffee machines. Many electronics enthu- siasts will be keen to use Linux as the basis of a new microcontroller project, but the apparent complexity of the operating system and the high price of de- velopment boards has been a hurdle. Here Elektor solves both these problems, with a beginners' course accompanied by a compact and inexpensive popula- ted and tested circuit board. This board includes eve- rything necessary for a modern embedded project: a USB interface, an SD card connection and various other expansion options. It is also easy to hook the board up to an Ethernet network. Populated and tested Elektor Linux Board Art.# 120026-91 • £57.80 • US $93.30 A comprehensive and practical how-to guide Design your own PC Visual Processing and Recognition System in C# This book is aimed at Engineers, Scientists and en- thusiasts with developed programming skills or with a strong interest in image processing technology on a PC. Written using Microsoft C# and utilizing ob- ject-oriented practices, this book is a comprehen- sive and practical how-to guide. The key focus is on modern image processing techniques with useful 80 09-2012 elektor BOOKS, CD-ROMs, DVDs, KITS & MODULES and practical application examples to produce high- quality image processing software. Analysis starts with a detailed review of the fundamentals of im- age processing. It progresses to explain and explore the prac tical uses of two highly sophisticated and freely downloadable, open source image processing libraries; AForge.NET and Emgu.CV, utilizing dotnet technology within the Microsoft Visual Studio envi- ronment. All code examples used are available - free of charge - from the Elektor website; you can easily create and develop your own results to demonstrate the concepts and techniques explained. 307 pages • ISBN 978-1-907920-09-7 £35.50 • US $57.30 Free Software CD-ROM included Elementary Course BASCOM-AVR The Atmel AVR family of microcontrollers are ex- tremely versatile and widely used. In Elektor maga- zine we have already published many interesting applications employing an ATmega or ATtiny micro- controller. The majority of these projects perform a particular function. In this book we focus more on the software aspects. Using lots of practical examples we show how, using BASCOM, you can quickly get your own design ideas up and running in silicon. 224 pages • ISBN 978-1-907920-11-0 £34.95 • US $56.40 Ultrasensitive wideband E-smog detector TAPIR Sniffs it Out! Attention boy scouts, professionals and grandfathers! This ultrasensitive wideband E-smog detector offers you two extra senses to track down noise that's nor- mally inaudible. TAPIR — short for Totally Archaic but Practical Interceptor of Radiation — also makes a nice project to build: the kit comprises everything you need. Even the enclosure, ingeniously consist- ing of the PCB proper! Using the TAPIR is dead easy. Connect the headphones and an antenna and switch it on. Move it around any electrical device and you'll hear different noises with each device, depending on the type and frequency of the emitted field. Kit of parts, incl. PCB Art.# 120354-71 • £13.30 • US $21.50 Circuits, ideas, tips and tricks CD 1001 Circuits This CD-ROM contains more than 1000 circuits, ide- as, tips and tricks from the Summer Circuits issues 2001-2010 of Elektor, supplemented with various other small projects, including all circuit diagrams, descriptions, component lists and full-sized layouts. The articles are grouped alphabetically in nine dif- ferent sections: audio & video, computer & micro- controller, hobby & modelling, home & garden, high frequency, power supply, robotics, test & measure- ment and of course a section miscellaneous for eve- rything that didn't fit in one of the other sections. ISBN 978-1-907920-06-6 • £34.50 • US $55.70 Package Deal: 12% off AVR Software Defined Radio This package consists of the three boards associated with the AVR Software Defined Radio articles series in Elektor, which is built around practical experiments. The first board, which includes an ATtiny2313, a 20 MHz oscillator and an R-2R DAC, will be used to make a signal generator. The second board will fish signals out of the ether. It contains all the hardware needed to make a digital software-defi ned radio (SDR), with an RS-232 interface, an LCD panel, and a 20 MHz VCXO (voltage-controlled crystal oscillator), which can be locked to a reference signal. The third board provides an active ferrite antenna. Signal Generator + Universal Receiver +Active Antenna: PCBs and all components + USB-FT232R breakout- board Art.# 100182-72 • £99.90 • US $133.00 elektor 09-2012 81 ELEKTOR STORE A professional PCB router Elektor PCB Prototyper This compact, professional PCB router can produce complete PCBs quickly and very accurately. This makes the PCB Prototyper an ideal tool for independ- ent developers, electronics labs and educational in- stitutions that need to produce prototype circuits quickly. The PCB Prototyper puts an end to waiting for boards from a PCB fabricator — you can make your own PCB the same day and get on with the job. Further information, demo video and ordering at www.elektor.com/prototyper. Art.# 100619-71 • £3,100 • US $4,900 Free mikroC compiler CD-ROM included Controller Area Network Projects The aim of the book is to teach you the basic prin- ciples of CAN networks and in addition the develop- ment of microcontroller based projects using the CAN bus. You will learn how to design microcontroller based CAN bus nodes, build a CAN bus, develop high- level programs, and then exchange data in real-time over the bus. You will also learn how to build micro- controller hardware and interface it to LEDs, LCDs, and A/D converters. 260 pages • ISBN 978-1-907920-04-2 £29.50 • US $47.60 Associated 60-piece Starter Kit available Fun with LEDs This booklet presents more than twenty exciting pro- jects covering LEDs, aimed at young & old. From an Air Writer, a Party Light, Running Lights, a LED Fader right up to a Christmas Tree. Use this book to repli- cate various projects and then put them into practice. To give you a head start each project is supported by a brief explanation, schematics and photos. In ad- dition, the free support page on the Elektor website has a few inspiring video links available that elabo- rate on the projects. A couple of projects employ the popular Arduino microcontroller board that's graced by a galaxy of open source applications. The optional 60-piece Starter Kit available with this book is a great way to get circuits built up and tested on a bread- board, i.e. without soldering. 96 pages • ISBN 978-1-907920-05-9 £16.95 • US $38.00 Bridging Android and your electronics projects AndroPod With their high-resolution touchscreens, ample com- puting power, WLAN support and telephone func- tions, Android smartphones and tablets are ideal for use as control centres in your own projects. However, up to now it has been rather difficult to connect them to exter-nal circuitry. Our AndroPod interface board, which adds a serial TTL port and an RS485 port to the picture, changes this situation. Andropod module with RS485 Extension Art.# 110405-91 • £53.35 • US $74.70 Meet BOB FT232R USB/ Serial Bridge/BOB You'll be surprised first and foremost by the size of this USB/serial converter - no larger than the mould- ed plug on a USB cable! And you're also bound to appreciate that fact that it's practical, quick to imple- ment, reusable, and multi-platform - and yet for all that, not too expensive! Maybe you don't think much of the various commercially-available FT232R-based modules. Too expensive, too bulky, badly designed, ... That's why this project got designed in the form of a breakout board (BOB). PCB, assembled and tested Art.# 110553-91 • £12.90 • US $20.90 A highly-practical guide Linux - PC-based Measurement Electronics If you want to learn how to quickly build Linux-based applications able to collect, process and display data on a PC from various analog and digital sensors, how to control circuitry attached to a computer, then even 82 09-2012 elektor BOOKS, CD-ROMs, DVDs, KITS & MODULES how to pass data via a network or control your em- bedded system wirelessly and more - then this is the book for you! The book covers both hardware and software aspects of designing typical embed- ded systems using schematics, code listings and full descriptions. 264 pages • ISBN 978-1-907920-03-5 £29.50 • US $47.60 110 issues, more than 2,100 articles DVD Elektor 1990 through 1999 This DVD-ROM contains the full range of 1990-1999 volumes (all 110 issues) of Elektor Electronics maga- zine (PDF). The more than 2,100 separate articles have been classified chronologically by their dates of publication (month/year), but are also listed alpha- betically by topic. A comprehensive index enables you to search the entire DVD. What's more, this DVD also contains the entire 'The Elektor Datasheet Col- lection 1... 5' CD-ROM series. ISBN 978-0-905705-76-7 • £69.00 • US $111.30 Processor design in the real world Microprocessor Design using Verilog HDL If you have the right tools, designing a microproces- sor shouldn't be complicated. The Verilog hardware description language (HDL) is one such tool. This book is a practical guide to processor design in the real world. It presents the Verilog HDL in an easi- ly digestible fashion and serves as a thorough introduction about reducing a computer archi- tecture and instruction set to practice. You're led through the microprocessor design pro- cess from the start to finish, and essential topics ranging from writing in Verilog to debugging and testing are laid bare. 340 pages • ISBN 978-0-9630133-5-4 £27.90 • US $45.00 Dual-layer DVD: 165 mins, video DVD Modern Valve Electronics This filmed seminar (presented by Menno van der Veen) starts with a short discussion of the classic ap- proach using valve load line graphs, followed by cur- rent sources and current foldback techniques. Next, the negative effect of cathode electrolytics is covered as well as reducing supply voltage interference. With the help of state of the art measurement techniques the (in)correctness of feedback is proven, while also clarifying what's happening deep within the core of the output transformer. ISBN 978-1-907920-10-3 • £24.90 • US $40.20 Improved Radiation Meter This device can be used with different sensors to meas- ure gamma and alpha radiation. It is particularly suit- able for long-term measurements and for examining weakly radio-active samples. The photodiode has a smaller sensitive area than a Geiger-Muller tube and so has a lower background count rate, which in turn means that the radiation from a small sample is easier to de- tect against the background. A further advantage of a semiconductor sensor is that is offers the possibility of measuring the energy of each particle. Kit of parts incl. display and programmed controller Art.# 110538-71 • £35.50 • $57.30 More information on the Elektor Website: www.elektor.com /store Elektor Regus Brentford - 1000 Great West Road Brentford - TW8 9HH - United Kingdom Tel.: +44 20 8261 4509 Fax: +44 20 8261 4447 Email: order@elektor.com 3ektor elektor 09-2012 83 COMING ATTRACTIONS NEXT MONTH IN ELEKTOR Transconductance Amplifier Although Analog Devices’ type AD844 opamp is primarily designed for current-feedback applications, its special structure makes it also very suitable for alternative possibilities in the field of controlled sources. For example, it allows a voltage controlled current source to be designed with ease, for use in measurement technology. Next month we will describe the operation of the AD844 and the construction of an instrumentation amplifier around this opamp. Cool! 7805 Drop-in The 7805 is unquestionably the most widely used fixed voltage regulator. Unfortunately this golden oldie has a habit of turning all the excess energy into heat. Wouldn’t it be nice to have a switching power supply controller as a drop-in replacement for the 7805? The switched device is sure to offer much higher efficiency as well as better specifications. In the Elektor labs, a small printed circuit board was designed around a TPS62150 buck con- verter capable ofturning an input voltage of 5. 5 to 17 V into a 5 Vstabilised rail at up toi A. By adjusting a number of resistance values other output voltages are also possible. Extensions for Elektor Improved Radiation Meter The radiation meter from Elektor November 2011 is used by many readers. The circuit is especially useful in studies of weak radioactive substances and measurements overtime. The microcontroller in this circuit has a bootloader, so the program can easily be tweaked. Next month we will discuss some possible adaptations. In addition, we describe some hardware changes to enable the measuring range to be extended. Article titles and magazine contents subject to change; please check the Magazine tab on www.elektor.com Elektor UK/European October 2012 edition on sale September 20, 2012. Elektor USA October 2012 edition published September ry, 2012. w.elektor.com www.elektor.com www.elektor.com www.elektor.com www.elektor.com wv Elektor on the web All magazine articles back to volume 2000 are available individually in pdf format against e-credits. Article summaries and compo- nent lists (if applicable) can be instantly viewed to help you positively identify an article. Article related items and resources are also shown, including software downloads, hyperlinks, circuit boards, programmed ICs and corrections and updates if applicable. In the Elektor Shop you’ll find all other products sold by the publishers, like CD-ROMs, DVDs, kits, modules, equipment, tools and books. A powerful search function allows you to search for items and references across the entire website. Glektor Fcnura- PiOdUCU vO 1 hra^=£Pii. V ' +-LF 7 . BM- Also on the Elektor website: • Electronics news and Elektor announcements • Readers Forum • PCB, software and e-magazine downloads • Time limited offers • FAQ, Author Guidelines and Contact | -Unsu 4 V>' u> iiir Smmjir Stf Cot l|*(i Fit H£«OD •’ifB i*V$I ItTi --tT-l fi^rw q-rffrcr « Vw Cr*-L"i*i Hifed! Mir Mil h’.-i trr iCit Kr" Ccmkng AflndUora FREE WFRIhJAR Crrb* S-diMf Unm M nd „- », K-II Ltt-Cfl *CT) litUi 'flour >!fP l iiiit ?|pr - “ J J1W Ml*, OlSf CUM 1 iral qci; thr** ir-riri&fctfv-jiii*] muh 'v jue Si.w | ClEitor .'iinba f dittan 20 3 2 | e VJH ■ y .*■ , ' : A PM-ril Inin - , Lip Te-sl Des.iqn M^ikCr ■■■ » rrrof r5vi r»-ii ialpu Mil'll ■ blllCtiri 84 og-20i2e lektor ORDERING INSTRUCTIONS, P&P CHARGES Non-online orders, except for memberships (for which see below), must be sent BY POST or FAX to Elektor International Media, 78 York Street, London W1 H 1 DP, United Kingdom. Online ordering: www.elektor.com/store Orders placed on our London office must include P&P charges (Priority or Standard) as follows: Europe: £6.00 (Standard) or £7.00 (Priority). Outside Europe: £9.00 (Standard) or £1 1 .00 (Priority) HOW TO PAY All orders must be accompanied by the full payment, including postage and packing charges as stated above or advised by Customer Services staff. Bank transfer into account no. 4027021 1 held by Elektor International Media BV with The Royal Bank of Scotland, London. IBAN: GB96 ABNA 4050 3040 2702 1 1 . BIC: ABNAGB2L. Currency: sterling (UKP). Please ensure your full name and address gets communicated to us. Cheque sent by post, made payable to Elektor Electronics. We can only accept sterling cheques and bank drafts from UK-resident customers or members. We regret that no cheques can be accepted from customers or members in any other country. Credit card VISA and MasterCard can be processed by mail, email, web, fax and telephone. Online ordering through our website is SSL-protected for your security. COMPONENTS If difficulties are envisaged in the supply of components for Elektor projects, a source will normally be advised in the article. Note, however, that the source(s) given is (are) not exclusive. TERMS OF BUSINESS Delivery Although every effort will be made to dispatch your order within 2-3 weeks from receipt of your instructions, we can not guarantee this time scale for all orders. Returns Faulty goods or goods sent in error may be returned for replacement or refund, but not before obtaining our consent. All goods returned should be packed securely in a padded bag or box, enclosing a covering letter stating the dispatch note number. If the goods are returned because of a mistake on our part, we will refund the return postage. Damaged goods Claims for damaged goods must be received at our London office within 1 0 days (UK); 1 4 days (Europe) or 21 days (all other countries). Cancelled orders All cancelled orders will be subject to a 1 0% handling charge with a minimum charge of £5.00. Patents Patent protection may exist in respect of circuits, devices, components, and so on, described in our books and magazines. Elektor does not accept responsibility or liability for failing to identify such patent or other protection. Copyright All drawings, photographs, articles, printed circuit boards, programmed integrated circuits, diskettes and software carriers published in our books and magazines (other than in third-party adverti-sements) are copyright and may not be reproduced or transmitted in any form or by any means, including photocopying and recording, in whole or in part, without the prior permission of Elektor in writing. Such written permission must also be obtained before any part of these publications is stored in a retrieval system of any nature. Notwithstanding the above, printed circuit boards may be produced for private and personal use without prior permission. Limitation of liability Elektor shall not be liable in contract, tort, or otherwise, for any loss or damage suffered by the purchaser whatsoever or howsoever arising out of, or in connexion with, the supply of goods or services by Elektor other than to supply goods as described or, at the option of Elektor, to refund the purchaser any money paid in respect of the goods. Law Any question relating to the supply of goods and services by Elektor shall be determined in all respects by the laws of England. August 201 2 MEMBERSHIP RATES FOR ANNUAL MEMBERSHIP Standard Plus United Kingdom & Ireland £54.00 £66.50 Surface Mail Rest of the World £68.50 £81.00 Airmail Rest of the World £86.00 £98.50 USA & Canada See www.elektor.com/usa for special offers HOW TO PAY Bank transfer into account no. 4027021 1 held by Elektor International Media BVwith The Royal Bank of Scotland, London. IBAN: GB96 ABNA 4050 3040 2702 1 1 . BIC: ABNAGB2L. Currency: sterling (UKP). Please ensure your full name and address gets communicated to us. Cheque sent by post, made payable to Elektor Electronics. We can only accept sterling cheques and bank drafts from UK-resident customers or members. We regret that no cheques can be accepted from customers or members in any other country. Credit card VISA and MasterCard can be processed by mail, email, web, fax and telephone. Online ordering through www.elektor.com/store is SSL- protected for your security. MEMBERSHIP CONDITIONS The standard membership order period is twelve months. If a permanent change of address during the membership period means that copies have to be despatched by a more expensive service, no extra charge will be made. Conversely, no refund will be made, nor expiry date extended, if a change of address allows the use of a cheaper service. Student applications, which qualify for a 20% (twenty per cent) reduction in current rates, must be supported by evidence of studentship signed by the head of the college, school or university faculty. A standard Student Membership costs £43.20, a Student Plus Membership costs £55.70 (UK only). Please note that new memberships take about four weeks from receipt of order to become effective. Cancelled memberships will be subject to a charge of 25% (twenty-five per cent) of the full membership price or £7.50, whichever is the higher, plus the cost of any issues already dispatched. Memberships cannot be cancelled after they have run for six months or more. elektor og-2012 85 w w w . e I e kto r- p roj ects . co m Sharing Electronics Projects Last update 19/07 I PIC32 Sound Pad Last update 13/07 | 4 memb* views Monitoring d aeromodeles ANDROID Utihser un telephone Android e pour... Last update 11/07 | 1 me Elektor RS485 Bus- Fullstandsmessung / r Messung des Fullstandes mittels... Last update 09/07 Hang Tux Presentation : This Last update;, ; 7 2 members --i—^on Automatic license plate recognition (ALPR) a simple Last update 05/07 members | Speed Projecting Display for Simple circuit that will project the speed... Horloge du bureau a tubes - Bfi classiques Connaissez-vous les "Nuirntrons ? Ces J- H incandescents a 7 segments sont utilise une horloge de bureau avec un... 1 Numitron desktop clock - Using only c >V I 4| DO YOU know “Numitrons"? Those incan u. iiKc are used here to make a 6 igi s “ L <£ 3 / Q 5 views Switched 7805 A small PCB the si z containing,.. rapide pour circuits analogiques tester rapidement des circuits a base hnmplq (filtres, oscillateurs Le I carte de prototypage I lineaires | Cette carte permet de d amplificateurs opera circuit imprime... 8 J efficient solenoid valve We have in our house a r ■ filtering the tap-water up fills a little reservoir of... ■sam -ZT Displayless WLAN Speaker with We W'W*. " ‘ WLAN Speaker for everywhere usage shelf. Configure it with a Web-Browser or a Smartphon. Radio Station, the... Elektor Projects is an online community for people passionate about electronics. Here you can share your projects and participate in those created by others. It's a place where you can discuss project development and electronics. Elektor's team of editors and engineers assist you to bring your projects to a good end. They can help you write an article to be published in Elektor maga- zine or even develop a complete product that you can sell in the Elektor Shop! Vote for your Favorite Proposal Get elektorized too! Check www.elektor-proiects.com □ ..Il- r :■ CiipiiuihrYii 'TiJUL-M Personal Amp An O for Low-Power Applications Mesh Networking WhvI^ (lie SNAP OS An ExfiminiiliPii of Parolid CepaciSsra Slgjrni-(WftJi ModrtVon. Explained ANALOG TE Artftiog Signnil Man,-i fi Sound Tone Defoes MCU-Bawd Auditor; Navigalion System Engineer an Ajternal to Joystick Control Electronics Design - PfiXtSSOrfi, P&WW, & Interfacing A L-»k Insickt an C lonczatior De-lfrJlcrR Diode OR Un intern. MOSFET Resistan PROGRAMMABLE I MCU-Bescd Slccp^t^^c Analysis DIY Sm-art Elecifronic Load Design Embedded Linux Sysl^m PIAHnrm* I'-ilurferflnev lmiFi|jnity fw Electronic Designs Joystick ConlrOf w.lh Bluetooth Connectivity MCU-Based Automatic Blood Pressure Cuff Coficufr^ntif 101 Gw .urrency In £ •vOrdnn'j 9s. Tilrnrt i'. 1 Genu™*! Cancuruncy PiMi ' F'riri.(:rilLn^ Pnqrrty Inwoman h Y.in.iLpinij 5?cqulri?inrrtti ■i And Mere SAVE 50% SPECIAL: SAVE 50% Celebrate Circuit Cellar’s 25 th Anniversary PROJECT Huw «, Bind At, AC T«J»| ItTE nV.F* Ih&JUfftf CunU'-.Jl {IIJillMMI HIV Kmi«t-ELn»4irTi(j»Pi«tiB. \j LOCATION UntotfSWM kOCATOt Cfrwtt LOCATION* Spain PACE U V PAGE- M pAbE Jt EMBEDDED ELECTRONICS ENGINEERING ENFQI ICATIONS Smart Swil & Control i Radio Fre< $25 Print or Digital :: $50 Combo Celebrate Circuit Cellar’s 25th year of bringing readers insightful analysis of embedded electronics technology. Visit www.circuitcellar.com/el912 to take advantage of these great deals. >IMUS OFFER! BONUS OFFER! BONUS OFFER! BBB Sign up today and you’ll also receive the Special 25» Anniversary Edition with your subscription* CIRCUIT CELLAR YEARS OF EMBEDDED INSIGHT ROUTE FASTER ! jjj] * — — 1 ■* t -mm- mma 'nr- K M v v* : : i "j * K< *_ ,juL VlVOil 4 'lKl ! • WITH PROTEUS PCB DESIGN Our completely new manual router makes placing tracks quick and intuitive. During track placement the route will follow the mouse wherever possible and will intelligently move around obstacles while obeying the design rules. All versions of Proteus also include an integrated world class shape based auto-router as standard. PROTEUS DESIGN SUITE ■ Hardware Accelerated Performance. ■ Unique Thru-View™ Board Transparency. ■ Over 35k Schematic & PCB library parts. ■ Integrated Shape Based Auto-router. ■ Flexible Design Rule Management. ■ Polygonal and Split Power Plane Support. Features: ■ Board Autoplacement & Gateswap Optimiser. ■ Direct CADCAM, ODB++, IDF & PDF Output. ■ Integrated 3D Viewer with 3DS and DXF export. ■ Mixed Mode SPICE Simulation Engine. ■ Co-Simulation of PIC, AVR, 8051 and ARM7. ■ Direct Technical Support at no additional cost. Prices start from just £150 exc. VAT & delivery Electronics Labcenter Electronics Ltd. 53-55 Main Street, Grassington, North Yorks. BD23 5AA. Registered in England 4692454 Tel: +44 (0)1756 753440, Email: info@labcenter.com Visit our website or phone 01756 753440 for more details