Professional Documents
Culture Documents
MARCH 2006
£3.80
www.elektor-electronics.co.uk
™xHRKCQIy451 28zv+:.
Call or log on to our website and apply for a FREE
400 page catalogue. You can purchase on the Net
from us 24/7/365 through our secure encrypted
system. Post and packing charges are modest and
you can have any of 8000+ unique products
delivered to your door within
Choke A Chicken Smart Card Reader/ 7-10 days of your order.
GT-3095 £8.50 + post & packing Programmer Kit
Relieve stress with a bit of KC-5361 £15.95 + post & packing
violence! This annoying chicken Jaycar has noticed a substantial increase in sales of
dances around and squawks. the KC-5361 Smart Card Programmer Kit &
Funny for about one second! ZZ-8800 Programmable Gold Wafer Card. We
Grab him by the throat and strongly suspect that this maybe due to persons
he screams and gags. unknown some how using these products to make
Funny forever! (not unlawfully generated access codes for the latest
recommended for cable T.V. set top boxes. We also wish to advise
children). Approx 12” that we discourage this activity. For those
tall. Requires 4 x AA legitimate users, the KC-5361
batteries (not incl.) Programmer Kit £15.95 &
ZZ-8800 Smart Card £3.85
"Clock Watcher’s" LED Clock Kits
KC-5416(blue) £55.25 + post & packing
are back in stock.
KC-5404(red) £41.35 + post & packing
Once again please be
These clocks are hypnotic!
Theremin Synthesiser Kit reminded that we cannot
They consist of an AVR driven clock circuit, that also
KC-5295 £14.75 + post & packing accept any responsibility for
produces a dazzling display with the 60 LEDs around the
the use of these devices in
perimeter. It looks amazing, but can't be properly explained
other than legitimate
here. We have filmed it in action so you can see for yourself
The Theremin is activities.
on our website www.jaycarelectonics.com! Kit supplied with
a weird musical double sided silkcreened plated through hole PCB and all
instrument that was board components
invented early Wafer Card as well as the
last century ZZ-8800 £3.85 + post & packing
This is a multi-chip 'smart card' based special clock
but is still housing!
used today. on the PIC 16F84A and is coupled
with a 24LC16B EEPROM, Available
The Beach in Blue
Boys' classic compatible with most
reader/programmer units (KC-5416) and
hit "Good Red (KC-5404).
Vibrations" featured available including the
aTheremin. By moving you hand programmer above.
between the antenna and the metal
plate, you can create strange sound High Performance Electronic Projects for Cars
effects. Kit includes a machined, silk BS-5080 £7.00 + post & packing
screened, and pre drilled case, circuit Australia's leading electronics magazine Silicon Chip, has developed a range of projects for performance
board, all electronic components, and cars. There are 16 projects in total, ranging from devices for remapping fuel curves, to nitrous controllers.
clear English instructions. The book includes all instructions, components lists, color pictures, and circuit layouts. There are also
chapters on engine management, advanced systems and DIY modifications. Over 150 pages! All the
We Stock...
Electronic Components,
projects are available in kit form.
High Range Adjustable
Sub-Assemblies & Electronic Kits Smart Fuel Mixture Display Temperature Switch with LCD
KC-5374 £8.95 + post & packing KC-5376 £22.75 + post & packing
Power Products This new ‘smart’ version has a few additional touches Heat can be a major problem with
& Accessories such as, auto dimming for night driving, emergency any car, especially modified and
lean-out alarm, and better circuit protection. Another performance cars. The more power,
Audio & Visual Equipment great feature, is the ‘dancing’ display which operates the more heat, so you need to
& Accessories when the ECU is operating in closed loop. Kit supplied ensure you have adequate cooling
Computer & Telecoms with PCB and all electronic components. systems in place. This temperature
Accessories • Car must be fitted with air flow switch can be set anywhere up to r
Ideal fo aust &
h
and EGO sensors (standard 2192°F, so it is extremely versatile. The ring ex
Burglar Alarms & monito mperature -
on all EFI systems) relay can be used to trigger an extra te
Surveillance Equipment brake RANG
E!
for full thermo fan on an intercooler, mount a sensor 2192°F
Lighting Products functionality. near your turbo manifold and trigger water spray
& Accessories cooling, or a simple buzzer or light to warn you of a
Recommended box high temperature. The LCD displays the temperature
Gadgets & Unique Gifts HB-6014 £1.40 each all the time, which can easily be dash mounted.
16
established in electronics to the extent that
only rank beginners would surmise the
existence of microhertz frequencies and
megafarad capacitances. Sure, these
exist in theory but no-one’s ever seen the Until recently, FPGAs were
equipment or capacitor to match.
practically reserved for
Although it’s not necessary right now to
burn your maths textbooks, recently the
specialists in high-tech
distance between micro and mega has companies. That’s all
dwindled and in fact both prefixes can changed now thanks to low
now be said to co-exist happily in two component prices and free
species of electronic component. The
design software, so it’s high
main subjects of this month’s issue,
microcontrollers and FPGAs, execute time to devote attention to
microinstructions from megabytes of this technology in Elektor
memory, not forgetting nanosecond sig- Electronics. The FPGA
nal setup times and several kilobits a sec-
module discussed in this
ond worth of data traffic on serial lines.
If you thought that the microcontroller
article forms the core of
was the next and perhaps final step in various upcoming projects
an evolutionary process that started with in the magazine.
the valve and went by way of the tran-
sistor and the integrated circuit, buckle
E M A
up for FPGAs. To illustrate the scale at
which we need to think now, some Versatile SC H
FPGAs are powerful enough to mimic a
N FO LD
vintage 6502 microprocessor including
O
its exact pin functionality, and still have
room to spare for ‘side activities’ like
serial interfacing and memory flashing.
FPGA Module
Readers tell us that they find FPGAs
impressive and even awe-inspiring, but
also off putting not just for design com-
plexity but mostly ‘solderability’!
Here at Elektor Electronics we’re not in Free C Booklet
the least afraid to deal with the latest in
FPGA and microcontroller land, witness
our Versatile FPGA Module, FPGA Pro-
totyping Board and Renesas R8C/13
This issue comes with a free 24-
Motherboard. Let the professionals do
the soldering — in all three cases we
page introduction to C pro-
supply the boards with all the dreaded gramming. The booklet is not
SMDs, BGAs and TQFPs and what have only a runway to an industry-
you ready fitted, so you can concentrate standard programming lan-
on the real thing: programming and guage, but also a prelude
developing turnkey applications with to articles on C for our
maximum intelligence and an absolute
low-cost R8C Starter Kit.
minimum of components. I wouldn’t say
wielding a full-blown FPGA or R8C
development system is a micro effort at
a nano investment but you can be cer-
tain of mega results. Glad to help you.
Jan Buiting
Editor
CONTENTS Volume 32
March 2006
no. 352
hands-on
16 Versatile FPGA Module
20 FPGA Prototyping Board
38 Application Board for R8C/13
46 Cheap Logger
54 A real µC PLC
62 Telephone Eavesdropper
72 Design Tips
Energy recovery
FBI siren with flashing light
Energy saver for relays
We devote attention to interesting but affordable
kits where we not only look at kits that are suitable Opamp with increased output current
for a commercial environment but which are also
ATICS
very interesting for hobby use.
technology
DOUT!
50 Travel Charger
58 E-blocks Making Waves
infotainment
34 The Triumphant March
of the 6502
77 Retronics:
Elektor Plotters (1988-1991)
79 Hexadoku (3)
Subscriptions: Elektor Electronics (Publishing),
Regus Brentford, 1000 Great West Road, Brentford TW8 9HH, England.
Tel. (+44) (0) 208 261 4509, fax: (+44) (0) 208 261 4447
Internet: www.elektor-electronics.co.uk
Email: subscriptions@elektor-electronics.co.uk
Rates and terms are given on the Subscription Order Form
Volume 32, Number 352, March 2005 ISSN 0268/4519 Head Office: Segment b.v. P.O. Box 75 NL-6190-AB Beek The Netherlands
Telephone: (+31) 46 4389444, Fax: (+31) 46 4370161
Elektor Electronics aims at inspiring people to master electronics at any person-
Distribution: Seymour, 86 Newman Street, London W1P 3LD, England
al level by presenting construction projects and spotting developments in elec-
tronics and information technology. UK Advertising: Huson International Media, Cambridge House, Gogmore Lane,
Chertsey, Surrey KT16 9AP, England.
Publishers: Elektor Electronics (Publishing), Regus Brentford, 1000 Great West Road, Telephone: +44 (0)1932 564999, Fax: +44 (0)1932 564998
Brentford TW8 9HH, England. Tel. (+44) (0) 208 261 4509, fax: (+44) (0) 208 261 4447 Email: r.elgar@husonmedia.com
www.elektor-electronics.co.uk. Internet: www.husonmedia.com
Advertising rates and terms available on request.
The magazine is available from newsagents, bookshops and electronics retail outlets, or on sub- International Advertising: Klaas Caldenhoven, address as Head Office
scription. Elektor Electronics is published 11 times a year with a double issue for July & August. Email: advertenties@elektuur.nl
Advertising rates and terms available on request.
Under the name Elektor and Elektuur, the magazine is also published in French, German and
Dutch. Together with franchised editions the magazine is on circulation in more than 50 countries. Copyright Notice
The circuits described in this magazine are for domestic use only. All drawings, photographs, printed circuit
International Editor: Mat Heffels (m.heffels@segment.nl) board layouts, programmed integrated circuits, disks, CD-ROMs, software carriers and article texts pub-
lished in our books and magazines (other than third-party advertisements) are copyright Segment. b.v. and
Editor: Jan Buiting (editor@elektor-electronics.co.uk) may not be reproduced or transmitted in any form or by any means, including photocopying, scanning an
recording, in whole or in part without prior written permission from the Publishers. Such written permis-
International editorial staff: Harry Baggen, Thijs Beckers, Ernst Krempelsauer, sion must also be obtained before any part of this publication is stored in a retrieval system of any nature.
Jens Nickel, Guy Raedersdorf. Patent protection may exist in respect of circuits, devices, components etc. described in this magazine. The
Publisher does not accept responsibility for failing to identify such patent(s) or other protection.
Design staff: Ton Giesberts, Paul Goossens, Luc Lemmens, Karel Walraven The submission of designs or articles implies permission to the Publishers to alter the text and design, and
to use the contents in other Segment publications and activities. The Publishers cannot guarantee to return
Editorial secretariat: Hedwig Hennekens (secretariaat@segment.nl) any material submitted to them.
Marketing: Margriet Debeij (m.debeij@segment.nl) © Segment b.v. 2006 Printed in the Netherlands
Elektor 2005
New
CD-ROM
This CD-ROM contains all editorial
articles, with the exception of New All articles in
Products items, published in Elektor Elektor Electronics
Electronics magazine Volume 2005.
Volume 2005 on CD-ROM
Using the supplied Acrobat Reader
program, articles are presented in Order now using the Order Form
the same layout as originally found in the magazine. in the Readers Services section
in this issue.
The DiskMirror utility on this CD-ROM allows your earlier Elektor
year volume CD-ROMs (1997-2004) to be added to a large archive Elektor Electronics (Publishing)
Regus Brentford
on hard disk for fast access and easy reference.
1000 Great West Road
A built-in search function allows you to find references in any article Brentford TW8 9HH
from the archive on hard disk, or from individual year volume United Kingdom
CD-ROMs you have available. Tel. +44 (0) 208 261 4509
See also
www.elektor-electronics.co.uk
IHDWXUHGSURGXFWV
$IIRUGDEOH&$1%XV6ROXWLRQV
&$186%LVDYHU\VPDOOGRQJOHWKDWSOXJVLQWRDQ\3&86%3RUW
DQGJLYHVDQLQVWDQW&$1FRQQHFWLYLW\7KLVPHDQVLWFDQEHWUHDWHG
E\VRIWZDUHDVDVWDQGDUG&203RUWVHULDO56SRUWZKLFK
HOLPLQDWHVWKHQHHGIRUDQ\H[WUDGULYHUVRUE\LQVWDOOLQJDGLUHFW
GULYHU'//IRUIDVWHUFRPPXQLFDWLRQVDQGKLJKHU&$1EXVORDGV
&$1LVDYHU\VPDOOGRQJOHWKDWSOXJVLQWRDQ\3&&203RUWRU
DQ\RWKHU56SRUWLQDQHPEHGGHGV\VWHPDQGJLYHVDQLQVWDQW
&$1FRQQHFWLYLW\7KLVPHDQVLWFDQEHWUHDWHGE\VRIWZDUHDVD
VWDQGDUG&203RUWVHULDO56SRUWZKLFKHOLPLQDWHVWKHQHHG
IRUDQ\H[WUDGULYHUV6HQGLQJDQGUHFHLYLQJFDQEHGRQHLQVWDQGDUG
&$186% &$1 $6&,,IRUPDW
DIIRUGDEOH&$1%XVWR86%DQG56
LQWHUIDFHVROXWLRQV SULFHGIURP
&$1
%URQ]H3UL]H:LQQHU
1$6$7HFK%ULHIV 86%,QVWUXPHQWV3&2VFLOORVFRSHV /RJLF$QDO\]HUV
3URGXFWVRIWKH<HDU
2XUUDQJHRI3&,QVWUXPHQWVPD\EHEXGJHWSULFHGEXWKDYH
DZHDOWKRIIHDWXUHVQRUPDOO\RQO\IRXQGLQPRUHH[SHQVLYH
LQVWUXPHQWDWLRQ2XU'60DQG360RVFLOORVFRSHVKDYH
VRSKLVWLFDWHGGLJLWDOWULJJHULQJLQFOXGLQJGHOD\HGWLPHEDVHDQGFRPH
ZLWKRXU(DV\6FRSHRVFLOORVFRSHVSHFWUXPDQDO\]HUYROWDJH
DQGIUHTXHQF\GLVSOD\DSSOLFDWLRQVRIWZDUHDQGRXU(DV\/RJJHU
GDWDORJJLQJVRIWZDUH:HDOVRSURYLGH:LQGRZV'//VDQGFRGH
H[DPSOHVIRUUGSDUW\VRIWZDUHLQWHUIDFLQJWRRXUVFRSHV
'6086%6FRSH/RJJHU 2XU$17DQG$17/RJLF$QDO\]HUVIHDWXUHFDSWXUHFKDQQHOV
[06V,QSXW&KDQQHOVZDYHIRUP RIGDWDDWDEOD]LQJ066VDPSOHUDWHLQDFRPSDFWHQFORVXUH
JHQHUDWRURXWSXW(DV\6FRSH (DV\/RJJHUVZ
LQFOXGHG SULFHGIURP
'60 $17
WRSRUW86%WR6HULDO$GDSWHUV
:LWKRYHUGLIIHUHQWPRGHOVDYDLODEOHZHSUREDEO\VWRFNWKH
ZLGHVWUDQJHRI86%6HULDO$GDSWHUVDYDLODEOHDQ\ZKHUH:HRIIHU
FRQYHUWHUFDEOHVPXOWLSRUWHQFORVXUHVW\OHPRGHOVLQPHWDODQG
SODVWLFDOVRUDFNPRXQWXQLWVZLWKLQWHJUDO368VXFKDVWKH86%
&20506HULDOLQWHUIDFHVVXSSRUWHGLQFOXGH5656DQG
56:HDOVRVXSSO\RSWRLVRODWHG56DQG56YHUVLRQVIRU
UHODLEOHORQJGLVWDQFHFRPPXQLFDWLRQV$OORXU86%6HULDOSURGXFWV
DUHEDVHGRQWKHSUHPLXPFKLSVHWVDQGGULYHUVIURP)7',&KLSIRU
86%&200 VXSHULRUFRPSDWLELOLW\SHUIRUPDQFHDQGWHFKQLFDOVXSSRUWDFURVV
3RUW,QGXVWULDO86%566HULDOZLWKZDOO :LQGRZV0$&26&(DQG/LQX[SODWIRUPV
PRXQWEUDFNHWDQG'&DX[LOLDU\RXWSXW SULFHGIURP
86%/&
/RZ3UR¿OH9HUVLRQ
DOVRDYDLODEOH 83&,6HULDO&DUGV
'LVFRYHURXUJUHDWYDOXHIRUPRQH\UDQJHRIPXOWLSRUW83&,VHULDO
FDUGV6XSSRUWLQJIURPWZRWRHLJKWSRUWVWKHUDQJHLQFOXGHV56
5656DQGRSWRLVRODWHGYHUVLRQV2XUSRUWDQGSRUW
PRGHOVFDQFRQQHFWWKURXJKH[WHUQDOFDEOHVRUWKHLQQRYDWLYHZDOO
PRXQWLQJ&20%2;
SULFHGIURP
83&,/
83&,+6 (DV\6\QF/WG
6FRWODQG6WUHHW
3RUW83&,566HULDO&DUGZLWK6SLGHU
&DEOHRU&20%2;,2H[WUD *ODVJRZ*4%8.
7HO)D[
:HEKWWSZZZHDV\V\QFFRXN
(0DLOVDOHV#HDV\V\QFFRXN
3ULFHVVKRZQH[FOXGHFDUULDJHDQG9$7ZKHUHDSSOLFDEOH
7
INFO & MARKET MAILBOX
Retronics
on multimeters (3)
Dear Sir — I enjoyed very
much Jan Buiting’s article on
analogue multimeters
(‘Retronics’, December 2005,
Ed.). I myself own an excel-
lent BBC Goerz Unigor A43
analogue multimeter that I
bought at a flea market. It
has a DC sensitivity of
100 kohms/volt and its low-
est DC current scale is 10
microAmperes.
In addition to the advantages
of analogue over digital
meters mentioned in the arti-
cle, I would like to call your Battery backup for bike connected battery ground to spot that our Hexadokus can be
attention to another one men- — help please dynamo ground. downloaded free of charge from
tioned by Robert A. Pease in (Mailbox December 2005 Unfortunately, Maplin no our website. Here’s some com-
his book Troubleshooting issue refers, Ed.) longer sell p-type MOSFETs so ment we got from you:
Analog Circuits. On page 17 Dear Editor — I have got my I could not build this circuit.
he says: dynamo backup circuit to I have also enclosed a photo “A great opportunity for us
work: a voltage doubling rec- of the finished unit. The han- lesser gods in electronics to
tifier solved the problem dlebar bracket is a Minoura win a prize”.
caused by the half-wave recti- battery lamp extension (long) “Can we have a microcon-
fier’s series capacitor. minus the lamp tube. troller version of it please.”
Alan Bradley (UK) “Took me two days to solve
I enclose the corrected but I think I have the solution.”
schematic. Note that the DC That’s a happy ending then Alan, “What a wonderful idea this
isolator capacitors are mount- congratulations on getting your Hexadoku; just what I would
ed separately beside the circuit to work. We also thank expect from Elektor.”
dynamo, whereas the circuit those readers who have written “I just love Sudokus and was
is mounted at the other end with suggestions to help Alan find hooked the moment my hus-
of the bike (near the battery (and solve) the problem. He also band showed your hexadeci-
pouch). informed us that he has further mal variety. It’s addictive and
The battery is also used for information available on the crazing. And tough, too.”
extra lamp(s) such as a turn migration of the circuit to FETs. “The normal 9x9 Sudoku was
indicator. starting to bore me. Your hex
The circuit seems to take variety got my grey matter
3 mA from battery when milling over numbers again.”
“Another advantage of ana- switched over to dynamo but Hexadokus “A great puzzle. I was
log meters is that they are even if that’s just noise While compiling this month’s already hooked on Sudokus
passive devices: They don’t picked up by the meter, I can Mailbox pages, we’re inundated but yours is even worse!”
inject noise into your circuit live with it. with solutions to our first and “Cost me one pencil and a
as digital meters can — even I found the free Linear second ‘Hexadoku’ puzzles rubber to solve;
battery powered ones. And Technology LTSpice program published in the January
they have a lot less capaci- very useful. and February 2006 issue.
tance to ground”. Apparently, we succeeded
Mr. Pease is referring to the An alternative circuit (simulat- in adding a lighter note to
noise generated inside digital ed with LTSpice) replaced the high-brow electronics stuff
meters by the A/D conver- optoisolator and BJT with a that normally fills our
sion process, of course. logic-level p-channel MOSFET pages. We were both
Congratulations Jan for your (protected by a zener), and pleased and surprised to
interesting article. see that a good number
Carlos Urbina Pacheco of correct solutions
(Mexico) were sent by family
members of our read-
Thanks for the compliment Car- ers. A number of
los, as they say, “it makes a wel- solutions reached us
come change from being at the by regular post
wrong end of the customer com- (thank you all for
plaints line”. The photograph using our new
shows an Unigor 4S meter from address). Readers
my collection. were also quick to
next one, please!” Visual Basic Course Windows 2000. the booklet will also run using
“Took a bit longer than the Dear Elektor people — I was Unfortunately, my PC has older versions of Visual Basic, but
decimal ones!” thrilled to see the free Visual Windows 98. Does this these, alas, are not free. Maybe
“Nice puzzle; blood, sweat Basic course booklet with the mean I am unable to pro- you should start looking for an
and beer!” January 2006 issue. A fan- ceed? I was unable to find a older VB version someone is will-
“Could not put it down and tastic initiative, thank you Mr ‘minimum requirements’ list in ing to sell at a low price.
got off the wrong subway sta- Petros Kronis and Elektor for your booklet.
tion.” your efforts! Jose Qvik (Netherlands)
“A most enjoyable distrac- When I wanted to download
tion, I will look forward to Visual Basic Express edition The big advantage of the latest PIC programming
more of these puzzles in the 2005 I got a message saying version of Visual Basic is that it’s Dear Editor and lab staff — I
future.” the product required free. Most programs discussed in am looking for a handbook
Advertisement
SRROLQJIRUVWDQGDUGERDUGV
<RXUSULFHFRQVFLRXV3&%VXSSOLHU 9HULILHG XSWROD\HUV
IURPWRSLHFHV
IURPZRUNLQJGD\VRQZDUGV
2QOLQHSULFHFDOFXODWLRQ
2QOLQHRUGHULQJ WHFKQRORJ\DWWKHULJKWSULFH
2QOLQHRUGHUWUDFNLQJ jODFDUWH XSWROD\HUV
2QOLQH+DQG' IURPWRSLHFHV
IURPZRUNLQJGD\VRQZDUGV
,QWHUHVWHG"&RQWDFWXV
\RXUERDUGRXUFKDOOHQJH
(PDLOHXUR#HXURFLUFXLWVFRP XSWROD\HUV
2QGHPDQG IURPSLHFHRQZDUGV
ZZZHXURFLUFXLWVFRP IURPZRUNLQJGD\VRQZDUGV
Real-Time Spectrum Analyzer Turn your PC into a powerful Digital Storage Oscilloscope!
See spectra and waveforms in See inside your circuit with simultaneous analog, logic and spectrum
real-time displayed simultaneously displays to make tracking down those elusive real-time bugs much easier.
Waveform Generator BitScope combines a high speed synchronized storage scope and logic
simultaneously on BNC A With "Smart POD" connected active probes and multiple software options
you've got the perfect low cost high performance test and debug solution!
Standard 1M/20pF BNC Inputs BitScope Smart POD probe connector USB 2.0 or Ethernet Connectivity Expandable and Programmable
200uV-20V/div with x10 probe 8 logic channels, cross-triggering Single cable to PC or switch Simple ASCII Protocol
S/W select AC/DC coupling Dual channel analog inputs Compressed data transmission BitScope Scripting Language
Switchable 50ohm termination Async serial I/O for external control Ethernet option uses UDP/IP Add active probes and devices
Arbitrary Waveform Generator Supports active probes Internet addressable device Supplies up to 500mA via POD
BitScope plugs into third party software tools and has an open API
for user programming and custom data acquisition.
Versatile FPGA M
Modern technology
for everyone
Paul Goossens
MA TICS
SCHE OUT!
N FO LD
O
Module
• Altera Cyclone FPGA
• 12,060 logic elements
• 4 MB configuration memory
• 8 MB user SRAM
• 1 MB user flash RAM
• on-board 50-MHz clock
If you want to use an FPGA in your • JTAG/programming interface
design, there are several things you
can’t do without, including a program-
• Byteblaster compatible
ming interface and configuration mem- • 80 user I/O lines
ory. We thought it would be a good • dedicated clock signals
idea to incorporate the standard items • indicator LED
normally associated with an FPGA into
a single electronics module, in order to
• built-in switch-mode power supply
avoid the need for everyone to reinvent • small multilayer PCB (110 x 77 mm)
the wheel each time. This module can • supplied ready to use
then be used as a ‘digital core’ for var-
ious circuits. A major benefit of this
approach is that it allows
designers to concentrate
on specific applica-
tions without It takes more than just an FPGA All the individual elements of the cir-
having to cuit can be easily identified in the
worry about
to make a circuit schematic drawing.
the sound- As already mentioned, you’ll need
ness of the some peripheral electronics to enable
FPGA element. you to use an FPGA in a practical cir- The design
cuit. One of the most important ele- Due to the size of the schematic draw-
ments beside the FPGA is the configu- ing of the FPGA module, we decided to
Getting started is ration memory. In contrast to most print it on a foldout which may be
the hard part FPGAs, the configuration memory found in the centre of the magazine.
retains its data when the supply volt- Let’s start at the beginning with the
For those of you who age is switched off. power supply. It is built around a
haven’t used FPGAs before, TPS75003 (IC2) and can work with an
this module and the associ- Each time the unit is switched on, the input voltage in the range of 4.5–6.5 V.
ated prototyping board FPGA must be configured again before This IC is specially designed for use in
described elsewhere in this issue it can fulfil its intended function. Fortu- FPGA circuits. It contains two switch-
form an ideal starting point for nately, FPGA manufacturers have mode power supply circuits and one
learning about FPGAs. developed special memory ICs that series regulator. The latter is not used
It’s impossible to avoid using SMDs in can configure FPGA ICs automatically in our circuit; only the two switch-
a circuit such as this. To make things when power is switched on. Our cir- mode circuits are used.
even worse, we decided to use an cuit includes one of these memory ICs.
FPGA in a BGA package for this cir- Easy programming of the FPGA and A step-down regulator that provides a
cuit, which means DIY soldering with the configuration memory during the 3.3-V supply voltage is implemented
a normal soldering iron is simply development phase is also highly using T1, D1, L1, C1 and associated
impossible. Soldering the other mem- desirable. That’s why a programming components. IC2 periodically drives
ber of the family (in a PQFP package) interface (using JTAG) also forms part FET T1 into conduction to allow a cur-
is also very difficult. However, using of the standard peripheral circuitry. rent to flow from the input voltage via
these ‘difficult’ components allows the Another quite important part of such a T1, L1 and C1. This causes the current
overall dimensions of the circuit board circuit is the power supply. The inter- through the inductor to increase,
to be kept reasonably compact. nal operating voltage of most such ICs which in turn causes capacitor C1 to
is quite low (1.5 V in our case). The be charged. When IC2 switches off the
Fortunately, you don’t have to worry power supply must be able to handle FET, the current flowing in L1 cannot
about assembling the board, because short current spikes without problems. stop immediately, so it continues to
the FPGA module is available from In addition, a different voltage is used flow through C1 and D1. R1, R3 and C3
Elektor Electronics with most of the for the inputs and outputs. Here we provide feedback so IC2 can determine
components pre-assembled. The only decided to use 3.3 V. The supply for whether it has to supply more power
components you have to solder by this voltage must also be able to or less power.
hand are the connectors. deliver fairly heavy currents and
Besides this module, you will need a remain stable under heavy loads. The values of these components have
programming interface that sits been chosen such that IC2 tries to
between the PC and the FPGA board. Our circuit also includes an oscillator, maintain the output voltage at 3.3 V.
Naturally, we’ve also developed a SRAM and flash memory. They can be Resistor R2 is a sense resistor. IC2 will
design for this interface. used freely by the application. limit the current if the voltage across
uration memory.
Here again, the sig-
nals are arranged
to be compatible
with the Byte-
blaster interface.
The circuitry
around T3–T5
forms an indicator
circuit that clearly
displays the status
of the FPGA using
bicolour LED D3.
Any error states
that may occur are
also indicate visibly
by D3.
An abundance
of I/O
As this circuit is
intended to be
used for all sorts of
applications, it has
an abundance of
I/O pins. They are
accessible via con-
nectors K3, K4, K7,
K8 and K2. These
Figure 1. The programming mode of the Quartus program. connectors fit stan-
dard pin headers
with 0.1” pin spac-
ing. That avoids
this resistor rises above 0.1 V. The And now for the digital part the difficulties of using SMD connec-
value used here (50 mΩ) results in a tors on the motherboard and thus
current limit threshold of 2 A. Now that we’ve looked after the sup- makes it quite easy to connect the
A similar circuit is built around T2, ply voltages, we can turn to the digital board to your own hardware.
with only the values of the feedback portion of the circuit. The first thing the Connectors K3, K4, K7 and K8 present
resistors being different. They are cho- FPGA needs is a configuration mem- an impressive total of 80 I/O pins of the
sen to yield an output voltage of 1.5 V. ory. That memory is present in the cir- FPGA to the outside world. The I/O
The electrolytic capacitors at the input cuit in the form of IC6, which has been lines are all routed to one side of each
buffer the input voltage. They also pre- designed to work with the FPGA. connector. The supply voltage (3.3 V)
vent fast current spikes from leaving When the MSEL signals from the and ground are available on the other
the board. That prevents generation of FPGA are at ground level, the IC side on alternating pins. You can use
interference that could impair the oper- expects to find a configuration memory the supply and ground pins to power
ation of nearby equipment. (such as the EPCDS4) connected to it. your own circuit if it doesn’t require too
The FPGA will then independently much current. This supply voltage is
The FPGA is powered from these sup- control the memory IC and read data also filtered on the module by a ferrite
ply voltages, but not directly. The sup- from it in order to configure itself based bead and two capacitors.
ply lines for the two sections of the on the data. That makes the process Connector K2 provides a special con-
FPGA are first fed through ferrite very easy in actual use. nection. Besides ground lines, it has
beads to block high-frequency radia- A programming connector (K5) is pro- several signals that are specifically
tion. The supply voltages are also vided for programming IC6. The pin intended to be used as clock signals.
buffered close to the IC by several assignments of this connector have Pin 10 is an input that can be used to
additional capacitors. That may appear been chosen to make it compatible supply an external clock signal to the
to be a bit of overkill, but fairly large with the Altera ‘Byteblaster’ program- FPGA. The remaining even-numbered
switching currents at high frequencies ming interface. pins are all connected to the outputs of
can flow through the FPGA, depending Connector K6 is used for in-circuit pro- the internal PLLs of the FPGA.
on the final circuit configuration. It is gramming of the FPGA from a PC. That Of course, it’s possible to provide an
always a good idea to keep the paths makes it unnecessary to first program a external clock signal on any other
of such currents as short as possible. design into the configuration memory. desired input of the FPGA, but these
Otherwise the circuit can easily gener- This connector can be used to quickly pins are specifically intended to be
ate too much undesirable interference. test a design without using the config- used for that purpose.
FPGA Prototyping
Paul Goossens
VGA
A genuine VGA output that you can
use to display text and imagery on a
}
PC monitor. It’s all done with only a
few standard components.
See page 24.
Ethernet
Your link to the Internet. The associat-
ed IC provides the coupling between
the analogue and digital portions.
See page 24.
USB
This USB interface makes communi-
cation with your PC fast and easy.
And it takes only five components,
including the connector!
See page 24.
Analogue I/O
Four analogue inputs and one ana-
logue output. In addition to all the
digital artillery on the board, an ana-
logue interface is naturally indispen-
sable. This I/O port has a resolution
of 8 bits, which is enough for most
applications.
}
See page 24.
PS/2
A port for a PC keyboard and
mouse.
See page 25.
LCD
A two-line LCD module with a maxi-
mum of 16 characters per line. An
essential part of every proper proto-
typing board!
See page 24.
Audio I/O
With 16-bit stereo input and output,
this prototyping board can also hold
its own in the audio world.
See page 25.
Displays
The ideal way to display numbers.
Also handy for displaying the date
or time.
}
10 Ω
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40
VGA HSYNC
FULLSPEED
VGA VSYNC
LOWSPEED
16
enables it to do something K3
USBD+
USBD-
BLUE0
BLUE1
GRN0
GRN1
RED0
RED1
DIG C
DIG D
1 15 5
AOUT A0
2 6
A1
ANALOG I/O
4 2 11
AIN1 OSC
5 3 9 +3V3
P2 INT
5 7 2 3 4 5 6 7 8 9
P3
PCF8574
a course in the form of a
6 9
P4
7 10 1
P5 A0 +5V
8 11 2
P6 A1
series of instalments in
9 12 3 R11 1 8x 10k
P7 A2
10
+3V3
8
2k2
2k2
2k2
2k2
+5V 100n T9
16
SCL SCL3V3
4 14
P0 SCL
R18 5 15 T8
C31 P1 SDA
6 IC6 13 SDA SDA3V3
P2 INT
1k
100n
7
P3 2x
9 PCF8574 FDV301N
P4
We’ve designed a prototyping board 10
P5 A0
1
11 2
LCD1
that enables the FPGA to be used for a 1
12
P6
P7
A1
A2
3 +3V3
VSS
variety of tasks. As you can see from VDD
2
3 8
the list of features at the head of the VO
S1 S2 S3 S4
article, it’s equipped with quite a few RS
4 +5V C33
5
modern interfaces. R/W
6 100n
E 16 SWITCH1
For many of our readers, designing a SWITCH2
7 4 14
circuit that will ultimately be imple- DB0 P0 SCL SWITCH3
162A
8 5 15
DB1 P1 SDA SWITCH4
IC8
mented in an FPGA will be a totally DB2
9
10
6
P2 INT
13
7
DB3 P3
new experience. For that reason, we’ll DB4
11 9
P4
PCF8574
+5V
R5 R6 R7 R8
12 1
start a series of articles on FPGA pro- 10
10k
10k
10k
10k
DB5 P5 A0
13 11 2
DB6 P6 A1
gramming in next month’s issue. It will DB7
14 12
P7 A2
3
22k
IC13 4
K13 C43
18 14 2 1 24 3 1
EN
R56 R46
VCC1
VCC1
VCC2
VDD
DEM0
4µ7
12.288MHz
22k
22k
C48
3 7 RESET
VINR PDAD 2
6 8 100n
VINL PDDA
IC12 10 LRCIN
LRCIN
20 11 BCKIN
VOUTR BCKIN
19 12 DOUT
VOUTL DOUT
15 DIN
PCM3006 DIN
K16 C44
TX ER
RX ER
RXD3
RXD2
RXD1
RXD0
RX DV
TX CLK
COL
CRS
RX CLK
TX EN
TXD0
TXD1
TXD2
TXD3
LED7
MDINT
MDC
MDIO
4 23
VREF1 NC
16 9
NC SYSCLK
4µ7 5 21
VREF2 VCOM
DGND
AGND
DEM1
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40
K17 C49 K4
C47 C46 17 22 13 C45
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39
Figure 1. Schematic diagram of the FPGA 4µ7
4µ7 4µ7 4µ7
3x BAS40-04W
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 D15 D16 D17
K12
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40
MOUSECLK
MOUSEDAT
KBDCLK
KBDDAT
RESET VGA
DIG DP
BCKIN
LRCIN
DOUT
DIG G
DIG L
DIG B
DIG A
DIG 4
DIG 3
DIG 2
DIG 1
DIG E
DIG F
K9
DIN
RED0 R38
665 Ω
RED1 R42 VGA RED 1 11
332 Ω
GRN0 R44 6
665 Ω
GRN1 R45 VGA GREEN 2 12
+3V3 332 Ω
BLUE0 R47 7
665 Ω
L3 BLUE1 R48 VGA BLUE 3 13
332 Ω
8
+3V3 C20 C21 C22 C23 C24 +3V3
4 14
2x 9
100n 100n 100n 100n 10n BAS40-04W
5 15
R28 R10 L4 D18 D19
C25 C26 10
220 Ω
220 Ω
10n 100n R9 16
51 8 40 21 22 17
2k2
VCCD
VCCA
VCCA
VCCIO
VCCIO
K6 14 15
SUB D15
13 38 55 R12 TX CLK
LED1/CFG1 TX CLK 33 Ω
16 37 52 R15 RX CLK
LED2/CFG2 RX CLK 33 Ω
36 48 R16 RXD0 VGA HSYNC
LED3/CFG3 RXD0 33 Ω
7 19 47 R17 RXD1 VGA VSYNC
TPOP RXD1 33 Ω
20 46 R19 RXD2
1 TPON IC5 RXD2 33 Ω +5V
9 45 R20 RXD3
C27 NC RXD3 33 Ω
8 10 44
NC LXT972A NC
27 43 MDC
270p TDI MDC D8 D9 D10 D11 D12 D13 D14
28 42 MDIO
50 Ω
270 Ω
270 Ω
270 Ω
270 Ω
270 Ω
270 Ω
270 Ω
TPIN TX EN
29 57 TXD0 ULN2003AD
3 10n TMS TXD0
30 58 TXD1
50 Ω
GND GND
13 50 DIG 1 1 16 R32
C34 25MHz GND GND B1 C1 1k
R30 14 61 R29 DIG 2 2 15 R33 T3
GND GND B2 C2 1k
GND
GND
GND
GND
GND
GND
2
2k2
22k1
ULN2003AD A,L1
16 L3
+3V3 B,L2
+3V3 DIG C 1 16 R51 13 L1
B1 C1 270 Ω C,L3
DIG D 2 15 R52 3
K14 B2 C2 270 Ω D L2
T6
FULLSPEED KBDDAT 1 2 DIG E 3 14 R55 5
B3 C3 270 Ω E
DIG F 4 13 R57 11
3 4 B4 C4 270 Ω F
DIG G 5 12 R58 15
FDV302P B5 C5 270 Ω G
KBDCLK DIG DP 6 11 R59 7 DIG1 DIG2 DIG3 DIG4
R39 5 6 B6 C6 270 Ω DP
1k5
7 10
B7 C7
LITE-ON LTC-4627JR
USBD+ E COM
K10 KEYBOARD
USB-B +5V 8 9
3
6
2 USBD- +3V3
FEEDBACK +5V
1 2 3
K15 K2 VIN BOOST C1
R49 1 3 5 7 9
1k5
MOUSEDAT 10n
1 2 IC1 ≤ 4A5
4 LM2679-5.0
3 4 L1
T7 7 1
SOFTSTART OUT
MOUSECLK 2 4 6 8 10 15µH R1
LOWSPEED 5 6 ADJUST
1k
4 8 5
FDV301N
R2 D3
C5 C6 C7 C8 C2 C3 C4
MOUSE D2
8k25
D5 D1
30BQ015
K1
2 D6 D4
1 6
3 4x FEEDBACK +3V3
30BQ015 2 3
VIN BOOST C9
IC2 10n
LED6
LED5
LED4
LED3
LED2
LED1
SWITCH4
SWITCH3
SWITCH2
SWITCH1
SDA3V3
DIPSW1
DIPSW2
DIPSW3
DIPSW4
DIPSW7
DIPSW6
DIPSW5
SCL3V3
DIPSW0
LM2679-3.3
L2
7 1
SOFTSTART OUT
15µH
ADJUST
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 4 8 5
R3 D7
K7 C13 C14 C15 C16 C10 C11 C12
8k25
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39
22µ 22µ 22µ 100n 180µ 180µ 180µ
20V 20V 20V 6V3 6V3 6V3
30BQ015 050370 - 11
For the drive signals, we use the same On the prototyping board, either option
VGA type of IC as for the LED drive signals. can be selected by the FPGA as desired
Several outputs of IC10 and IC11 are by switching FETs T6 and T7 on or off.
Our prototyping board even has its own used to switch the anodes to ground Here again, the two data lines are wired
VGA output. The circuitry for this can be under control of the FPGA. Five leads directly to the FPGA.
found around K9. Three super-cheap are used to switch transistors T1–T5. In
D/A converters are implemented using this way, we can use signals We’ll perform a few experiments with
six resistors. The synchronisation signals DIG1–DIG4 and DIG L to control which the USB bus in the eighth instalment.
can remain in digital form. As signal part of the display is active.
reflections can be expected here, all of
these lines are protected against over- Driving this display is somewhat difficult
shoots by a set of fast Schottky diodes because the various parts of the display
(D15–D19). must be driven in rotation. We’ll illus-
trate how to do this in the second
Generating a VGA signal is easier than instalment of the FPGA course. Analogue I/O
it appears. After reading the seventh
instalment of the course, you’ll know Besides the digital I/O options, the
exactly how it’s done. board has four analogue inputs and one
analogue output. These 8-bit I/O ports
are provided by IC3, which also has an
I2C interface. For that reason, this I/O
Digital I/O option will also be described in the
third instalment of he FPGA course.
We can easily imagine that the proto-
Ethernet typing board will be used as a control
unit for something or other. There are
The Ethernet interface is built around eight digital I/O lines to allow user
IC5, which converts digital signals into hardware to be connected to the proto-
analogue signals and the other way typing board.
around, all according to the Ethernet LEDs
standard. Driving this interface is fairly The IC we selected for this purpose (IC4)
complex. In the ninth instalment, has an I2C interface. This interface is LEDs D8–D14 can be driven directly
we’ll use this interface to perform some also used to communicate with another from the FPGA module by signals LED1-
experiments on a network. IC that we’ll describe shortly. LED7. IC7 buffers the drive signals.
Whenever an input is at a logic High
The circuit around T8 and T9 has level, the corresponding output is pulled
already been used in another Elektor to ground. The currents through the LEDs
Electronics design. It converts the 3.3-V are limited by resistors R12–R27.
I2C signals into 5-V I2C signals.
This type of drive is very simple. In the
7-segment The I2C bus uses a serial data transmis- first instalment of our FPGA course,
sion protocol. The way this is implement- we will use these LEDs to study various
displays ed in the FPGA will be described in the digital functions.
third instalment of the course.
The board has four 7-segment displays
with decimal points, which are housed
together with three separate LEDs in a
single package (D20). This display has
several common-anode leads (5 in total).
They can be individually connected to USB Pushbuttons
the supply voltage to determine which of
the five areas of the display should be A standard USB interface is built round One of the input options of the proto-
illuminated. Here four of them are used connector K10. It can be optionally con- typing board takes the form of pushbut-
for the four 7-segment displays and asso- figured to present itself as a fast or slow tons. This is provided by pushbutton
ciated decimal points. The fifth lead pro- USB device. The PC recognises a fast switches S1–S4. Signal lines
vides current to the three separate LEDs. USB device by the fact that the D+ USB SWITCH1–SWITCH4 are held low by
line is pulled up to the positive supply resistors R5–R8 when the pushbuttons
The anode leads can be used to con- voltage by a resistor. For a slow device, are not pressed. If a pushbutton is
trol which elements of these five areas the D– line of the USB is pulled to pressed, the associated signal line is
light up. ground by a resistor. pulled up to the supply voltage. Signal
PS/2
A PS/2 keyboard and mouse can be
connected via connectors K14 and K15.
Both signals on this bus are connected
DIP switches directly to the I/O pins of the FPGA
module. As with most of the other I/O
Switch module S5 houses eight small ports, the FPGA provides ‘intelligent’
switches, which are wired the same way control for these signals. Even the bidi-
as pushbuttons S1–S4. They allow an rectional data signal can be processed
additional eight signal inputs of the directly by the FPGA without the inter-
FPGA to be controlled by the user. vention of any external ICs. This commu-
nication uses a special serial transmis-
A good application for switches of this sion protocol, which we’ll examine more
sort is to use them for enabling or dis- closely in the sixth instalment.
abling various options. We will use
these DIP switches in the second
instalment of the FPGA course. The “brains” on the Versatile FPGA Unit.
Power supply
All of this is rounded out by the power
Audio I/O supply. That’s the only part of the circuit
that isn’t controlled by the FPGA.
The circuitry around IC12 forms a gen-
uine 16-bit stereo input/output port. The IC1 and IC2 are both step-down con-
sampling frequency is set to 48 kHz by trollers. Each of these ICs forms a step-
the clock rate of IC13. down converter in combination with an
inductor, a diode and buffer capacitors.
This IC communicates with the FPGA via The advantage of these converters is that
five signal lines, which will be described a high input voltage doesn’t cause the
in more detail in the fourth instal- supply to dissipate a lot of power in the
ment of the course. Naturally, that will form of heat, unlike a series-regulated
also include an example of an applica- power supply using a 7805 or the like.
tion in which the IC is driven by the
FPGA. The input voltage on K1 can be con-
nected either way round. D1 and
D4–D6 sort things out so the polarity of
the voltage at the inputs of IC1 and IC2
is always correct. The electrolytic
capacitors at the input ensure that fast
switching currents stay on the board
LCD where they belong. As a result, the
power supply generates relatively little
The 2-line by 16-character LCD (LCD1 interference.
on the schematic diagram) is driven by
IC6 and IC8. These ICs operate on the The FPGA is powered via K2.
same principle as the ones used for the The Ethernet interface built around IC5.
(050370)
Development
In this issue, which is bursting with FPGAs and microcontrollers, they could not possibly
be omitted: development kits! We devote attention to interesting but affordable kits
where we not only look at kits that are suitable for a commercial environment but which
are also very interesting for hobby use.
The first few steps are always difficult. This is also true of Even the choice between an FPGA and a microcontroller
course when working with FPGAs, microcontrollers and may not be that immediately obvious. A microcontroller is
DSPs. Particularly in order to acquaint commercial devel- less complex than an FPGA, but an FPGA, on the other
opers in an easy way with new products, various chip hand, offers many more possibilities.
manufacturers offer so-called ‘development kits’ (some- The development boards have a number of inputs and
times also called ‘starter kits’). But if you would like to use outputs for communication with other devices (that they
them at home for yourself, then that is generally not a may potentially control). The RS232 port remains a very
problem at all. You can usually just order a kit from the familiar interface. In many cases headers are used, so
appropriate distributor for private purposes. There is then that every pin from the IC can be accessed easily. Some
nothing to stop you from messing about with your chosen boards have a number of ADCs and DACs and occasion-
kit. The only catch is that you ‘just’ have to decide which ally CAN, SPI and 1-Wire-interfaces make an appear-
kit you would like to get started with. And this can be ance. For programming, each board has its own specific
much more involved than you would think at first glance. connector. Microchip uses a so-called ICD programming
In this article we attempt to give you an overview of inter- interface, while others use RS232, JTAG or some other
esting and affordable kits. We selected a few kits from specific interface. The same holds true here: try to think
each category and have summarised the important ahead of what you may need at a later stage.
details in a table. In the large table we have included a number of critical
characteristics so that it becomes relatively easy for you
to make the final decision.
Options Nevertheless, we will provide some guidance to the start-
As already mentioned, before you start your development ing developer by describing the broad characteristics of
effort, you have to make a choice from the different microcontrollers, DSPs and FPGAs.
options on offer from the various manufacturers. It is a
good idea to not just consider what you need at this par-
ticular moment, but also to think ahead about possible Microcontrollers
extensions you may wish to add at a later date. Imple- A microcontroller is essentially a computer in one chip
menting a small design in an FPGA is generally not a (refer Figure 1). The arithmetic unit is integrated
problem, but a larger design (i.e., more gates) can be together with all the I/O and memory in one IC, so that
more trouble to make fit. That is why development kits no additional chips are required (in contrast to a micro-
are often equipped with one of the larger members, if not processor which does need additional chips). Microcon-
the largest member, from a family. For microcontrollers trollers are used mainly for controlling electronic equip-
too, it is good to take into account your future require- ment, such as, for example, our recent SMD Oven (see
ments. Using fewer inputs and outputs is always possible. Elektor Electronics January 2006).
Wanting to use more than the IC provides is impossible. The difference between an 8-bit and 16-bit controller is
mainly the speed. A 16-bit controller can, compared to ations that are necessary for digital signal processing.
an 8-bit controller with the same number of MIPS (Million For example, a DSP has a special register structure and
Instructions Per Second), process twice as much data. mechanisms to carry out an FFT (Fast Fourier Transform,
Most of the demo boards have been designed in such a a mathematical operation to analyse the frequencies in a
way that they can function on their own. That means in signal) as quickly as possible and to move large blocks
most cases that there is a microprocessor on the board of data as efficiently as possible.
that runs a (demo) program. In addition there is then the These days the boundary between DSPs and microcon-
possibility to simulate the board using the bundled soft- trollers is becoming increasingly blurred, for example the
ware and, if the program is not quite 100 percent cor- PIC series from Microchip. The microcontrollers are then
rect, use debug-mode to iron out the last wrinkles. provided with the partial functionality of a DSP (which
In the text box you can read some more regarding the means additional instructions).
choices for a particular type of microcontroller.
FPGAs
DSPs An FPGA (Field Programmable Gate Array) is, as the
DSP means Digital Signal Processor. Such a processor is name implies, a ‘field’ with programmable logic gates
really a kind of specialised microprocessor. The signifi- and programmable internal connections (see Figure 2).
cant difference between a microcontroller and a DSP is It is a real millipede. An FPGA can be programmed so
that a DSP has been optimised for the mathematical oper- that it carries out all kinds of logical operations. Ranging
Timer
G-LUT
FPGA
I/O Buffer
ROM/
I/O CPU FLASH
PSM PSM
I/O Buffer
050324 - 16
RAM
Programmable Switch Matrix
Figure 1. Block diagram for a typical microcontroller. Figure 2. Typical architecture of an FPGA.
Manufacturer / Programming
Microcontrollers Type of IC supplied I/O LCD Power Supply R.R.P.
Website Interface
Microchip / standard 9V DC
PICDEM 2 Plus PIC18F452 and PIC16F877 ICD RS232 2x16 £ 59
www.microchip.com adapter
Microchip / standard 9V DC
PICDEM 4 PIC12F1320 and PIC16F627A ICD RS232; PIC16LF72 I/O expander 2x16 £ 76
www.microchip.com adapter; 9V battery
Maxim/Dallas
DS89C450-K00 Semiconductor / DS89C450 RS-232 2x RS232; 4x 8-bit I/O - 6-9 V DC adapter £ 62
www.maxim-ic.com
DSP’s
ADDS-21261/Cyclone Cyclone EP1C3 (FPGA) and ADSP- JTAG for FPGA, USB for USB; RS232; JTAG; expansion
Altera / www.altera.com - via adapter £ 140
Evaluation Kit 21261 (SHARC DSP chip) SHARC header
18-, 28,- & 40-pin PIC16XXXX PRO MATE II, MPLAB PM3, PIC-
on CD MPLAB IDE, MPASM, MPLAB C18 5k potentiometer, TC74 temperature sensor, piezo buzzer
and PIC18XXXX START PLUS or MPLAB ICD 2
8-, 14-, & 18-pin PIC16XXXX PRO MATE II, MPLAB PM3, PIC- NanoWatt technology/supercapacitor circuit, four 5k potentiometer,
on CD MPLAB IDE
and PIC18XXXX START PLUS of MPLAB ICD 2 space for LIN transceiver and motor driver
DS89C430, DS89C440,
on CD Microcontroller Tool Kit (MTK) Software only; PC (MTK) 64kB Flash memory, 128kB SRAM
DS89C450, DS5000
ZDS II Integrated Development Supplied serial or USB Smart 256-1k bytes RAM, 1-4k flash memory, 2 16-bit timers, comparator.
not exchangeable on CD
Environment, ANSI C-compiler Cable Optional: 8 channel 10-bits ADC, temperature sensor
ZDS II Integrated Development Supplied serial or USB Smart 1-64k bytes Flash/ROM, 256-4k bytes RAM, up to 60 I/Os, up to 24
not exchangeable on CD interrupts, up to 4 16-bit timers, up to 12 channels 10-bit ADCs,
Environment, ANSI C-compiler Cable optional: DMA controller, SPI and I2C.
Evaluation versions of Keil uVision and
Compatible with 8051, PWM generator, 10-bit ADC, 3 16-bit timers,
not exchangeable on CD Ulink or Hitex debugger Tantino-Eco, Tantino USB (supplied)
27 general purpose I/O, 768 bytes RAM, 16k flash, potentiometer
DAvE
In Elektor / KD30, NC30, HEW, Flash Development 8-bit timer, 12 channel 10-bit ADC, 5 external & 11 internal inter-
not exchangeable Software only; PC
on website Toolkit rupts, 4kB flash, 10k potentiometer
PIC24 and dsPIC33 families on CD MPLAB IDE MPLAB ICD 2 temperature sensor TC1047A, 10k potentiometer, 256kb EEPROM
not exchangeable MAX-IDE Software only; PC MAX1407 ADC/DAC, potentiometer, JTAG interface board, LCD board
Spartan-3, Coolrunner-II, On paper and CD- Evaluation versions of Xilinx ISE &
Supplied JTAG3 cable 3-bit, 8-colour VGA display port, 1MB SRAM
XC9500XL ROM EDK
ByteBlaster II parallel download Temperature sensor, potentiometer 128kB SRAM, onboard power
not exchangeable on CD Quartus II Web Edition
cable meterr
from basic logic gate functions (AND, OR, XOR, NOT, sorts out these interconnections for you, so you don’t
etc.) to complex combinational logic such as mathemati- need to do much there yourself.
cal functions and decoders. It is even possible to emulate FPGAs have evolved from CPLDs (Complex Programma-
a complete (8051) microprocessor in an FPGA (provided ble Logic Device). As a consequence of their internal
that the FPGA has enough gates, of course). architecture, FPGAs have greater design flexibility com-
pared to CPLDs. On the downside, the increased flexibil-
These ports are formed by CLBs, which are connected in ity has also increased the complexity.
a matrix arrangement. Each CLB consists of multiple However, don’t be taken aback by the overwhelming
lookup tables (LUT), a few multiplexers and optionally a number of possibilities and accompanying data, descrip-
number of flip-flops. So the CLBs carry out all logic func- tions, tutorials and other things. Once you’ve started
tions. By connecting the CLBs with programmable with FPGAs, chances are that you cannot live without
switches to each other in the right way, the desired func- them any more.
tionality is obtained. The development software generally (050324-1)
2QOLQHSULFHFDOFXODWLRQ
2QOLQHRUGHULQJ WHFKQRORJ\DWWKHULJKWSULFH
2QOLQHRUGHUWUDFNLQJ jODFDUWH XSWROD\HUV
2QOLQH+DQG' IURPWRSLHFHV
IURPZRUNLQJGD\VRQZDUGV
,QWHUHVWHG"&RQWDFWXV
\RXUERDUGRXUFKDOOHQJH
(PDLOHXUR#HXURFLUFXLWVFRP XSWROD\HUV
2QGHPDQG IURPSLHFHRQZDUGV
ZZZHXURFLUFXLWVFRP IURPZRUNLQJGD\VRQZDUGV
Are eight-bit processors something from the past or is it still possible to do some-
thing useful with them? Elektor Electronics went looking and discovered that the
good-old 6502, in a world of threaded computing and dual-core processors, still
has a following of faithful fans.
In the 1970’s and 80’s three 8-bit processors dominated elegant 8-bit processor. Many thousands of enthusiasts
the market: the 6809 from Motorola, the Z80 from Zilog across the whole world still work daily with the 6502
and the 6502 from MOS. By far the most popular of and make it do things that were not considered possible
these three was the in 1975.
6502: its low cost (when
introduced, the 6502 set
you back about 25 dol-
lars) and the advanced
Price war History
The 6502 processor cele-
design for its time made When the 6502 was introduced in 1975 it cost brates its 30th anniver-
sure that the 6502 con- about 25 dollars. That made it a serious com- sary this year. The intro-
quered the world in a petitor to the processor it was copied from, the duction was preceded by
short time as the brain in 6800, which by comparison costs a whopping a scandal: the designers
popular home-computers 179 dollars. No wonder computer manufacturers of the 6502 had, in the
such as the such as Apple and Commodore went for the first instance, developed
Commodore 64 and the 6502. Steve Wozniak from Apple had his eye in another processor: the
Apple II. the 6800, but the enormous price difference ulti- 6501. Unfortunately, it
mately forced the decision. was a virtual copy of the
We are now some 30 6800 processor from
years later and proces- Motorola. This is not a
sors that are many thousands of times faster than the surprise, because the same designers developed the
6502 now dominate the market. But… that does not Motorola 6800! Shortly after the 6800 processor
mean that there are no applications to be found for the appeared on the market, a dispute arose between
Motorola and the 6800 designers. This conflict resulted
in the resignation of most of the designers, who were
promptly hired by MOS Technology (in the 70’s
Motorola’s biggest competitor). MOS recognised the
potential for the 6800 and asked the designers to design
a processor that was pin-compatible with the 6800. That
became the 6501, which was much cheaper because the
development costs were negligible.
Figure 4.
One of the two PCBs
that comprise the 6502
built from discrete
parts by Dieter Müller.
(source: website
Dieter’s Hobby
Projects)
Copying
You can also copy a 6502 using ‘discrete’ components
such as 7400-series ICs, RAMs and EPROMs. This is
what Dieter Müller did with some old bits he had at
home. He nearly succeeded, using about 40 ICs and two
PCBs (Figure 4). The most important concession is a dif-
ferent timing, but his processor knows all 6502- and
Figure 5. 65C02 opcodes (see http://people.freenet.de/
At FPGA Arcade dieter.02/m02.htm).
various 6502 hardware
for games are emulated A different approach is to start with an FPGA and to
in an FPGA. build into it the complete functionality of a 6502. An
Application board
Base camp for high endeavours
Gunther Ewald
and Burkhard Kainka
D5 IC2
JP11
1N4002 7805 POWER
K1
EXT USB
+5V +5V
C10 C11 C12 C13
F1
R11
220µ 100n 100n 10µ Polyfuse P1
25V 16V
33k
100mA JP1
ANALOG
+5V 10k +5V JP2
+5V +5V +5V PROG
R9 R10 R17 +5V
JP12 K9 LCD
4k7
4k7
10k
R8
POWER D7 1
K5 K6 K7 K8 VSS
4k7
LC DISPLAY 2 x 16
S1 XOUT P0.3 5
C18 R/W
VSS MODE CONTRAST 10k 6
E
D6 100n XIN P0.4 7
D0
RESET VCC P0.5 8
D1
P1.7 P0.6 9
+5V D2
P1.6 P0.7 10
D3
R3 JP6 RXD0 IVCC 11
D3 D4
1k TXD0 P3.0 12
D5
R2 JP4 P1.3 AVSS 13
D2 C1 D6
1k P1.2 P3.1 14
D7
R4 JP5 P1.1 AVCC
D4 100n
1k P1.0 P3.2
R1 JP3 P4.5 P3.3
D1 16 17
1k +5V
TXD0 TXD1
RXD0
SERIAL RXD1 C3
PROGRAMMING R5
C7 C4
K4
1k5
+5V 100n
1 C15 10µ 16V 100n
4 8 17 24
6 4µ7
VDD
JP7
VDD_PLL
VDD_3V3
VDD_233
2 1 19
TXD RST
7 25V USB 5 20
2 RXD VDD
3 K4
V+
8 1 16 12 IC1 9 R13 C9
PROG.
C8
C14 C1+ SHTD_N DSR_N 220k
4 JP8 13 10 R14
EE_CLK DCD_N 220k
9 3 IC3 14 11 R12 10µ 16V 100n
4µ7 C1– K4 EE_DATA CTS_N 220k
5 25V 14 11
T1OUT T1IN USB PL2303 R16
13 12 2 15
R1IN R1OUT DTR_N DP 27 Ω
8 9 3 16
SUB D9 R2IN R2OUT JP9 RTS_N DM
7 10 6 3 K2
T2OUT T2IN RI_N R15
COM 4 C2 USB 22 2 USB-B
PORT C17 C2+ TRI_MODE 27 Ω
MAX232 K4 26 23 1
K3 PLL_TEST LD_MODE
5 15 100n
4µ7
SER.
1 C2–
25V JP10 7 25 6 4 5
6 V- GND GND_PLL
21 18
2 6 K4 GND GND_3V3
C16
7 USB OSC1 OSC2
3 27 28
4µ7 R6 X1
8 25V
47k
4
C6 C5
9
5 10p 10p
12MHz
050179 - 3 - 11
SUB D9
Figure 1. The circuitry on the application board provides two serial ports, a USB interface and an LC display to connect the R8C daughter board to the outside world.
Driver installation
LIST IC3 = MAX232
Miscellaneous:
You may have already used a Prolific Resistors: JP3-JP6,JP12 = jumper
USB adapter with your system. In that R1-R4,R7 = 1kΩ JP7-JP11 = 3-way SIL pinheader
case, the interface will be recognised R5 = 1kΩ5 K1 = 2-way PCB terminal block, lead
as soon as the board is connected to R6 = 47kΩ pitch 5mm
the PC. If it isn’t, or if you experience R8,R9,R10 = 4kΩ7 K2 = USB socket, type B for PCB
R11 = 33kΩ mounting
problems using the USB port, you R12,R13,R14 = 220kΩ K3,K4 = 9-way sub-D socket, angled
should install the latest version of the R15,R16 = 27Ω pins, PCB mount
driver. You can obtain the driver by R17 = 10kΩ K5-K8 = 16-way SIL pinheader
downloading the file 050179-3-11.zip P1,P2 = 10kΩ K9 = LCD module, 2x16 characters
from the Elektor Electronics website S1 = pushbutton with 1 make contact
Capacitors: (e.g. TS695)
(www.elektor-electronics.co.uk). It con- C1-C4,C8,C11,C12,C18 = 100nF F1 = 100 mA Polyfuse
tains the file ‘PL-2303 Driver C5,C6 = 10pF X2 = 12MHz quartz crystal
Installer.exe’. C7,C9,C13 = 10µF 16V radial PCB, bare, order code 050179-1
Run the driver installer file before con- C10 = 220µF 25V PCB, ready-assembled and tested, order
necting the board. Any older version of C14-C17 = 4µF7 25V radial code 050179-92
the driver present in the PC will be LCD with backlight, order code
Semiconductors: 030451-72
deleted automatically when the new D1-D4,D6 = LED Poly-LED display, order code
driver is installed. The next time the D5 = 1N4002 030451-73
board is connected (or another inter-
050179-1
JP1
Prog. Analog
K1
JP2
R11 R17
Reset
LCD1
C18
RxD1 TxD1
CNVSS P0.1
D7
R10
res P0.2
R9
D5
Xout P0.3
R8 Vss mod
R2 Xin P0.4
C10
Vcc P0.5
R3
P1.7 P0.6
C11
JP3JP5JP4JP6
P1.6 P0.7
D1 D4 D2 D3
RxD0 IVcc
IC2
TxD0 P3.0
P1.3 AVss
P1.2 P3.1
C1
P1.1 AVcc
P1.0 P3.2
R1 P4.5 P3.3 C12
C13
R4
K7
K5
K6
K8
C14 JP11
ext
Power
100mA
C17 X1
F1
K3 USB C9
USB
C7
C3
JP9
C6
C5
ser.
IC3 JP10 C4
IC1
JP8 R13
K2
Serial prog.
COM port K4 R12
programming
C8
JP7
C2 R14
K4 USB
JP12
R16
R15
K3 C15
R6
R5
C16
P2
R7
Power LED
D6 Contrast LCD
Figure 6. The fully assembled prototype board. The component overlay is slightly different from the production version shown in Figure 5.
Board assembly
The printed circuit board (Figure 5) is
also available fully assembled so
readers with relatively little soldering
experience don’t have to worry about JP 11:
problems with the Prolific IC (IC1), toward K7/K8
which is only available in a 28-lead (‘ext’ position,
SMD package (SSOP-28). If you assem- with power coming
ble the circuit board yourself, you from an external supply)
should start with this IC because it’s JP 3–6: fitted (LEDs
easier to solder if the board is other- connected)
wise empty. JP 12: fitted (‘Power’ LED
connected)
Numerous Elektor Electronics SMD JP 2: fitted (debug mode) KD30 debugger
projects have shown that they can be JP 7–10: toward IC3 (both interfaces Up to now, we’ve only described how
soldered without using special SMD via RS232) to download finished programs into
tools. Start by soldering two diagonally the microcontroller and run them.
opposite leads in place, after first care- You should check the supply voltage on When you’re developing a program,
fully positioning the IC. A check with the board before plugging in the especially one that’s relatively com-
a loupe will show whether you have a R8C/13 daughterboard, in order to plex, it’s helpful to use a debugger.
steady hand. If necessary, you can still avoid any risk to the microcontroller. That allows you to interrupt the pro-
adjust the position relatively easily at LED D6 should light up after you con- gram at any desired location, view
this stage. Continue by soldering an nect an AC adapter with 9-V DC out- memory contents, execute single
entire row of leads with a sufficient put. The voltage measured on K6 steps, and much more.
amount of solder. Any excess solder between pin 5 VSS (Pin 5) and pin 7 The microcontroller must always be in
can be easily removed afterwards with (VCC) must have a value of +5 V. After debug mode when you use the debug-
a length of solder wick. If your final verifying this, disconnect the AC ger, which means that jumper JP2
inspection with a loupe does not reveal adapter and plug in the daughter board must remain fitted. The Reset button
any solder bridges, everything is OK. while no power is applied to the board. isn’t necessary in this case, because
The author has also found that strong Now comes the most exciting moment! you can only use software commands
reading glasses (3 dioptre) are an Reconnect the 9-V AC adapter. The from the debugger to start and stop
excellent alternative to a loupe. ‘Power’ LED will light up. Connect K4 your program.
They’re almost as good as stereo to the COM1 serial port of the PC. You We’ve prepared an extensive descrip-
microscope, at only a fraction of the can immediately download a program tion of how to get started with the
price. now, because JP2 is configured for debugger and placed it on the Elektor
debug mode. Use the FDT program as Electronics website at www.elektor-
The remaining components shouldn’t described in the February 2006 issue of electronics.co.uk. Deeopnding on the
present any special difficulties. You Elektor Electronics. A good choice for amount of feedback we get, a special
can omit the pin headers (K5 and K8) if your first download is the ‘port_toggle’ R8C activity page may also be created,
desired. If you wish, you can later con- program. The programming tool will so check out the website.
nect flat cable here or wire only the indicate whether the download (050179-3)
connections you actually need to the process completed successfully.
prototyping area. A socket header has Next, remove jumper JP2 and briefly References:
proven to work well as an LCD connec- press the Reset button. The four LEDs www.glyn.com
tor. The matching LCD module can connected to Port P1 should start www.glyn.de
then be fitted with long pin headers blinking. E-mail: elektor-r8c@glyn.de
and simply plugged into the board. If you want to use the USB interface, fit
JP7 and JP8 in the proper positions
R8C forum:
(toward the USB connector). That will
Initial test connect RXD1 and TXD1 to the USB
For hints and tips about using the
R8C/13 board, check out the ‘R8C 16-
Before using the board for the first converter IC. After that, you must con- bit Micro Starter Kit’ topic in our Forum
time, you should re-inspect the compo- figure FDT to use the virtual COM menu at www.elektor-electronics.co.uk.
nent assembly and solder joints and fit interface. Everything else works Naturally, we would be pleased if you
the necessary jumpers. The following exactly the same as with a real RS232 post your own tips and tricks on this
jumper settings are important: interface. forum for the benefit of other readers.
Number One Systems - Oak Lane - Bredon - Tewkesbury - Glos - United Kingdom - GL20 7LR UK
Cheap Logger
Use a web router to read the
gas/water/electricity meters
Jeroen Domburg & Thijs Beckers
This month we’ll turn an inexpensive router into a data logger. This is provided with sensors
that monitor the readings on gas, water and electricity meters. One of the benefits of using a
router is that the logger can be connected directly to an internal computer network and can
therefore be accessed from any PC with an Internet browser.
The Sweex LB000021 is still one of the cheapest routers that can run
Linux. At the time of writing, this model was available on the Internet for
less than £20, including postage costs.
When we look inside this router we see a pair of unpopulated headers on
the board. The smaller of the two (circled in red) is the serial port, which
we’ll use for this project.
This is the board with the microcontroller, which we’ll hook up to the port.
The circuit is so simple that it can easily be built on a piece of
experimenter’s board.
R2
10 Ω
20
S1
The sensors are optical and the types
used depend on the meter they have to
1
RESET PB7
19 R3 read. The general idea is that the sen-
18 10 Ω
Ub
2
PB6
17 S2
sor ‘looks’ at the gas, water or electric-
TxD PD0 IC1 PB5
3 16 ity meter.
RxD PD1 PB4
GND
6
PD2 PB3
15 R4 Most modern electricity meters have
7 14 10 Ω
PD3 PB2
S3
an LED, which flashes every time a
8 13
9
PD4 PB1
12
certain amount of power has been con-
PD5 PB0
11
PD6
R5 sumed. This pulse can of course be
10 Ω
ATTiny2313 easily detected by a simple LDR. Older
XO XI S4
10 4 5
meters have a rotating disc with black
D1 D2 D3 D4 X1
C1 C2 C3 C4 C5 C6
X1 = 20MHz 050360 - 2 - 15
Figure 1. The microcontroller circuit is fairly simple and can easily be built on a piece of
experimenter’s board (see inset).
markers. These meters can be read sion of the firmware. The firmware mal router. It’s worth noting that the
with the help of reflective optical sen- contains a program that takes care of meter firmware hasn’t stopped the
sors such as the CNY70, or the OPB704 the communications with the micro- internal switch from working: the four
(more expensive, but better). controller and makes sure that the LAN ports and the WAN port are con-
Gas and water meters usually have a counters are read at the right time. As figured as a single switch by this
mark on one of the least significant we mentioned earlier, this occurs every firmware.
digits (often the ‘0’ or ‘6’). A reflective five minutes. The data are stored in the So far so good, but how can you obtain
sensor can be used without too many internal RAM of the router. This has this firmware? The answer is very sim-
problems in these cases as well. the advantage that about a year’s ple: the required firmware is available
Whichever type of method is used for worth of data can be stored; the disad- from both the Elektor website [1] (file
the measurements, all sensors occa- vantage is that all this data will be lost number 050360-11.zip), and the
sionally exhibit a drop in their resist- if there is a power cut. Luckily, this can author’s own site [2]. The Linux kernel
ance. The capacitors connected to the easily be prevented by the inclusion of and all other tools used are licensed
sensors (see Figure 1) and some clever a back-up battery in the power supply; under the GPL (General Public
firmware in the microcontroller enable this will be covered in detail later on. License), which means that the source
these resistance changes to be read. The firmware inside the router con- code of the programs has to be made
The firmware keeps track of the num- tains a simple web server and several available along with the firmware. The
ber of times that the current drops server-side scripts; these enable every- author has of course complied with
below a certain value and hence how thing, including the network settings this requirement. He has also made the
often a change of resistance has and sensor calibrations, to be accessed tools available that were written
occurred. This count gives a good indi- via a browser. It is also possible to use specifically for use with the meter
cation of the consumption over a given the browser to view the data in differ- firmware. These can also be down-
time. The counters can be read or reset ent formats. The data of one or more loaded from the above-mentioned
via the serial port of the microcon- selected sensors can be viewed as a sites.
troller. The calibration of the sensors graph. Alternatively, the raw data can Installing the firmware is fairly simple:
also takes place via this route. be downloaded as a CSV file, for use in the router already has a facility to
The microcontroller’s serial port is con- Excel. upload a firmware upgrade and this
nected to a header in the router (JP2). The facility to update the firmware method can also be used to smuggle
This header normally isn’t mounted on hasn’t been forgotten either. Using this our firmware into the router; refer to
the board. The serial port of the router update facility, the official Sweex the inset for more info. If you want to
ends up at this header (see Figure 2). firmware can be flashed back into the flash the original firmware back into
The router itself runs a dedicated ver- router, so it can be used again as a nor- the router, you can use the method
*
router powered for some 20 minutes.
Six beefy NiMH cells give a back-up
author:
time of about three hours. During this Jeroen Domburg is currently
period the meter continues to take studying electronic engineering
*zie tekst readings. The measurements of all con- at the Saxion University in
BT1
nected meters are therefore preserved. Enschede (The Netherlands). He
U BT
The circuit in Figure 3 shows how a
is an enthusiastic hobbyist,
back-up supply should be connected.
who spends much of his spare
This circuit should be inserted
between the adapter and the router. time on microcontrollers,
050360 - 2 - 17
The two diodes ensure that no current electronics and computers. In
can flow from the adapter to the bat- this section we will be able to
Figure 3. The back-up supply is inserted into the tery and vice versa. The resistor pro- examine and build some of his
supply line. This diagram shows that it is a fairly vides enough current to the battery to projects.
simple circuit. keep it fully charged during normal
Travel Charger
Free power in the mountains
Karel Walraven
Recharging batteries for devices such as digital cameras can be a problem when you’re on
holiday in a remote or inhospitable region. You won’t find an electrical outlet anywhere.
Naturally, you can count on an Elektor Electronics designer to whip up a solution using a solar
panel and a DIY Li-ion battery charger.
I was due a bit of a holiday, so I sug- exactly 4.1 or 4.2 V (always read the obscure components. The TL431 volt-
gested to management that I’d step manufacturer’s specifications to deter- age reference is an old standby that
out for half a year. Their response was mine the right value) and add current you can obtain almost everywhere. For
less than enthusiastic, and my own limiting to keep the current within the rest, it consists of a few ordinary
enthusiasm was soon dampened when bounds. The charging current will transistors and a power transistor, all
I had a good look at what it would automatically decrease as the cell of which can be replaced by any rea-
cost. The outcome was thus four becomes charged (see Figure 1 for the sonable equivalents. The Schottky
weeks of trekking through the Anna- charging characteristic). diode can be any type that can handle
purna region in Nepal. You can assume that the cell is fully 1 A, or if necessary you can use an
To meet my electrical energy needs, I charged when the charging current ordinary 1N4001. The input voltage
took along a solar panel and a simple drops to 1/20C or less. Just to reiterate, can also be higher, although beyond a
Li-ion charger built from discrete com- the charging voltage is critical – the certain point you’ll have to fit a heat
ponents. I didn’t have a lot of time, and allowed tolerance is only 1%. That’s sink for T1.
in the spirit of the motto ‘better a good not very much, because 1% of 4.2 V is
copy than a bad design’, I cribbed the only 42 mV. That means you have to
accompanying circuit from a well- measure the output voltage carefully to Design philosophy
known Chinese company. ensure that it stays within tolerance. It’s always interesting to examine
As you doubtless know, charging The nice thing about this circuit (Fig- someone else’s design carefully in
lithium cells is actually quite easy. You ure 2) is that it’s easy to build as a DIY order to figure out the underlying
generate a well-regulated voltage of project because it doesn’t use any design philosophy.
Capacity (mAh)
Current (mA)
800
Voltage (V)
VOLTAGE
(IC2). That’s a prudent choice, 4.0
because a good reference is a funda- 600
mental requirement if you want to be 3.5 CURRENT
a TL431
near the end of the tolerance range, BD140
330 Ω
1%
correct the reference voltage by fitting
a resistor in parallel with R21 or R23.
You can simply use the trial-and-error R6 R7 R15 R14 R1 R8 +4V2
method by trying a succession of val- 650mA
3k3
2k67
1k
1k
1k
1k
+ BATT.
ues until you obtain the correct volt-
1% 1%
age. Once that’s done, you can solder SENSE
the resistor permanently in place. 7
1 - BATT.
IC1.B
2V324
6
Naturally, a reference voltage of 3.3 V
represents an arbitrary choice. It could
9 T2
also be a bit higher or a bit lower. It 14
IC1.C
0V143
0Ω47
0Ω47
2k4
3k3
3k9
47k
red green
tivity of the circuit to the input offset R2 R13
5 T3
14mV R10
2
Control circuitry IC1.A 47k
4
Now we come to the actual control cir- BC557
cuitry. We want to have: R19 R11
C3
220 Ω
2k00
Indicator
The first three items all affect the out- a normal Li-ion battery is around 0.7 to We haven’t said anything yet about the
put voltage. The output current can be 1 times its capacity. This charger deliv- indicator portion of the circuit, which
reduced by lowering the output volt- ers a maximum current of 0.65 A, consists of the circuitry around IC1a.
age, and if the battery becomes hot, which makes it suitable for batteries This bit of electronics is not essential
the charging current must be reduced rated at 0.65 Ah or more. to the operation of the circuit, but it is
by lowering the output voltage. The current with a fully discharged nevertheless very important. As a user,
Here we have a topology in which battery would ordinarily be higher you naturally want to know where
three opamps (IC1b, IC1c and IC1d) than the above-mentioned 0.65 A. The things stand. The nice thing about this
can simultaneously control a single current can be easily measured by con- indicator is that it responds to the
output. That’s possible using a sort of necting a small resistance in series. charging current. That means you can
OR-gate arrangement. In the Here that role is fulfilled by R17 and be sure that charging is actually taking
schematic diagram, you can see that R18, with two resistors being used due place, which avoids simple errors such
the outputs are simply connected to the magnitude of the current and as forgetting to connect the mains
together. Under normal conditions, the power dissipation. The current adapter or a bad battery contact.
that would naturally lead to problems generates a voltage across these resis- Here again the reference voltage is
whenever one opamp tries to increase tors, and IC1d compares this voltage divided down, this time by R12/R19, to
the output voltage while another one with a reduced reference voltage a voltage of approximately 14 mV. If the
tries to reduce it. That problem can be obtained from a voltage divider. If the voltage drop resulting from the charg-
solved by putting diodes or transistors voltage generated by the charging cur- ing current through R17/R18 is less
after the opamps. rent is higher than the comparison than this value (with no battery con-
In this case, a more elegant solution is voltage, IC1d takes control by reducing nected or a fully charged battery), the
to use opamps with open-collector out- the voltage on the shared output. That internal open-collector output transis-
puts. That means each opamp can only lowers the charging voltage for the tor of IC1a will be cut off. The red LED
reduce the voltage on the shared out- battery and thus reduces the charging in D1 will be off in that case, but the
put. Resistor R8 provides the pull-up current to the desired level. green one will be on because it is con-
voltage. It supplies the base current for When the battery becomes fully nected to 3.3 V and to ground via a
T2, which in turn drives T1 into conduc- charged, the control function provided 220-Ω resistor.
tion and voilà, the positive terminal of by IC1c prevents the voltage from ris-
the battery is connected to the positive ing above 4.2 V. The battery voltage is In the opposite case, with sufficient
supply voltage. This gives us a system in compared with the reference voltage charging current flowing, IC1a will pull
which each parameter (voltage, current, via two voltage dividers (R15/R16 and its output low. In that case LED will be
and temperature) has its own opamp R7/R4, respectively), and if necessary on and T3 will conduct to short out the
that can reduce the output voltage. IC1c reduces the voltage on the green LED and keep it dark. Using a
shared output. bi-colour LED for D1 thus provides a
Current regulation The logic of the temperature monitoring perfectly clear charging indicator.
As a rule of thumb, you can assume circuitry with IC1b is similar. A thermis- Have you already realised the signifi-
that the maximum charging current of tor (NTC resistor) is built into the bat- cance of selecting 14 mV as the refer-
C O N S T R U C T I O N G U I D E L I N E S
Elektor Electronics (Publishing) does not provide parts and components ponents in the correct position? Has correct polarity been observed? Have
other than PCBs, fornt panel foils and software on diskette or IC (not neces- the powerlines been reversed? Are all solder joints sound? Have any wire
bridges been forgotten?
sarily for all projects). Components are usually available form a number of If voltage levels have been given on the circuit diagram, do those meas-
retailers – see the adverts in the magazine. ured on the board match them – note that deviations up to ±10% from the
Large and small values of components are indicated by means of one of specified values are acceptable.
the following prefixes : Possible corrections to published projects are published from time to time
in this magazine. Also, the readers letters column often contains useful
E (exa) = 1018 a (atto) = 10–18 comments/additions to the published projects.
P (peta) = 1015 f (femto) = 10–15
T (tera) = 1012 p (pico) = 10–12 The value of a resistor is indicated by a colour code as follows.
G (giga) = 109 n (nano) = 10–9
M (mega) = 106 µ (micro) = 10–6
k (kilo) = 103 m (milli) = 10–3
h (hecto) = 102 c (centi) = 10–2
da (deca) = 101 d (deci) = 10–1
In some circuit diagrams, to avoid confusion, but contrary to IEC and BS
recommandations, the value of components is given by substituting the rel- color 1st digit 2nd digit mult. factor tolerance
evant prefix for the decimal point. For example,
3k9 = 3.9 kΩ 4µ7 = 4.7 µF black – 0 – –
Unless otherwise indicated, the tolerance of resistors is ±5% and their rat- brown 1 1 ×101 ±1%
ing is 1⁄3–1⁄2 watt. The working voltage of capacitors is ≥ 50 V. red 2 2 ×102 ±2%
orange 3 3 ×103 –
In populating a PCB, always start with the smallest passive components, yellow 4 4 ×104 –
that is, wire bridges, resistors and small capacitors; and then IC sockets, green 5 5 ×105 ±0,5%
relays, electrolytic and other large capacitors, and connectors. Vulnerable blue 6 6 ×106 –
semiconductors and ICS should be done last. violet 7 7 – –
grey 8 8 – –
Soldering. Use a 15–30 W soldering iron with a fine tip and tin with a resin white 9 9 – –
core (60/40) Insert the terminals of components in the board, bend them gold – – ×10–1 ±5%
slightly, cut them short, and solder: wait 1–2 seconds for the tin to flow silver – – ×10–2 ±10%
smoothly and remove the iron. Do not overheat, particularly when solder- none – – – ±20%
ing ICS and semiconductors. Unsoldering is best done with a suction iron
or special unsoldering braid. Examples:
Faultfinding. If the circuit does not work, carefully compare the populated brown-red-brown-gold = 120 Ω, 5%
board with the published component layout and parts list. Are all the com- yellow-violet-orange-gold = 47 kΩ, 5%
A real µC PLC
using an AT89S8252 board
Erik Martens
What turns a mC board into a real PLC? A PLC is a controller with a program stored in memory,
where reliability, availability and safety are of the utmost importance. Only when a mC board
can be operated as a PLC and it complies with industrial standards can it be called a real PLC.
This project covers all aspects to turn Should the level of the supply voltage Firmware
a standard AT89S8252 µC board into a to voltage regulator IC4 drop below
real PLC, using a minimum of off-the- about 8.2 V, it will be reported to the The main PLC program works under
shelf components. To add the PLC µC via P1.3, after which all output supervision of the so-called firmware.
functionality to an AT89S8252 board modules are immediately turned off. An example of this firmware has been
we require a small section of extra soft- included in this article and you will find
ware (firmware) in the microcontroller. Two input modules have been it to be relatively small (about 100
Your own µC PLC program then works included in the circuit diagram, but bytes). The µC PLC firmware was writ-
under supervision of this firmware. you can add as many as you need to ten using the TASM shareware assem-
ports P0, P2 or P3. The inputs are elec- bler. The use of this assembler has been
trically isolated, can take +24VDC sig- covered in previous Elektor articles:
System overview nals, are protected against voltage ‘89S8252 Flash Microcontroller Board’
To turn a standard AT89S8252 board spikes and polarity reversal. (Dec. 2001), ‘Microcontroller Basics
into a PLC we make use of four I/O The output sections are also electri- Course’ parts 1 and 2 (Jan./Feb. 2002).
pins on the microcontroller (P1.0 to cally isolated. You can connect as These articles also describe the differ-
P1.3). When the controller is reset it many output modules as you need to ent ways in which the microcontroller
knows from the state of the flip-flop ports P0, P2 or P3. However, the output software can be put into the microcon-
(IC2a and IC2b, read via P1.0) whether sections can only be active when T1 trollers (external programmer, SPI).
a hardware reset or an internal reset conducts. This will only happen when
occurred. After a hardware reset the all operating conditions are satisfied The firmware takes care of the follow-
firmware sets the flip-flop using P1.1. (P1.1 and P1.2 high, STOP/RUN/RESET ing functions:
Port P1.1 also turns off all output sec- switch in the RUN position and a high
tions (a high level from P1.1 turns off enough supply voltage). Reset
T1 via IC3d and IC2d). After a reset the µC will immediately
To program the µC you can use the start running the firmware. If a hard-
The STOP/RUN/RESET switch (S1) is SPI port (P1.5, P1.6 and P1.7) on the ware reset occurred, the PLC will start
used by the firmware to start and stop µC. The programming can only take the first PLC cycle if all other conditions
the PLC program. This switch can also place when the reset line is active. are satisfied (STOP/RUN/RESET switch
be used (via R3) to force a hardware For this reason R8-R11 and IC3a have in the RUN position and a good supply
reset of the µC. P1.2 is used to read the been added, so that a high RS232 voltage). When an internal reset occurs
state of the STOP/RUN/RESET switch. input (for example DTR) will keep the (when the cycle time was exceeded),
When the switch is in the STOP posi- µC reset line permanently high. The the STOP/RUN/RESET switch first
tion, all outputs are automatically programming functionality via the needs to be set to the STOP position,
turned off. LEDs D7 and D8 show the SPI port is not shown in the circuit and then to the RUN position, before
current status of the PLC program. diagram. the PLC cycle will start again
Please note: this project is has not been tested or post-engineered by the Elektor Electronics laboratory.
R6
D7
470Ω
R3
C6
1k
green T1
RUN
100n
RS232:
reset µC IC3.A IC3.B IC3.C 40
R9 R10 IC2.A R4
TIP125
1 1 1
1k
27k 8k2
1k2
9 31
& RESET EA/VP
IC2.D
IC2.C IC3.E
30 3 R7
R8 R11 ALE/P P1.2 &
D9
C5 29 4 & 1
RESET
PSEN D8
STOP
P1.3
RUN
27k
4k7
IC2.B
10µ 1 39
4V7 & P1.0 P0.0
63V red
2 38 STOP
P1.1 P0.1
37 S1 R5
P0.2
IC1
1k
36
P0.3
input module 5 35 IC3.F
P1.4 P0.4
2k2 10k 6 34
4V7
P1.5 P0.5 1
SPI 7 33
P1.6 P0.6
8 32
1 P1.7 P0.7
1 3 AT89S8252
1k
+24VDC 10 21
P3.0 P2.0
11 22 output module 1N4001
P3.1 P2.1 47k
12 23
0V
P3.2 P2.2 BC327
05K25 13 24
2 4 P3.3 P2.3
green 14 25
SFH610-2 P3.4 P2.4
green 1 6 5
1N4148 15
P3.5 P2.5
26
16 27
P3.6 P2.6 470k +24VDC
17 28
input module P3.7 P2.7
2k2 10k X1 X2 220k
2 4
4V7 20 19 18
X1
BD243C
270 Ω 0V
1 CNY17-3
SFH601 1N4001
1 3
1k
+24VDC C7 C8
R2
4 7k
D3 D4 R1
C1
4k7
Hahn
EI4811172 1000µ 63V
030158 - 11
RUN-STOP function STOP condition all output modules are has an on-chip watchdog timer. This
The most important task of the turned off. timer is used to keep an eye on the
firmware is to make sure that all con- cycle time of the PLC program. At the
ditions are satisfied before starting a Supply voltage monitoring start of every PLC cycle the watchdog
PLC cycle. A PLC cycle can be started Before the start of every PLC cycle timer is reset. Should a PLC cycle take
if the following conditions are met: the firmware checks that the supply too long, for example caused by an
voltage is (still) in order. Should the endless loop within the PLC program,
•the STOP/RUN/RESET switch is in supply voltage at the input of voltage the internal watchdog will generate
the RUN position; regulator IC4 drop below about 8.2 V, an internal reset of the µC. In the
a new PLC cycle will not begin and reset state of the µC P1.1 will immedi-
•the supply voltage is high enough; the ERRPS routine will be called ately become ‘high’, which causes all
instead. This routine can be used to output modules to be turned off. The
•the STOP/RUN/RESET has been store variables into a non-volatile firmware will then detect that an
switched from RUN-STOP-RUN after memory (the EEPROM in the µC) internal reset occurred (by the state of
the PLC cycle time has been before the supply voltage drops too flip-flop IC2a/b) and will enter the
exceeded. far for the µC to stop functioning. If STOP condition. Despite the fact that
there is only a temporary drop in volt- the STOP/RUN/RESET switch is in the
STOP/RUN/RESET switch age (caused by interference, for RUN position, the PLC program will
This switch is used to control the run- example), which doesn’t reset the µC, remain in the STOP condition. The
ning of the PLC program. When the the PLC cycle will start again as soon program only exits from this condition
switch is turned to the STOP position as the supply voltage is restored. when the STOP/RUN/RESET switch is
the currently running cycle is still com- turned to STOP. This behaviour pre-
pleted, after which no new PLC cycle PLC cycle-time watchdog vents the PLC from starting again
is started. When the PLC is in the You may know that the AT89S8252 immediately after the PLC cycle time
Using the µC PLC firmware MOVX A,@DPTR store contents of address 16 into the accumulator
4
to restore variables from the EEPROM voltage after
voltage regulator
3
of the microcontroller. The example
2
below shows how to get the contents
1
of EEPROM address 16 and store it in
the accumulator (see Listing 1). service routine service routine
ERRPS ERRPS
voltage P1.3
when the STOP/RUN/RESET switch is
set to the RUN position (warm start). 030158 - 12
ERRPS: The ERRPS routine is called And finally... The source code for the controller
once when the supply voltage is This project forms the basis of a real firmware has been made freely avail-
turned off or when it falls below a PLC, where you are free to add a large able to Elektor Electronics readers by
critical level. In this routine you could number of input and output modules the author. This file can be down-
store permanent variables (these are according to your requirements. It also loaded from our website under no.
variables that have to keep their complies with industrial standards for 030158-11.
value during a power failure) into the signal interfacing, operation and control. (030158)
microcontroller EEPROM. The follow-
ing example shows how the value of
the B register is stored in the micro-
controller EEPROM at address 16
(see Listing 2).
switch is in the RUN position. This rou- consequences if you don’t comply with all relevant safety standards. For this reason it’s important that
tine could be used to light an LED that you follow all instructions shown on the safety guidelines page, regularly printed near the back of the
indicates that a program error has magazine. When you use the transformer recommended in this article you can mount the circuit into a box
occurred. This LED should be extin- that complies with the Class-II standard.
guished again in the INIPLC routine.
;RESET mC
START ANL WMCON,#11111110B ; disable watchdog
JB P1.0,SOFT ; jump, software reset
;HARDWARE RESET mC
HARD CLR P1.2 ; disable outputs using P1.2, because P1.1 will be used to set the reset-flipflop
CLR P1.1 ; set the reset-flipflop
JNB P1.0,HARD ; jump, wait until the reset-flipflop is set
SETB P1.2 ; enable outputs using P1.2
ACALL INIUC ; mC initialisation following a reset
SJMP NCYC
;SOFTWARE RESET mC
SOFT ACALL ERRCY ; STOP/RUN/RESET switch in RUN position after the cycle-time was exceeded
JB P1.2,SOFT ; jump, wait for the STOP/RUN/RESET switch to be in the STOP position
ACALL INIUC ; mC initialisation following a reset
SJMP NCYC ; jump, STOP/RUN/RESET switch was set to STOP
;PLC CYCLE
PLC JNB P1.2,NCYC ; jump, STOP/RUN/RESET switch is set to STOP
JB P1.3,NCYC ; jump, faulty supply voltage
SJMP WDTR ; jump, conditions are met to start a new PLC cycle
NCYC ANL WMCON,#11111110B ; disable watchdog
SETB P1.1 ; disable outputs using P1.1
JNB P1.3,PSOK ; jump, supply voltage OK
ACALL ERRPS ; faulty supply voltage
PSNOK JB P1.3,PSNOK ; jump, wait until the supply voltage is OK
PSOK MOV R2,#100 ; delay: #100 x #50 x 2ms = 10.000ms = 10ms
DEL0 MOV R1,#50 ;
DEL1 DJNZ R1,DEL1 ;
DJNZ R2,DEL0 ;
JNB P1.2,NCYC ; jump, STOP/RUN/RESET switch is in STOP position
JB P1.3,NCYC ; jump, faulty supply voltage
ACALL INIPLC ; PLC initialisation after the STOP/RUN/RESET switch is set to RUN,
; or when the supply oltage returns
CLR P1.1 ; enable outputs using P1.1, STOP/RUN/RESET switch is set to RUN
; and the supply voltage is OK
ORL WMCON,#11100000B ; WMCON: ms WMCON: ms
; #000xxxxx 16 #100xxxxx256
; #001xxxxx 32 #101xxxxx512
; #010xxxxx 64 #110xxxxx1024
; #011xxxxx 128 #111xxxxx2048
ORL WMCON,#00000001B ; enable watchdog
WDTR ORL WMCON,#00000010B ; watchdog-timer reset
;PLC PROGRAM
MAIN ...
LJMP PLC ; jump, next PLC cycle
;CYCLE TIME ERROR (STOP/RUN/RESET switch set to RUN after the cycle-time is exceeded)
ERRCY RET
E-blocks M g W
John Dobson
ak in
Many of you may be familiar with using the A/D inputs of the PICmicro microcontroller but
using D/As is less common. This short article examines how it is possible to use Flowcode
and E-blocks to produce a simple sinewave oscillator for use in testing audio circuits.
There is often a requirement for a simple sinewave oscil- smaller signals. The frequency will need to be around
lator you can use for testing audio circuits. The E-blocks 1 kHz – that’s mid-range audio. A quick check of the
system includes a D/A converter (DAC) so why not make specification of the MAX5385 D/A states that it has a
a general-purpose waveform generator with it? settling time of 20 µs for an output accuracy of “half of
To start with, you need to decide on the range of values the least significant bit”. If we have 256 samples per
you want to produce and do some calculations on the waveform then this would give us a maximum output fre-
overall parameters to check the project is feasible. The quency of 200 Hz. In theory that’s not high enough, but
D/A has an output range of 0 to 5 V in 255 equal steps. as we are using a sinewave, with small incremental steps
It does not make sense to go too near the supply rails in between samples, the system has a fighting chance of
case some headroom is needed for a buffer device, so to coping and we can always resort to reducing the number
keep things simple, go for a maximum of 4 V peak-to- of samples per waveform if it does not perform well.
peak output. This can be divided down in software to get
Get to grips with D/As
Data +127 Data +127 127 - Data 127 - Data Good news: D/As are relatively simple to use. You feed
Read data forwards Read data backwards Read data forwards Read data backwards
5 255
them a number and the analogue output level equals the
Voltage output (V)
In practice
First, let’s look at the hardware. We’re going to be using
the E-blocks SPI bus Board shown in the introductory Figure 2. NVM stuffing program.
photograph. This goes onto the Multiprogrammer board
which happens to have a PIC16F877 on it. You could
use almost any PIC with a USART. The SPI board goes on
port C and we have an LC display on port B and a key-
pad on port D.
The SPI board has a MAX5385 DAC as well as a 64-
kByte SPI bus and non-volatile memory (NVM). You may
first want to get the data into the NVM. As a future exten- Figure 3. Simple program to take NVM data and send it to the DAC.
sion of the project, consider building up a portfolio of dif-
ferent waveforms inside the NVM and then call them up
separately as needed using the keypad and LCD for
selection.
To populate the NVM, a program was written that stuffed
the core 64 data values into the NVM. A counter from
0–63 was set up, followed by a routine that writes indi-
vidual bytes of data to sequential NVM locations. In
Flowcode this is quite easy, you just initialise the SPI bus
and then write a program with 64 icons, each of which
writes a byte of data, as shown in Figure 2.
The next step will be to write a separate program to
check that the core values produce the first quarter of the
sine wave. This was fairly straightforward – again a
counter is established, reading the value from NVM loca-
tions 0 to 63 in turn, followed by a routine forwarding
the data from the NVM to the DAC. The Flowcode that
did it may be seen in action in Figure 3.
The oscillogram in Figure 4 shows you the first output
waveform for the first quarter cycle. It’s a bit rough
around the edges but looks like a quarter of a
sinewave. Unfortunately the time period for a quarter
cycle was 3 ms – giving a final frequency of under
Programs available
for download
In all mains-operated equipment certain approved switch, the contact gap in the
important safety requirements must be off position is not smaller than 3 mm.
met. The relevant standard for most The on/off switch must be fitted by
sound equipment is Safety of Informa- as shor t a cable as possible to the
tion Technology Equipment, including mains entry point. All components in
Electrical Business Equipment (Euro- the primary transformer circuit, includ-
pean Harmonized British Standard BS ing a separate mains fuse and separate
EN 60950:1992). Electrical safety under mains filtering components, must be
this standard relates to protection from placed in the switched section of the
• a hazardous voltage, that is, a volt- primary circuit. Placing them before the
age greater than 42.4 V peak or on/off switch will leave them at a haz-
60 V d.c.; ardous voltage level when the equip-
• a hazardous energy level, which is ment is switched off.
defined as a stored energy level of If the equipment uses an open-con-
20 Joules or more or an available struction power supply which is not
continuous power level of 240 VA separately protected by an ear thed
or more at a potential of 2 V or metal screen or insulated enclosure or
more; otherwise guarded, all the conductive
• a single insulation fault which would parts of the enclosure must be protec-
cause a conductive part to become tively earthed using green/yellow wire
hazardous; (green with a narrow yellow stripe – do
• the source of a hazardous voltage not use yellow wire with a green stripe).
or energy level from primary power; The ear th wire must not be daisy-
1. Use a mains cable with moulded-on plug.
• secondary power (derived from chained from one part of the enclosure 2. Use a strain relief on the mains cable.
internal circuitry which is supplied to another. Each conductive part must 3. Affix a label at the outside of the enclosure near the mains entry stating the
and isolated from any power be protectively ear thed by direct and equipment type, the mains voltage or voltage range, the frequency or fre-
source, including d.c.) separate wiring to the primary ear th quency range, and the current drain or curent drain range.
point which should be as close as pos- 4. Use an approved double-pole on/off switch, which is effectively the ‘discon-
Protection against electric shock is sible to the mains connector or mains nect device’.
achieved by two classes of equipment. cable entry. This ensures that removal 5. Push wires through eyelets before soldering them in place.
Class I equipment uses basic insu- of the protective earth from a conduc- 6. Use insulating sleeves for extra protection.
lation ; its conductive parts, which may tive part does not also remove the pro- 7. The distance between transformer terminals and core and other parts must
become hazardous if this insulation tective ear th from other conductive be ≥ 6 mm.
fails, must be connected to the supply parts. 8. Use the correct type, size and current-carrying capacity of cables and wires
protective earth. Pay particular attention to the metal – see shaded table below.
Class II equipment uses double or spindles of switches and potentiome- 9. A printed-circuit board like all other parts should be well secured. All joints
reinforced insulation for use where ters: if touchable, these must be protec- and connections should be well made and soldered neatly so that they are
there is no provision for supply protec- tively earthed. Note, however, that such mechanically and electrically sound. Never solder mains-carrying wires
tive earth (rare in electronics – mainly components fitted with metal spindles directly to the board: use solder tags. The use of crimp-on tags is also good
applicable to power tools). and/or levers constructed to the rele- practice.
The use of a a Class II insulated vant British Standard fully meet all insu- 10. Even when a Class II transformer is used, it remains the on/off switch whose
transformer is preferred, but note that lation requirements. function it is to isolate a hazardous voltage (i.e., mains input) from the pri-
mary circuit in the equipment. The primary-to-secondary isolation of the
when this is fitted in a Class I equip- The temperature of touchable parts
transformer does not and can not perform this function.
ment, this does not, by itself, confer must not be so high as to cause injury
Class II status on the equipment. or to create a fire risk.
Electrically conductive enclosures Most risks can be eliminated by the
that are used to isolate and protect a use of correct fuses, a sufficiently firm mains system (sometimes it is possible this magazine. However, the publishers
hazardous supply voltage or energy construction, correct choice and use of to fit this inside the mains outlet box or do not assume, and hereby disclaim,
level from user access must be protec- insulating materials and adequate cool- multiple socket). any liability for any loss or damage,
tively earthed regardless of whether the ing through heat sinks and by extractor direct or consequential, caused by
mains transformer is Class I or Class II. fans. * Sometimes called residual current errors or omissions in these guidelines,
Always keep the distance between The equipment must be sturdy: breaker – RCB – or residual circuit cur- whether such errors or omissions result
mains-carrying parts and other parts as repeatedly dropping it on to a hard sur- rent breaker –RCCB. from negligence, accident or any other
large as possible, but never less than face from a height of 50 mm must not cause.
required. cause damage. Greater impacts must These guidelines have been drawn up
If at all possible, use an approved not loosen the mains transformer, elec- with great care by the editorial staff of
mains entry with integrated fuse holder trolytic capacitors and other important
and on/off switch. If this is not avail- components.
able, use a strain relief (Figure, note 2) Do not use dubious or flammable 3-core mains cable to BS6500 1990 with three stranded
on the mains cable at the point of entry. materials that emit poisonous gases. conductors in thick PVC sheath
In this case, the mains fuse should be Shor ten screws that come too
placed after the double-pole on/off close to other components. Max current 3A 6A 13 A
switch unless it is a Touchproof® type Keep mains-carrying par ts and conductor size 16/0.2 mm 24/0.2 mm 40/0.2 mm
or similar. Close to each and every fuse wires well away from ventilation holes, Nom cond area 0.5 mm2 0.75 mm2 1.25 mm2
must be affixed a label stating the fuse so that an intruding screwdriver or overall cable dia. 5.6 mm 6.9 mm 7.5 mm
rating and type. inward falling metal object cannot touch
The separate on/off switch (Figure, such parts. Insulated hook-up wire to DEF61-12
note 4), which is really a ‘disconnect As soon as you open an equipment, Max current 1.4 A 3A 6A
device’, should be an approved double- there are many potential dangers. Most Max working voltage 1000 V rms 1000 V rms 1000 V rms
pole type (to switch the phase and neu- of these can be eliminated by discon- PVC sheath thickness 0.3 mm 0.3 mm 0.45 mm
tral conductors of a single-phase mains necting the equipment from the mains conductor size 7/0.2 mm 16/0.2 mm 24/0.2 mm
supply). In case of a three-phase sup- before the unit is opened. But, since Nom cond area 0.22 mm2 0.5 mm2 0.95 mm2
ply, all phases and neutral (where used) testing requires that it is plugged in overall wire dia 1.2 mm 1.6 mm 2.05 mm
must be switched simultaneously. A again, it is good practice (and safe) to
pluggable mains cable may be consid- fit a residual current device (RCD)*, 3-flat-pin mains plug to BS 1363A
ered as a disconnect device. In an rated at not more than 30 mA to the
Telephone Eavesdro
Galvanic isolation is a
special feature of this
telephone amplifier, which
includes a line output
connection for a hi-fi system.
From an idea by
Markus Müller
Although in some countries, including High Voltage level. The peak value of the ringing
the UK and Germany, analogue tele- voltage can thus be over 120 V. Despite
phone connections are something of a The amplifier described here has the the low current available, this is dan-
dying breed, most residential cus- special feature, not shared by any of its gerous: not just to humans, but also, in
tomers use analogue apparatus, even predecessors, of a line output. This particular, to connected electronic
in cases where the underlying connec- means that it can be connected to an devices. When the receiver is lifted, a
tion is over ISDN. ordinary hi-fi system. This requires, as current of between 10 mA and 30 mA
a glance at the circuit diagram in Fig- flows and the DC voltage falls to
There is little reason to change: first, ure 1 will show, complete galvanic iso- around 12 V. The analogue voice signal
ISDN telephones are rather expensive, lation between the telephone network is superimposed on this voltage.
and second, ISDN connection starter and the mains. Now we shall look at Private telephone exchange systems
packs generally include an a/b adap- the parts of the circuit in turn. and a/b adaptors can work at much
tor which allows the connection of old The amplifier has two RJ45 telephone- lower DC voltages (often 24 V)
analogue telephones to the ISDN sys- style sockets connected in parallel at because the distance to the telephone
tem. What a lot of analogue tele- its input, to simplify adding the circuit itself is much shorter.
phones lack, and which most modern into an existing cabling arrangement.
ISDN devices provide, is a loud- An analogue telephone connection
speaker. works essentially as shown in Fig- Amplification and filtering
ure 2. In the quiescent state the Of course, the telephone amplifier
The experienced Elektor Electronics exchange provides a DC voltage of must be designed to work at any of
reader will have no difficulty in nominally 60 V between the a-wire these voltages. It is the noble duty of
adding a loudspeaker. Several and the b-wire. The actual voltage input capacitor C2 to isolate these DC
designs for telephone amplifiers have level varies significantly with the dis- levels from opamp IC1 (an LF356). A
appeared previously in Elektor Elec- tance from the exchange and can be as high-voltage type is essential, and the
tronics, but there has never been a low as 40 V or as high as 80 V. To ring component recommended in the parts
circuit to which we cannot make the telephone to signal an incoming list can easily cope with 400 V.
some improvements or add new and call, the exchange superimposes an Next we must ensure that the AC
interesting features. AC voltage of up to 75 V on the DC component is also reduced to a level
+15V
+6V +6V
C5 C6 R7 R9 R11 Line
K1
220Ω
2Ω2
1 1k
D1 R1 1V35
2 P1 10µ 63V 100n
10k
R6 R10
3 C14
2k2
1k
4 BAT85 250k
C4 C7 C11 C10 3n3
5 2 8 6
6 220µ 470µ 100n
RJ45 68p
16V 16V
+6V8 1 1V53
3 7 IC2
5 R5
6 6N138
C2 R3 R4 IC1 1k 3 7 5
2 IC4
10k 100k 1
4 C12
15n 6V8
K2 LF356 +6V8
1 470µ
D2 R2 16V
2 C1 2 IN 5 LS1
C3 2
8k2
6 8
3 IC3 OUT1
1n 2µ2
4 BAT85 63V
6N138
5 3 OUT2 8
6 IN 8Ω
RJ45 +6V C13
2V2
+6V
IC6 5 7 3
+15V
>9V D4 7806 470µ
R12 C9 6 TDA7052 16V
3k3
>9V
1N4002 330n
1 7
VCC +V R8
C18 C17 C15 C16 IC5 C8
3k3
D3 P2
NMV0512SA
100n 100n 2 5 1n
10µ 10µ GND 0V 10k
63V 63V
030379 - 11
Figure 1. The telephone and audio parts of the circuit are kept strictly separate.
receiver down
POTS central
ring signal
home
exchange
receiver lifted
POTS central
030379 - 12a 030379 - 12b
Measured characteristics
Characteristic curve A shows the frequency response of the telephone +3
amplifier. The measurement was made at the line output, and thus -0
corresponds to the values for the loudspeaker output. The upper fre- -3
-6
quency range is shown for the two extreme settings of P1, and the LS = ∞
-9
effect of capacitor C4 is clearly visible. The –3 dB frequency of -12
LS = 8Ω
9.9 kHz (at –20 dB) falls to 6.8 kHz when P1 is set to maximum. d
-15
B -18
At the low-frequency end the effect of the loudspeaker is significant. r
-21
With the loudspeaker connected the corner frequency is 140 Hz, A
-24
whereas without the loudspeaker it is 100 Hz. Since the output -27
-33
put signal by about 1 dB, we have artificially superimposed the -36
curves so that they may be compared more easily. -39
-42
20 50 100 200 500 1k 2k 5k 10k 20k
Here are some of the characteristics as measured on the prototype: Hz 030379 - 13
Sensitivity Full drive, 1 V line level 60 mV Pmax (THD+N = 1 %) Voice signal 750 mW
Maximum output level THD+N = 1 % 1.6 V Minimum THD+N B = 22 Hz to 22 kHz 0.6 %
Maximum bandwidth 100 Hz to 9.9 kHz Signal-to-noise ratio at 500 mW, B = 22 Hz to 22 kHz 55 dB
Minimum bandwidth 140 Hz to 6.8 kHz Signal-to-noise ratio at 500 mW 57 dB
Minimum THD+N B = 22 Hz to 22 kHz 0.26 %
Quiescent current consumption 72 mA
THD+N B = 22 Hz to 22 kHz, LS1 = 8 Ω 1%
Current consumption at Pmax 0.3 A
Signal-to-noise ratio 250 mV in, 1 V out, B = 22 Hz to 22 kHz 55 dB
Current consumption when overdriven maximum 0.4 A
Signal-to-noise ratio 250 mV in, 1 V out 57 dBA Minimum supply voltage 9V
ROTKELE )C(
IC1
Although this arrangement is slightly C5 IC2 IC3
R3
R4
C9
noisy, the circuit has adequate band-
width and the gains in terms of linear- C8
C6
R1 R8
1-973030
ity and low distortion more than com- R2
D1
D2
pensate. C7 C11
C3 C10
P2
C1
K2
The current though IC2 is translated IC5
030379-1
R7
R9
IC4
into a voltage for the following output C15
C16
T
amplifier by R8. C9 removes the DC D4
C14
component of the signal on R8, and >9V IC6
0 C17 R11 C13
also forms a second high-pass filter
R12 R10
with a relatively low corner frequency C18 T C12
D3 LS1
OUT1
Optocoupler tolerances
Optocouplers have wide tolerances. If possible, use a type 6N138
with a current transfer ratio (CTR) of between 250 % and 450 %, as
otherwise IC2 and IC3 may attenuate the signal too much. If the volt-
age across R8 is a few tenths of a volt too low (a tolerance of 10 %
is allowable), its value can be increased to raise the voltage, and vice
versa. The circuit is so simple that if necessary other standard opto-
couplers with a Darlington output, such as the IL300, can be used
with a suitable adjustment to the resistor value. The CTR of IC2 is
easy to calculate: CTR = (UR8/R8) / (UR6/R6). Changing R8 naturally
affects the gain of the circuit, although for reasonable adjustments
this should not cause any problems.
just as well, but here the required mately 120 kHz. However, in our labora- circuit are separated. Populating the
capacitance is obtained using two tory prototype the frequency appeared board should present no difficulties. Do
capacitors in order to prevent a DC to be a little higher: we measured the not forget the wire links (the circuit
level appearing on the line output, ripple frequency to be approximately will work without them, but will be
which is taken from one of the ampli- 300 kHz. This does not affect the per- more susceptible to interference).
fier’s outputs. Because of this, the gain formance of the telephone amplifier, Sockets should be used for the ampli-
at the line output is only 33 dB. R10 but it does simplify the measures we fiers but not for the optocouplers, so
ensures that the two electrolytics need to take in the circuit to suppress that the isolation voltage is not com-
remain charged so that there is no interference. promised.
‘click’ when an external amplifier is
connected to the line output. R11 The fixed voltage regulator is the com- The connection points for the external
makes the output short-circuit-proof, mon-or-garden 7806, with its input pro- components (potentiometer, line
and C14 provides additional filtering to tected from reverse polarity connection socket, loudspeaker and power supply
remove high-frequency interference. To by a diode. The regulator has a drop- socket) lie around the edge of the
prevent undesirable coupling through out voltage of 3 V, and so the input board and should be fitted with termi-
the power supply connections, the voltage obtained from a mains adaptor nal pins.
optocouplers and the amplifier are sep- must be at least 9 V. Of course, the
arately smoothed (by R7 and C7, and telephone amplifier can also be pow- The circuit can be built into an ordi-
R9, C10 and C11 respectively). ered from a battery, although the cur- nary plastic enclosure, but a metallic
rent consumption is quite high. We screen (a piece of tin or unetched
measured a quiescent current con- printed circuit board) should be fitted
Power supply sumption of 72 mA on the prototype directly under the printed circuit board,
There is little point in galvanically iso- (even using a low current LED for taking care not to cause a short circuit.
lating the telephone line from the audio power indicator D3), with peak current The screen should be connected to the
electronics if their power supplies are up to 0.4 A (using an 8 Ω loudspeaker); metal enclosure of potentiometer P2
not also kept separate. To this end we battery operation is thus only appropri- and to ground. P2 should be fitted as
use a NMV05125SA DC-DC converter ate if the device is to be used occasion- close as possible to its connection
which converts an input voltage of 6 V ally. In any case, a PP3-style battery points on the board, and its connection
to an output voltage of 15 V while pro- will not last long, and it would be bet- wires twisted.
viding galvanic isolation up to 3 kV. ter to use four AA cells with IC6
The input voltage is a little higher than replaced by a wire link and D4 ideally For best audio results a small, good-
the maximum value of 5.5 V specified replaced by a Schottky diode such as quality loudspeaker should be used
in the data sheet, but is clearly within the 1N5822 (40 V, 3 A). At 0.4 A this inside a large enclosure rather than in
the ‘absolute maximum rating’ of 7 V. Schottky diode drops only 0.3 V, con- the electronics box, with the loud-
In practice, it works well, and thanks siderably less than the 0.8 V drop of a speaker being located a few metres
to the low load, the output voltage is 1N4002. away from the telephone to prevent
slightly higher than the 14.4 V that one feedback. Alternatively, the line output
would expect with an input voltage of can be connected to a hi-fi system.
6 V. The converter presents a rather Keep your distance
aggressive load to the fixed voltage The steps we have taken to achieve The circuit discussed in this article is
regulator, resulting in an output ripple galvanic isolation are clear in the not approved for connection to the
voltage of 0.1 Vpp. According to the printed circuit board layout of Figure 3. public switched telephone network
manufacturer’s data, the converter As can be seen, the ground planes for (PSTN) in the United Kingdom.
switches at a frequency of approxi- the telephone and audio parts of the (030379-1)
Microcontroller Basics
Burkhard Kainka
Linear Motors
and their modern applications
Dr. Thomas Scherer
Source: Siemens AG
A linear motor is simply one which produces motion in a straight line rather than in a cir-
cle. We give an overview of the technology and its applications, including examples of
‘genuine’ linear motors and related devices.
Although space does not permit a full introduction to precise head drive mechanism was required than the
electromagnetic theory in this article, we should men- rotary stepper motor design like that used in floppy disk
tion that there are linear drive systems where electricity drives. Under control of specially-designed position sen-
is turned into motion in a straight line which we never- sors, the ‘voice coil’ mechanism, as it is known,
theless do not count as genuine ‘linear motors’. These achieves previously unattainable tracking precision
are so-called dynamic actuators which operate on a and, thanks to the high force available, fast seek times.
very simple principle using a magnet and a coil, and In machine tools actuators are starting to be used for
which have long been used in various applications. simple and short linear motions, replacing pneumatic
systems. In these, the roles of coil and magnet are
A good example of this type of drive is the classical reversed: the coil is fixed and the magnet or piece of
dynamic loudspeaker. Figure 1 is a diagram of its metal moves. In contrast to pseudo-linear actuators,
construction. Its operation is simple and well known: a where the linear motion is derived from the rotation of a
coil in a magnetic field experiences a force propor- conventional electric motor using a rack and pinion or
tional to the current flowing in it. Apart from applica- a belt drive, these solutions have the advantage of
tions in sound production, this principle has been in use being smaller and simpler.
for almost 20 years in the positioning mechanisms for
read/write heads in hard disk drives. Once capacities Further advantages include less wear and tear, high
exceeded 40 Mbyte and track widths shrank, a more power and consequent ease of use and reliability. Since
iVÌÊÞÕÀÊLVÃÊÌÊÌ iÊÌiÀiÌ ÊV«iÝÊÃÞÃÌiÊ>`iÊÌÀ>ë>ÀiÌ
LVÃÊ>ÀiÊÃ>ÊÃivVÌ>i`ÊiiVÌÀV /
iÊ
ÊLÕÃÊÃÊ>ÊÀiÃiÌ]Ê
}
Ê`>Ì>ÊÀ>ÌiÊLÕÃÊvÀÊ
VÀVÕÌÃÊ>`Ê«ÀÌi`ÊVÀVÕÌÊL>À`ÃÊÌ
>ÌÊV> VÕV>Ì}Ê LiÌÜiiÊ iiVÌÀVÊ `iÛViÃÊ Ê
LiÊVLi`ÊÌÊVÀi>ÌiÊvÕVÌ}ÊiiVÌÀV ÃÌÕ>ÌÃÊÜ
iÀiÊ
}
Ê`>Ì>ÊÀi>LÌÞÊÃÊÀiµÕÀi`°Ê
"iÊ ÕÃiÊ vÊ Ì
iÊ
Ê LÕÃÊ ÃÊ Ê Ì
iÊ >ÕÌÌÛiÊÊ
>««V>ÌÃÊ>`ÊÃÞÃÌiðÊ7Ì
ÊÌ
iÊ
LVÃÊ
`ÕÃÌÀÞÊÜ
iÀiÊÌÊÃÊLi}ÊÕÃi`Ê>ÃÊ>ÊÃÕLÃÌÌÕÌiÊvÀÊ
ÌiÀiÌÊL>À`ÊÞÕÊV>ÊViVÌÊÞÕÀÊÜÊÃÞÃÌiÊ
V««iÀÊÜÀ}ÊÃÊÊV>ÀðÊ/
iÊ
LVÃÊ
>ÃÞÊ
ÌÊÌ
iÊÌiÀiÌ°Ê/
ÃÊ`ÕiÊÃÊ«iÀviVÌÊÌʵÕVÞÊ
ÊÌÊ>ÜÃÊÞÕÊÌÊi«ÞÊÌ
ÃÊ«ÀviÃÃ>ÊLÕÃÊÃÞÃÌiÊÊÞÕÀÊÜÊ
>``Ê>ÊëiÊÜiL«>}iÊÌÊÞÕÀÊiLi``i`ÊÃÞÃÌi°Ê/
ÃÊÌ
iÊ«iÀÌÃÊi>ÃÕ >««V>ÌðʫiiÌ}Ê
ÊÃÊ >Ê V«iÝÊÌ>ÃÊ Ê >}Õ>}iÃÊiÊ
]Ê
ÀiiÌ®Ê`>Ì>ÊÌÊLiÊëiVÌi`ÊÀiÌiÞ°Ê««V>ÌÃÊVÕ`iÊÀi>`}ÊÕÌÊ>Ê LÕÌÊ `}Ê ÃÊ ÜÌ
Ê ÜV`iÊ >`Ê
LVÃÊ ÃÊ >VÌÕ>ÞÊ ÛiÀÞÊ Ã«i°Ê ÃÊ >Ê
Üi>Ì
iÀÊÃÌ>Ì]ÊÃÜÌV
}Ê}
Ì}ÊÃÞÃÌiÃÊ>`ÊÌÀ}Ê>`ÊVÌÀ}ÊÊ Ã«iV>ÊvviÀÊÌÊiVÕÀ>}iÊÞÕÊÌÊÛiÃÌ}>ÌiÊ
ÊÜiÊ>ÀiÊ>}Ê>Û>>LiÊ
>V
iÃtÊ/
iÊ>««V>ÌÊ>Ài>ÊÃÊÌÀÕÞÊëiVÌ>VÕ>Àt >Ê
LVÃÊ
>ÃÞÊ
ÊÌÊ>ÌÊÎä¯Ê`ÃVÕÌ°ÊÊvviÀÊÞÕÊ
½ÌÊÀiÃÃÌt
Ê
LVÃÊ
>ÃÞÊÌiÀiÌÊÌ\
LVÃÊ
>ÃÞÊ
ÊÌ\
ÜV`iÊ*ÀviÃÃ>Ê Ê Ê ËÊ££n°ää ÜV`iÊ*ÀviÃÃ>Ê Ê Ê Ê ËÊ££n°ää
LVÃÊ
ÊL>À`ÊÊÊ Ê Ê ËÊÊÊ£{°Èx
LVÃÊ
ÊL>À`ÊÊÊ Ê Ê Ê ËÊÊÊ£{°Èx
LVÃÊ
ÊL>À`ÊÊÊ Ê Ê ËÊÊÊ£°Îä ÓÊÝÊ
LVÃÊ
ÊL>À`ÊÊ Ê Ê Ê ËÊÊÊÎn°Èä
ÓÊÝÊ
LVÊ1- ÊÕÌ«À}À>iÀÊÊ Ê Ê ËÊ£x{°Èä
LVÃÊ1- ÊÕÌ«À}À>iÀÊÊ Ê ËÊÊÊÇÇ°Îä
LVÃÊ-ÜÌV
ÊL>À`ÊÊÊ Ê Ê Ê ËÊÊÊ£{°Èx
LVÃÊÃÜÌV
ÊL>À`ÊÊÊ Ê Ê ËÊÊÊ£{°Èx
ÓÊÝÊ
LVÃÊ
ÊL>À`Ê Ê Ê Ê ËÊÊÊÈÇ°ää
LVÃÊÌiÀiÌÊL>À`Ê Ê Ê ËÊÊÊÇ£°x
ÓÊÝÊ*
£ÈnÇÇÊ Ê Ê Ê Ê ËÊÊÊÓ£°ää
*
£ÈnÇÇÊ Ê Ê Ê ËÊÊÊ£ä°xä
Ì
iÀiÌʼVÀÃÃÛiÀ½ÊV>LiÊ Ê Ê ËÊÊÊÊÊx°Îä /Ì>ÊÛ>Õi\Ê Ê Ê Ê Ê ËÊ{Ón°xä
Energy recovery
1 +U B 2 +U B 3 +U B
D1
D1
D2 UC
D2
UB
D3
A
SIGNAL T1 SIGNAL T1 T1
R1 R1 SIGNAL R1
UA
Peter Lay current is switched off (Fig- So far we have not actually recov- relative to ground the open-circuit
ure 1). If an LED is wired in ered any energy. Figure 3 voltage at point A is the sum of
Energy is becoming more and series with the flywheel diode shows a theoretical design where the capacitor voltage due to the
more expensive, and so we are (Figure 2) it will flash every time the energy stored in the relay coil recovered energy and the supply
always on the lookout for ways to there is an inductive spike with is recovered so that it can be voltage. In particular, the voltage
save energy in circuits. The the transistor turns off. The dura- used to supply a (low-power) cir- at point A is higher than the sup-
author has decided to look at tion and brightness of the flash cuit. The greater the inductance ply voltage.
how to recovery energy from a (and indeed, whether the spike is of the coil and the more fre-
relay switching circuit. large enough to destroy the LED!) quently it is switched, the more The author would be interested in
If a relay is driven by a transistor depend on the rate of change of energy is stored in capacitor C. discussing these ideas further with
switching stage it is usual to con- the current in the relay coil and its The zener diode (in series with readers. His e-mail address is
nect a flywheel diode in parallel inductance: the flywheel diode) limits the max- info@peterlay.de.
with the coil to short out the back imum voltage to which the capac- (050310-1)
EMF produced when the relay ui = –L di / dt itor can be charged. Measured
10k
gency calls. A small lamp will pin 5 that drives the 1N4001
4...12V
also flash synchronously with the loudspeaker. The 4 14 10
10k
2I 2I
R
A2 A2
A1 A1
R RL R RL
-UB
050201 - 2 - 11 -UB
050201 - 2 - 12
Klemens Viernickel number of other components. output of the first opamp is con- will then start to deliver more and
This design takes up board nected to the input of a further non- more current to the output via the
Integrated opamps offer advan- space and is relatively expen- inverting opamp stage as well as resistor, and the sum of the output
tages such as ease of use, good sive, tending to offset the advan- being connected to the output of the currents of the two opamps thus
price-performance ratio and tages of the integrated device. circuit via a resistor. The first opamp flows through load resistor RL.
small physical size. However, An alternative possibility is to thus drives the second non-inverting By adding another resistor we can
they seldom have an output cur- boost the output drive capability amplifier which provides all the out- compare the current contributions
rent drive capability of greater by connecting opamps in paral- put current of the circuit as long as from the two opamps (Figure 2).
than about 12 mA, and so they lel. The output current will then that remains within its normal capa- The complete circuit with two
are not suitable for use in 20 mA be approximately proportional bility. As the output current demand opamps is shown in Figure 3.
current loop applications, for to the number of opamps. increases the second opamp will The principle of the circuit can be
example. One solution is to add Instead of a single opamp a reach the limit of its drive capabil- extended to more opamps with
a driver stage with the necessary dual or quad device is used to ity. Its gain will then fall off and a their output currents being added
output power, comprising per- achieve greater output power. voltage difference will develop together (see Figure 4).
haps two to four transistors and a The idea is shown in Figure 1. The across its inputs. The first opamp (050201-2)
+U B
3 4 +U B
RF
RS
3I
A1 2I
RI
I A3
A2
A1
RS RL R RL
u IN
A2
R
I
-UB 050201 - 2 - 14
050201 - 2 - 13
-UB
The ‘Kaleidoscope’ E
How was it for you?
Larry Kossek
been noted and will no doubt be considered when we quate, but nevertheless it was a splendid effort
next get the opportunity to make similar offers. regardless” Another commented: “many of the programs
A KiCAD enthusiast has suggested that we run a tutorial require a large investment of time and the limited nature
series on this software, good idea, any volunteers out of the demo software means that it was not worth the
there willing to take this on? time and effort.” Reading between the lines it seemed
that many respondents were looking for advice on
Some programs received critical remarks, the latest offer- the best system to purchase, but such recommenda-
ing from Protel for example attracted a number of nega- tions were not what we intended and are anyway
tive comments while another reader observed that: almost impossible to make for this type of software.
“Boardmaker Win is far too expensive for private use!!” Many had hoped for fuller versions of the software but
It came as no surprise that the most popular programs we can only pass on the version which is supplied to us.
attracted praise (e.g. EASY PC), and especially SPlan It will only take one publisher to release a freeware ver-
and Sprint Layout were often mentioned. sion with more features for the others to follow suit to
“SprintLayout fulfils my requirements more precisely than maintain market share.
any of the other programs”.
One reader suggested that a future DVD might feature
PC-based test equipment and circuit simulation software.
Another reader thought a DVD containing programming
tools and program development environments would be
useful. These suggestions have been noted and may be
incorporated in future DVDs.
ical parts list was printed and an for PCs! The program from B.
artist’s impression of the assem- Lewetz was called Mondriaan
bled plotter, we were inundated after the Dutch artist (1877-
with questions like ‘how to 1944). Although it supported just
assemble the thing’ and where to six basic commands from the
obtain Skiffy parts, Binder mag- much larger HPGL set, the pro-
nets, Berger stepper motors and gram effectively made the project
Rotring pen refills. Fortunately, come alive after a two year wait.
Jan Buiting size!), and the X motion handled one of our advertisers, Meek-it Reader response was overwhelm-
by a pen carriage covering a from The Hague, Holland, ing as the missing link between
This story starts in May 1988 span of about 50 cm along a stepped in and offered a kit of hardware and software had been
with the publication of an article guide bar. The May 1988 article parts to build the plotter. catered for at long last. The
with the delightfully simple and came with a set of mechanical famous ‘Columbia’ and ‘nozzle’
technically correct title ‘Plotter drawings of the (mostly alu- After al the hubbub around the drawings were supplied with the
(part 1)”. The design was based minium) parts to cut, mill, drill and mechanical construction, silence program, along with a few pen
on a mechanical drawing and file before you could even start reigned when we published calibration and plotter test files.
an accompanying letter sent to us dreaming of assembling the plot- part 2 of the article in June 1988. Market leading programs like
by one J. Arkema from the ter. These drawings were pro- In it, we duly described the algo- Autocad and Autosketch at the
Netherlands. This was at a time duced manually on an ordinary rithms that (we assumed) would time employed only six HPGL
that plotters were noisy, slow and drawing stand. It turned out a enable talented readers to write commands so the Elektor plotter
expensive PC adjuncts only seen quite unusual job for our drawing their own drivers to control the did just fine on the Centronics
in the cellars of professional engi- staff, and it took several versions plotter from a PC. A wrong port. In the UK, Cliff Gregory
neering bureaus running Auto- before a ‘blueprint’ was pro- assumption, as virtually no optimised the mechanical design
CAD or similar programs. Of duced that could be read by response was received and for of the Elektor plotter and started
course, the electronics hobbyist someone accustomed to working quite some time it seemed that no to supply ‘Plotter Mk3’ kits com-
had different things in mind to do with a lathe. Mind you, no plotter one had the fuzziest notion of prising ball bearings and stainless
with a plotter, if only he could get was available, let alone a pro- what we meant by octants, step- steel parts.
his hands on one: drawing gram or a PC. per motor look-up tables and
schematics and ‘printing’ PCB MC3479 control bytes, let alone Finally, in September 1991 we
artwork! Unfortunately, to this Unfortunately, despite the efforts Bresenham’s algorithm. published another plotter driver,
day a working high-end plotter, that went into producing the The silence was broken in March this time written in Turbo Pascal
particularly one of Hewlett drawings, a poor balance was 1990 when we were finally able and supporting 17 HPGL com-
Packard, is a fairly rare find. struck between the mechanical to publish “Plotter Mark 2”, dis- mands. Supplied on a 360 kB
The proposed plotter, then, was a construction (wrapped up in cussing a few mechanical 5.25 inch floppy disk (and later
simple X-Y type, with the Y move- about two pages) and the elec- improvement to the original on 3.5 inch), it turned out to be
ment carried out by a platen mov- tronics we all understood so design but more importantly a huge sales success.
ing the paper sheet (up to A2 much better. Although a mechan- ‘partly HPGL compatible’ driver (065015-1)
Retronics is a monthly column covering vintage electronics including legendary Elektor designs. Contributions, suggestions and requests are welcomed; please send an
email to editor@elektor-electronics.co.uk, subject: Retronics EE.
- *Ê "8
iÝÌÊÃÃÕi\ÊÊÊ ÊÊÊÊÊÊÊÊÊÊÊ
Ì
iÊv>ÃÌÊÊÌÊ>ÊVÀVÌÀiÀtÊ
7>ÌÊÌÊÜÊiÛiÀÞÌ
}Êi>V
ÊÌ
¶Ê
-iiVÌÊÞÕÀÊÜÊ>Õ>ÊÃÕLÃVÀ«ÌÊ>`Ê
ÀiViÛiÊ>ÊvÀiiÊ£7ÊÕÝiÊ
Ê/ÀV
}
ÌI
(]HPSHISLVW[PVUZ!
,SLR[VY,SLJ[YVUPJZHUU\HSZ\IZJYPW[PVUZ[HUKHYK
@V\YLJLP]LPZZ\LZPUJS\KPUN[OL1\S`(\N\Z[KV\ISLPZZ\L
,SLR[VY,SLJ[YVUPJZHUU\HSZ\IZJYPW[PVU73<:
@V\YLJLP]LPZZ\LZPUJS\KPUN[OL1\S`(\N\Z[KV\ISLPZZ\L
WS\ZHJVW`VM[OL,SLR[VY,SLJ[YVUPJZ=VS\TL*+964
UVYTHSWYPJL@V\YZH]PUN!HWWYV_
7SLHZLÄSSV\[[OL6YKLY-VYT^P[O[OPZPZZ\L
:\IZJYPW[PVUYH[LZHUKJVUKP[PVUZTH`ILMV\UKH[[OLIHJRVM[OPZPZZ\L
6MMLYH]HPSHISL[V:\IZJYPILYZ^OVOH]LUV[OLSKHZ\IZJYPW[PVU[V,SLR[VY
,SLJ[YVUPJZK\YPUN[OLSHZ[TVU[OZ6MMLYZ\IQLJ[[VH]HPSHIPSP[`
PUZZLE INFOTAINMENT
Hexadoku
Puzzle with an electronic touch
Entering the competition
Please send the numbers in the grey
boxes by email, fax or post to
! % * . ) , $ ' "
" % & . ) # ,
% " , + *
' * # . "
* # - $ & '
+ " & - # * ) worth £248.55
' " % ,
and three
Elektor Electronics
) . $ # &
Shop Vouchers
worth £35 each.
RESERVE YOUR COPY NOW! The April 2006 issue goes on sale on Thursday 16 March 2006 (UK distribution only).
UK subscribers will receive the magazine a few days before this date. Article titles and magazine contents subject to change.
Name: ............................................
Address: ............................................
Please cut out or photocopy this form, com-
Post code: ............................................ plete details and hand to your newsagent.
Telephone: ............................................ Elektor Electronics is published on the third
Date: ............................................ Friday of each month, except in July.
Signature: ............................................ Distribution S.O.R. by Seymour (NS).
In the Elektor Electronics Shop you’ll find all other products sold by the pub-
lishers, like CD-ROMs, kits and books. A powerful search function allows you
to search for items and references across the entire website.
03-2006
description; for books, state the full title; for photocopies of articles, state full name of article and month and year of publication.
PLEASE USE BLOCK CAPITALS.
Sub-total
Prices and item descriptions subject to change. Please send this order form to *
The publishers reserve the right to change prices (see reverse for conditions)
without prior notification. Prices and item descriptions
P&P
shown here supersede those in previous issues. E. & O.E.
Total paid Elektor Electronics (Publishing)
Regus Brentford
1000 Great West Road
Brentford TW8 9HH
Name
United Kingdom
Tel.: (+44) (0) 208 261 4509
Address + Post code
Fax: (+44) (0) 208 261 4447
Internet: www.elektor-electronics.co.uk
sales@elektor-electronics.co.uk
*USA and Canada residents may
(but are not obliged to)
Tel. Email use $ prices, and send the order form to:
Old Colony Sound Lab
P.O. Box 876, Peterborough
✁
✁
EL03 Email: custserv@audioXpress.com
Order Form
03-2006
* Offer available to Subscribers who have not held a subscription Expiry date: .................................................
to Elektor Electronics during the last 12 months. Offer subject to availability.
See reverse for rates and conditions. Verification code: .........................................
SWITCH ONLY:
Start date: ....................................................
Name
Issue number: ..............................................
Subscription
* cross out what is not applicable Fax: (+44) (0) 208 261 4447
Internet: www.elektor-electronics.co.uk
EL03 subscriptions@elektor-electronics.co.uk
ORDERING INSTRUCTIONS, P&P CHARGES
Except in the USA and Canada, all orders, except for subscriptions (for which see below), must be sent BY POST or FAX to our Brentford address
using the Order Form overleaf. On-line ordering: http://www.elektor-electronics.co.uk
Readers in the USA and Canada may (but are not obliged to) send orders, except for subscriptions (for which see below),
to the USA address given on the order form. Please apply to Old Colony Sound for applicable P&P charges. Please allow 4-6 weeks for delivery.
Orders placed on our Brentford office must include P&P charges (Priority or Standard) as follows:
UK: £4.00 Europe: £5.00 (Standard) or £7.00 (Priority) Outside Europe: £8.00 (Standard) or £12.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. 40209520 held by Elektor Electronics (Publishing) / Segment b.v. with ABN-AMRO Bank, London. IBAN: GB35
ABNA 4050 3040 2095 20. 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 (Publishing) / Segment b.v.. We can only accept sterling cheques and bank drafts
from UK-resident customers or subscribers. We regret that no cheques can be accepted from customers or subscribers in any other country.
Giro transfer into account no. 34-152-3801, held by Elektor Electronics (Publishing) / Segment b.v. Please do not send giro transfer/deposit
forms directly to us, but instead use the National Giro postage paid envelope and send it to your National Giro Centre.
Credit card VISA, Access, MasterCard, JCBCard and Switch cards can be processed by mail, email, web, fax and telephone. Online ordering
through our website is SSL-protected for your security.
COMPONENTS
Components for projects appearing in Elektor Electronics are usually available from certain advertisers in this magazine. If difficulties in the supply
of components are envisaged, 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 Brentford office within 10-days (UK); 14-days (Europe) or 21-days (all other countries). Cancelled orders All cancelled orders
will be subject to a 10% 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 Electronics (Publishing) 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 advertisements) 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 Electronics (Publishing) 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 Electronics (Publishing) 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 Electronics (Publishing) other
than to supply goods as described or, at the option of Elektor Electronics (Publishing), 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 Electronics (Publishing) shall be determined in all respects by the laws
of England. January 2006
Standard Plus
United Kingdom £41.90 £48.80
Surface Mail
Rest of the World £54.50 £61.40
USA & Canada US$ 95.50 US$106.50
Airmail
Rest of the World £68.90 £75.80
USA & Canada US$120.00 US$131.00
Bank transfer into account no. 40209520 held by Elektor Electronics The standard subscription order period is twelve months. If a perma-
(Publishing) / Segment b.v. with ABN-AMRO Bank, London. IBAN: GB35 nent change of address during the subscription period means that
ABNA 4050 3040 2095 20. BIC: ABNAGB2L. Currency: sterling (UKP). copies have to be despatched by a more expensive service, no extra
Please ensure your full name and address gets communicated to us. 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
Cheque sent by post, made payable to Elektor Electronics (Publishing) service.
/ Segment b.v.. We can only accept sterling cheques and bank drafts Student applications, which qualify for a 20% (twenty per cent) reduc-
from UK-resident customers or subscribers. We regret that no cheques tion in current rates, must be supported by evidence of studentship
can be accepted from customers or subscribers in any other country. signed by the head of the college, school or university faculty. A
standard Student Subscription costs £33.50, a Student Subscription-
Giro transfer into account no. 34-152-3801, held by Elektor Plus costs £40.40 (UK only).
Electronics (Publishing) / Segment b.v. Please do not send giro transfer/ Please note that new subscriptions take about four weeks from receipt
deposit forms directly to us, but instead use the National Giro postage of order to become effective.
paid envelope and send it to your National Giro Centre. Cancelled subscriptions will be subject to a charge of 25% (twenty-
five per cent) of the full subscription price or £7.50, whichever is the
Credit card VISA, Access, MasterCard, JCBCard and Switch cards can higher, plus the cost of any issues already dispatched. Subsciptions
be processed by mail, email, web, fax and telephone. Online ordering cannot be cancelled after they have run for six months or more.
through our website is SSL-protected for your security. January 2006
ISBN 90-5381-195-8
£12.95 / US$ 22.90
Home Automation
New
The CD-ROM contains specifications, standards Order now using the Order Form
and protocols of commercially available bus and network systems. in the Readers Services section
For developers, there are datasheets of specific components and in this issue.
various items with application data. End-users and hobbyists will find
Elektor Electronics (Publishing)
ready-made applications that can be used immediately.
Regus Brentford
1000 Great West Road
The documents included on the CD-ROM have been classified Brentford TW8 9HH
according to communication media: mains (power line), coaxial cable, United Kingdom
Tel. +44 (0) 208 261 4509
telephone line and wireless (RF).
See also
www.elektor-electronics.co.uk
INDEX OF ADVERTISERS
Allgood Technology, Showcase . . . . . . . .www.allgoodtechnology.com . . . . . . . . . . . . . . .80 KMK Technologies Ltd, Showcase . . . . . .www.kmk.com.hk . . . . . . . . . . . . . . . . . . . . . . .81
Avit Research, Showcase . . . . . . . . . . . . .www.avitresearch.co.uk . . . . . . . . . . . . . . . . . .80 London Electronics College, Showcase . .www.lec.org.uk . . . . . . . . . . . . . . . . . . . . . . . . .81
Beta Layout, Showcase . . . . . . . . . . . . . .www.pcb-pool.com . . . . . . . . . . . . . . . . . . .45, 80 MQP Electronics, Showcase . . . . . . . . . .www.mqpelectronics.co.uk . . . . . . . . . . . . . . . .81
Bitscope Designs . . . . . . . . . . . . . . . . . .www.bitscope.com . . . . . . . . . . . . . . . . . . . . . .15 New Wave Concepts, Showcase . . . . . . .www.new-wave-concepts.com . . . . . . . . . . . . .81
Burn Technology LTD, Showcase . . . . . . .www.burntec.com . . . . . . . . . . . . . . . . . . . . . . .80 Number One Systems . . . . . . . . . . . . . . .www.numberone.com . . . . . . . . . . . . . . . . . . . .45
Future Technology Devices, Showcase . . .www.ftdichip.com . . . . . . . . . . . . . . . . . . . . .3, 80 Virtins Technology, Showcase . . . . . . . . .www.virtins.com . . . . . . . . . . . . . . . . . . . . . . . .81
Schematic &
PCB Layout New Features
! Powerful & flexible schematic capture. in Version 6.8
! Auto-component placement and rip-up/retry PCB routing.
! Polygonal gridless ground planes. ! Interactive Design Rule Check.
! Libraries of over 8000 schematic and 1000 PCB parts. ! Mitring / Unmitring.
! Bill of materials, DRC reports and much more. ! Enhanced track editing.
! Struct/Array expansion.
Mixed Mode SPICE Circuit Simulation
! Berkeley SPICE3F5 simulator with custom extensions for
! ELF/DWARF file loader.
true mixed mode and interactive simulation.
! Expanded model libraries.
! 6 virtual instruments and 14 graph based analysis types.
! 6000 models including TTL, CMOS and PLD digital parts. Call Now for Upgrade Pricing
! Fully compatible with manufacturers’ SPICE models.
ECD
Edition 3
Now with a new
user interface!
ISBN 90-5381-159-1
£14.95 (US$ 26.50)
Elektor’s Components
Database gives you easy
access to design data for
over 5,000 ICs, more than
35,000 transistors, FETs,
Elektor Electronics
thyristors and triacs, just (Publishing)
under 25,000 diodes and Regus Brentford
1,800 optocouplers. 1000 Great West Road
Brentford TW8 9HH
All databank applications
United Kingdom
are fully interactive, allowing
the user to add, edit and Tel. +44 (0) 208 261 4509
complete component data. Fax +44 (0) 208 261 4447
C Basics
The structure of a C program ............................................................. 6
The main function............................................................................. 6
Comments in C .................................................................................. 6
The #include directive .................................................................. 7
Keywords in C .................................................................................... 7
Operators in C
Arithmetic operators ......................................................................... 11
Relational operators ......................................................................... 11
Logical operators.............................................................................. 11
Shortcuts .......................................................................................... 12
Functions in C
The function concept........................................................................ 13
Declaring a function ......................................................................... 13
Calling a function.............................................................................. 14
Program Control
If ....................................................................................................... 16
if...else.............................................................................................. 16
switch ............................................................................................... 17
for ..................................................................................................... 18
while ................................................................................................. 19
do...while .......................................................................................... 20
Appendix
Header file sfr_r813.h....................................................................... 21
Header file math.h............................................................................ 23
elektor electronics 3
Foreword
Why C?
Many electronics hobbyists have used microcontrollers successfully, and they have
also written wonderful programs in assembly language. As the size and complexity of
an assembly-language program increase, the desire for a more effective
programming environment also increases. Anyone who has tried to implement a
mathematical function in assembly language, such as 1/x, sin(x) or the like, knows
the problems. Here a high-level language such as C, which is the industry standard
in the microcontroller and microprocessor world, offers decisive advantages. C
programs are portable, which means the program structure can be transferred to
other types of microcontrollers after it has been written. The only things that have to
be modified are the port assignments and the settings for the special function
registers.
Professional programmers claim that an assembly-language program that would take
14 days to generate can be generated in 2 to 3 days in C. What’s more, an
increasing number of semiconductor manufacturers are making highly effective
development environments available at no charge. That’s another good reason to
start using C.
But there’s a hitch. As we all know, the gods have ordained that success doesn’t
come without hard work. An introductory course in the C language and sample
programs from technical magazines can help you overcome the initial hurdles, but
will take a while before you can write you own programs. You will also have to master
a certain amount of specialist vocabulary. As can be seen from contributions to
microcontroller forums and questions asked in these forums, that forms a significant
problem for many electronics hobbyists.
This booklet is limited to the basic elements of the C language. We have intentionally
omitted complex C structures such as pointers, arrays, strings, structures, unions and
the like. This booklet is intended to serve as a reference for beginners. It cannot
replace a basic course in C, nor is it intended to do so.
4 elektor electronics
C Basics
The structure of a C program
All C programs consist of several parts, such as comments, preprocessor
instructions, declarations, definitions, expressions, assignments and functions. The
following listing shows a simple example.
/* FILE :my1c.c */
/* DATE :Wed, Nov 23 2005 */
/* DESCRIPTION :Program toggles leds on port_1 */
/* CPU TYPE :R8C */
compiler directive
#include "sfr_r813.h"
variable
declaration
long t; comments
setup_r8c()
function 1
{
prc0 = 1; /* Protect off */
cm13 = 1; /* Xin Xout */
cm15 = 1; /* XCIN-XCOUT drive capacity: HIGH */
cm05 = 0; /* Xin on */
cm16 = 0; /* Main clock = No Division mode */
cm17 = 0;
cm06 = 0; /* CM16 and CM17 enable */
asm("nop"); /* Waiting for stable oscillation */
asm("nop"); /* Assembly-language code
asm("nop");
asm("nop"); assembly-language code
ocd2 = 0; /* Change main clock */
prc0 = 0; /* Protection on */
pd1 = 0x0F; /* Set ports 1.0-1.3 to output*/
}
function 2 value
toggle_leds() assignment
{
while (1) endless loop
{
p1 = 0x00;
timing loop
for (t=0; t<150000; t++);
p1 = 0x0F;
main function
void main(void)
elektor electronics 5
The main function
Every C program must include at least one function, which is called the main
function. This is the primary function in a C program, and it is always the first function
to be called when the program is run. It’s considered good programming style to have
the main routine consist primarily or entirely of function calls, instead of containing
the entire code of the program. That makes the program a lot easier to understand
and maintain, and it allows the programming effort to be divided among several
programmers for large projects. The main function is declared in the same manner
as any other function.
All instructions and functions belonging to main are enclosed in curly brackets
{…} . This is called ‘block building’. In the above example, void means ‘empty’
and indicates that the main function does not require any input parameters and
does not return any result after the instructions are executed. The two instances of
the void keyword can also be omitted if desired.
Comments in C
All text strings and phrases that don’t form part of the actual program are called
‘comments’. Comments are ignored by the compiler, which means they do not
occupy any space in memory. However, they are quite valuable for explaining the
program (or important parts of the program) to other people. And of course, they’re
very useful for the author of the program as well. In many cases, you may not
remember why you wrote the code in a particular manner when you look at your
program several days later. And no matter how appropriate the saying ‘lean is
keen’ may be in other contexts, it certainly doesn’t apply to computer programs.
Single-line comments begin with two diagonal slashes and end automatically at
the end of the line.
6 elektor electronics
#include
There are many declarations and functions that are not included in the ANSI
standard for the C language, even though they may be necessary or very useful.
They are commonly ‘hidden’ in libraries. You have to tell the compiler to include
these library files, which are called ‘header files’, so it can use these declarations
and functions when it compiles your C source code. You can recognise header
files by the .h file extension.
Examples:
#include "stdio.h"
#include "sfr_r813.h"
The Renesas library. The names and bits of the registers of the R8C
microcontroller, such as p1 , pd1 , p1_7 etc., are defined here.
Keywords in C
A total of 32 terms known as ‘keywords’ are defined in the ANSI standard for the C
language. These keywords are reserved for the compiler. All keywords must be
written in lower-case characters, and they are not allowed to be used for other
purposes (such as naming variables).
elektor electronics 7
Constants and Variables
Number systems
The C language can work with several different number systems (number bases):
decimal, octal, and hexadecimal.
Numbers stated without any special identification (notation) are interpreted as
decimal numbers by default. Numbers in all other number systems must be
specially identified. Octal numbers begin with 0 , hexadecimal numbers with 0x ,
and binary numbers with 0b .
Decimal(10) – 0123456789 5
Octal(8) 0… 01234567 05
The English (US) convention is always used for numerical notation. That means a
full stop (‘period’) is used as the decimal marker for floating-point numbers. In C,
the comma is used in as a separator in lists of numbers or variables. A colon
marks a range of numbers.
Examples: USA
3.14159
3,4 3 and 4
0:3 0->3, thus 0, 1, 2, and 3
Data types
In C, the type of a variable must be declared before it can be used. Otherwise the
compiler will not know how much memory to allocate for the variable. Basically,
you should always select a type that is adequate for the intended purpose and
requires the least amount of memory space. The most important data types are
listed below.
_Bool 8 0, 1
char 8 0 -> +255
signed char 8 -128 -> +127
int, short 16 -32768 -> +32767
unsigned int 16 0 -> +65535
long 32 -2147483648 -> +2147483647
float 32 -1.17..e-38F -> +3.4..e-38F
8 elektor electronics
Examples:
Constants
Constants are numbers that cannot be changed in the program. That also includes
all ‘normal’ numbers. Whole numbers (integers, or int ) are written without a
decimal marker (decimal point). Floating-point numbers (float ) have a decimal
point followed by additional digits. Characters (char ) are enclosed between
single quotation marks ( ' ). Constants are declared using the #define
keyword.
The names of constants, variables and functions can be freely selected, but
they are not allowed to contain any keywords or operator symbols.
Basically, only the letters of the English alphabet, numerals and the
underscore ( _ ) are used for names. You should chose names that give a
good indication of the practical meaning of the constant. For instance,
alarm_btn is much more meaningful than t1 .
Variables
A variable is an item stored in memory that can be changed in the program.
Variables can be numbers, letters, or text strings. In C, all variables must be
declared before they can be used. Variables are considered to be ‘statements’,
which means variable declarations must be terminated with a semicolon ( ; ).
Variables are defined as follows:
type <label> ;
; because this is a
processor instruction
Examples:
_Bool keypress ;
long counter ;
float radius ;
elektor electronics 9
Variables are assigned values as follows:
<label> = value ;
;
Examples:
!
Commands and instructions for the processor, which are called
‘statements’, are terminated with a semicolon ( ; ).
10 elektor electronics
Operators in C
Arithmetic operators
The symbols for arithmetic operators in C correspond to the familiar symbols used
on pocket calculators:
!
x = x+y ; // compute x + y and store the result in x
x = -x ; // change the sign of the variable x
Relational operators
Relational operators are used to compare variables. They return the result true
or false , depending on the event.
Logical operators
The logical operators AND, OR and NOT can be used to execute the familiar
operations of digital logic.
AND OR NOT
b a a && b a || b !a
0 0 0 0 1
0 1 0 1 0
1 0 0 1 1
1 1 1 1 0
elektor electronics 11
Example:
The Renesas C compiler for the R8C has several additional logical operators that
can be used for bitwise operations on variables:
Examples:
Shortcuts
Americans are masters at inventing shortcuts. That’s especially true for Dennis
Ritchie and Brian Kernigham, the inventors of the C language. Many programmers
type in their programs using the ‘hunt-and-peck’ system, so they try to avoid any
unnecessary typing effort.
Example:
12 elektor electronics
Functions in C
The function concept
Functions are the essence of the C programming language. A function can be
called from the main routine or from any other function. Every C program must
include at least one function, which is called main() . It is automatically called
when the program is started.
Functions are individual program segments (blocks) that perform specific activities
(operations), such as the familiar operations performed by pocket calculators:
1/x expects to receive a number as input in order to calculate its inverse value.
In C, this is described as a function with an input parameter.
sin and log , on the other hand, are functions that require one input
parameter.
Declaring a function
The general form of a C function is: ;
type function_name(type var1,type var2,type var3,...) ;
Examples:
void wait_1(void)
asm("nop"); // Call no operation in assembly language
The word void tells the compiler that the function wait_1 does not require any
input parameters and does not return any result. The void keywords can also be
omitted:
wait_1() ;
asm("nop");
elektor electronics 13
If a function contains more than one instruction, the instructions must grouped into
a block by enclosing them in curly brackets ( { } ). In that case the semicolon at
the end must be omitted.
no ;
wait_2()
{
asm("nop") // Wait three times
asm("nop")
asm("nop")
}
no ;
int t;
wait_3(int several_times)
for(t=0;,t<= several_times;t++);
Calling a function
Functions are called by simply stating their names. This can be done at any
location in the program. After the function has been processed, which can be
recognised by the ; in case of a function containing only one instruction or the
curly bracket } in case of a function containing several instructions, a return to the
calling location occurs automatically. The keyword return has a different
meaning in C than in assembly language. In C, it designates the return value
instead of the end of a subroutine or function.
14 elektor electronics
Examples:
Calling a function from the main routine without any input or return parameters:
void main(void)
{
wait_1();
}
Calling a function from the main routine with an input parameter but no return
parameters:
void main(void);
{
wait_3(100);
}
Calling a function from the main routine with input and return parameters:
void main(void);
{
no_of_litres = _volume(a,b,c);
}
elektor electronics 15
Program Control
if
It frequently happens that an instruction or block of instructions should only be
executed if a certain condition is satisfied. A condition is satisfied if a test of the
condition returns the value true . Every number except zero is regarded as
true ; zero is regarded as false .
If several instructions are to be executed when the condition is satisfied, they must
be grouped into a block.
no ;
if (condition)
{
statement_1
statement_2
statement_3
// . . .
}
no ;
Examples:
if(button == 3) if(button == 3)
red_led = _on; {
grn_led = _off;
red_led = _on;
}
if...else
If one instruction or block of instructions is to be executed when a condition is
satisfied, while an another instruction of block of instructions is to be executed
when the condition is not satisfied, an if...else conditional statement is
used. ;
The general form is:
;
if (condition) statement_1 ; else statement_2 ;
16 elektor electronics
Examples:
;
==
if(button == 3)
red_led = _on; ;
else if(button == 3)
grn_led = _on; {
block grn_led = _off;
red_led = _on;
}
markers else
if(button == 3) {
{ grn_led = _on;
grn_led = _off; red_led = _off;
red_led = _on; }
}
else
grn_led = _on;
switch
If a conditional statement has more than one or two possible outcomes, it is very
tedious to implement it using the if...else structure. In that case it’s better to
use the switch /case structure with multiple alternatives. This type of program
control can be compared to a rotary selector switch with multiple positions (cases).
switch (variable)
{
case constant_1 ;
instruction_1;
break;
case constant_2;
instruction_2
break;
case constant_3;
instruction_3
case // . . .
break;
default instruction_x;
}
no ;
elektor electronics 17
block of instructions is executed. Program control returns to the caller of the case
statement when the break keyword is reached. If none of the cases listed in the
case statement is found, the instruction following default is executed. The
default portion can be omitted if it is not necessary.
Example:
switch (_button)
{
case 1:
red_led = _on;
block break;
case 2:
yel_led = _on;
break;
case 3:
grn_led = _on;
markers
default blu_led = _on;
}
may be
omitted
for
A for loop is used if part of a program must be executed multiple times.
18 elektor electronics
Examples:
int t;
variables
a = 2;
b = 10;
c = 4;
count variable
int i;
for(i = a; i < b; i+ = c)
{
red_led = _on;
red_led = _off;
}
while
A while loop is used when execution is tied to a condition.
When the while loop is called, the value of the condition (_condition) is first
tested. If the result is positive (true), the instructions (instruction_x ) are
executed repeatedly until the result of the test is false.
elektor electronics 19
Example:
#define true 1
==
while(i == true)
{
i = button_pressed();
blink_led();
}
do...while
A while loop will not be executed if the condition is not satisfied at the
beginning of the loop. If it is necessary for instructions to be executed at least
once, the condition must be tested at the end instead. A do...while loop is
used in such cases.
;
Example:
#define true 1
do
{
i = button_pressed();
blink_led();
}
while(i == true);
==
20 elektor electronics
Appendix
Examples:
pd1 = 0x0F;
/* port1, bits 0:3 = output
bits 4:7 = input */
pd2_3 = 1;
/* port2,bit3 = output */
… and the following example shows how to output data via a port:
Examples:
p1 = 0x0F;
/* port1, bits 0:3 = 1
bits 4:7 = 0 */
pd2_3 = 0;
/* port2,bit3 = 0 */
elektor electronics 21
Protection registers (PRCR)
The PRCR registers can be used to protect the contents of other important
registers against overwriting (if the program goes out of control, for instance).
Examples:
prc0 = 1;
/* write protection disabled */
prc0 = 0;
/* write protection enabled */
Examples:
cm13 = 1;
/* Xin/Xout on ports p46 and p47
= ext. xtal */
cm15 = 1;
/* Xin/Xout driver high */
external crystal cm16 = 0;
oscillator mode /* prescaler for CPU clock */
prescaler
setting cm17 = 0;
oscillator gain /* prescaler for CPU clock */
Examples:
cm05 = 0;
/* enable Xin/Xout on ports p4.6
and p4.7 */
cm06 = 0;
/* enable prescaler */
22 elektor electronics
The Oscillator Stop Detection (OSD) register is used together with the other
registers to select the clock source, and it is also responsible for monitoring the
clock signal.
Examples:
osd2 = 0;
/* enable external xtal osc. as
CPU clock source */
osd2 = 1;
/* disable external xtal osc. */
system clock
select bit
elektor electronics 23
Microcontroller
Basics
Microcontrollers make things
possible that vastly exceed
what could be done previous-
ly. Innumerable applications
show that almost nothing is
impossible. There’s thus
every reason to learn more
about them, but that raises ISBN 0-905705-67-X
the question of where to 230 Pages
find a good introduction to £18.70 (US$ 33.70)
this fascinating technology.
This book clearly explains
the technology using various
microcontroller circuits and Elektor Electronics
programs written in several (Publishing)
different programming Regus Brentford
languages. In the course 1000 Great West Road
of the book, the reader Brentford TW8 9HH
gradually develops increased United Kingdom
competence in converting
his or her ideas into micro- Tel. +44 (0) 208 261 4509
controller circuitry. Fax +44 (0) 208 261 4447