E-book-15-ElektorBlockbusters-uk

95
Elektor blockbusters Artikeltitel • 1 Top-15 articles from Elektor Elektor Blockbusters

Transcript of E-book-15-ElektorBlockbusters-uk

Page 1: E-book-15-ElektorBlockbusters-uk

Elektor blockbusters Artikeltitel • 1

5

Top-15 articles from Elektor

ElektorBlockbusters

Page 2: E-book-15-ElektorBlockbusters-uk

Elektor blockbusters Contents • 2

ContentsElektor RFID Reader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Stand Alone OBD-2 Analyser. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

ElekTrack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

Making Waves at C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24

Digital Inspector . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

Profiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

ECIO PLC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

Universal JTAG Adaptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

GBECG. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

Tilt Gamepad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .57

Micro Webserver . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .60

Software Defined Radio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

Wireless USB in miniature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

A 16-bit Tom Thumb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

USB Flash Board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89

Page 3: E-book-15-ElektorBlockbusters-uk

elektor electronics - 9/200626

ELEKTOR RFID ReaderHANDS-ON MICROCONTROLLERS

Gerhard H. Schalk

RFID cards are becomingincreasingly popular inmany fields wherepreviously barcodes and chipcards were used. They openup many new possibilities, suchas applications in travel cards oreven banknotes. As befits apremier electronics magazine,Elektor Electronics is offering itsreaders with this issue not only afree RFID card but also a professionalRFID reader for your own applications.The design described here can both readfrom and write to all types of RFID cardthat are compatible with the MIFARE andISO 14443-A international standards.

For MIFARE® and ISO 14443-A cards

In developing the Elektor ElectronicsRFID reader we have aimed to makethe device as universal as possible. So,for example, the reader can be used in

conjunction with a PC over a USB con-nection, or in stand-alone mode usingits liquid crystal display. It is very sim-ple to use the free PC-based program

‘MIFARE Magic’ to read and write allkinds of MIFARE cards withoutinstalling special software in thereader.

Elektor blockbusters Elektor RFID Reader • 3

Page 4: E-book-15-ElektorBlockbusters-uk

MIFARE Magic directly supports arange of contactless 13.56 MHzMIFARE cards, including the PhilipsMIFARE UltraLight, MIFARE 1K andMIFARE 4K. The MIFARE Magic win-dow (Figure 1) also offers the facilityto send individual commands to thecard with a click of the mouse. Thisallows you to determine the character-istics of different cards very easily.Examples of compatible cards includethe MIFARE UltraLight RFID card sup-plied with this issue, and described inmore detail in a separate article, andsmart cards used on many publictransport systems all over the world —for example, the London UndergroundOyster card In stand-alone operation, for examplein an access control application, thereader can be used directly with thefirmware we have developed. Onswitch-on the reader immediatelylooks for cards within the range of theantenna (a few centimetres) and readsany cards it finds in that area. The LCD(if connected) then shows the cardtype along with its serial number, andthe switching output of the reader isactivated.The reader is constructed around thenewest Philips reader IC typeMF RC522 and a type LPC936 micro-controller. Since the reader IC is onlyavailable in an HVQFN32 package, wehave decided to solve the problems ofmounting and soldering by makingavailable ready populated and tested

reader boards fitted with pre-pro-grammed microcontrollers.The Elektor Electronics RFID reader isnaturally ideal for experimenting withthe free MIFARE UltraLight card. Thesystem includes a powerful microcon-troller and I2C, SPI, UART and USBinterfaces, and free development tools

are available. This makes it suitable fordeveloping dedicated applicationssuch as door and gate openers, mem-bership card systems, storing pass-words and configuration data, pay-ment systems, security for domesticappliances such as televisions, videorecorders and PCs, monitoring battery

9/2006 - elektor electronics 27

Figure 1. The MIFARE Magic program developed for the Elektor Electronics RFID reader allows MIFARE andISO 14443-A RFID cards to be read, written and programmed.

SpecificationsElektor Electronics RFID reader:

• Near-field reader for 13.56 MHz RFID cards

• Compatible with MIFARE and ISO 14443-A cards

• Allows both reading and writing

• USB interface for connection to PC

• Ready for immediate use without programming

• Free PC-based software available

• Stand-alone (including portable) operation using LCDmodule

• Dedicated MF RC522 reader IC

• Dedicated microcontroller on reader board

• SPI and I2C interfaces

• Spare 8-bit microcontroller port

• Buffered switching output

• Available as ready populated and tested SMD circuitboard

• Can be modified for user applications

• Programming tools available

MF RC522 reader IC:

• Highly-integrated single-chip reader for ISO 14443-A andMIFARE cards

• Supports contactless data transmission at 106 kbit/s,212 kbit/s and 424 kbit/s

• 50 mm approx. read/write range (depending on antenna)

• Integrated MIFARE Classic cryptography

• Programmable over UART, I2C or SPI

• 64 byte transmit and receive FIFO buffer

• Programmable reset and power-down modes

• Programmable timer

• Internal oscillator allows direct connection of 27.12 MHzcrystal

Elektor blockbusters Elektor RFID Reader • 4

Page 5: E-book-15-ElektorBlockbusters-uk

packs and much more besides. Thecombination of secure identity, datastorage and contactless interfaceopens up many opportunities for novelapplications.

Reader hardwareFigure 2 shows the block diagram ofthe reader. The basic reader functions,including the creation of the HF mag-netic field, modulation and demodula-tion, and the generation of theISO 14443 data stream, are carried outin the MF RC522. It is simplest to thinkof the MF RC522 as a contactlessUART driven directly by the microcon-troller. In the Elektor Electronics readerwe have used an 8051-compatibleLPC936 microcontroller from Philips.The CPU takes only two cycles perinstruction and is clocked at 16 MHz.This speed and the 16 kbyte Flash

memory are sufficient for an enormousrange of possible applications. Pro-grams for the microcontroller can besimply written using any 8051 com-piler. Communications with the PC arehandled by an FT232R USB/RS232interface chip from our friends atFuture Technology Devices (FTDI).The full circuit diagram is shown inFigure 3. When connected to a PC,power is taken from the USB via mini-connector K1. The FT232R USB inter-face chip is configured to report thereader as a high-power device whenthe bus is initialised (during ‘enumer-ation’). As a bus-powered device thereader can then draw a current of up to500 mA. When enumeration is com-plete the /PWRNEN signal on pin 11 ofIC1 changes state, making P-channelMOSFET T2 conduct. The 5 V supply isthen passed through to voltage regula-tor IC5. The output of the LM2937 pro-

vides the 3.3 V supply for the LPCmicrocontroller (IC3) and theMF RC522 (IC4). Red LED D6 showswhen the 3.3 V supply is present. If 5 Vpower is not provided via the USB con-nector Schottky diode D4 allows anexternal power supply to take overautomatically. Either four AA-size cells(the enclosure suggested in the partslist will accept these) or a 5 V mainssupply capable of delivering at least300 mA can be used.Figure 4 shows an overview of theinternal functions of the MF RC522reader IC in the form of a (greatly sim-plified) block diagram. The output driv-ers of the device allow direct connec-tion of transmit and receive antennaswithout external active amplificationcircuitry. A few passive componentsprovide the essential matching to theantenna characteristics. The analogueinterface handles demodulation anddecoding of the reply data sent by thecard. The digital block is responsiblefor constructing the ISO 14443A orMIFARE protocol frames and accompa-nying error detection (parity and CRC).The FIFO buffer allows 64-byte blocksto be sent and received in ISO 14443mode (‘T=CL’ protocol). In MIFAREmode the largest data blocksexchanged are at most 16 bytes long,and so there is no need for the micro-controller to split up the commandpackets. The registers of the MF RC522can be programmed over the SPI, asyn-chronous serial or I2C interfaces. Sincethe LPC936 microcontroller only hasone asynchronous serial interface, andthis is required for communicationswith the PC, the I2C interface is usedto talk to the MF RC522.If desired an LCD module can be con-nected to port P0 of the LPC936 viaconnector K2. P0.0 is buffered by atransistor and provides a switched out-put, and the SPI and I2C interfaces ofthe microcontroller afford plenty ofopportunities to expand the reader byadding extra hardware. For example, areal-time clock could easily be addedto allow for time monitoring, and theswitched output could control a dooropener; see also the pages about theRFID reader on the Elektor Electronicswebsite.

Get startedThe double-sided printed circuit boardfor the Elektor Electronics RFID readeris shown in Figure 5. It is only possi-ble to reflow solder the reader IC, andso we are making the board available

elektor electronics - 9/200628

HANDS-ON MICROCONTROLLERS

MF RC522

Optional Power Supply5V

USB

I / OLCD

RS232

060132 - 13

I2C

I2C

FT232RUSB / UART

VoltageRegulator

Ant

enna

Mat

chin

gC / PhilipsLPC 935

RFID Reader

Figure 2. Block diagram of the Elektor Electronics RFID reader.

AnalogInterface

FIFO Host

Register Bank

Serial UARTSPII2C

ContactlessUART

MFRC5222

060132 - 14

Figure 4. Block diagram of the Philips MF RC522 reader IC.

Elektor RFID Reader • 5 Elektor blockbusters

Page 6: E-book-15-ElektorBlockbusters-uk

9/2006 - elektor electronics 29

K2

K1

12345

MIN

I US

B-B

C3

100n

C1

47p

C2

47p

C5

100n

D2

YE

D1

GR

R2

1k

R1

1kC

4

100n

D5

BA

T54

D4

BA

S19

C31

100n

L1

T2

IRL

M6402

R13100k

C30

22

LM

2937IC

5

C32

22

D3

RER

12

1k

X1

16MH

z

C7

12p

C8

12p

T1

IRL

M6402

R16

10k

D6

CP

U P

WR

R15

1k

R5

4k7

C6

100n

564

IC2.B1

231

IC2.A1

9810

IC2.C1

121113

IC2.D1

JP1

JP2

R3

4k7

R4

4k7

C10

100n

C9

100n

C12

100n

C11

100n

X2

27.12MH

z

C13

12p

C14

12p

L2560n

H

L3560n

H

CB

US

3 PW

RN

EN

CB

US

0 TX

LE

D

CB

US

1 RX

LE

D

CB

US

4 SL

EE

P

FT

232RQ

FN

3V3O

UT

VC

CIO

CB

US

2

US

BD

M

US

BD

P

RE

SE

T

IC1

OS

CI

OS

CO

TE

ST

TX

D

GN

D

VC

C

GN

DG

ND

GN

D

RX

D

DT

R

RT

S

DS

R

DC

D

CT

S

19

30

1720

24

3132R

I

16

222110111514 18272826

4

1

23678

9

R6

1kC16

100n

C17

220p

C19

220p

C18

*C20

*

C21

27p

C23

27p

C22

*C24

*

C25

68p

C27

68p

C26

*C28

* R84

7

R94

7

L4An

t.

L5An

t.

R7

2k2

+4V8...+6V

C15

1n

D7 R

17

1k

R1410k

T3BC

517

IC2

147

+5V

P1.3/S

DA

/INT

0

P2.5/S

PIC

LK

P89L

PC

935

P1.4/IN

T1

P2.2/M

OS

I

P2.3/M

ISO

P1.0/T

XD

P1.1/R

XD

P1.2/S

CL

P1.5/R

STP3.1/X

1P

3.0/X2

P2.4/S

S

P0.7/T

1

IC3

P1.6

P1.7

P2.0

P2.1

P2.6

P2.7

P0.0

P0.1

P0.2

P0.3

P0.4

P0.5

P0.6

VS

S

VD

D

262524

21

18 17

12 11 10131415162728

23222019

89

7

65 412

3IC

2 = 74HC

02

R10

10

R11

10

C29

22

10kP

1

+5V

LC

DIS

PL

AY

LC

D1

VSS

VDD

R/W

VO

RS

D0

D1

D2

10D3

11D4

12D5

13D6

14D7

1516

12

34

56E

78

9

K

A

R/W

RSED4

D5

D6

D7

060132 - 11

see text*

voir texte

*sieh

e Text*

zie tekst*

+3V3

MF

RC

522

AL

E S

DA

NR

ST

PD

D7 S

CL

D1 A

5

D2 A

4

D3 A

3

D4 A

2

D5 A

1

D6 A

0

IC4

PVDD

DVSS

DVDD

AVDD

TVDDAU

X1

AU

X2

VM

IDAVSS

TV

SS

TV

SS

PV

SS

SV

DD

I2C

IRQ

TX

1

TX

2

OU

T

OS

C

RX

D

TX

D

13

RX

17

1512

23

19201611

18

IN2122

1014

EA

32 24 252627282931 30

4

1

23

65 9

78

Figure 3. Complete circuit diagram of the reader, which can operate either in stand-alone mode, using the LCD module, or in conjunction with a PC using the USB interface.

Elektor RFID Reader • 6 Elektor blockbusters

Page 7: E-book-15-ElektorBlockbusters-uk

ready populated and tested. Instruc-tions are also provided for building theunit into the suggested enclosure,which we can also supply.The two jumpers on the reader board(JP1 and JP2) are not fitted for normaloperation. Assuming the LCD moduleis connected to the reader board, theunit is ready for operation as soon aspower is applied, and the serial num-ber of any RFID card within range ofthe reader’s antenna will appear onthe display. If the display appearsblank, the contrast should be adjustedusing P1.To use the reader with a USB connec-tion to a PC, the free CMD-FDTI-USBdriver must be downloaded from theElektor Electronics website. This par-ticular driver is required because theFT232R contains the Elektor Electron-ics Vendor ID and Product ID.When the RFID reader is connected tothe PC using the supplied USB cableWindows will automatically detect thenew USB device. The freshly-down-loaded driver should be selected forthe unit. If problems arise, the ‘Instal-lation Guide’ on the FTDI website(www.ftdichip.com) can be consultedfor assistance: this guide is also appli-cable to the modified driver.Installing the CMD-FTDI driver installsboth the ‘D2XX’ (direct) and ‘VCP’ (vir-tual COM port) drivers. The VCP driverallows the USB link to be treated fromthe point of view both of the PC and ofthe microcontroller as an ordinaryRS232 connection.The D2XX driver is required if it isdesired to modify the unit in a waythat requires changes to the internalconfiguration data stored in EEPROMin the FT232R. This can be done usingthe PC-based program MPROG, avail-able as a free download from the FDTIwebsite: MPROG will work only withthe D2XX driver.

MIFARE MagicOnce the driver has been installed,MIFARE Magic, a specially-written PC-based program for the Elektor Elec-tronics RFID reader, can be run. This isalso available as a free download, fromwww.elektor-electronics.co.uk. Afterdownloading the program the contentsof the ZIP file must be copied into asubdirectory of your choice. Start theprogram with a double-click onMifareMagic.exe, with the readeralready connected to the USB port.This allows MIFARE Magic to find thereader automatically. There is no need

elektor electronics - 9/200630

HANDS-ON MICROCONTROLLERS

(C) ELEKTOR 060132-1

C1

C2

C3

C4

C5

C6

C7

C8

C9C10

C11

C12

C13

C14

C15

C16

C17

C18

C19

C20C21C22

C23C24

C25C26

C27C28

C29 C30

C31

C32

D1

D2

D3

D4

D5

D6

D7

IC1IC2

IC3 IC4

IC5JP1

JP2

K1

K2

L1

L2

L3

P1

R1

R2

R3

R4

R5

R6

R7

R8 R9

R10R11

R12 R13

R14

R15

R16

R17 T1

T2

T3

X1

X2

060132-1T

-

-

++

14 1

Figure 5. The double-sided printed circuit board incorporates the antenna. The reader IC is not suitable forhand soldering and so the board is available ready populated and tested.

Elektor RFID Reader • 7 Elektor blockbusters

Page 8: E-book-15-ElektorBlockbusters-uk

9/2006 - elektor electronics 31

COMPONENTSLISTResistors(all SMD case 0805, 5%)R1,R2,R6,R12,R15,R17 = 1kR3,R4,R5 = 4k 7R7 = 2k 7R8,R9 = 4 7R10 = 270R11 = 10R13 = 100kR14,R16 = 10kP1 = 10k -preset, SMD, 4 mm SQ

Capacitors(all SMD case 0805, 16 V, ceramic)C1,C2 = 47pF NP0C3,C4,C5,C6,C9,C10,C11,C12,C16,

C31 = 100nFC7,C8,C13,C14 = 12pF NP0C15 = 1nF NP0C17,C19 = 220 p NP0 C18,C20 = not fittedC21,C23 = 27pF NP0C22,C24 = not fittedC25,C27 = 68pF NP0C26,C28 = not fittedC29,C30, C32 = 2μF2

SemiconductorsD1 = SMD LED (0805) green,

low-currentD2 = SMD LED (0805) yellow,

low-currentD3,D6,D7 = SMD LED (0805), red,

low-currentD4 = BAS19 (200 mA; SOT23)D5 = BAT54S (30V / 300 mA; SOT23)T1,T2 = 6402 (p-channel MOSFET, 20V /

3.7A; SOT23)T3 = BC517 (npn Darlington; TO92 case)IC1 = FT232RQFN (QFN32 case, FTDI)IC2 = 74HC02 (TSSOP14 case; NOR

gate)IC3 = P89LPC936FDH-S (SSOP28 case;

Philips)IC4 = MFRC52201HN1 (HVQFN32case;

Philips)IC5 = LM2937 (low-drop, 3V3, SOT223

case)

MiscellaneousX1 = 16MHz quartz crystal (18pF parallel

capacitance; 5·3.2mm)X2 = 27.12MHz quartz crystal (18pF

parallel capacitance; 5·3.2mm)K1 = miniature USB-B socket, SMD,

5-wayL1 = SMD ferrite (1.5 A; 0805 case)L2,L3 = 560nH SMD inductor (0805 case)JP1,JP2 = 0.1-in. jumper (see text)LCD1 = LCD module with 2x16 characters

and backlightEnclosure, dim. 146x91x33 mm with LCD

window and battery compartment for 4AA bateries

PCB, order code 060132-91 (populatedand tested, including USB cable; seeElektor SHOP pages andwww.elektor.com)

Compatible LC display (see Elektor SHOPpages and www.elektor.com)

89LPC936 source & hex code files; freedownload from www.elektor.com

Mifare Magic PC software incl. sourcecode; free download fromwww.elektor.com

Elektor RFID Reader • 8 Elektor blockbusters

Page 9: E-book-15-ElektorBlockbusters-uk

to select a COM port, as MIFAREMagic uses the D2XX driver internally.Figure 6 shows the ‘Terminal’ view ofMIFARE Magic. This mode emulates aVT100 terminal and displays all thecharacters sent by the LPC microcon-troller over the FTDI interface.The firmware in the LPC microcon-troller defaults to ‘terminal’ mode onpower-up. As soon as the readerdetects a new card within its field itactivates the card. The reader deter-mines whether the card is a MIFAREUltraLight, MIFARE 1K or MIFARE 4K.The entire memory contents of thecard are read out and displayed on theMIFARE Magic terminal. For MIFARE1K and 4K cards the standard MIFAREkey is used. If the card uses a differentkey the data stored in certain sectorswill not be readable. To use a differentterminal program instead of MIFAREMagic (such as HyperTerminal or thebuilt-in terminal in the LPC FlashMagic programming tool), the VCPdriver must be used and the terminalprogram must be told the number ofthe relevant COM port. The parame-ters for the port are as follows: 115200baud, no parity, 8 data bits and onestop bit.The ‘Window’ menu allows MIFAREMagic to be switched between the‘Terminal’ view, the ‘MIFARE Ultra-Light’ and the ‘Show All Cards’ views.The ‘MIFARE UltraLight’ window (seeFigure 7) allows various card com-mands to be executed with a click ofthe mouse. This makes it easy to pro-gram a MIFARE UltraLight card, suchas the sample supplied free with thisissue. When this window is openedthe firmware in the LPC microcon-troller on the reader board switchesfrom terminal mode into PC readermode. Here the microcontroller waitsfor a card command from the PC andcalls the corresponding function in itssoftware. This mode is useful whendeveloping applications on the PC.The ‘Show All Cards’ window displaysthe serial numbers of all cards cur-rently detected by the reader. This isuseful for testing reader range and thecapacity of the reader to deal with mul-tiple cards simultaneously.

Program-it-yourselfFor dedicated applications it is possi-ble to modify or completely rewriteboth the firmware in the LPC936 andthe software running on the PC. Anyupdates to the reader firmware willalso require reprogramming the

elektor electronics - 9/200632

HANDS-ON MICROCONTROLLERS

Figure 6. The ‘Terminal’ view of MIFARE Magic shows all the characters sent by the reader over the USB interface.

Figure 7. The ‘MIFARE UltraLight’ and ‘Mifare Standard‘ windows allow simple programming of the RFID card.

Figure 8. The free PC-based Flash Magic program can program the LPC microcontroller over the USB interfaceof the Elektor Electronics RFID reader.

Elektor RFID Reader • 9 Elektor blockbusters

Page 10: E-book-15-ElektorBlockbusters-uk

LPC936. The most up-to-date softwarewill always be available on the ElektorElectronics website for free download.Updates will be reported on the newspages of the website and in the maga-zine under ‘Corrections and Updates’.The LPC on the reader board can beprogrammed directly over the USB portusing the free PC program ‘FlashMagic’ (see Figure 8). This program,from Embedded Systems Academy(www.esacademy.com) and sponsoredby Philips (www.semiconductors.com)supports a range of Philips microcon-trollers.Both jumpers JP1 and JP2 must be fit-ted on the reader board before the LPCmicrocontroller can be programmed.Interested readers will find a detaileddiscussion of how to program thedevice on the Elektor Electronics web-site along with a list of all the MIFAREUltraLight reader and card commands.The reader firmware was developedusing the Keil mVision3 C compiler forthe LPC microcontroller. All the com-mands necessary for developing dedi-cated applications are made availableas functions and so it is not necessaryto deal directly with the individual reg-isters of the MF RC522.The listing shows the code necessaryto activate a MIFARE UltraLight cardand read a data block. The data will betransmitted using the serial interfaceof the microcontroller.As mentioned above, the PCreader mode of the LPCfirmware allows aPC appli-cation toi n v o k ecard func-tions. Usingthis modefunction invoca-tion is doneusing a very sim-ple serial protocolto communicate withthe program runningin the microcontroller.When the function hasbeen executed theresponse is returned to thePC. The naming and parame-ters of the functions are identi-cal in the PC software and inthe microcontroller firmware.The source code for the PC-basedMIFARE Magic program and for themicrocontroller software can bedownloaded for free from the ElektorElectronics website.

(060132-1)

9/2006 - elektor electronics 33

Listingwhile(1){

status = ISO14443_Request(WUPA, &bATQ);if(status != STATUS_SUCCESS)

continue;

status = ISO14443_Anticoll(Level1,0,&abSNR[0]);if(status != STATUS_SUCCESS)

continue;

status = ISO14443_Select(Level1, &abSNR[0], &bSAK);if(status != STATUS_SUCCESS)

continue;

// Check if UID is completeif((bSAK & 0x04) == 0x04){

// UID not completestatus = ISO14443_Anticoll(Level2,0,&abSNR[4]);if(status != STATUS_SUCCESS)

continue;

status = ISO14443_Select(Level2, &abSNR[4], &bSAK);if(status != STATUS_SUCCESS)

continue;}

// Read UltraLight Block 0..3status = Read(0,abDataBuffer);

}

Elektor blockbusters Elektor RFID Reader • 10

Page 11: E-book-15-ElektorBlockbusters-uk

PROJECTS VEHICULAR TEST EQUIPMENT

46 elektor electronics - 6/2007

Interpret‘trouble

codes’without a PC

Folker Stange and Erwin Reuss

This handy analyser makes a simple job of rummaging through the information stored by the client–accessible part of your car’s computer. It works with all current OBD-2 protocols and can read and erase trouble codes stored in the vehicle and reset the MIL display. All this without the help of a PC or a visit to a service station.

Since the turn of the millennium more and more new car models have been fi tted with the latest version of the on board diagnostic interface OBD-2. With the increasing sophistication of mod-ern engine management many new owners have seen the benefi ts of an OBD analyser such that it is fast be-coming an essential part of the garage tool kit along with the torque wrench and spark plug spanner.It has been reported that sometimes when owners fi t a new car radio or sat-nav system to their car the vehicle management system unnecessarily registers a fault, similarly some owners who have modifi ed the engine to ac-cept an alternative fuel have noticed that the engine management can in-correctly interpret the engine condition

and trigger an error. In some cases the engine management can even be switched into an emergency condition. Whatever the cause the outcome is the same; a dashboard mounted MIL (mal-function indicator light) comes on, a fault condition is stored and it is neces-sary to make an (expensive) visit to the nearest garage to have the ‘trouble’ put right and the MIL reset. With the OBD analyser described here in your glove box it is a simple job to connect to the OBD socket, fi nd out what the trouble is, reset the error and continue on your journey. On cost grounds alone the price of the analyser will be more than repaid by avoiding just a single unnecessary visit to a dealership garage.A number of OBD analysers have been

featured in the electronics press (in-cluding Elektor Electronics) describing an interface between the OBD connec-tor and a laptop. The approach we have adopted here is however far less cumbersome, this stand-alone unit does not require a notebook or battery, recognises all the usual OBD-2 or EOBD protocols and is small enough to stow in your car’s glove box. Operation is quite straightforward using just two buttons, 580 of the commonest trouble codes can be recognised and described on its running text display.

The CircuitThe OBD-2 analyser employs an AT-90CAN128 microcontroller from the AT-mega128 family from Atmel. This par-

Stand Alone OBD-

Stand Alone OBD-2 Analyser • 11 Elektor blockbusters

Page 12: E-book-15-ElektorBlockbusters-uk

476/2007 - elektor electronics

ticular model has an on-board CAN bus interface as shown in Figure 1.The controller is supplied pre-pro-grammed with the AGV4900 fi rmware which handles the user-interface in-cluding push buttons, buzzer, LEDs and LCD.Pin assignments the OBD-2 connector are given in Figure 2. In order to sup-port all the current OBD-2 protocols the analyser needs to be able to inter-face to several b i -di rect ional interfaces:

K/L interfacePWM interfaceVPWM interfaceCAN interface

The fi rst three of these in the circuit diagram (Figure 3) have been imple-mented using transistors and compa-rators confi gured to meet the interface standards. The specifi ed pull up resis-tors for the K and L signals have a rela-

-2 AnalyserISO/KWP

16 x 3 LCD DISPLAY

CAN

socket

070038 - 12

Key

VPWM

PWM

AGV4900

handheld scanner

BA

Figure 1. Block diagram of the OBD-2 analyser.

161515

+12 V

L-LineK-Line

CAN-H

S-GND

C-GND

PWM+VPWM

CAN-L

PWM-

1413

1211

109

87

65

43

21

070038 - 14

Figure 2. Pin defi nitions of the OBD-2/EOBD connector.

Specification• Automatic or manual selection of OBD-2 protocol

• Very fast automatic protocol scan (0.1 to 2.6 s per protocol)

• Fast software boot sequence (ready to go around a second after switch on)

• Read and display important vehicle information (depending on the vehicle)

• Real-time sensor reading (selectable)

• Vehicle chassis number display (if supported by the vehicle manufacturer)

• Readout and display of the trouble code memory

• Read out and display of Freeze-Frame data

• Erasure of trouble code memory

• Language selection (English or French)

• 580 trouble codes with description in running text

• All existing OBD protocols for private vehicles are supported:

ISO9141-2

ISO14230-4 (KWP2000)

J1850 PWM

J1850 VPWM

ISO15765-4 (CAN, 11/29 Bit, 250/500 kbits/s)

• Power for the analyser is supplied from the vehicle’s OBD-2 connector (12 V)

• Backlit 3-line LC display with adjustable contrast

• Acoustic signal gives audible feedback and beeps when trouble codes recognised

• LED Indicators for connection status and data traffi c fl ow

• Simple operation using just two push buttons

• Connection for a standard OBD-2 cable

• Handheld format: 80x135x30 mm (wxhxd), weight 150 g (approx.)

• Supplied as a kit through Elektor SHOP

Points to noteThe OBD analyser is only suitable for vehicles fi tted with an OBD-2/EOBD connector.

EOBD is fi tted to vehicles sold in the EU:

- after 01.01.2001, for petrol engine vehicles.

- after 01.01.2004, for diesel engine vehicles.

Before the analyser is plugged into any vehicle manufactured before these dates, it is important to check compatibility with the OBD-2 standard. The website of Florian Schäffer [3] contains a databank of vehicles where you check to see if yours is OBD-2 compatible.

Stand Alone OBD-2 Analyser • 12 Elektor blockbusters

Page 13: E-book-15-ElektorBlockbusters-uk

PROJECTS VEHICULAR TEST EQUIPMENT

48 elektor electronics - 6/2007

tively low impedance so MOSFETs have been used here as drivers. The CAN bus driver IC type PCA82C250 takes care of the CAN interface.The user-interface software is logically designed such that just two push but-tons are required to operate the ana-lyser and select all possible menu op-tions. Connections for the buzzer, the ‘connect’ and ‘Data Traffic’ LEDs should not require any further explana-tion. Control of the three-line LCD is a little more complex, a fi ve wire SPI in-terface connects the display to the con-troller. LED backlights ensure that the display is night time readable. The rel-atively low controller clock speed (8 MHz) is a good compromise, produc-ing a low level of EMI emissions while still giving ample operating speed for this application.

nadian readers). Stange Distribution are specialists in OBD related equip-ment and produce several OBD-2 con-trollers for applications in the fi eld of OBD development.All the OBD analyser functions can be selected from the menu using just two keys. One feature of the software is the very quick boot procedure which en-sures that the device is ready for use in little more than a second after switch-on. The most important 580 trouble codes have a plain text description of the fault which is displayed in running text (in the language chosen). This fea-ture helps promote a quick and effec-tive diagnosis of the problem. In the vast majority of cases there will be no need to look up the code in an OBD trouble code book.

The Firmware

The heart of the OBD-2 analyser is the pre-programmed microcontroller with the designation AGV4900 [1] available solely from Stange Distribution [2]. The software was developed by co-author Erwin Reuss. Like similar OBD projects the fi rmware for this analyser is only available pre-programmed into the mi-crocontroller where it is copy protect-ed. The source fi les are not available for download. Without this software copy protection is would not be possi-ble to offer the analyser in kit form. There is no possibility for the home constructor to assemble a low-cost ver-sion of this design unless of course all the necessary software is written from scratch.A menu option switches all display in-formation between either English or French (for the convenience of our Ca-

K2

1

2

3

4

5

6

7

8

9

PCA82C250

IC4

CANH

CANL

VREF

TXD

RXD

RS5

6

3

2

1

4

7

8

Q1

8MHz

C5

22p

C4

22p

C10

100n

+5V

LED1 LED2

R1

1k

R12

1k5

+5V

S1 S3

RN2

10k

8

7

R8

100

R7

100

C7

470p

C6

470p

+5V

R9

33

+5V

BZ1

F/CM12P

R5

33

D2

1N4148

EA DOG-M163ELCD

CAP1N CAP1B

VO

UT

VC

C

RS

T

R/W VIN

GN

D

PS

B

CSB

26 40 37 36 25 24 35

D0

34

D1

33

D2

32

D3

31

D4

30

D5

29

D6

28

D7

A120

A2

C119

C2

27 23

38

39RS

21

E

1

2

3

Q6

BS170

6

7

1IC2.B

4

5

2IC2.A

10

11

13IC2.D

8

9

14IC2.C

RN2

10k

4

3

RN2

10k

6

5

RN3

6k8

3

4

RN2

10k

10

9

12

RN2

10k

Q7

BS250D4

1N4148

+8V +5V

Q5

BS170

(OC3C/INT5)PE5

(OC3B/INT4)PE4

(OC3A/AIN1)PE3

(XCK0/AIN0)PE2

PD2(RXD1/INT2)

PD3(TXD1/INT3)

PB7(OC2/OC1C)

PF7(ADC7/TDI)

PF6(ADC6/TDO)

PF5(ADC5/TMS)

PF4(ADC4/TCK)

(IC3/INT7)PE7

PD0(SCL/INT0)

PD1(SDA/INT1)

(T3/INT6)PE6

(RXD/PDI)PE0

(TXD/PDO)PE1

PG4(TOSC1)

PG3(TOSC2)

AT90CAN128

PB6(OC1B)

PB5(OC1A)

PB3(MISO)

PB2(MOSI)

PF3(ADC3)

PF2(ADC2)

PF1(ADC1)

PF0(ADC0)

(XCK1)PD5

PG2(ALE)

PB4(OC0)

PB1(SCK)

(AD7)PA7

(AD6)PA6

(AD5)PA5

(AD4)PA4

(AD3)PA3

(AD2)PA2

(AD1)PA1

(AD0)PA0

(A15)PC7

(A14)PC6

(A13)PC5

(A12)PC4

(A11)PC3

(A10)PC2

(IC1)PD4

PG1(RD)

PG0(WR)

PB0(SS)

(A9)PC1

(A8)PC0

(T2)PD7

(T1)PD6

RESET

XTAL1 XTAL2

IC3

AG

ND

AV

CC

AREF

VC

C

VC

C

GN

D

GN

D

PEN

20

24 2363

64 52 21

53 22

19

18

43

34

33

17

16

15

14

13

12

11

10

54

55

56

57

58

59

60

61

44

45

46

47

48

49

50

51

42

41

40

39

38

37

36

35

25

26

27

28

29

30

32

31

62

1

9

8

7

6

5

4

2

365

RN1

10k

109

RN1

10k

RN1

10k

3

4

Q8

BS250D5

1N4148

RN1

10k

8

7

56

RN3

6k8

+5V

RN3

6k8

2

1

Q3

Q4

BS170

RN3

6k8

8

7

RN1

10k

2

1

R4

100k

R3

100k

R11

560

R6

560

+12V +5V

D1

1N4004

+12V

IC2IC2 = LM339N12

3

+12V

C1

100n

C2

100n

C3

100n

7805

IC5

78L08

IC1

+8V

+5V

070038 - 11

2x

K-Line

L-Line

CAN-H

CAN-L

PWM-Interface

VPWM-Interface

CAN-Interface

K/L-Interface

K OUT

L OUT

KL IN

PWM+ OUT

PWM- OUT

PWM IN

VPWMIN

VPWMOUT

PWM-

PWM+VPWM

+12V

red green

AGV4900

Figure 3. The AVR microcontroller with on-board CAN interface is the main part of the circuit diagram.

Stand Alone OBD-2 Analyser • 13 Elektor blockbusters

Page 14: E-book-15-ElektorBlockbusters-uk

496/2007 - elektor electronics

Putting all the bits togetherAttention has been paid to the PCB layout (Figure 4); SMD components have not been used for this design to

simplify component mounting. The PCB is produced to industry standard using FR4 type board with gold plat-ing. Gold is chemically inert and gives

the board almost unlimited shelf life. The plating also ensures that there should be no problems of corrosion which have been reported when lead-

Figure 4. The PCB is an SMD-free zone.

COMPONENTSLISTResistorsRR1 = 1kR3,R4 = 100kR5,R9 = 33R6,R11 = 560R7,R8 = 100R12 = 1k 5RN1,RN2 = 10k SIL-10 arrayRN3 = 6k 8 SIL-8 array

CapacitorsC1,C2,C3,C10 = 100nFC4,C5 = 22pF

C6,C7 = 470pF

SemiconductorsD1 = 1N4004D2,D4,D5 = 1N4148IC1 = 78L08IC2 = LM339NIC3 = AT90CAN128 (Atmel; QIL case),

programmed as “AGV4900” (Stange Distribution)

IC4 = PCA82C250 (Philips)IC5 = 7805LED1 = 3mm, redLED2 = 3mm, greenQ3-Q6 = BS170 (TO92)Q7,Q8 = BS250 (TO92)

MiscellaneousQ1 = 8MHz quartz crystal (HC49/S)

LC-Display 3x16 lines, type EA DOGM163E; with background light: EA LED55X31-A

S1,S3 = PCB mount pushbutton type 40-XX B3F (Omron) with matching aluminium cap

DC buzzerX2 = 9-way sub-D plug (male), PCB mountIC socket 14-wayIC socket 8-wayQIL socket (4 segments of 16 pins)PCBCase with front panel foilMounting materials

Note: Kit of parts no. 070038-71 contains all components, the case (with front panel foil fi tted), mounting materials and OBD-2 cable, see Elektor SHOP advert or www.elektor-electronics.co.uk

Stand Alone OBD-2 Analyser • 14 Elektor blockbusters

Page 15: E-book-15-ElektorBlockbusters-uk

PROJECTS VEHICULAR TEST EQUIPMENT

50 elektor electronics - 6/2007

free solder is used on unplated boards. Gold has excellent tinning properties and allows the use of either lead-free or lead/tin solder. Apart from the need to take care with component place-ment and soldering, no special elec-tronic skills or programming compe-tence is needed to complete this project.Except for the two LEDs ‘connect’ and ‘data-traffi c’, the two pushbuttons and the LC display all other components are mounted on the PCB side printed with the component outlines and iden-tification (Figure 5). Mounting the component starts with soldering each of the individual resistors into place followed by the diodes, capacitors, crystal, IC sockets, resistor networks (make sure they are the right way round), voltage regulator and then the transistors. The 7805 should fi rst be mechanically secured before the leads are soldered in place. Once the buzzer

used in this project is unfortunately only available in either the TQFP or MLF/QFN outline and neither of these are really suitable for a self-build project. The controller is therefore sup-plied (in MLF outline) already mounted on a small carrier board. It is only nec-essary to fi t an intermediate pin/socket arrangement to connect the carrier board to the main PCB. The pin layout of this connector is the same as a QIL64 package (Quad in line, 64 Pins). All the components for this connector are included in the kit, to ensure suc-cess it will be necessary to follow the instructions carefully, a mistake here will be diffi cult to correct.The complete socket is made up of four strips (Figure 7) fi tted to the main PCB, each strip is fi xed in place initially by soldering just one pin of each of the strips, this allows the fi nal layout of the complete socket to be easily adjusted until it exactly matches the layout.

and the sub-D connector are fi tted the board can be flipped over and the pushbuttons, display and LEDs sol-dered into place.The AT90CAN128 chip from Atmel

Figure 5. The PCB component side. Figure 6. The two push buttons, LEDs and LCD are mounted on the other side of the PCB.

Figure 7. The controller board connector is made up of four sections.

Stand Alone OBD-2 Analyser • 15 Elektor blockbusters

Page 16: E-book-15-ElektorBlockbusters-uk

516/2007 - elektor electronics

Once you are sure that the four strips are accurately aligned (check that they are also all at the same height on the board) all the remaining pins can be carefully soldered to complete the socket.The carrier board can now be fitted with the pins. The supplied pin strips must be carefully separated into 8-pin lengths. Any rough corners can be smoothed down with a fine file. The strips are pushed fully into the socket Figure 8a (They only fit one way round: the thinner tapered pins go into the socket).The controller board can now be positioned onto the pins (Figure 8b) ensuring that pin 1 is correctly aligned (to the left by C10). The 64 pins can now be carefully soldered onto the controller board (Figure 8c).Once all the components have been fi tted a short test can be carried out by connecting a 12-V supply to the sub-D con-nector (pin 9 = +12 V, pin 1 or 2 = 0 V). The current drawn by the analyser should not ex-ceed about 150 mA. The dis-play backlight will be lit and the boot loader version number will appear on the display followed by the greet-ing message. The short self-test is now complete.The fi nished PCB can now be mounted in the case: Fit the pushbutton caps and the sub-D cover, remove the protective fi lm from the display and with the display facing downwards

position the PCB into the front cover of the case. The small countersunk screws can now be carefully screwed in and tightened. Lastly, fi t the remain-ing half of the case and the OBD-2-An-alyser is now ready for action!

Analyser operationThe fi rst requirement before the OBD-2 analyser can be used is that the car is fi tted with the corresponding OBD-2 connector (see the advice given in ‘points to note’ elsewhere in this arti-cle). If it is, the supplied OBD-2 cable is inserted into the OBD-2 connector in

the car. The connector shouldn’t be too diffi cult to lo-cate, regulations insist that it must be mounted in the vehi-cle within 1 metre of the driv-er’s seat. A concise operating manual for the analyser is available to download from www.elektor-electronics.co.uk. A shortform manual is also sup-plied in the kit of parts so we will not delve too deeply into the fi ner points here. An on-line simulator is also available on our website so you can fa-miliarise yourself ‘virtually’ with the analyser operation.At switch-on it is possible to alter the display contrast (Fig-ure 9a). This is achieved by holding down keys A and B and plugging the analyser into the OBD-2 socket. The con-trast changes each time key A is pressed. Once you are hap-py with the setting release key A and press B to store it. This basic method is used to control the analyser: Key A cy-cles you through the menu op-tions while key B confi rms a selection or provides a re-sponse from the equipment.The display now shows the greeting ‘ELEKTOR OBD2 1.4’ with the start menu (Figure 9b) following shortly after-

Figure 8. The three steps to mount the controller board.

Figure 9. Displays: (a) Contrast setting, (b) Start menu, (c) Status display, (d) MIL/DTC PID Menu, (e) DTC trouble code number.

a

b

c

d

e

cba

Stand Alone OBD-2 Analyser • 16 Elektor blockbusters

Page 17: E-book-15-ElektorBlockbusters-uk

PROJECTS VEHICULAR TEST EQUIPMENT

52 elektor electronics - 6/2007

wards with the options: Start Diag,Protocol and Language. When the ana-lyser is regularly used on the same ve-hicle and you are sure of the correct protocol then it can be selected other-wise option code 0 tells the analyser to automatically fi nd the correct protocol. A press on key B begins the scan (if the vehicle interface is not compatible with OBD protocol the test ends with a fail-ure message). When the scan has run the display will show the state of the MIL/DTC indicating if any troubles were present (Figure 9c). Selecting the option Live Data with button B will show the actual value of a parameter. The chassis number or vehicle ID can be read and the communication Proto-col displayed as well as the option to rescan.The current reading of a sensor (live data) is given in the PID (parameter identifi er) menu. The example shown in Figure 9d is a reading of the intake Mass Air Flow (MAF in g/s). Pressing key B takes you back to the previous menu. When a failure has been detect-ed by the engine management system the analyser will indicate that the MIL is on (MIL:ON), and the number of stored DTCs (Diagnostic Trouble Code) is given (Figure 9e) .There is now a choice between displaying the troublecodes or freeze frame data. For trouble codes the code number is displayed

The example in Figure 11 indicates a sensor reading when trouble was logged; trouble F000 a PID 0D (speed) of VSS = 33 km/h measured. Button A takes you through successive parame-ters while button B returns to the pre-vious menu.The downloadable user’s manual con-tains overviews of all the menu op-tions, selections and display messag-es. When you want to get more familiar with its operation, try the online simu-lator mentioned earlier, or better still put your order in and build your own OBD-2 Analyser! An extra fi le contain-ing soldering and assembly hints can also be downloaded from the Elektor Electronics website.

(070038-I)

Literature[1] Datasheet for the AGV4900-Controller:

www.obd-diag.de

[2] Source of the AGV microcontroller: www.stange-distribution.de

[3] http://www.blafusel.de/misc/OBD-2_scanned.php

along with (in most cases) a detailed description of the fault (see Figure 10).When the trouble codes are displayed, pressing key A brings up an option to clear the codes from the vehicle’s memory.More information about the failure can be gleaned by selecting Freeze Frame. When an error is detected by the en-gine management system the on board computer will take a snap-shot or freeze frame of all sen-sor readings and store them in the vehicle’s memory. A check of this data can pro-vide a valuable insight into the cause of the failure. In selecting freeze frame trouble codes it is possible to select succes-sive sensor va-lues stored around the time that the fai-lure oc-cur-red.

errors found:2 of 4

error code 2

error 2description

select error 3with button B

070038 - 13

Figure 10. Trouble code menu showing a description of the trouble in running text.

Figure 11. The Freeze frame menu (PID select).

Stand Alone OBD-2 Analyser • 17 Elektor blockbusters

Page 18: E-book-15-ElektorBlockbusters-uk

PROJECTS GPS

36 elektor - 10/2007

ElekTrackTracking & tracingwith GPSChris Vossen

Position determination is all the rage. The manufacturer of the well-known TomTom navigation system has become a publicly traded company, and the alarm systems of expensive cars and other vehicles often comprise positioning systems so they can report where the vehicle is located. However, such systems are rather expensive, so we decided to take the DIY approach and develop our own version, dubbed ElekTrack.

Nowadays we want to know the cur-rent position of everything. Where’s that package I ordered? Is the book I want already back in the library? Has my nephew’s train arrived already? Technology has advanced so much in recent years that there’s almost no sit-uation we can imagine that doesn’t al-ready have a solution. And otherwise we provide a solution!

Big BrotherPeople are often a bit nervous about organisations that keep track of every-thing, but in some cases this is exactly what we want. For example, consider car security and alarm systems. Those of us who can afford the latest May-bach or Mercedes SLR will doubtless encounter stringent security require-ments when they take out insurance for their vehicles. Quite often these cars must be fitted with security sys-tems that include vehicle tracking and tracing capability in addition to stand-ard anti-start and alarm functions. This means that they have a built-in GPS-based positioning system that reports

the vehicle location to a message cen-tre. Stolen vehicles are indicated by red spots on a map in the control room.

Passenger cars are not the only vehi-cles being fitted with tracking sys-tems. Lorries and boats can also ben-efit from such systems. More and more excavating machines are also being fitted with security systems, because they are stolen by the truckload. With a built-in track & trace module, these pricy machines can be tracked down and recovered.

Of course, not everybody has an exca-vating machine or a Bentley in the ga-rage, but it’s still possible to find other interesting uses for a GPS tracker. For example, on a scooter or motorcycle. And if you’re a private detective, such a system is bound to make your eyes light up.

We developed the ElekTrack to give our readers an opportunity to experi-ment with GPS tracking. Due to the large number of SMD components and the difficulty of soldering such

components, we decided to supply this module fully assembled only.

Objective of the designWhat must a tracking aid be able to do in its simplest form? Naturally, you want to be able to track the unit’s lo-cation. We chose the most obvious so-lution for the position determination part: GPS. With this, the system can identify its position nearly everywhere in the world. In addition, GPS is pres-ently very accurate, and as long as the European Galileo system [1] is not yet operational, it is the best ‘alternative’.We decided on SMS for data transmis-sion. Although data transmission is not actually live with this approach, it is possible almost everywhere and at all times. The GPRS network would have been another good option for data transmission. GPRS works with a di-rect link via the Internet, so data can

Figure 1. As you can readily see from the schematic, everything revolves around the GSM modem.

ElekTrack • 18 Elektor blockbusters

Page 19: E-book-15-ElektorBlockbusters-uk

3710/2007 - elektor

be displayed live on a computer with Internet access. The loca-

tion could thus be queried without any time delay,

and the data could be stored ‘live’ in a da-

tabase. However, we gave the pref-

erence to the simpler SMS

system.The de-

sign

thus consists of two main modules: a GPS module and a GSM module.The GSM module is a type Q2686 from Wavecom. This module can be con-trolled using Wavecom OpenAT com-mands, and it has a built-in microcon-troller. The main advantage of this is shorter development time compared with using a separate modem, since it is not necessary to implement a mi-crocontroller or any peripheral logic. Everything is located in a single mod-ule. This also keeps the overall design nicely compact.

For the GPS module, we decided on the Copernicus from Trimble. This is a suc-cessor to the Lassen iQ, which already showed what it could do in the USB

GPS receiver design published in the May 2005 issue of Elektor Electronics.

Schematic diagramA glance at the schematic diagram in Figure 1 quickly shows that everything is built around the GSM modem. The GPS module is connected to UART2 of the modem via a logic-level converter (IC3). The circuitry around T3, T4 and T5 detects whether the antenna circuit is shorted, open, or connected normal-ly. The GPS module supplies power to the active antenna via T1 and T2.Two supply voltages are necessary for proper operation of the circuit: 4.5 Vand 3.3 V. They are provided by IC5 and IC6. IC5 (a LT3430) is a buck convert-

VBAT

T1

VBAT

T2

VBAT

T3

VBAT

T4

VCC_

1V8

5

CHG_

IN6

BAT_

RTC

7

CHG_

IN8

SIM_VCC9

VCC_

2V8

10

SIM_IO11

SIMPRES12

SIM_RST13

SIM_CLK14

BUZZ_OUT15

BOOT16

FLASH LED17

/RESET18

ON_OFF19

BAT_TEMP20

AUX_ADC21

SPI1-CS22

SPI1-CLK23

SPI1-I24

SPI1-IO25

SPI2-CS28

SPI2-IO27

SPI2-I29

SPI2-CLK26

RXD230

TXD231

CTS232

RTS233

MIC2N34

SPK1P35

MIC2P36

SPK1N37

MIC1N38

SPK2P39

MIC1P40

SPK2N41

GPIO042

GPIO4443

SCL44

GPIO1945

SDA46

GPIO2147

GPIO2048

INT149

INT050

GPIO151

VPAD-USB52

GPIO253

USB-DP54

GPIO2355

USB-DM56

GPIO2257

GPIO2458

COL0/GPIO459

COL1/GPIO560

COL2/GPIO661

COL3/GPIO762

COL4/GPIO863

ROW4/GPIO1364

ROW3/GPIO1265

ROW2/GPIO1166

ROW1/GPIO1067

ROW0/GPIO968

RI1/GPIO4269

DCD1/GPIO4370

TXD1/GPIO3671

RTS1/GPIO3872

RXD1/GPIO3773

DSR1/GPIO4074

CTS1/GPIO3975

DTR1/GPIO4176

PCM_SYNC77

PCM_IN78

PCM_CLK79

PCM_OUT80

GND

101

GND

102

GND

103

GND

104

IC2

Wavecom Q2686

C1

100n

R1

100k

GND

1

SW2

VIN3

VIN4

SW5BO

OST

6

GND

8

GND

9

BIAS10

VC11

FB12

SYNC

14

SHDN15

GND

16

GND

17

IC5

LT3430

C17

22n

C18

220p

R13

3k3

R12

12k7

R14

4k99

D8

30BQ060

D5

1N4148C11

680n L547uH

10V

C12

100u

GND

50V

C16

4u7

D6

RS3K

L4

BLM21P300S

D7

SM8S33A250V

C15

100n

GND

1

GND

2

GND

4

GND

13

GND

14

GND

15

GND

27

GND

28

RF-IN3

LNA5

OPEN7

SHORT8

BOOT10

XRESET11

VCC

12

TXD-B24

TXD-A23

RXD-A21

RXD-B20

PPS19

XSTANDBY16

RESERVED9

IC4

Copernicus GPS Receiver

4V3

4V3 1V8 2V8

GND

VIN1

GND

2

ON/OFF3

NC4

VOUT5

IC6

LP2985

GND

4V3 3V3

10V

C14

10u16V

C13

1u

C19

100n

3V3L3100nH

C7

100n

C8

18p

T3 MMBT3906 T4

R10

4k7

R11

4k7

R7

56R2

R8

10k

R61k

T5

MMBT3904

R4

1k

R510R

R910k

T2BC848

T1

IRLML6402

R3

100k

3V3

D41N4148

GND

GND

OVCC21

GND

2VL

3

IVL24

OVL15

IVCC18

THREE-STATE6 VC

C7 IC3

MAX3375E

1V8

C9

100n

C10

100n

GND

GND

EN1

C1+2

C1-4

C2+5

C2-6

T1IN11

R1OUT9

FORCEON12

FORCEOFF16

INVALID10

R1IN8

T1OUT13

V-7

V+3

VCC

15GN

D14

IC1

MAX3221E

C4

100nC5

100n

GND

3V3

C3

100n

C6

100n

C2

470p

1

2

34

5

6

D2

DALC208

VCC1

GND2

RST3

VPP4

CLK5

IO69

10K1

Simcard Holder

1V8

1 63 42 5

D1

ESDA6V1SC6

GND

D3

R2

470R

L1BLM21B102

L2BLM21B102

R1510

k

K3

2V8GND

K2

Vbat

Vbat

GND

RXD_INTXD_OUTEXT_INPUT3EXT_INPUT2EXT_INPUT1

TXD_

OUT

RXD_

IN

2345

1

K4

T6MMBT3904

T7MMBT3904

T8MMBT3904

R17

4k7

R18

4k7

R19

4k7

C20

10n

C21

10n

C22

10n

R22

10k

R23

10k

R24

10k

R1682k

R2082k

R2182k

GND

D11

1N4148

D10

1N4148

D9

1N4148

2V8

DI0DI1DI2

040161 - 11

D12R25470R4V3

K5

1V8

2x

ElekTrack • 19 Elektor blockbusters

Page 20: E-book-15-ElektorBlockbusters-uk

PROJECTS GPS

38 elektor - 10/2007

er operating a frequency of 200 kHz. Resistors R12 and R14 determine the output voltage, which is set to approxi-mately 4.5 V.IC6 provides the supply voltage for the GPS module. It generates a fixed 3.3-V output voltage from a 4.5-V input volt-age. Three identical level converters are formed using T6, T7 and T8. They convert the relatively high input volt-ages to logic levels that comply with the specifications of the GSM modem.

IC1 is a standard RS232 converter, which among other things can be used for connecting the unit to a PC in order to program the modem. You can also use IC1 as a port for your own appli-cations. D1 and D2 protect the input of the GSM module against static dis-charges that can occur when the SIM card is inserted in the socket.

LED D3 shows the status of the GSM link. If it is continuously on, the mo-dem is not logged in to the network. It starts blinking as soon as the modem logs in successfully. LED D12 shows the status of the GPS module.

External connectionsThe power supply can work with an external 12-V or 24-V system. Based on tests, the ElekTrack requires an exter-nal supply voltage of at least 8 V for proper operation. The external pow-er source must also be able to supply sufficient current. Relatively high peak currents occur when the GSM modem is transmitting data. The average pow-er consumption of the unit is around 500 mW, so a 9-V battery would only last for approximately 2 hours. A scoot-er or motorcycle battery will hold out for a lot longer. Naturally, it would al-ways be possible to modify the soft-

at+cpin?

If the modem responds with ‘+CPIN: READY’, the SIM card does not need a PIN code. If you receive the response ‘+CPIN:SIM PIN’ instead, the SIM card needs a PIN code, and this will first have to be eliminated. The cur-rent firmware does not yet support automatic PIN code use. This may be implemented in a future version of the firmware. Check our website for the latest version.

If you enter the command

at+cpin=xxxx

(where ‘xxxx’ is the pin code of the SIM card), you will receive ‘OK’ in response.

Next you have to request disabling of PIN checking by entering the follow-ing command:at+clck=”SC”,0,xxxx (where ‘xxxx’ is again the PIN code of the SIM card). The modem will again respond with ‘OK’.

In order to check whether the modem can now log into the network automat-ically, you have to reset it with

ware in order to reduce the current consumption. For instance, you could implement a function to place the GPS module in sleep mode with an SMS command and awaken it with another command.

Naturally, the unit also has antenna connectors: one for the GPS module and one for the GSM module. The mo-dem also has several logic inputs. They can be used for purposes such as con-necting an alarm to the ElekTrack. A voltage above approximately 8 V will cause the digital input of the GSM mo-dem to be triggered. When this hap-pens, a text message can be sent to one of two previously programmed tel-ephone numbers. You will have to im-plement this in the software yourself, since this function is not yet included as standard. Perhaps it will be imple-mented in a firmware update.

The GPS module can be configured using various commands. For this pur-pose, the module must be linked to a PC by a cable. A program such as Hy-perTerminal for Windows must be used to configure the ElekTrack unit. The se-rial port of the PC must be configured as shown in Figure 2.

StartupThe first thing you have to do is to check whether the SIM card is pro-tected by a PIN code. Use the follow-ing command for this:

ElekTrack • 20 Elektor blockbusters

Page 21: E-book-15-ElektorBlockbusters-uk

3910/2007 - elektor

at+cfun=1

If everything goes well, the upper LED (D12) will start blinking after a bit less than a minute. This means that the mo-

dem has successfully logged in to the network. If you wish, you can check this by entering the command

at+cops?

The modem will respond with+COPS: 0,2,20408OK

(here ‘20408’ is the operator number,

Better than GPSThe Global Positioning System (GPS) was origi-nally developed for military use. In response to steadily increasing demand for accurate position determination, the GPS system was released for civilian use a bit at time. At first, the accuracy of the satellite signals was intentionally degraded by the US authorities who originally established the system. This restriction was removed a few years ago, so consumers can now use the full resolution of the system. This allows GPS to be used to determine positions with an potential error of up to three metres. The positioning ac-curacy depends on the number of ‘visible’ satel-lites and whether a WAAS or EGNOS signal is received.

The terms WAAS and EGNOS relate to systems that can be used in combination with GPS to increase positioning accuracy. WAAS stands for ‘ Wide Area Augmentation System’, while EGNOS stands for ‘European Geostationary Naviga-tion Overlay Service’. The EGNOS and WAAS systems do the same thing, but the former is for Europe and the latter for North America. Each system consists of a network of satellites and ground stations that generate a GPS correction signal that can be used to increase positioning accuracy by a factor of up 5 on average. A re-ceiver that supports WAAS or EGNOS generates positions that differ from true positions by less

than 3 metres in more than 95% of all cases.

EGNOS currently consists of three geostationary satellites and several ground stations distributed over Europe. The ground stations collect infor-mation from each other and generate a correc-tion signal. The ground stations know their own locations with high accuracy, and they compare their positions with the signals received from the satellites, since the paths of the satellite sig-nals can be distorted by atmospheric conditions and other causes. The correction signal is then transmitted to the geostationary satellites. This data has the same format as the standard GPS signal, so it can be read by any GPS receiver that supports WAAS.

EGNOS is as joint project of ESA, Eurocontrol and the European Commission, and it works with the American GPS navigation system and the Russian Glonass navigation system. The EG-NOS satellite number for Europe is 33. Many GPS systems indicate whether they are receiv-ing a correction signal. The term ‘differential’ is also used for this.

The MSAS system, which operates the same way, is used in Asia.

ElekTrack • 21 Elektor blockbusters

Page 22: E-book-15-ElektorBlockbusters-uk

PROJECTS GPS

40 elektor - 10/2007

which depends on the provider.)Now the modem will log into the net-work automatically as soon as power is applied to the module.

SecurityThe first thing you have to do is to change the password. The default password is ‘elektor’. To change the password, first enter the following command to request the password:at+password?The modem will respond with ‘+PASS-WORD:: elektor’. To change the pass-word, use the command:at+password=”gpsmodule”Note: you must enter the quotation marks as shown; otherwise you will re-ceive an error message. The maximum password length is 20 characters.

GPS statusThe GPS module is connected to the serial port of the modem. Two com-mands for requesting data from the GPS module are implemented in the first version of the firmware. The first command is

at+gpshealth?

The following is an example of a pos-sible response from the modem:

Rcvr status code = 0x01 (Don’t have GPS time yet)Receiver health byte = 0x11Battery backup: BBRAM not available at start-upAntenna feedline fault: An-

was able to determine a valid posi-tion. When the module is first enabled, the receiver status code indicates the number of satellites being received. When the receiver has managed to de-termine a valid position, the lower LED (D3) starts blinking. If this LED is on continuously, something is wrong. It could mean that the module is not re-ceiving enough satellites, but it could also mean that the antenna is connect-ed incorrectly.

Normal useNow that you have determined that a link has been established, you would like to know the latitude and longitude coordinates. Enter the following com-mand for this:

at+gpsposition?

The modem will return a set of coordi-nates in response, such as

Long: 5.803043 E; Lat: 50.941492 N;OK

tenna line open/shortType of fault: Open detectedOK

From this, you can deduce that the GPS module does not have any valid coor-dinates at present. The antenna status indicates a fault situation. The fault type indicates that the antenna con-nection is open-circuited. The antenna is probably not connected.

If the command is issued again after the antenna has been connected, you might receive the following response:

Rcvr status code = 0x00 (Do-ing position fixes)Receiver health byte = 0x01Battery backup: BBRAM not available at start-upAntenna feedline fault: OKOK

Here you can see that the antenna status is ‘OK’. If the antenna input is short-circuited, a ‘Short circuit’ sta-tus message will appear. The receiver status code reports that the receiver

Figure 2. The settings shown here must be used for serial communication.

Figure 3. ElekTrack knows exactly where to find Elektor’s new head office!

ElekTrack • 22 Elektor blockbusters

Page 23: E-book-15-ElektorBlockbusters-uk

4110/2007 - elektor

Of course, you want to be able to re-quest the coordinates via SMS so you can request the position of the mod-ule remotely. To prevent unauthor-ised persons from receiving a reply from the module if they send a text message to it, the module must have a password. Send the following mes-sage to the module via SMS to assign it a password:

info:<password>:<phonenum>orINFO:<password>:<phonenum>

Note: ‘info’ must be written either entirely in upper case or entirely in lower case. The password you con-figured using the at+password com-mand must be entered here in place of <password>.

The <phonenum> parameter is option-

al. The reply is returned to the sender by default. If you want to have the re-ply be sent to a different number, you can use this parameter to specify the desired number.

After a few seconds, the ElekTrack will send a text message via SMS with the longitude, latitude and altitude data, which can be used to determine the lo-cation of the ElekTrack unit. For exam-ple, you can do this online at [2] (Fig-ure 3) or [3].

The ElekTrack is supplied as fully as-sembled unit, and you can order it via our webshop at www.elektor.com. The latest version of the software is also available on our website. And of course, we always appreciate hearing from our readers about interesting ide-as and applications.

(040161-1)

Web Links[1] en.wikipedia.org/wiki/Galileo_positioning_system

[2] www.gpscoordinates.eu

[3] http://boulter.com/gps

Practical problemsAnyone who writes software knows that little bugs always find a way to creep into the code. When were first devel-oping the software, we had problems with sending SMS messages. It seemed like the SMS service of the modem somehow didn’t want to work. After spending several hours looking for the source of the problem and reading through documentation, we came up with the simple but brilliant idea of trying a different SIM card. That meant a quick trip to the shop to pick up a new SIM card. And just imagine our surprise when we discovered that there were no problems at all with the new card!

Of course, we found it rather remarkable that everything worked OK with the new SIM card, so we contacted the supplier. It turned out that there was indeed a bug in the modem firmware. Logging in to the SMS service evident-ly did not work properly with some types of SIM cards. This problem has been corrected in the latest version of the firmware.

Another problem that is probably familiar to most soft-ware developers is the difference between little-endian and big-endian memory organisation. The GPS module outputs latitude and longitude coordinates as doubles in radians. The GPS module operates in little-endian mode, while the GSM module operates in big-endian mode. When you import the data (as ASCII values), the order of the bytes must therefore be reversed. If you convert little-endian radian data in a big-endian processor, the results are naturally all over the map. We overlooked this detail at first. Your first impulse is to think that you made a mistake in the code that performs the conversion. In retrospect it’s all pretty obvious, but in the midst of the fray it’s a hard nut to crack.

ElekTrack • 23 Elektor blockbusters

Page 24: E-book-15-ElektorBlockbusters-uk

elektor electronics - 4/200656

Making Waves TECHNOLOGY E-BLOCKS

John Dobson

In last month’s article on making a sound waveform we used the E-blocks SPI bus D/A andmemory board to generate a sound waveform of around 400 Hz. In using Flowcode I read thatthe flowchart is first converted into C and then into assembly code, and that you can embed Cinto your Flowcode programs to speed the operation up. In this article I describe my attempts touse C to speed up the sound waveform generator. At the same time Idiscovered how you can use Flowcode to learn C programming.

To generate code for the PIC microcon-troller, Flowcode processes a flowchart in a number of steps. Let’s have alook at how this works:

Step 1Flowcode initially takes your flowchart and generates C from it. As anexample of this let’s look at a simplecounter program (COUNTER1.FCF) inFlowcode and its C equivalent. In Figure 1 you can see the counter inFlowcode: we declare the value of vari-able COUNT as 0; then we have a loopicon. The Loop WHILE 1 declares anendless loop as ‘1’ is always true.

Inside the loop we have icons toincrease the value of COUNT by 1, waitfor one second and then output thevalue of COUNT to port C. I have a16F877 PIC micro with LEDs countingup in a binary sequence on port C.

Step 2If you open Windows Explorer and lookin the directory where theCOUNTER1.FCF Flowcode file is savedyou will find that Flowcode has gener-ated a number of files one of which isCOUNTER1.C. This is the C equivalentof the COUNTER1 flow chart program.If you open this file in Notepad you will

see the program in Figure 2.Here we have shown the program intwo parts, side by side – to save spaceon this page. Firstly, Flowcode hasdefined some of the constants the Ccompiler needs with statements like‘char PORTC@0x07;’. This defines theC variable ‘PORTC’ as being hex(that’s what the ‘0x’ stands for)address 07. Similarly TRISC is definedas being hex 87. TRISC is the datadirection register on the PIC micro andthe TRISC register on the 16F877 I amusing is at hex 87. Similarly, many ofthe other PIC micro and circuit specificfunctions – such as the clock speed,

Making Waves at C • 24 Elektor blockbusters

Page 25: E-book-15-ElektorBlockbusters-uk

the pins for the internal USART etc. aredefined. (Note that in C when a linebegins ‘//’ this indicates that the lineis a comment and not a line of code.)There are no macros or subroutines inour program so these sections areblank, but there is a variable definedas type CHAR called FCV_COUNT.This is our COUNT variable from theFlowcode program. This is the firsthint in how you can use the C icon inFlowcode to embed code into a Flow-code program: all variables in Flow-code are prefixed by ‘FCV_’ whentransferred to the C compiler. Thismeans that when referring to a Flow-code variable in a C icon you must alsoprefix the variable with ‘FCV_’. (inci-dentally, FCV stands for FlowCodeVariable.)After the declaration of variables yousee the first line of C:

Void main(){

This is a function declaration within Cto indicate that this is our main pro-gram. This is the equivalent to theSTART icon in Flowcode. The pair ofbraces indicate that there are no vari-ables passed to this function, and the‘open’ curly bracket ’{‘ indicates thestart of the main function, and you cansee a ‘close’ curly bracket ‘}’ at the endof the program.After this we have two more declara-tions – for the A/D converter – todeclare these pins as analogue inputs –and to turn the timer interrupt on.These are declared inside the mainprogram loop as they can be altered bythe user within the Flowcode program.After this we have the main program:FCV_COUNT is declared as being 0,corresponding to our first flow charticon, then there is a while (1) state-ment followed by further code insidecurly braces: this means execute theroutine inside the curly braces forever.Inside the braces we have theFCV_COUNT increment, and a delay of1 second. Note that these lines of Ccode end with a semicolon. Lines of C

4/2006 - elektor electronics 57

at C E-Blocks and Flowcode do your C programming

Figure 2. C equivalent of COUNTER1.FCF.

Figure 1. A simple Flowcode counter.

Making Waves at C • 25 Elektor blockbusters

Page 26: E-book-15-ElektorBlockbusters-uk

code are always terminated with a ‘;’.Then we have the line ‘TRISC=0x00’.We saw earlier that TRISC is the datadirection register. This line of codewrites value 0 to TRISC which declaresall of the port C pins as outputs. Avalue for hex FF would declare all thepins as inputs. Our last line of C codein the loop writes the value of ourCOUNT variable to port C.The last line here is a kind of safetynet: in the case where we do not havean endless loop in our Flowcode pro-gram, then the C program will getstuck at this point and execute thisline forever. This is the equivalent tothe END icon in Flowcode. If you havea C program without an END loop likethis then you get a curious effect: theprogram counter in the PIC microdevice keeps incrementing until it rollsover back to address 0000, at whichpoint your program will start to runagain.Well, that was not as hard as I hadexpected: C is a mysterious languagebut it seems that if we start from a flow-chart then, with a little explanation, theC becomes readable. Admittedly all thedeclarations are difficult to understandbut Flowcode seems to take care ofthem, so I won’t worry too much whatthey all mean. Besides, a good introduc-tion to C was supplied free of chargewith last month’s Elektor.

Back to the plotSo back to our original objectives ofincreasing the speed of the waveformgenerator program I wrote. Well, I dulycompiled my program ‘SINE WAVEGEN.FCF’ from last month’s instal-ment, and looked at the C produced.What I noticed was that every timeFlowcode used a DAC_SEND_CHARicon it went through a lot of lines of Cto declare further variables andaddress references that the C compilerneeds. The reason Flowcode does thisis that it has to assume that you don’tknow what you are doing (thank good-ness!) and it has to set all the parame-ters of Port C for serial communication,each time you use the SPI DAC macroicon, just in case you are using port CI/O pins for other functions. Wellmaybe we can take out some of theselines of C to speed things up? Idecided to tackle this in two stages:firstly replace a DAC_SEND_CHARicon with the C equivalent to makesure I had replicated the function of theprogram, and secondly to then startaltering the C code to see if I could

make it more efficient.Going back to the main program I sim-ply replaced one of theDAC_SEND_CHAR icons with a C icon.Then I looked up the equivalent C ofthe DAC_SEND_CHAR icon andpasted it into the new C icon. Then Iadjusted the variable declarations tomake sure the C icon picked up myOUTVAL Flowcode variable, andrecompiled the program to make surethat it still worked. Eventually it did. Having got to first base I then com-mented out all the unnecessary lines ofC – of the original 34 lines of C code,which a DAC_SEND_CHAR icon pro-duces only 9 were actually needed!There was a certain amount of trial anderror here – I just kept commenting outlines until the program stopped work-ing! The program produced is calledSINC3.fcf and you can download it fromthe Elektor Electronics website. The filenumber is 065032-11.zip and you canfind it under Magazine April 2006

Unfortunately however I was unsuc-cessful in making the DAC go anyfaster – the speed limitation turned outto be the speed of the SPI but itself –let me explain!

Within the code of theDAC_SEND_CHAR Flowcode com-mand, the 8-bit SPI data is sent in twobytes. The last four bits of the first bytecontain the most significant data nib-ble, and the four most significant bitsof the second byte contain the leastsignificant nibble. Other bits in eachSPI data byte are reserved for chip con-figuration etc. The DAC_SEND_CHARFlowcode icon takes OUTVAL andprocesses it like this:

dac_val = (FCV_OUTVAL & 0xF0) > 4;sspbuf = dac_val;delay_us(3);

dac_val = (FCV_OUTVAL & 0x0F)<< 4;

sspbuf = dac_val;delay_us(3);

Looking at the top routine: first wetake OUTVAL and AND it with hex F0(binary 11110000) and then shift left by4 bits (that’s the ‘> 4’), then we set theSSPBUF register in the chip with theresult and wait 3 s. Whatever getsplaced in the SSPBUF register will besent by SPI. The second routine is sim-ilar: take OUTVAL, shift left by fourbits, set SSPBUF and wait 3 s. Thelast statement is the key: SSPBUF is

the serial buffer in the PIC device and itwill take 3μs for the buffer to clear asthe information is sent one bit at atime. If you write to the buffer againbefore 3 s has elapsed you will over-write the data mid way through theserial send operation which producessome very strange results, as the SPIbus ceases to function correctly.

So, it turns out that the frequency ofour oscillator is determined by thespeed of the SPI bus. For those of youthat want the maths: each sampletakes 6 s; 256 samples per waveformgives a theoretical minimum period of1.5 ms or around 650 Hz.Oh well…time to reduce the number ofsamples to 64…

(065032-1)

Programs available fordownload

• COUNTER1.fcf• SINC3.fcf

File number: 065032-11.zip

Location: MAGAZINE April 2006 ‘E-Blocks making Waves at C’

elektor electronics - 4/200658

TECHNOLOGY E-BLOCKS

Earlier in this series

Electronic Building Blocks,November 2005.

E-blocks and Flowcode,December 2005.

E-blocks in Cyberspace,January 2006.

E-blocks – now you CAN,February 2006.

E-blocks Making Waves,March 2006.

Articles may be downloaded indi-vidually from our website.

For a complete overview of avail-able E-blocks visit SHOP at

www.elektor-electronics.co.uk

Making Waves at C • 26 Elektor blockbusters

Page 27: E-book-15-ElektorBlockbusters-uk

PROJECTS LOGIC ANALYSER

38 elektor electronics - 9/2007

DigitalInspectorFour-channel logic analyserRonald de Bruijn

When checking digital signals a logic analyser is indispensable, especially since many circuits use microcontrollers these days. In this article we describe an easy to build circuit that can cope with most digital signals and also has a memory function.

The best way to inspect digital signals is with a logic analyser. Sometimes it’s useful to be able to do this on-site, or you may have to take a ‘floating’ meas-urement. The four-channel logic ana-lyser described here is suitable in both situations due to its compactness and because it can be battery powered. The maximum sampling rate is 2 MHzand the circuit has sufficient memory to store 1024 samples of the signal. The dot-matrix display with a resolution of 64 by 128 pixels shows a clear repre-sentation of the digital signals.

SchematicAt the heart of the circuit is IC2 (a PIC18F4850, see Figure 1). This PIC controller samples the signals and

drives the display. It is controlled via five push buttons (S1 to S5). The crystal (X1, 10 MHz) de-termines what the max-imum sampling rate is. The internal PLL of the microcontroller is used

to give the controller an internal clock frequency of 40 MHz, which is the max-imum frequency recommended by Mi-crochip for this type of chip.Diodes D1 to D8 protect the inputs against too high or negative voltag-es. The input signals are fed to IC1, a 74HC04N, which is used as a buffer. The fact that the signals are inverted doesn’t matter in this case, since we can easily convert the signals back via the software. The signals go directly from the buffers into the controller via RA1 to RA4, where the software takes over (see Control).Preset P1 is used to set the contrast of the display and T1 turns on the background light of the display. Bz1 gives an audible warning when a new sampling cycle starts and when you

change between run and hold mode.The five switches used to control the circuit don’t require a hardware de-bounce circuit, since this is taken care of by the software.The power supply for the circuit con-sists of two parts: a stabilised 5 V sup-ply and a 9 V supply for the display light. The source for these voltages can either be a 9 to 12 V mains adapter or a 9 V rechargeable battery.A simple charging circuit for the bat-tery is also included (T2, R1, R17, D12), which comes into action whenever a mains adapter is connected. Assuming a standard LED with a forward voltage drop Vf of 1.5 V is used, the charging current for the battery will be:

(1.5 – 0.6) / 56 = 16 mA.

A 9 V NiMH battery with a capacity Cof 170 mAh is then charged at about 0.1 C,so no damage will occur if it is charged con-tinuously. The battery will be fully chargedin about 10 hours with this circuit. During the charging LED D12 will be on. If an ordinary (non-rechargeable) battery is

SpecificationSample frequency: 200 Hz-2 MHzChannels: 4Range: 0 to 5 VMemory: 1024 samples per channelTrigger levels: +Ve and –VeTrigger pattern: can be set for each inputDot matrix LCD: 64 x 128 pixelsSupply: 9 V PP3 battery

Digital Inspector • 27 Elektor blockbusters

Page 28: E-book-15-ElektorBlockbusters-uk

399/2007 - elektor electronics

used, the circuit around T2 can be left out.

ControlSwitch S1 is used to select the sam-pling frequency. The rates that can be selected are 5/10/20/50/100/200/500s/div and 1/2/5 ms/div. S2 selects the channel that is used to trigger the cir-cuit. S3 is used to tell the PIC if it is to trigger on a rising or falling edge and S4 can arm and stop the circuit, or clear the display. One short press of S4 arms

the circuit. After the trigger signal oc-curs it will take 1024 samples per chan-nel and store them. Pressing S4 briefly again will make the circuit read in a new set of 1024 samples after the next trigger signal. When S4 is held down for longer the display is cleared. The last settings for the sampling frequen-cy, the trigger channel and the trigger condition are stored inside the EEP-ROM of the microcontroller. These set-tings are then used as the initial state when the circuit is next turned on.S5 turns the backlight on or off. After

X1

20MHzC2

22p

C1

22p

+5V

R16

10k

R13

10k

R14

10k

R15

10k

K2

060092 - 11

T1

BC337

R19

1k

R21

220

BZ1

R2

10k

R20

47

+5V +9V

20k

P1

+5V

LC

DIS

PL

AY

9 81

IC1.D

R9

100k

R5

330CH4

5 61

IC1.C

R10

100k

R6

330CH3

3 41

IC1.B

R8

100k

R4

330CH2

1 21

IC1.A

R7

100k

R3

330CH1

R12

10k

R11

10k

D5

1N4148

+9V

D8

1N4148

D4

D7

D1

D2

D3

D6

+5V

C5

100n

IC1

14

7

C6

100n

+5V

K3

2

3

1

D11

1N4004

R1

680

D12R17

56

T2

BC337

BT1S6

C3

100n

C4

100n

7805

IC3

9V

+9V

+5V

12V

4x

4x

11 101

IC1.E

13 121

IC1.F

+5V

S4

S3

S2

S1

S5

D9

D10

1N4148

RD4/PSP4/ECCP1/P1A

RA5/AN4/SS/HLVDIN

RB0/INT0/FLT0/AN1

RC0/T1OSO/T13CKI

RE1/WR/AN6/C1OUT

RE2/CS/AN7/C2OUT

RD0/PSP0/C1IN+

RD1/PSP1/C1IN-

RB2/INT2/CANTX

RD2/PSP2/C2IN+

RD3/PSP3/C2IN-

PIC18F4580-I/P

RA3/AN3/VREF+

RA2/AN2/VREF-

RA0/AN0/CVREF

MCLR/VPP/RE3

RB1/INT1/AN8

RB7/KBI3/PGD

RB6/KBI2/PGC

RB5/KBI1/PGM

RB4/KBI0/AN9

RD7/PSP7/P1D

RD6/PSP6/P1C

RD5/PSP5/P1B

RC3/SCK/SCL

RC4/SDI/SDA

RE0/RD/AN5

RC1/T1OSI

RA4/T0CKI

RC7/RX/DT

RC6/TX/CK

RB3/CANRX

RC2/CCP1

RA1/AN1

RC5/SDO

IC2

OSC1 OSC2

11

15

40

39

38

37

35

36

34

33

3112

10

32

16

17

18

19

20

21

22

13 14

26

25

24

23

30

27

28

29

1

3

2

4

6

5

7

8

9

2x

IC1 = 74HC04

Figure 1. From the circuit diagram it is clear that the microcontroller takes care of just about everything.

Digital Inspector • 28 Elektor blockbusters

Page 29: E-book-15-ElektorBlockbusters-uk

PROJECTS LOGIC ANALYSER

40 elektor electronics - 9/2007

about one and a half minutes, or when in a ‘Lo_Batt’ condition, the micro-controller automatically turns off the backlight.

OperationIn order to obtain the highest possible sampling rate we initially let the micro-controller store the samples in its RAM when the trigger event occurs. For this we use the following software instruc-tion: movff port a, postinc0. This in-struction copies the contents of port ato the RAM and increments the RAM address by one. This cycle is then re-

an ‘S’ and the display shows the first 128 samples of each channel. Switches S1 and S2 can now be used to scroll through the memory. A short press of S1 or S2 causes small jumps through the memory; a longer press of S1 or S2 creates larger jumps. The cursor at the bottom of the display shows which area of memory is currently shown.Another quick press of S4 makes the circuit read in a new set of samples and store them in memory. The display keeps showing the same area of mem-ory as for the previous samples. This is of course very useful when you’re studying the signals that follow a short

peated 1024 times. At the end of this, 128 samples are read from the RAM and shown on the display. This proc-ess is repeated once a second.If no new trigger event occurs for about three seconds (depending on the sam-pling rate), the circuit reads in 128 samples and shows them on the LCD. In this way we can tell what condition (high or low) the inputs are.A quick press of S4 turns on the mem-ory function. This is indicated by an ‘R’ on the right of the screen. The circuit then waits for the trigger event. Once this has occurred and the 1024 samples have been stored the ‘R’ changes into

C4I3

K3

D12

S6C3

IC32

13

R15

R14

D11

R16

R13

D3D5D4D1

I4

R11 IC2R12

R3R4R6R5

X1

R7

C2

C5

C1

R9IC1

D7

R8D6D8

K2

R10

D2

I2

I1P1

I5S2S1

R17

S5T2

31

BT1

BZ1

S4T1

3

R21

1

R1C6

D10

D9

R2

R19R20

S3

Figure 2. As can be seen from the component layout, the construction of the circuit isn’t difficult. Connector K2 is placed such that the display can be mounted directly above the double-sided PCB.

Components listResistorsR1 = 680R2,R11-R16 = 10 kR3-R6 = 330R7-R10 = 100kR17 = 56R19 = 1kR20 = 47R21 = 220P1 = 20k preset, multiturn, vertical

mounting

CapacitorsC1,C2 = 22pFC3-C6 = 100nF

SemiconductorsD1-D10 = 1N4148D11 = 1N4001D12 = LED, 5mm diam.T1,T2 = BC337IC1 = 74HC04IC2 = PIC18F4580-I/P, programmed,

Elektor SHOP # 060092-41IC3 = 7805

MiscellaneousBz1 = AC buzzerX1 = 10MHz quartz crystalGraphic LC display, 128 x 64 pixels,

e.g. DEM128064A or NLC128x64 (Conrad Electronics # 187429)

Case 186 x 123 x 41mm with com-partment for 9V battery, e.g. Strapu-box (Conrad Electronics # 522775)

S1-S5 = pushbutton Multimec RA3FTL6 w. knob AQC09-24.2

S6 = on/off switch9-V battery clip5 wander sockets, screw mount (for

connection to I1-I5)Kit of parts incl. case: Elektor SHOP #

060092-71PCB layout: free download from

www.elektor.com, file # 060092-1

Digital Inspector • 29 Elektor blockbusters

Page 30: E-book-15-ElektorBlockbusters-uk

419/2007 - elektor electronics

time after the trigger event.If you hold down S4 a bit longer, un-til the buzzer gives a beep, the cir-cuit reads in a new set of samples and stores them in memory. But this time the display won’t show the same area of memory; instead it jumps right back to the beginning.If you hold down S4 longer still (until you’ve heard two beeps), the logic ana-lyser comes out of memory mode and returns to the standard mode where 128 ‘live’ samples are always shown on the display.

ConstructionIn this design we haven’t used any SMDs. The layout is fairly sparse, with all components easily accessible. The soldering should therefore not cause any problems.We would like to come back to the con-nection between the display and the board. There is enough room above the board for the display. The easiest way to connect the display to the board is to first solder a single pin-header strip

to the display board. Next, plug a wire-wrap socket into this pin-header and plug the other end into the main board. Check that the display is at the right height and then solder the wirewrap socket to the main board.When you use the recommended en-closure for this circuit you should first file off the corners of the board at the side of the input signals. The board will then fit perfectly.

CommentsWhen you’re not using all of the chan-nels it is advisable to connect the un-used channels to ground. You’ll often find that open inputs can pick up in-terference, which results in a garbled display.It should be clear that this analyser is not suitable for use with very high fre-quencies. Applications for this device are found with ‘slower’ microcontrol-lers, serial communications, etc. Even so, this simple circuit can make your life a lot easier during the development of a digital (microcontroller) circuit.

For this project we’re offering a com-plete kit of parts (order code 060092-71), which consists of the display, the main board, a programmed microcon-troller, the components and the enclo-sure. All that’s left for you to do is sol-der the components to the board and mount it in the enclosure. After con-necting a battery or mains adapter you can start analysing straight away.For those of you who want to etch the board yourselves, the layout can be downloaded from our website at www.elektor.com, under file number 060092-1.zip. And if you have the facil-ity to program the PIC microcontroller, you can also download the source code from our site (file # 060092-11.zip).

(060092-I)

Publicité

Digital Inspector • 30 Elektor blockbusters

This hands-on book covers a series of exciting and fun

projects with PIC microcontrollers. You can built more

than 50 projects for your own use. The clear explanations,

schematics, and pictures of each project on a breadboard

make this a fun activity. You can also use it as a study

guide. The technical background information in each

project explains why the project is set up the way it is,

including the use of datasheets. All software used in this

book can be downloaded for free, including all of the

source code, a program editor, and the JAL open source

programming language.

446 pages • ISBN 978-0-905705-70-5 • £27.00 • US$ 54.00

Elektor

Regus Brentford

1000 Great West Road

Brentford TW8 9HH

United Kingdom

Tel. +44 20 8261 4509

Order quickly and safe through www.elektor.com/shop

PIC MicrocontrollersSilent alarm, RGB fader, poetry box,night buzzer and more!

Page 31: E-book-15-ElektorBlockbusters-uk

HANDS-ON MILLING

14 elektor electronics - 1/2007

ProfilerConstruction kit for a general-purpose milling machineHarry Baggen

Have you always dreamed of having your own milling machine

but found them just too expensive? If so, we have

the perfect solution for you. Working in close

collaboration with the Belgian manufacturer

Colinbus, we have put together a construction

kit for our readers that enables you to build a

professional milling machine for a fraction of

the cost of a ready-made model. This machine

is suitable for a wide variety of jobs, ranging from

making parts for models to milling circuit boards.

As an electronic hobbyist or profes-sional, you have to work with more than just pure electronics, and you of-ten have to deal with a lot of mechan-ical tasks. This includes jobs such as making printed circuit boards, rout-ing wiring, and fashioning a suitable enclosure with a corresponding front panel. Some of these jobs require suitable tools if you want to achieve good results – at least if you want to do it all yourself.

Many hobbyists, as well as design-ers of prototypes and small develop-ment labs, would certainly be able to make good use of a small milling ma-

chine for this sort of work. Investing in such a machine may be affordable for commercial use, but the situa-tion is a bit different for home use. A good, accurate milling machine can easily cost several thousand euros, and even then you only have a basic model without all the bells and whis-tles (such as vacuum swarf removal and a high-speed spindle motor).We launched this project especially for all electronics hobbyists and pro-fessionals who regularly pursue their job and/or hobby at home. The idea for this construction project arose spontaneously during a conversa-tion with Frank Jacops of the Belgian

company Colinbus, which special-ises in milling machines. When you talk with someone who not only sells milling machines but also designs them from the ground up, the conver-sation quickly turns to the fact that most electronics types have splen-did ideas about all the nice things they could do with such a machine, but the price is an obstacle in most cases. Frank Jacops understood this immediately (he has been an avid reader of Elektor Electronics for many years), and he suggested offering a construction kit at a special price for a limited time, exclusively for readers of Elektor Electronics.

Elektor blockbusters

Page 32: E-book-15-ElektorBlockbusters-uk

151/2007 - elektor electronics

Naturally, we must admit that the kit is not exactly

inexpensive at £ 1099 or 1599 plus shipping costs, but this still repre-sents a savings of nearly £ 1400 rela-tive to a comparable ready-assembled model. That’s an attractive reward for a day or so of assembly work.

Of course, several small milling ma-chines are also commercially avail-able at a lower cost, but they are all quite small and have limited features. If you look at the photos in this arti-cle, you can see that we’re talking about a completely different category here. Robust construction, high accu-

racy, and a generous working area of 30 40 cm — now that’s something you can sink your teeth into! This ma-chine is suitable for all sorts of jobs, such as dispensing, potting, camera

inspection, boring holes in boxes, milling front panels,

and even

3Dmodelling (using

separate software). You can also mill circuit boards with this machine, although the manufacturer explicitly wishes to state that this model is not designed primarily for this purpose, since it requires even higher accu-racy. However, based on our experi-ence it yields excellent results for av-erage PCBs, and the necessary soft-ware is included.

Assembly of the machine is quite straightforward, and the clearly written instructions practically ex-clude any problems. The accompa-nying circuit boards with the drive electronics are fully assembled and tested, so all you have to do is in-stall and connect them.

Design

The ‘Elektor Profiler’, as we have christened the machine, is the small-est milling machine produced by Col-inbus. Its construction is largely the same as the commercial CBR-40 mod-el (see www.colinbus.com).The machine is made from steel and aluminium parts. This combination of materials provides sufficient weight and stability to withstand the motion of the machine, while the accuracy of the guideways and the speed of travel are very high thanks to the use of aluminium extrusions.The MultiStab system, which uses three rollers per edge travelling along precision steel rods pressed into alu-minium extrusions, provides good mechanical guidance with minimum play. This design is used for all three axes. One roller of each set of three for each guideway assembly can be manually positioned to adjust the amount of play as necessary. Each of the three axes is driven by a spindle with a special zero-backlash nut.The milling machine is controlled by a built-in processor board fitted with a Renesas H8/3003 and a driv-er board fitted with three ST L6208 ICs, which look after driving the three stepper motors. This approach makes the timing independent of the connected PC. The computer simply sends commands and coordinates to the processor board, which proc-esses and executes the commands independently.The processing power of the built-in microcontroller is not sufficient to drive all three stepper motors at the

‘Profiler’ technical specificationsDimensions 453 (w) x 583 (d) x 468 (h) mm

Max. working area 300 (X) x 400 (Y) x 100 (Z) mm

Interface Serial

Power 240 V, 50–60 Hz

X/Y/Z linear transport MultiStab guideways

X/Y/Z drive Stepper motors

Positioning speed 60 mm/s

Mechanical resolution 0.0075 mm

Software resolution 0.025 mm

Software Colinbus User Interface

Conversion program for Gerber and Excellon files

Elektor blockbusters

Page 33: E-book-15-ElektorBlockbusters-uk

HANDS-ON MILLING

16 elektor electronics - 1/2007

same time (this trick is reserved for the larger and more expensive Col-inbus models), so it can only drive two at the same time. The machine can thus execute smooth motions in a two-dimensional plane. For 3D motions, it switches rapidly back and forth between two axes, which

makes it appear that all three motors move simultaneously. This has little noticeable effect in practice, since the steps resulting from the interpo-lation are very small.The control board in the milling ma-chine has a serial interface, but a standard USB to RS232 adapter can

be used without any problems to op-erate the machine via the USB port of the PC.The spindle motor supplied with the milling machine is a fairly basic mod-el from Ferm, which allows you to start using the machine right away. Naturally, you can also fit other types of motors, but we should remark here that a true professional-quality spin-dle motor can easily cost more than the entire construction kit.

Construction kitWhat do you get for the price of £1099 or 1599? The photos in Figure 1 and Figure 2 show almost all the parts included in the kit. They include all the mechanical parts, screws and bolts, guideway rollers, spindles, bearings, stepper motors, cables and so on, plus the drive electron-ics on the two pre-assembled circuit boards. The previously mentioned Ferm spindle motor (and associated bracket) is also included in the kit. A MDF panel (also included in the kit) serves as the base plate.The companion software for the milling machine consists of two pro-grams: a user-friendly interface for configuring and operating the ma-chine and a conversion program for PCB layouts (see below).The kit includes assembly instruc-

Figure 1. The mechanical parts of the construction kit.

Figure 2. The assembled circuit boards and the spindle motor and bracket.

You can order the construction kit

for the Profiler milling machine

by filling in the Order Form on

the Elektor Electronics website at

www.elektor.com (click ‘Milling

Machine’ under ‘Quick Service’).

The price is 1099 pounds (1599

euros) including VAT, plus

shipping charges. The shipping

charges depend on the country

and are stated on the website

Order Form.

The kit is supplied and invoiced

directly and exclusively by the

manufacturer, i.e. not by Elektor.

There are also several optional

extras available for the machine.

Consult the Colinbus website for

information about these options.

Elektor blockbusters

Page 34: E-book-15-ElektorBlockbusters-uk

171/2007 - elektor electronics

tions that provide a step-by-step de-scription of how to put the machine together.There’s not much that can go wrong during assembly. The various parts fit together very accurately thanks to the combination of precision holes in the steel panels and the steel rods in the aluminium extrusions, so no further alignment is necessary. You have to provide the necessary wir-ing for the two circuit boards for the control and drive electronics, and the connectors and transformer must be soldered in place.All the assembly steps are clearly described in the instructions. How-ever, we would like to clarify a few details here.Once the machine is partially assem-bled, the guideways must be adjust-ed. The accuracy of the entire mill-ing machine depends entirely on this adjustment. The guideways for the bridge (on the sides) have of three rollers, of which one can be adjusted using an adjustment plate. It must be adjusted so there is very little play, but it should not be made too tight, since otherwise the rollers will jam. A similar construction is also lo-cated at the top of the bridge and in the motor column, but the latter part must be partially disassembled to access the rollers.The drives use spindles with trap-

ezoidal threads that run in special plastic nuts (see Figure 4). These nuts are fitted with transverse pins that provide the coupling to the bridge or the boring column. The Xand Y spindles must also be care-fully aligned to achieve the specified accuracy and linearity. Note that the

special plastic nuts on these spin-dles must be lubricated using only the special grease included with the kit. Do not use normal grease!The rest of the assembly process is adequately described by the instruc-tions included with the kit.

Figure 3. Cross-section drawing of the boring head mount on the bridge. Figure 4. Detail of the plastic nut with the transverse pins, which provide a zero-play coupling.

Figure 5. The boring column and the guideway in the bridge.

Elektor blockbusters

Page 35: E-book-15-ElektorBlockbusters-uk

HANDS-ON MILLING

18 elektor electronics - 1/2007

SoftwareThe user interface specially written for the Colinbus milling machine pro-vides the operator interface for the machine (Figure 6). This program is designed such that even inexperi-enced users can work with it easily.

The screen is composed of several windows. The effective working sur-face of the machine is shown in the right-hand window. After loading a file, you can use the mouse to place the object to be machined in the de-sired location on this surface. The ma-

chine will then start working at ex-actly this position. You can also spec-ify the values of all the settings and preferences for the machine. In addi-tion, you can operate all machine axes manually using this program. Every-thing you can think of can be config-ured here, such as reading memory points, relative zero points and so on with micrometre accuracy.The user interface includes a PCB contouring program (Figure 7), which you can use to edit and merge the Gerber and Excellon files generated by commonly used PCB programs and then convert the coordinates in these files into the contours used by the milling machine. You can manu-ally specify the reference points to be used on the circuit board and then use them to ensure that the data in the Gerber and Excellon files are reg-istered exactly with each other (the Gerber file contains the data for the PCB tracks, while the Excellon file contains the hole data). The file gen-erated by the program can then be imported into the user interface pro-gram so you can see the PCB layout, which you can drag to a specific lo-cation on the working surface.If you want to process 3D files (such as DXF files), you will need the sepa-rate RAMS3D program, which is not included in the construction kit due to the special price.Finally, there’s something for diehard DIYers: the entire command set for controlling the milling machine is freely available, so you can also write your own code.

1001 jobsThis robust, versatile milling machine opens up a world of opportunities for handy hobbyists and profession-als who aren’t afraid to roll up their sleeves. With it, making rectangular openings in a box is a piece of cake and a machining a slot in a front pan-el for a slider is no sooner said than done. What’s more, this milling ma-chine is a handy tool for things that have nothing to do with electronics. For instance, you can use it to make your own parts for a model airplane or toys for your kids (and donate your jigsaw to local charity!).

In short, there are more than enough things you can do with this machine. Once you’ve used it, you won’t want to do without it.

(060232-1)

Figure 6. The user interface. The working surface of the machine is shown at the upper right.

Figure 7. Gerber and Excellon files can be read in with the PCB contouring program and converted into contour data for the milling machine.

Elektor blockbusters

Page 36: E-book-15-ElektorBlockbusters-uk

PROJECTS PROGRAMMABLE LOGIC CONTROL

64 elektor - 3/2008

A full PLC application board comprising isolated outputs, in-puts, LC display and CAN bus connectivity…sounds good! But you’d also like to hear that it’s low cost, based on an ECIO module and easy to program using Flowcode, the all graphics method of mastering PICs (and other micros, too).

PLCA PLC (programmable logic control) is a device typically used as the central, intelligent, control element in a flow-chart-designed industrial process, usually for mass manu-facturing or quality checking and goods sorting. Conveyor belt controls will typically be PLCs.PLCs exist commercially and their (high level) programming languages have been standardized to a wide extent. Unfor-tunately the price tag of almost any commercial PLC puts it well out of reach of enthusiasts. A pity, because many Elek-tor readers have affinity with industrial control systems.PLC command sequences are in a way like computer pro-grams — they follow a predefined sequence of events with all the options for conditional loops, event timers, logic conditions, event counters, analogue values (temperature; liquid level; pressure) and simple result logs.If you have a slightly complex process you’d like to con-

trol using electronics on a machine, then a PLC is a good choice because of its (electrical) robustness and flexibility when it comes to connecting the real world through relays and optocouplers.To be able to program a PLC (i.e. define the sequence of events to happen in a process) you need to write a pro-gram. Once debugged and simulated on a PC, you can download the program to the PLC and from then on it’s fingers crossed.PLC programs can be edited, debugged, extended, opti-mized and of course stored and retrieved. Right, just like any PC or microcontroller program!

Circuit descriptionThe circuit diagram of the ECIO PLC is shown in Figure 1.The circuit comprises a number of distinct elements which we’ll discuss below.

ECIOThe ECIO module is the brain of the board. It is used to con-trol all of the peripheral devices on the board. ECIO mod-ules, introduced in the October 2007 issue of Elektor [1], represent an ultra low-cost way of entering the world of PIC microcontroller programming. ECIOs are available from the Elektor Shop with good discounts for volume orders. Here we use the 40-pin version called ECIO-40P.

RelaysThe relays the PLC is using to switch electrical devices on and off are controlled via ECIO pins RB4–RB7. Outputting a logic Low to these pins will switch off the corresponding relay and outputting a logic High will switch on the corre-sponding relay coil. If a relay is enabled then the LED next to that particular relay will light to give a visual on/off rep-resentation. The relays are used to provide electrical isola-tion between the ECIO module and the external switched voltage (which could be the 230 V mains). This means that power devices running from high voltages like 48 VDC or

ECIO PLCCheap, DIY and with CAN!Ben Rowland (Matrix Multimedia) & Luc Lemmens (Elektor Labs)

Here’s the first real-life application of ECIO modules introduced in the October 2007 issue of Elektor. An ECIO acts as the brains of a PLC board that has relays, opto-isolators, CAN (!) connectivity and an LCD. All this I/O capacity together with Flowcode allows the board to act as a versatile, powerful PLC for quite complex control and automation projects. The LCD module is used to display ASCII characters to the user as a means of troubleshooting during the software development stage or for monitoring the system.

ECIO PLC Features• CAN bus connection

• 4 optically isolated inputs

• 4 relay driven outputs

• 2x16 character alphanumeric LCD

• Flowcode-programmed but will also take PIC18 hex files

• Free Flowcode for ECIO

• USB connectivity for programming

ECIO PLC • 36 Elektor blockbusters

Page 37: E-book-15-ElektorBlockbusters-uk

653/2008 - elektor

230 VAC can be controlled safely via the ECIO module.

Each set of relay contacts (NO and NC) is brought out to three pins of a PCB mount screw terminal block — the cen-tre pin (C) is the pole.

Opto-isolatorsThe opto-isolated inputs are special in not having a plus (+) and a minus (–) input terminal. Inside IC1, the two diodes on each input are in fact LEDs so the polarity of the control

voltage you wish to apply to ECIO PLC does not matter! The opto-isolator outputs are connected to ECIO pins RA0–RA3. These input pins will be at logic zero for no input voltage and at logic one for a voltage of 3.5 V or more. The opto-isolators are used to provide an isolation layer from input voltages. This means that relatively high voltages can be used to safely control the ECIO module. The signals you want to process in the ECIO PLC are applied to the circuit through PCB mounted 2-way screw terminal blocks. LEDs D1-D4 show the logic status of the opto-isolator inputs.

TXCAN1

RXCAN2

CLKOUT/SOF3

TX0RTS4

TX1RTS5

TX2RTS6

OSC2

7

OSC1

8

VSS

9

RX0BF10

RX1BF11

INT12

SCK13

SI14

SO15

CS16

RESET17 VD

D18

IC3

MCP2515

TXD1

VSS

2VD

D3

RXD4

RS8

CANH7

CANL6

VREF

5

IC4

MCP2551

X1

20MHz

C4

22p

C2

22p

RESET

25V

C7

10u

VDD USB

VDD USB

JP1

2

31

K6

1

23

45

67

8 9

1011

1213

1415

16IC1

TLP620-4

K1

K2

K3

K4

VDD USB

RA0

RA1

RA2

RA3

K9

D1

T1

BC547

VDD USB

D2

T2

BC547

VDD USB

D3

T3

BC547

VDD USB

D4

T4

BC547

VDD USBOI0

OI1

OI2

OI3

123456789

1011121314151617181920

4039383736353433323130292827262524232221

VDD USB

RESETRA0

GND

RA1RA2RA3RA4RA5

RD0RD1RD2RD3RD4RD5RD6RD7

VDD_EXT

RE0RE1RE2

GNDRC0RC1RC2RC6RC7RB0RB1RB2RB3RB4RB5RB6RB7

1234567891011121314

K5

VDD USB

RC6

RC0RC1RC2

RD6RD7

RE0RE1RE2

RA4RA5

RESETB40C1500

2

1

4

3 B1

25V

C1

10u

C3

100n

C5

100n

1 3

2

IC2μA78M05CKC

+12V

VDD_EXT

D5

VDD USB

25V

C6

10u

RB1

RB2

RB3

RC7

RB0

VDD USB P1

10k

RD4

RD5

RD0RD1RD2RD3

T5

BC547

D8D6

1N4001Re1

+12VK14

T7

BC547

D12D10

1N4001Re3

+12VK18

T6

BC547

D9D7

1N4001Re2

+12VK15

T8

BC547

D13D11

1N4001Re4

+12VK19

RB5RB4

RB7RB6

R7

390R

R8120R

R6220R

R1A

R1B

R1C

R1D

R4A

R4B

R4C

R4D

R5A

R5B

R5C

R5D

R2A R2B R2C R2DR3A R3B R3C R3D

R9A

R9B

R9C

R9D

R10A

R10B

R10C

R10D

OI0

OI1

OI2

OI3

123456789

10111213141516

LCD1

VDD USBR11

33R

CAN

HCA

N L

CONTRAST

NOC

END

NOCNC

NOCNC

NOCNC

ECIO

+9V - +20V

R1 = 4x 4k7R4 = 4x 220R R5 = 4x 220R

R2 = 4x 10kR3 = 4x 330R

R10 = 4x 1k

NC

LC D

isplay

2 x 1

6

NODE

R9 = 4x 2k2

070786 - 11

Figure 1.Circuit diagram of the ECIO PLC board. Minimal hardware — great potential in terms of I/O.

ECIO PLC • 37 Elektor blockbusters

Page 38: E-book-15-ElektorBlockbusters-uk

PROJECTS PROGRAMMABLE LOGIC CONTROL

66 elektor - 3/2008

CANThe CAN (controller area network) interface is used for add-ing the ECIO PLC onto a CAN network. CAN is ‘hip’ and few PLCs we have seen offer this connectivity. Here we use an MCP2515 CAN controller chip and an MCP2551 line driver. The CAN controller chip is connected ECIO peripheral pins set up to do SPI comms. There is also an interrupt pin, which is connected to ECIO pin RB2 and a chip select pin, which is connected to ECIO pin RB3. The CAN controller has its own 20 MHz clock derived from a quartz crystal, X1. The actual connection of the CAN bus to the ECIO is by way of K9, a 2-way PCB mount screw terminal block. Jump-er JP1 has to be installed only if the MCP2551 is the end node of the bus.

LCDThe LCD module is used to display ASCII characters to the user as a means of troubleshooting during the software de-velopment stage, or for monitoring the system as it’s busy checking and controlling the events in the automated proc-ess. The LCD is connected to ECIO pins RD0–RD5 with the four data bits taking up bits 0–3, the RS bit taking up bit 4and the Enable bit taking up bit 5. P1 is the LCD contrast adjustment.

Power supplyNothing special in this department — the usual 7805 volt-age regulator (IC2) and the traditional set of decoupling ca-pacitors. A bridge rectifier is used ahead of the regulator to

T5R9

C7

R10 D8

K2

K4

K3

K1

R11

D13

R5

Re4

P1

T8

D9

T6

T7

D12

Re2

Re3

D4

D3IC1

R1 R3

D1

D5

T4

T3

T2

R2

D2

T1

R4R7

R8

IC3

X1

IC4

C4

C2

R6

D11

JP1

K9

K7

D7

K10

K8

D10

D6K11K6

C1

B1IC2

C3 C5C6

14

Re1

213

K5

1

Figure 2.The unstuffed ECIO PLC

board is available from Elektor.

COMPONENTS LISTResistorsR1 = 8-pin SIL array 4 x 4k 7*R2 = 8-pin SIL array 4 x 10k *R3 = 8-pin SIL array 4 x 330 *R4,R5 = 8-pin SIL array 4 x 220 *R6 = 220R7 = 390R8 = 120R9 = 8-pin SIL array 4 x 2k 2*R10 = 8-pin SIL array 4 x 1k *R11 = 33P1 = 10k preset* see text

CapacitorsC1,C6,C7 = 10μF 25V radial

C2,C4 = 22pFC3,C5 = 100nF

SemiconductorsD1-D5,D8,D9,D12,D13 = 3mm LEDD6,D7,D10,D11 = 1N4001B1 = B80C1500 (round case; 80Vpiv @

1.5Ap)T1-T8 = BC547IC1 = TLP620-4IC2 = 7805IC3 = MCP2515-I/PIC4 = MCP2551-I/P

MiscellaneousRe1-Re4 = 12V relay, SPDT, e.g. Omron

G5LE-1X1 = 20MHz quartz crystal

K1,K4,K9 = 2-way PCB screw terminal block, lead pitch 5mm

K5 = 14-way boxheaderK6 = AC/DC low-V adapter socket,

PCB mount, e.g. CUI Inc. # PJ-002B (Digikey # CP-002B-ND) or Cliff Elec-tronic Components # DC10B (Farnell # 224960)

K7,K8,K10,K11 = 3-way PCB screw ter-minal block, lead pitch 5mm

ECIO = ECIO-40P processor module (Elektor Shop)

LCD1 = LCD, alphanumerical, 2x16 characters, e.g. Displaytech 162

JP1 = 3-way SIL pinheader with jumperPCB, order code 070786-1 from

Elektor Shop

ECIO PLC • 38 Elektor blockbusters

Page 39: E-book-15-ElektorBlockbusters-uk

673/2008 - elektor

allow the ECIO PLC board to be powered by AC as well as DC wall warts with an output voltage between 9 and about 20 volts. For the DC connection, polarity is irrelevant.

Phew, that ECIO PLC board has a lot of connections to the outside world and to prevent losing track of all those I/O lines and associated devices we’ve made a summary in Table 1.

ConstructionThe component mounting plan of the PCB designed for ECIO PLC is shown in Figure 2. As usual the copper track layout may be downloaded from our website for those with the wherewithal to etch & drill their own circuit board at home. All others will like to hear that the bare board is available ready-made from the Elektor Shop.No SMD components are used in this project so stuffing the board should be mostly plain sailing if you use care and precision in handling and soldering the parts. The 8-pin re-sistor arrays containing four individually wired resistors (i.e. not top commoned!) may prove difficult to get. Instead of arrays, you can also use four individual resistors mounted vertically side by side.Give your completed board a good visual inspection before inserting ICs and powering up for the first time.

ECIO hardware Testing — I/O and CANTo help you find your bearings we have written a simple and instructive ECIO test program, of which the Flowcode listing is shown in Figure 3. Download it, load it into Flow-code, run the simulation, compile and blow it into the ECIO module.

The program includes a general PIC setup routine that does all the port and I/O pin configuring on the ECIO. For ex-ample, ECIO lines RB4-RB7 are set up as output lines (for the relay drivers). The test program is simple to use: if you drive the opto-isolator on RA0, the relay on RB4 will be en-ergised. Similarly with the combination RA1/RB5, and so

The ECIO family of USB programmable microcontrollers pro-vides a simple way of adopting microcontroller technology into your projects. The device behaves just like a normal mi-crocontroller — but when you plug the USB lead in and press the reset switch you can send a new program to the device. This makes the ECIO one of the lowest cost USB-compatible PIC programmers in the world.

Currently there are two products in the range: ECIO-28P and ECIO-40P. These devices are based on PICmi-cro 18 series devices; the 18F2455 and the 18F4455 respectively.

The ECIO microcontrollers are pre-programmed with a boot-loader program which allows you to send a new program to the microcontroller via USB, in principle as many times as you like. ECIO is compatible with hex code from any appropri-ate compiler. ECIO is directly compatible with Flowcode — a graphical programming language which greatly simplifies the

code generation process — but can also be used with any C compiler or Microchip’s own develop-ment suite MPLAB.

ECIO is well supported with a wide range of learning and develop-ment tools including (free) Flowcode and inexpensive E-blocks.

ECIO – the cheapest USB PIC progger out there

GND

RC1

RC0

/RESET

VDD USB

GND

ECIO40 CONNECTIONS

RA0/AN0

RA1/AN1RA2/AN2

RA3/AN3

RA4/AN4RA5/AN5

RE0/AN5

RE1/AN6RE2/AN7

RD0

RD1RD2

RD3RD4

RD5

RD6RD7

RC7/RX/SDORC6/TX/CK

RB1/AN10/INT1/SCK

RB0/AN12

RB3/AN9

RB2/AN8/INT2

RB5

RB4

RB7RB6

RC2

VDD EXT

EC

IO40P

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

40

39

38

37

36

35

34

33

32

31

30

29

28

27

26

25

24

23

22

21

RC1

RC0

/RESET

VDD USB

GND

ECIO28 CONNECTIONS

RA0/AN0

RA1/AN1RA2/AN2

RA3/AN3

RA4/AN4RA5/AN5

RC7/RX/SDORC6/TX/CK

RB0/AN12

RB3/AN9

RB2/AN8/INT2

RB5

RB4

RB7RB6

RC2

VDD EXT

EC

IO28P

1

2

3

4

5

6

7

8

9

10

11

12

13

14

28

27

26

25

24

23

22

21

20

19

18

17

16

15

RB1/AN10/INT1/SCK

Table 1. ECIO connections overviewRelay Output ECIO I/O PinRelay Re1 (K14) RB4Relay Re2 (K15) RB5Relay Re3 (K18) RB6Relay Re3 (K19) RB7Opto-Isolator Inputs ECIO I/O Pin / LEDK1 RA0 / D1K2 RA1 / D2K3 RA2 / D3K4 RA3 / D4CAN (from CPU) ECIO I/O PinSerial Data Out RC7Serial Data In RB0Serial Clock RB1/Interrupt RB2/Chip Select RB3LCD ECIO I/O PinD0 RD0D1 RD1D2 RD2D3 RD3RS RD4Enable RD5

ECIO PLC • 39 Elektor blockbusters

Page 40: E-book-15-ElektorBlockbusters-uk

PROJECTS PROGRAMMABLE LOGIC CONTROL

68 elektor - 3/2008

on. The display will show: ‘Elektor ECIO PLC board’ (no? adjust that LCD contrast!). Neither family members nor PIC geeks may be too impressed but if this works then a whole lot of PIC code is being executed and you can safely as-sume that all hardware is functioning as it should.The CAN test utility discussed in the inset is also included in the free software download for this project. The two test programs provided are educational and certainly worth looking at even if you do not actually build the project (hint: use the free Flowcode version to begin with). The archive file number is 070786-11.zip.

PLC programmingAll ECIO PLC programming bears great resemblance to E-blocks and Flowcode so if you have any experience with these you’re in luck. If not, there’s a mass of information out there on the Internet [1], in previous issues of Elektor and in the Flowcode package itself. Best of all, Flowcode for ECIO is free [1].Writing a process control program for the ECIO PLC under-scores what Flowcode is all about: rather than worrying about syntax and PIC assembly code you are working at a fairly high level, setting up a full-blown flowchart of the program and let Flowcode arrange all the compiling, ini-tializing, error tracking and code downloading to the ECIO module. Of course you can simulate your PLC program so there’s a good chance of instant success when the ECIO PLC board is connected up to the real world.More advanced users may want to rely on their own meth-ods of producing PIC18 code using C++ compilers or simi-lar. The ECIO even accepts straight hex code from all you assembly code diehards out there. Simply use the free USB I/O drivers to connect ECIO to your PC.

(070786-I)

Web Link and reference[1] http://www.matrixmultimedia.com/ECIO-X.php

[2] EasyControl I/O, Elektor October 2007.

Figure 3.This Flowcode program

runs a hardware test on the ECIO PLC.

CAN interface testingCAN is essentially good for sending complex message struc-tures between a number of ECUs (microcontrollers). The test program written for Flowcode simply looks for an echo of the outgoing CAN message. This could be used to see how many nodes are on the network or used to calculate the dis-tance between nodes based on echo time, etc.

Basically the ECIO test program is sending out a specific CAN message with an standard ID of 12. When the Multi-programmer receives a CAN message it checks the ID and if it is equal to 12 then it resends the message ID 12. The ECIO continues to send out this message ID until it receives a CAN message back. Once it has received a message back it checks the ID and then confirms or denies if the echo was successful.

For this test you will need another ECIO PLC board or an E-blocks Multiprogrammer connected to an E-blocks CAN module. One ECIO PLC board will send several messages over the CAN bus. The other one will ‘listen’ until a prede-fined message appears and then replies to the ECIO. When the CAN transmitter is started the display reads ‘Startup’, followed by ‘Done’ a bit later once the CAN controller is initi-alized. If the CAN connection is okay the display shows ‘Mes-sage returned’, if not, you’ll see ‘Message failed’.

ECIO PLC • 40 Elektor blockbusters

Page 41: E-book-15-ElektorBlockbusters-uk

PROJECTS JTAG ADAPTOR

56 elektor electronics - 5/2007

UniversalJTAG Adaptor

For programming and emulation

Marcel Cremmel

This adaptor was originally intended to allow programming of the memory and CPLD of the PSD813 used in the GBECG Gameboy cartridge, which converts this games console into an electrocardioscope (see October 2006 issue). But it’s much more universal than that (see box entitled ‘In-Circuit JTAG’) Our adaptor connects to a PC parallel port and uses the JTAG IEEE 1149.1 protocol.

Informed microelectronics amateurs will of course be aware that other ‘In-Circuit’ programmable devices use this same port (parallel) and an identical protocol. Unfortunately, the program-mer/emulators intended for these de-vices are not compatible — far from it in fact: so there’s no point hoping for a mixed marriage!However, closer examination of the cir-cuit diagrams of certain programmers suggested by the IC manufacturers

shows that the differences are relatively minor and in fact concern the intercon-nections between the LPT port signals and the JTAG connectors. So a few mul-tiplexing functions is all it takes to pro-duce a ‘universal’ adaptor.Had it been achieved using convention-al logic components, the circuit of our adaptor would have been quite com-plex, with different electronics for each of the sections for the different types of processor. Using an EP900 program-

mable logic circuit (Altera, on free offer from Elektor) makes it possible to offer a very cheap and simple programmer.Many manufacturers have adopted the JTAG (Join Test Action Group) protocol for programming, debugging, and test-ing their ICs in situ on the board (IC for In Circuit). Fortunately, you don’t need to know all the details of this protocol to be able to use it: the PC software (usually free) and the target compo-nents each include a JTAG core that al-

Universal JTAG Adaptor • 41 Elektor blockbusters

Page 42: E-book-15-ElektorBlockbusters-uk

575/2007 - elektor electronics

lows them to communicate completely transparently.The devices involved have special ‘JTAG’ pins that you merely need to connect to the pins of the same name on the programmer connector. The size (number of contacts) and pinning of this connector differ from one manufacturer to another. This information is given in the various diagrams shown in the box-es of Figures 1–4, concerning respec-tively Altera CPLDs and EPLDs (Byte-blaster II) (Figure 1), Xilinx CPLDs and EPLDs (Parallel Download Cable) (Fig-ure 2), MSP430 microcontrollers from Texas Instruments (LPT IF 4 wire JTAG Communication) (Figure 3) and the PSD, uPSD and DSM families (Flashlink FL101) from ST Microelectronics (Figure 4). It should also be noted that there is a certain discrepancy in the naming of the signals between the different JTAG connectors.

ADAPTOR CIRCUITThe heart of the circuit (Figure 5), which with its 44 pins could hardly go unnoticed, is an EP900 PLD. This PLD forms the link between the PC’s parallel port, K1, and the four DIL pin headers for the JTAG connections to the four tar-gets, named respectively MSP430 (K2), FLASHLINK (K3), XILINX (K4) and AL-TERA (K5). SW, a dual-gang DIP switch comprising contacts JP1 and JP2, al-lows selection of one of the 4 types of programmer recognized by the JTAG adaptor (see truth table in the circuit diagram, also given on the component overlay on the board). These four op-tions appear in the form of the same number of HE-10 headers in the bottom right-hand part of the circuit. Each op-tion has its own logic structure with-in the EP900; all these various sub-as-semblies using logic gates are shown in Figure 6.Each of these structures is drawn from the manufacturers’ programmer circuits. For reasons of effi ciency, the EP900’s logic structure is described in Altera’s AHDL language. The circuit diagram is easier for an electronics technician to read, but the ‘AHDL’ form is more ef-ficient here. Just for information, the ‘source’ fi le (.tdf) for the contents of the EP900 is given in the inset.At the bottom left we fi nd the…

POWER SUPPLYThe EP900 PLD is quite an old IC al-ready! It requires a 5 V supply, but as its consumption is quite high, the pro-

12

34

56

78

9

TCK

TDO

TMS

TDI10

VCC

VCC

TCK

VCC

TDO

TMS

TDI

GND

060287 - 12

1k

VCC

1k 1k1k

TargetAlteraDevice

1 2

3 4

5 6

7 8

9

TCK

TDO

TMS

TDI 10

GND

VCC

GND

Figure 1. CPLD and EPLD (Byteblaster II) from Altera: 10-pin DIL connector.Software: Quartus II Web Edition, Quartus II Programmer [1]

1 2

3 4

5 6

7 8

9 10

TMS

TCK

TDO

TDI

11 12

13 14

VCC

GND

060287 - 13

VCC

VCC

TDI

TMS

TCK

TDO TDI

TMS

TCK

TDO TDI

TMS

TCK

TDO

XILINX

1 2

3 4

5 6

7 8

9 10

11 12

13

GND

GND

GND

GND

GND

GND 14

VCC

TMS

TCK

TDO

TDI

Figure 2. CPLD and EPLD (Parallel Download Cable) from Xilinx: 14-pin DIL connector.Software: ISE WebPACK [2]

12

34

5

J1

J2

6

78

VCC TOOL

VCC TARGET

TEST/VPP

9

11

10

12

1314

VCC

1 2

3 4

5 6

7 8

9 10

11 12

13

TDI

TMS

TCK

GND

RST

TDO

14

VCC out

VCC in

TCLK

TEST

VCC /AVCC /DVCC

VSS /AVSS /DVSS

47k

R1C2

C1

C3

10n/2n2

100n

TDI/VPP

TMS

TCK

TDO/TDI

RST/NMI

TDI/VPP

TMS

TCK

TDO/TDI

RST

TEST/VPP

MSP430Fxxx

060287 - 14

Figure 3. MSP430 microcontrollers (LPT-IF 4-wire JTAG Communication) from Texas Instruments: 14-pin DIL connector. Software: IAR-Kickstart [3]

JTAG ‘In-Circuit’ – some applications– PSDs, uPSDs and DSMs from ST Microlectronics

– MSP430 microcontrollers from Texas Instruments

– EPLDs and CPLDs from ALTERA

– EPLDs and CPLDs from XILINX

Universal JTAG Adaptor • 42 Elektor blockbusters

Page 43: E-book-15-ElektorBlockbusters-uk

PROJECTS JTAG ADAPTOR

58 elektor electronics - 5/2007

gramming adaptor can’t be powered di-rectly from the outputs of the PC’s LPT port. To simplify implementation and al-low us to dispense with a special dedi-cated power supply, we have decided to power the adaptor from the power rails in the target systems. But these are usually content – especially nowa-days! – with 3 V or 3.6 V, which is not enough to power the EP900.So we’ve fi tted the adaptor with a very fl exible switched capacitor voltage con-verter that supplies a regulated 5 V out-put from an input voltage anywhere be-tween 2.7 and 5.5 V! Yes, that’s right: the converter works just as well with an input voltage either lower or higher than the output voltage, with an effi -ciency of around 90%! Bravo to the Burr Brown engineers (that company since taken over by Texas Instruments, which explains why the spec. sheet has to be obtained from the TI website). Howev-er, the current is limited to 30 mA.

starting with the SM components. Watch out – certain of them, in particu-lar capacitor C1, are tucked away at the centre of the board, right between the legs of the PLCC44 socket (into which the EP900 is going to be plugged, on the other side). Take care to solder the regulator IC2 carefully, as without this, nothing else will work. It’s surround-ed by capacitors that are bigger than it is. Take care to identify the values of the SM components correctly (resistors often have coded value information: 103 means 10 k , 1203 means 120 k ;things are trickier with the capacitors, which are often not identifi ed or iden-tifi able. Once the SM components are fi tted, you can fi t the row of resistors, the rest of the conventional compo-nents, the selector SW, the headers K2 (MSP430) to K5 (ALTERA), the PLCC44 socket, fi nishing off with the 25-pin sub-D connector K1. Make sure you pick the male version of the printer connector (LPT); the female version won’t make for a very good connection! One little note about the dual selector SW: it’s not always easy to get hold of a dual DIP switch, so we’ve left enough room to fi t a quad one, but you’ll need to cut off the spare legs before you fi t it.If you’re making your own board, it’s equally possible to make it single-sid-ed – the second side of the double-sided board is in fact only used to avoid the need for the wire links that a single-sid-ed version will require. Construction is the same, but in this case, it’s prefer-able, for reasons of practicality, to start off by fi tting various wire links, using tinned copper wire.Take care to avoid shorts with the wire links positioned between the ‘FLASH-LINK’ and ‘XILINX’ connectors, which are relatively close together.All that remains is to plug the EP900 into its socket. Check the quality of your construction one last time (soldering, component values – luckily there’s only one value for the conventional resis-tors), as there is no way of testing the proper operation of this circuit except by trying it out for real! Note about the EP900 PLD (order code 060287-41): this is available pro-grammed, free of charge (apart from standard postage and packing charges) from the Elektor SHOP. If you order PCB # 060287-1, the programmed IC will be automatically supplied with it.

TARGET CONNECTIONSWatch out – you must only use one connector at a time! In most cases, a

The only awkward point for amateurs is the size of the regulator IC (it’s only available in an SM version), making it tricky to solder. But luckily it only has six pins. So its now or never, to try your hand with an SM device. Position IC2 accurately on its pads. Apply a little sol-der to one of the pad + legs. Once the solder has set, solder the leg diametri-cally opposite the previous one. If eve-rything is OK, now solder the remain-ing legs. If you create a solder bridge between two legs, remove it using de-soldering wick.

CONSTRUCTIONAs shown in Figure 7, the board de-signed for this project is double sided; it uses only a very few SM components, mainly around the EP900. Naturally, these are to be fi tted on the track side of the board. So let’s get stuck in! For reasons of practicality, we recommend

12

34

56

78RST

9

11

TDI

TMS

TCK

10

12

13 TDO14

1 2

3 4

5 6

7 8

9 10

11 12

13

GND

TDI

VCC

TMS

TCK

TDO 14

GND

GND

RST

USERPC BOARD

10k

100k

100k

100k

100k

10n

TDI - PC5

VSTBY or PC2

TMS - PC0

TCK - PC1

TDO - PC6

General I/O - PC3

General I/O - PC4

General I/O - PC7

System Reset Circuity(connect directly to RST

input on PSD)

PSD or PSD Port C

User I/O Signals060287 - 15

Figure 4. PSD, uPSD and DSM families (Flashlink FL-101) from ST Microelectronics: 14-pin DIL connector.Software: among others, PSDsoft Express [3] for programming the PSD813 in the ECG cartridge for Game Boy.

About the authorMarcel Cremmel, the author, has been a qualifi ed lecturer in Electrical Engineering, electro-nics option, since 1979 (state certifi ed by the French National Education system).

After completing his fi rst years of teaching in the School of Engineering in Rabat in Morocco, under the Co-operation scheme, in 1982 he was assigned to the Louis Couffi gnal College in Strasbourg, in the BTS SE section (Higher Technician’s Certifi cate, ‘electronics systems’).

His job requires him to cover all fi elds of electronics, though his preference is for telecom-munications, video, microcontrollers (MSP430 and PIC) and programmable logic devices (Altera).

Alongside electronics, his other passion is motorbikes in all their forms: touring, competitions, etc. His personal website is at http://electronique.marcel.free.fr/

Universal JTAG Adaptor • 43 Elektor blockbusters

Page 44: E-book-15-ElektorBlockbusters-uk

595/2007 - elektor electronics

K1

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

1

2

3

4

5

6

7

8

9

R1100R

R3100R

R4100R

R5100R

R10100R

R9100R

R11100R

R12100R

R6100R

R7100R

R13100R

R14100R

R15100R

R16100R

R17100R

R8100R

STROBE

AUTOFDX

D0

D1

D2

D3

D4

D5

D6

D7

GND1

GND2

GND3

GND4

GND5

GND6

GND7

GND8

R28

100k

R29

100k

R30

100k

R31

100k

R32

100k

SUB D25

+5V

ERROR

INIT

SLCTIN

ACK

BUSY

PE

READY

C1

100n

+5V

R35

10k

R36

10k

R37

10k

D0

D1

D2

D3

D4

D5

D6

D7

INIT

ACK

BUSY

PE

STRB

AFDX

ERR

SLCT

RDY

JP2JP1

R20100R

R24100R

R25100R

R19100R

R21100R

R22100R

R23100R

R26100R

R18100R

R27100R

EP900LC

IC1

SEL0

SEL1

CLK2

CLK1

I/O

I/O

I/O

I/O

I/O

I/O

I/O

I/O

I/O

I/O

I/O

I/O

I/O

I/O

I/O

I/O

I/O

I/O

I/O

I/O

I/O

I/O

I/O

23

44

22

20IN

19IN

21IN

30IN

25IN

26IN

27IN

41IN

32

31

34

33

35

37

38

40

43

42

IN

IN

IN

10

11

12

13

14

15

16

18

24

17NC

39NC

28

29

36

1

3

4

5

2

7

9

8

6

+5V

1 2

3 4

5 6

7 8

9 10

K5ALTERA 1 2

3 4

5 6

7 8

9 10

11 12

13 14

K3FLASHLINK

1 2

3 4

5 6

7 8

9 10

11 12

13 14

K4XILINX

1 2

3 4

5 6

7 8

9 10

11 12

13 14

K2MSP430

TDO

TDO F

TMS TDI

TCLK

TCK TMS

TDI TMS

TCK RST

TDO TCK

TCK A

Nstat TDO

VCC IN VCC IN

VCC IN

R34

100k

R3310

k

TCK A

TDO

TMS TDI

TDI TMS

Nstat TDO

TCK TMS

TDO TCK

TMS TDI

TCK TMS

TCK RST

Nstat TDO

TMS TDI

TDI TMS

TCK RST

TDO F

TDO TCK

TDO

TMS TDI

TCK TMS

TDO TCK

TCK RST

TCLK

TDI TMS

VCC IN

VCC IN

VCC IN

JP2JP1

ON ON

OFF ON

ON OFF

OFF OFF

ALTERA

XILINX

PSD

MSP430

060287 - 11

REG710NA-5

PUMP+ PUMP-

IC2OUTIN

EN

2

5 1

3

6 4

C2 C4C5 C7

C3

220n

+5VVCC IN

Figure 5. The EP900 takes pride of place in the centre of the circuit for the universal JTAG programmer. It’s available ready-programmed, free of charge, when you order the PCB 060287-I.

Universal JTAG Adaptor • 44 Elektor blockbusters

Page 45: E-book-15-ElektorBlockbusters-uk

PROJECTS JTAG ADAPTOR

60 elektor electronics - 5/2007

simple 10- or 14-way ribbon cable, with a crimped connector at each end (watch out for the orientation!) is used to es-tablish the electrical links between the target and the adaptor (see the circuit diagrams of Figures 1 through 4 and the pinning of the relevant connectors).If you have direct access to the rear of the PC, the adaptor can be inserted di-rectly into the LPT port, without using an extender cable interconnecting the PC and the JTAG adaptor.

USB adaptorsThe latest offi ce and notebook PCs no longer have parallel ports (LPT) – a highly regrettable decision, especial-ly for this project! To make up for this, you can fi nd USB/LPT adaptors, but do make sure you check their compatibil-ity with our JTAG programmer; many of them will only accept printers. We can’t go into details of the programming pro-cedures for all the possible targets, so we’re going to confi ne ourselves to one example, the…

GameBoy ECG cartridgeThe cartridge uses an SMD connector with a pitch of 1.25 mm (K3). To make the cable, we recommend you follow the following procedure.1. Press a piece of 14-way ribbon cable to a female DIL14 connector;2. Use the Molex connector and the wires already prepared in the compo-nents list (see Elektor Electronics Oc-tober 2006) to make up the appropriate 6-way connector for K3;3. Solder the four wires TCK, TDI, TDO and TMS and the two power supply wires to both connectors;4. Check the connections with a conti-nuity tester and then insulate the sol-dering with heat-shrink sleeving.

And there you go, all ready to program the PSD813s in the GameBoy ECG cartridge.One last remark: the adaptor is compat-ible with Byteblaster II (Altera); it does not work with the fi rst version of the driver (Byteblaster on its own, with-out the II). This old driver was used by the MaxPlus II software, and has been replaced by Quartus for two or three years now).

(060287-I)

D0 TCK

D4 ACK

D1

D2

D3

D6

TDO

PIN7

TMS

PIN8

PIN6

TDI

BUSY

READY

ERROR

AFDX

TRI

TRI

TRI

TRI

TRI

WIRE

WIRE

WIRE

WIRE

ALTERA

D0

D1

D2

TRI

TRI

TRI

TDI

TCK

TMS

NOT

D3

ACK

BUSY

READY

WIRE

WIRE

WIRE

WIRE

XILINX

VCC

AND2

D6

PE

ERROR

D4

TDO

D0

D1

D2

TRI

TRI

TRI

TDI

TCK

TMS

NOT

D3

FLASHLINK

NOT

READYWIRE

D5 RSTN

NOT

TDO

D6

BUSY

ERROR

WIRE

WIRE

WIRE

PE

ACK

D0

D1

D2

TRI

TRI

TRI

TDI

TCK

TMS

NOT

MSP430

SLCT

TRI

TDO PE

WIRE

INIT TEST

NOT

TRI

STRB RST

AFDX

BUSY

ERROR

WIRE

WIRE

WIRE

ACK

WIRE

READY

060287 - 16

Figure 6. Nothing like it to illustrate the fl exibility of a PLD like the EP900! A single device can fulfi l several complex logic functions.

Figure 7. Component overlay for the board designed for this project. The track layout is available for free download.

Universal JTAG Adaptor • 45 Elektor blockbusters

Page 46: E-book-15-ElektorBlockbusters-uk

615/2007 - elektor electronics

Bibliography and Internet links

[1] https://www.altera.com/support/software/download/sof-download_center.html

[2] http://www.xilinx.com/ise/logic_design_prod/webpack.htm

[3] http://focus.ti.com/docs/toolsw/folders/print/iar-kickstart.html

[4] http://mcu.st.com/mcu/modules.php?name=Content&pa=showpage&pid=57

REF710-5 data sheet:

http://focus.ti.com/lit/ds/symlink/reg710-5.pdf

Supplementary information, fi le # 060287-11.zip, free download from: www.elektor-electronics.co.uk

‘AHDL’ source fi le for the EP900Contrary to fi rst impressions, an AHDL fi le can tell you a lot. Looking at this one a little more closely, it’s easy to spot the various options (->).

subdesign prog_jtag_univers(TDO,Nstat_TDO,TDO_F : input;STRB,AFDX,INIT,SLCT : input;D[6..0] : input;SEL[1..0] : input; -- 0->ALTERA,1->XILINX,-- 2->FLASHLINK,3->MSP430ACK,BUSY,READY,ERROR: output;TCK_A,TMS_TDI,TCK_TMS,TDO_TCK,TDI_TMS,TCK_RST,PE : bidir;)variableTCK_A,TMS_TDI,TCK_TMS,TDO_TCK,TDI_TMS,TCK_RST,PE : tri;beginTCK_A.in=D0; TCK_A.oe=AFDX;case SEL[] iswhen 0 -- ALTERA=> TMS_TDI.in=D1 ; TMS_TDI.oe=AFDX;TCK_TMS.in=D3 ; TCK_TMS.oe=AFDX;TDO_TCK.in=D2 ; TDO_TCK.oe=AFDX;TDI_TMS.in=D6 ; TDI_TMS.oe=AFDX;TCK_RST.in=GND; TCK_RST.oe=GND;ACK =D4;BUSY =TDO;PE.in=GND; PE.oe=GND;READY=Nstat_TDO;ERROR=GND;when 1 -- XILINX=> TMS_TDI.in=D2 ; TMS_TDI.oe=!D3;TCK_TMS.in=D1 ; TCK_TMS.oe=!D3;TDO_TCK.in=GND; TDO_TCK.oe=GND;TDI_TMS.in=GND; TDI_TMS.oe=GND;TCK_RST.in=D0 ; TCK_RST.oe=!D3;ACK =GND;BUSY =D6;PE.in=D6; PE.oe=VCC;READY=Nstat_TDO & D4;ERROR=VCC;when 2 -- FLASHLINK=> TMS_TDI.in=D2 ; TMS_TDI.oe=!D3;TCK_TMS.in=GND; TCK_TMS.oe=GND;TDO_TCK.in=!D5; TDO_TCK.oe=VCC;TDI_TMS.in=D1 ; TDI_TMS.oe=!D3;TCK_RST.in=D0 ; TCK_RST.oe=!D3;ACK =GND;BUSY =GND;PE.in=!TDO_F; PE.oe=VCC;READY=D6;ERROR=GND;when 3 -- MSP430=> TMS_TDI.in=D0 ; TMS_TDI.oe=!SLCT;TCK_TMS.in=D1 ; TCK_TMS.oe=!SLCT;TDO_TCK.in=D2 ; TDO_TCK.oe=!SLCT;TDI_TMS.in=INIT; TDI_TMS.oe=VCC;TCK_RST.in=STRB; TCK_RST.oe=!AFDX;ACK =GND;BUSY =GND;PE.in=TDO; PE.oe=!SLCT;READY=GND;ERROR=GND;end case;end;

For info: the ‘Jedec’ programming fi le (prog_jtag_univers.jed) is available from the Elektor website (www.elektor-electronics.co.uk).

ComponentslistResistorsR1,R3-R27 = 100R28-R32,R34 = 100k (SMD)R33,R35,R26,R37 = 10k (SMD)(R2 not fi tted)

CapacitorsC1 = 100nF (SMD 1206)C2,C4 = 2μF2 (SMD 1206)C3 = 220nF (SMD 1206)C5,C7 = 47μF 10V radial(C6 not fi tted)

SemiconductorsIC1 = EP900LC (programmed, order

code 060287-41) *IC2 = REG710-NA5

MiscellaneousK1 (K_LPT) = 25-way sub-D plug, (male),

right-angled pins, PCB mountK2 (FLASHLINK), K3 (MSP430), K4 (XI-

LINX) = 14-way 2-row pinheaderK5 (ALTERA) = 10-way 2-row pinheaderJ1,J2 (SW) = 2-way DIP switchPLCC-44 socketProject software, fi le # 060287-11.zip,

free download from Elektor websitePCB, order code 060287-1 * Ready-programmed PLD supplied free

when ordering PCB # 060287-1 from the Elektor SHOP

OptionalParts for the cable connection to K3 on

the GBECG:- 14-way (2x7) press-on IDC socket- Molex socket, 6-way, 1.25mm lead

pitch (RS Components # 279-9178)- 6 wires with crimped contacts for

Molex connector (RS Components # 279-9544)

Universal JTAG Adaptor • 46 Elektor blockbusters

Page 47: E-book-15-ElektorBlockbusters-uk

elektor electronics - 10/200632

GBECGHANDS-ON ELECTROCARDIOGRAPH

Marcel Cremmel

Lots of electronics hobbyist dreamof recording an electrocardiogram(ECG) using a circuit built at home. Usuallyout of technical curiosity, as numerous problems have to beresolved in order to properly sample the heart’s electrical activity. Alternatively, some peoplerequire personal medical monitoring while under a cardiologist’s care. And then it’s great to beable to make your own ECG and show it to your GP or clinical staff.

The idea of using a Nintendo Gameboygames console equipped with a spe-cial cartridge was inspired by theworld-famous Elektor GBDSO [1] (a bigthank you goes out to Steve Willis forhis help with this project).

Our electrocardiograph utilizes threeelectrodes: one on each wrist, thethird on the left leg. The electronicdevice, built on a cartridge that slipsinto any Gameboy model, processesthe sampled signals and produces avery high quality ECG scrolling acrossthe LCD (see the various illustrations).

The electrocardiogram implementsthe method of M. Einthoven (see theinset on the next page). It only usestwo active electrodes, a third beingused to set the no-signal level of thefirst two. All leads are single-ended.Despite this simplicity, the results arenoticeable and even recognized asusable by a cardiologist. The electro-cardiograph easily meets the initialspecifications for which it was

designed: to monitor tolerance to theanti-malaria medication.

To do that, we measure the QT interval(see Figure 1) which should remain‘normal’. Figure 1 [2] matches up theelectrical activity sampled and the car-diac cycle phases, as follows:

P-Wave: Auricular contraction; theblood coming from the veins ispushed into the ventricles.

QRS Complex: Ventricular contraction;the blood contained inside ispushed into the arteries.

Both of these waves produce the ‘lub-dub’ heartbeat sounds.

T-Wave: Repolarisation of the ventri-cles; the ventricular muscle returnsto rest.

The electronics!After this little ‘dose’ of general knowl-edge, let’s deal with our favourite sub-ject: describing the GBECG electronicstructures and making the board.

Just as with the GBDSO [1] (ElektorElectronics October and November2000), the specific electronics and soft-ware (in Flash memory) are groupedonto a cartridge that slips into the con-sole’s connector. In this way, theGameboy is transformed into a power-ful electrocardiograph!The electronic device processes thevery low voltages sampled betweenthe two active electrodes. The single-ended leads are designated DI, DII andDIII according to their localisation (seedrawing in Figure 2).

The most common lead is DI.Due to its low peak-to-peak amplitude(of the order of one mV), the EMF (elec-tromotive force) measured is consider-ably amplified (about 1000 ) before itcan be converted to 8-bit digital. Thesampling frequency selected is 477.84Hz, compatible with the spectrum ofan ECG signal.The digital signal is then taken care ofby the console processor. It is thenplaced in an 8 kBytes cyclic buffer

GBECG • 47 Elektor blockbusters

Page 48: E-book-15-ElektorBlockbusters-uk

10/2006 - elektor electronics 33

GameBoyElectroCardioGraph

Characteristics:• Cartridge compatible with Nintendo Gameboy con-

soles type Classic, Pocket, Colour or Advance

• Single-ended connections using 3 electrodes

• Sensitivity: 1.6 mV full scale

• Common mode rejection: 100 dB

• Trace memory : 68 s

• Scrolling display

• Temporal window: 2.6 s in acquisition mode (1.3 s or2.6 s in consultation mode)

• Heartbeat indicator

• Battery power supply required

• Approx. 2 hours use from battery power

It is practically impossible to grasp the operation of thishome-made electrocardiograph instrument without a mini-mum of medical knowledge. We deal with the heart of thesubject. First of all...

A bit of history…In passing, let us payhomage to WillemEinthoven who discov-ered the relationshipbetween electrical phe-nomena and muscularcontraction of the humanheart about 100 yearsago. He received theNobel Prize in 1924 forthat discovery.

Willem Einthoven, inventor ofthe electrocardiograph.

and a bit of biology…The heart is an autonomous muscle: it is the only one notcontrolled by the brain. The ‘sinus node’, located in the rightauricle, triggers nerve flows that control the heart muscles.These contract (‘depolarisation’ in medical lingo) and relax(‘polarisation’) in order to make up the blood pump thatgives us life. The contraction is caused by a change in elec-trical polarity on each side of the cellular membranes.During the relaxation phases, the electrical charges find theirstate of equilibrium before being stimulated again.

The resulting potentials are transmitted to the skin surface.They can then be sampled by cutaneous electrodes, as thehuman skin is sufficiently conductive.

A wise placement of the electrodes allows a cardiologist todeduce the heart’s mechanical behaviour (and its defects!)by analysing the electrical activity.

The Electrocardiogram (ECG)

Technology has greatly evolved since the 1920s. The first patients dipped theirhands and feet in basins full of very salty water!

String galvanometer, The U-shaped magnet ends are enveloped in water coolingtubes (well before PCs!) Photos : Stichting Einthoven Foundation

GBECG • 48 Elektor blockbusters

Page 49: E-book-15-ElektorBlockbusters-uk

memory and reread to show the ECGin real time on the screen, in ‘scrolling’mode.

The analogue partPresenting an adequate signal to theinput of the digital analogue converterpresents a challenge to the electronicsengineer because there are a numberof technical problems to analyse andresolve.

Differential amplifierThe peak-to-peak amplitude of the sig-nals sampled between the electrodesis very low at just 2 mV max.Also, both the human body and theconnecting wires to the electrodes arestrongly influenced by high noise lev-els radiated by mains wires and otherpower carrying leads inside buildings.Capacitive coupling, although verylow, produces a relatively high voltage(often over 1 V) to appear with respectto ground, despite the relatively lowfrequency of just 50 Hz or 60 Hz.To begin with, it would seem difficultto isolate the useful signal because itsamplitude is 1,000 times lower than allthe interference around! Moreover, themains frequency is included in the use-ful spectrum; so the filtering solutiondoes not work here.However, considering the wavelengthof the mains voltage (6,000 km!), it issafe to assume that that each point onthe skin receives the same inducedpotential thanks to its conductivity.Therefore, a common-mode voltage isdeveloped with respect to the elec-trodes.In this case, the solution becomesobvious: we’re going to use a differen-tial instrumentation amplifier with anadequate common-mode rejection ratio(CMRR):

In this formula:SP = amplitude of the interference: 1 VSECG = ECG amplitude: 1 mVS/N= signal to noise ratio: 40 dBOr : CMRR 100 dB.

In addition, the amplifier must becharacterised by a very high inputimpedance (> 10 M ) and a low offsetvoltage.Numerous integrated instrumentationamplifiers exist (the AD624, for exam-

CMRRS

SdB

S

NdB

p

ECG

elektor electronics - 10/200634

HANDS-ON ELECTROCARDIOGRAPH

R

Q S

PECG T

auricular contraction diastole(repolarisation)

ventricular contraction 050280 - 27

Figure 1. Relationship between the measured electrical activity and the cardiac cycle phases.

differentialamplification

AD1

F1

K

IC1.A + IC1.B

1/2summing

F4

F5

IC1.C

EA

EB

EC

IC1.D

differentialamplification

AD2

F2

IC2.D

lowpassfilterA3

F3

IC2.C

reference:2V5

050280- 13

auto-zerocontrol

F6

IC2.A

ECG

Figure 3. Block diagram of the analogue part of the circuit.

I

II

III

050280 - 12

Figure 2. These single-pole leads are used to implement the electrocardiograph.

GBECG • 49 Elektor blockbusters

Page 50: E-book-15-ElektorBlockbusters-uk

10/2006 - elektor electronics 35

AU

DIO

IN

RA

MC

S

RE

SE

T

EC

LK

K2

+5V

A10

A11

A12

A13

A14

A15

GN

D

3231

WR

30

RD

2928

A0

27

A1

26

A2

25

A3

24

A4

23

A5

22

A6

21

A7

20

A8

19

A9

18171615141312

D7

4

D6

5

D5

D4

D3

D2

D1

D0

67891011321

+5V

C15

100n

R25

100k

+5V

+5V

K1

K3

+5V

C17

100n

C19

10

C6

100n +5V

AD

C08831IM

IC3

VIN

+

VIN

-

VR

EF

CL

K D0

CS

6

84

2

735

1

R3

22kR12

12k

C5

100n

C7

100n

C4

100n

R74k7

2 3

1IC

1.A910

8IC

2.C

65

7IC

1.B

13 12

14IC

2.D

C1560p

5%

C233n 5%

R1

2M2

1%

R622k1%

R5220k

1%

R14220k

1%

R447k1%

R8

100k1%R9

10k1%R11

100k1%R

1347k1%

R17

100k

R18

100k

+5V

65

7IC

2.B23

1IC

2.A

1312

14IC

1.D

R2147k

D1

BA

V99

D2

BA

V99

R247k

R1547k

+5V

+5V

R20390k

C10

1n

D3

BA

V99

+5V

R19

1k

R10

210k1%C

8

1

R16

2M2

R22100k

C14

100n

R23

1MR24

1M

C16

100n +5V

T1

BC

848B +5V

C9

470p

C12

2n2

D4

BA

V99

D5

BA

V99

IC2

11 4

+5V

C11

100n

C13

100n

PD

0/AL

E/A

S

CN

TL

2/PS

EN

PS

D813F

2A

PD

1/CL

KIN

PC

2/VS

TB

Y

PC

3/TS

TAT

PC

1/TC

K

PC

4/TE

RR

CN

TL

0/WR

CN

TL

1/RD

PC

5/TD

I

PD

2/CS

I

PC

0/TM

S

PC

6/TD

O

PC

7/DB

E

PA0/D

0

PA1/D

1

PA2/D

2

PA3/D

3

PA4/D

4

PA5/D

5

PA6/D

6

PA7/D

7

AD

IO10

AD

IO11

AD

IO12

AD

IO13

AD

IO14

AD

IO15

AD

IO0

AD

IO1

AD

IO2

AD

IO3

AD

IO4

AD

IO5

AD

IO6

AD

IO7

AD

IO8

AD

IO9

IC4

-90M

RS

T

PB

0

PB

1

PB

2

PB

3

PB

4

PB

5

PB

6

PB

7

23242526272829303233343536373839 404342

41

2221201817161514

454413 12 11 10

1946 31

525150494847 37 6 5 4

8

21

9

IC1

11 4C

3

100n

+5V

IC1 = T

LV2254A

IDIC

2 = TLV

2254AID

JTAG

EA

EB

EC

GN

D

GN

D

EL

EC

TR

OD

ES

TD

O

TD

I

+5V

TM

S

TC

K

GN

D

IC1.C

910

8

AD

D

RE

SE

T

A10

A11

A12

A13

A14

A15

WR

RD

A0

A1

A2

A3

A4

A5

A6

A7

A8

A9

D0

D1

D2

D3

D4

D5

D6

D7

PB

0

PB

1

CS

CL

KD

O

RE

SE

T

+5V

GN

D

GN

D

TP

TP

TP

TP

TP

TP

TP

TP

TPTP

524.25kHz

131.0625kHz

2V5

CL

K

1,0485MH

z

262.125kHz

CL

K C

AN

DO

CS

050280 - 11

Gameboy Connector

EC

GT

P

22kP

1

Figure 4. The bulk of the work is handled by the ISP flash memory, IC4 and IC3, an A/D converter, Serial I/O. The Gameboy processor handles the processing.

GBECG • 50 Elektor blockbusters

Page 51: E-book-15-ElektorBlockbusters-uk

ple). These are very high-performancedevices and need no adjustment. Butquality comes at a cost.We decided to make the differentialamplifier using more economical oper-ational amplifiers. This also allows sig-nificant savings in cost and power con-sumption. Moreover, these opampsfunction perfectly with a single 5 Vpower supply (this is not the case forthe AD624). The disadvantage is thepresence of an adjustable potentiome-ter to optimise the CMRR.

Block diagram and wiring diagramFigures 3 and 4 respectively give theblock diagrams for the analogue partand the complete circuit diagram. Thereferences associated with each func-tion (ICx.y) identify the operationalamplifiers for the structural diagramsthat show the functionality. The instrumentation amplifier is madeup of functions F1 and F2. Function F3is a 2nd order low pass filter with aroll-off of 170 Hz and a damping factorm of 0.73 (i.e., near Butterworth). It willfaithfully attenuate all unwanted com-ponents outside of the useful fre-quency spectrum and replaces theanti-aliasing filter for the DAC(digital/analogue converter) that fol-lows it.The gain distribution in the circuit is asfollows: A1 = 21 , A2 = 4.7 and A3 =10 . The total amplification is 987, incompliance with our objectives. Theother functions (F4, F5 and F6) assistthe instrumentation amplifier in orderto ensure its proper operation. In fact,the operational amplifiers have a sup-ply voltage of between 0 V and 5 V.The ideal no-signal voltage on each ofthe terminals is 2.5 V. Setting this levelis not a problem in most cases: adivider bridge with two resistors isappropriate (R23 and R24). It is harderfor the two input amps because wemust take care not to compromise theirinput impedances.The problem is solved using the third,common, ECG electrode (see Figure 3)and the functions of F4 and F5.It can be shown that the voltage Sequals half the sum of the voltage (EA+ EB). It is compared to the ‘2.5-V’ set-ting, and the error voltage is amplifiedto produce an ECG signal that can beprocessed. As there is no current flowin the electrodes, voltages EA and EBare equal to EC (give or take a fewmV). In this way, the human skin actu-ally helps to keep EA and EB equal tothe target level of 2.5 V. That is the goal

elektor electronics - 10/200636

HANDS-ON ELECTROCARDIOGRAPH

01V75 4V25

050280 - 14

255

VECG

NECG

Figure 5. The transfer function is determined by divider bridge R3/R12.

1

+5V

32

050280 - 15

ECLKWR

A0 - A15 D0 - D7

RDRAM_CS

GNDAUDIO INRESET

GAME BOY

top view

Figure 6. Connector pinout for the Gameboy cartridge (view from above).

GBECG • 51 Elektor blockbusters

Page 52: E-book-15-ElektorBlockbusters-uk

we are seeking: the no-signal voltageof the opamps is as desired withoutreducing the input impedance.Moreover, a natural, but very annoyingphenomenon occurs when we placethe electrodes: an electromotive force(EMF) contact potential is producedbetween the skin and the electrodemetal. This ‘micro-cell’ is very weak (afew mV) but it is not eliminated by theinstrumentation amplifier. On the con-trary, it is amplified!Functions F4 and F5 partially reducethis effect, but the offset in S1 and S2may still reach 1 V in differential mode.This value is unacceptable and istherefore compensated by function F6.F6 compares the average S3 signalvalue with the 2.5 V setting. The errorvoltage is integrated (time constantR16C8 = 2.2 s) in order to produce theZERO signal. This continuous voltageoffsets the S3 signal until its averagevalue is stabilised at 2.5 V.To increase the amplitude of this com-pensation, two diode pumps C9-D4-C11 and C12-D5-C13 produce –3 V and+8 V supply voltages for IC2.

The digital partThe digital-analogue conversion is per-formed by IC3. It integrates a real dif-ferential amplifier, but requires anexternal reference voltage. This is sim-ply derived from the 5 V power supplyusing a potential divider (R23/R24)buffered by T1. The precision and thestability are average at best, but stillsufficient for this application. Thedivider R3/R12 determines the transferfunction (see Figure 4).The asymmetry with respect to 2.5 V isjustified by the asymmetrical shape ofan ECG in relation to its average value.The DAC provides its NECG results in‘serial’ format. It is controlled by the CSand CLK signals — the first triggersthe conversion (its frequency is 477.84Hz) and the second clocks the dataoutput (on DO).

The PSD813F2A Gameboy cartridge plugs into a con-nector which accommodates the con-sole’s microprocessor buses:• Addresses: A15 to A0• Data: D7 to D0• Check: ECLK, WR, RD and RESET

The first Gameboy games consoles onthe market from about 1989 had amicroprocessor similar to the old Z80,which explains the size of the buses.

The most recent consoles are equippedwith much more powerful CPUs, butfor commercial reasons the old car-tridges (and even older than those) stilloperate on the current Gameboys. Thatis also the case for our electrocardio-graph!The PSD813F2 is an integrated circuitthat’s perfectly adapted for making acartridge for a Gameboy console.Unfortunately, we do not have enoughspace in this article to describe itscomplete functionality (see [3]). Insummary, the PSD813F2 includes:• a configurable microprocessor inter-

face that can be adapted to all 8-bitmicroprocessors on the market,

including the vintage Z80;• 128 kBytes of Flash memory (only

32 kBytes are utilised by the electro-cardiograph object code, whichleaves space for extensions or otherthings...);

• a complex programmable logicdevice (PLD) that takes care of theaddress decoding;

• a 16-cell sequential Complex Pro-grammable Logic Device (CPLD). Itis responsible for the serial-to-paral-lel conversion of the DAC frames torelieve the CPU and produce thesquarewave signals required for thediode pumps;

• 27 I/O configurable ports;• 2 kBbytes RAM (not used).

Moreover, a JTAG interface is used tocompletely configure the ‘on circuit’component via connector K3, whichshould not fail to interest all of youelectronics hobbyists. The PSDSoftEx-press development environment canbe downloaded for free on the manu-facturer’s website.As you can see from the diagram (Fig-ure 4), the connection between theconsole bus and the PSD813 is simple:the signals of the same name are con-nected.The only particularity that could be

interpreted as an error: the data busconnections are crossed! That enabledus to simplify the board layout and thebinary file of the GBECG control pro-gram was changed to suit.

The softwareThe software is entirely written inassembly language. The author usedthe ‘Gameboy Assembler Studio’ envi-ronment by Nicklas Larsson (freewareavailable on the web [4]).The assembly language was necessarybecause the specifications require a‘scrolling’ display in real time. That

10/2006 - elektor electronics 37

TheauthorThe author, MarcelCremmel, has been a quali-fied teacher in ElectricalEngineering (withElectronics option) since1979 (French NationalEducation state diploma).

After having initially taughtat the Mohammedia deRabat Engineering Schoolin Morocco as a participantin the Cooperation pro-gram, he was assigned tothe Louis Couffignal HighSchool in Strasbourg in1982, in the BTS EL section(Certificate, SeniorElectronics Technician).

Although his profession forces him to deal with all domains of electronicsMarcel has a preference for telecommunications, video, microcontrollers(MSP430 and PIC) and programmable logic circuits (Altera). In addition to elec-tronics, his other passion is motorcycles in all forms: touring, races, etc.

His personal website is at http://electronique.marcel.free.fr/

GBECG • 52 Elektor blockbusters

Page 53: E-book-15-ElektorBlockbusters-uk

occupies the CPU of the first consolesat a level of 80% due to the ‘old’ man-ner in which the screen memory isorganised (separate screen memoryand character memory).The software can be thought of as han-dling four tasks:

1. InitialisationsThis task is executed at switch-on orafter a reset,• Initial assignment of variables.• Configuration of I/O ports.• Initialisation of the LCD. The screen

has 160 x 144 pixels, but for technicalreasons, the useful part is reduced

to 160 x 96 pixels. The lower part(160 x 48) is utilised for fixed mes-sages.

• Internal timer: this is programmedto produce interrupts at a rate of477.84 Hz (sampling frequency).

• Sound generator: this is pre-pro-grammed to produce a cardiac‘beep’ when required.

2. Main loopThe main loop simply detects theaction of certain keyboard keys andmodifies the operating mode:• Start: acquisition mode• Select : stop mode

• : zoom _1 in stop mode• : zoom _2 in stop mode

3. Timer interrupt programThis task is executed a rate of 477.84times per second. It carries out the fol-lowing functions:• Debounced readout of the keyboard

state.In run mode:• triggers a new conversion;• acquisition of the last sample (result

of the previous conversion);• all 4 samples (or 119.46 times per

second);• calculation of the ‘average sample’

elektor electronics - 10/200638

HANDS-ON ELECTROCARDIOGRAPH

EP

S05

0280

- 1

EPS050280 - 1

EP

S05

0280

- 1

Figure 7. Copper track layout and component mounting plan of the double-sided board designed for the GBECG.Soldering of IC3 is particularly difficult, so we’re supplying the board with all components pre-soldered.

COMPONENTLIST(all SMD, except K1)

Resistors(all 0805 case)R1 = 2M 2 1%R2,R15,R21 = 47kR3 = 22kR4,R13 = 47k 1%R5,R14 = 220k 1%R6 = 22 k 1%R7 = 4k 7R8,R11 = 100k 1%R9 = 10kR10 = 210k 1%R12 = 12kR16 = 2M 2R17,R18,R22,R25 = 100kR19 = 1kR20 = 390kR23,R24 = 1MP1 = 22 k preset (Bourns 3314G)

Capacitors(all 0805 case except C8 and C19)C1 = 560pF 5%C2 = 33nF 5%C3-C7,C11,C13-C17= 100nFC8 = 1μF (1208)C9 = 470pFC10 = 1nFC12 = 2nF2C18 = not fittedC19 = 10μF (1208P)

SemiconductorsIC1,IC2 = TLV2254AIDIC3 = ADC08831IM (Analog Devices)

or TLC0831CD (Texas Instruments)IC4 = PSD813F2A-90M

(STMicroelectronics), programmed,order code 050280-41

D1-D5 = BAV99T1 = BC848B

MiscellaneousK1 = Molex connector, 5-way, Dubox

89882-405, Digikey # 90148-1102-ND

Programming connections:K3 = Molex connector, 6-way, 1.25mm

lead pitch, type 53261-0671 (Digikey# WM7624CT-ND)

Optionally: FlashLink programmingconnection:

Molex 6-way connector, 1.25mm leadpitch, female (Digikey # WM1724-ND)

6 wires with pin terminations for Molexconnector (Digikey # WM1775-ND)

Electrodes:Cutaneous probes or clips are available

from medical supplies outlets5-way SIL pinheader4 mm plate (3x)6 m screened audio cablePCB, with all components ready fitted,

tested, order code 050280-91

GBECG • 53 Elektor blockbusters

Page 54: E-book-15-ElektorBlockbusters-uk

= average of the last 4 samples;• detection of the R-wave in order to

trigger the cardiac ‘beep’;• loading the 8 kBytes cyclic buffer

with the average sample.

4. Interrupt program, V-BlankThis interrupt is produced at the endof each LCD vertical sweep. The rateis: fv = 59.73 Hz; or every two aver-aged samples.

The program also takes care of refresh-ing the display.• Run mode: the LCD shows the last

samples (or 320 averaged sampledvalues on the cyclic buffer), whichtraces the last 2.68 s on the screenwidth.

• Stop mode: depending on the zoomvalue: 1 or 2, the LCD shows thelast 320 or 160 samples, whichtraces the last 2.68 s or 1.34 s on thescreen width.

In stop mode, the program also detectsaction on the or keys allowingthe use to move around within thescreen memory. During the display of the ECG trace,the program draws the vertical andhorizontal scales. The latter moveswith the trace in order to improve read-ability. The source code file of the

GBECG control program is available asa free download from the Elektor Elec-tronics website, the file number is050580-11.zip, see under month ofpublication. Improvements and addi-tions are welcome.

Building itThe use of SMD components isunavoidable. In fact, the underside ofthe board must be perfectly smooth(therefore, no through wires or pins) sothat it can slip into the cartridge case.To save you the trouble of strugglingwith (and losing) those tiny SMD parts,we are supplying the GBECG printed

circuit board with all componentsalready soldered in place, and thePSD813 programmed, all at an afford-able price (see the inset). The ordercode is 050280-91.All that is left to do is find an oldGameboy cartridge case and clear outthe two half-shells a little. Photo Aillustrates the cutouts to make.The wider cutout in the upper half-shell is due to potentiometer P1 whichotherwise prevents closing the case.

AdjustmentThe only adjustment consists in opti-mising the CMRR of the differential

10/2006 - elektor electronics 39

The electrodesA good ECG can only be obtained with good, well-placedand properly-wired electrodes.

To limit the effect of undesirable signals, it is recommendedthat you use shielded cables. Electronically, ‘audio’ cablesare perfectly suited to this function. In practice however theyare much too fragile, We therefore propose making smalladaptors on which the cable clasps eliminate practically allrisk of breaking (see Figure F),

You will see that the shielding is only connected at the car-tridge side and that it is isolated on the electrode side inorder to avoid any contact with the skin.

‘4 mm’ type plugs make it possible to use commercially avail-able electrodes (Figure G).

The clip is very practical and adapted for children. But theprice of these two electrodes may discourage many readers(more than £6 each and you will need three off!)

Homebrew electrodes can be made from coins as illustratedin the opposite photo. The author used French Florin (FF)coins which are made from nickel. Solder a 4-mm socket andthe electrode (Figure H is ready to use.

Three rubber bracelets keep them in place on the wrists andthe lower calf. These bracelets can be made by cutting rib-bon for straps to the proper length and gluing them to theself-adhesive ‘Velcro’ tape at both ends. We can also usesections from air chambers from a motorcycle or a scooter.

E F G H

A

GBECG • 54 Elektor blockbusters

Page 55: E-book-15-ElektorBlockbusters-uk

amplifier. For that, you need a functiongenerator and an oscilloscope or an ACvoltmeter. Begin by making the meas-urement circuit in Figure B (the capac-itor has a capacitance of 10 μF). Top tobottom: EA, EB, EC, GND.Plug the device into the fixed connec-

tor K1, observing the orientation, andonly then connect the generator. In thisway, we inject a common-mode testsignal. Adjust the generator: 50 Hzsine wave with amplitude 1 V. Insertthe cartridge in the Gameboy with theupper half-shell removed in order to

access the ECG test point. Turn on thepower and measure the AC componentof the ECG signal. Then adjust P1 tominimise the peak-to-peak amplitude.It should be less than 25 mV in order toobtain an S/N ratio in excess of 40 dB.

Final checkThis step is not strictly required. Itspurpose is to ensure proper operationof the electrocardiograph by injectinga signal and by verifying the result onthe screen.Most benchtop signal generators areincapable of reliably producing thevery low levels required for this check.Therefore, we must greatly attenuatethe GBF signal. That is what thedevice shown in Figure C does.The signal is effectively divided by100. In this way, we inject a 1 Hz sinu-soidal signal and a 140-mV DC ampli-tude signal. These should result in animage on the LCD screen similar tothat in Figure D.The sinewave is aligned with the firstdotted line and has a DC amplitude of 7divisions, or 7 200 μV = 1.4 mV.The fixed connector K1 on the car-tridge is not very sturdy. To limit therisk of deformation or of it being tornout, restrain the three shielded cableson the cartridge cover with two cableties, as illustrated in photo E.The cable ties we used on our proto-type of the GBECG do not touch theinternal components. They require four2 mm holes to be drilled which do notsignificantly weaken the shell.

(050280-1)

We would like to extend our thanks to ProfessorsSchalij and Maan, Leiden University Hospital, the

Netherlands, for their valuable assistance.

Bibliography[1] GBDSO — Gameboy DigitalStorage Oscilloscope, Elektor Electronics October and November 2000.

Internetreferencesand links[1] http://chem.ch.huji.ac.il/~eugeniik/history/einthoven.html

elektor electronics - 10/200640

HANDS-ON ELECTROCARDIOGRAPH

B

C

D

GBECG • 55 Elektor blockbusters

Page 56: E-book-15-ElektorBlockbusters-uk

[2] http://www.e-cardiologie.com/examens/ex-electro2.shtml

[3] http://www.st.com/stonline/prod-ucts/

[4] http://www.devrs.com/gb/Additional documents andprogram sources on

http://www.elektor.com

http://www.infoscience.fr/histoire/biograph/biograph.php3?Ref=128PSD813 datasheet

http://www.st.com/stonline/products/literature/ds/7833.pdfADC08831IM datasheet

http://www.ortodoxism.ro/datasheets2/6/0rcoik1yuwhx1dj2ogg8wid7sfcy.pdf

10/2006 - elektor electronics 41

OperatinginstructionsPlacement of the electrodes

It is absolutely necessary to clean the skin and the electrodeswell with a cotton and ether or alcohol, In this way, the elec-tromotive force EMF on the contacts, which may saturate theamplifiers, are limited considerably.

The standard lead is ‘DI’:

• EA electrode: right wrist

• EB electrode: left wrist

• EC electrode: left foot (lower calf)

Utilisation of ‘contact’ products based on potassium chlorideconsiderably improve the quality of the measurements.

The best ECGs are obtained when the patient is calm andlying down so that the only muscle in action is the heart.

Operation

• Live start-up: welcome screen is displayed.

• Go to the acquisition screen: press Start, A, B or Select.

• ECG acquisition: ifthe electrodes areproperly placedand the patient iscalm, the readingshould be stabilisedin a few seconds and look like the one illustrated inFigure I.

Do not use this ECG as a reference; the shapes may varyappreciably from one individual to another.

If no trace appears after thirty seconds, clean the skin belowthe electrodes using a pad and ether or alcohol.

Irregularity of the trace may be reduced by using a ‘contact’product.

• Stop mode: pressing the Select button stops the acquisi-tion. You can then analyse the memory which contains68.6 s worth of ECG.

: zoom x 1

: zoom x 2 (see below)

: Move ahead

: Move backwards

A beep sound will be heard each time an R wave is detect-ed. The volume can be adjusted with the volume button onthe console.

Attention: The screen memory is erased when power isremoved.

AttentionThe GBECG electrocardiograph describedin this article has not received medicalapproval and is therefore not intendedfor professional use. The instrumentmust always be powered by batteries inorder to respect protection category III.

I Scales (zoom 1x)

Elektor blockbusters GBECG • 56

Page 57: E-book-15-ElektorBlockbusters-uk

PROJECTS GAMEPAD CONVERSION

42 elektor electronics - 9/2007

Tilt GamepadUpgrade your Gamepad with acceleration sensorsXin Wang and Marko Westphal

Users of the Nintendo Wii and Play station 3 ‘tilt’ controllers have raved about the more intuitive

control these devices offer. Up until now there hasn’t been a comparable gamepad available for the

dedicated PC gamer but why should they be left out of all the fun? Join in by adding this two-axis

tilt sensor to a standard gamepad, it is particularly good for vehicle and flight simulation as well as

adventure games. Give those thumbs a rest and start waving your arms around!

A tilt gamepad senses the angle at which the handheld controller is moved and converts that measure-ment into equivalent digital outputs which would be produced by pressing the up/down left/right buttons on the gamepad. It is not nec-essary to press any of the but-tons to control direction; the on-screen object is controlled simply by tilting the gamepad. In this design the movement is detected by an acceleration sensor manufactured by Ana-log Devices and sensor val-ues are processed by an Atmel ATmega8 microcontroller. The entire circuit fits onto a small PCB which converts a standard gamepad into a tilt gamepad.

The sensorThe novel component in this design is the analogue accel-eration sensor type ADXL322 from Analog Devices. This 2-axis device produces two in-dependent output voltages proportional to the inclina-tion of the sensor in the x and y planes. The supply voltage can be in the range of 2.4 V to

6 V. The two analogue output signals have a sensitivity of 420 mV/90 . The sensor range is ±2 g and it is supplied in an SMD CP-16 package which can-not be soldered into place using a con-

ventional soldering iron so the PCB is supplied with this component already mounted.

Signal processingThe output signals from the ac-celeration sensor are analogue so it is necessary to process them using a microcontroller with an on-board A/D convert-er. The Atmel ATmega8 is an 8-bit microcontroller with six multiplexed analogue inputs which can be selected inter-nally as an input to the 10-bit resolution A/D converter. Up to 23 of its pins can be configured as general-purpose digital I/O pins.The two analogue signals rep-resenting the X/Y tilt from the acceleration sensor are connected directly to the A/D converter inputs of the mi-crocontroller. The signals are digitised, filtered and then converted into digital output signals which emulate the up/down, left/right function of the direction buttons on the origi-nal gamepad.The X and Y values are sam-

PC6 (RESET)1

PD0 (RXD)2

PD1 (TXD)3

PD2 (INT0)4

PD3 (INT1)5

PD4 (XCK/T0)6

VCC

7

GND

8

XTAL1

9

XTAL2

10

PD5 (T1)11

PD6 (AIN0)12

PD7 (AIN1)13

PB0 (ICP)14

PB1 (OC1A)15

PB2 (SS/OC1B)16

PB3 (MOSI/OC2)17

PB4 (MISO)18

PB5 (SCK)19

AVCC

20

AREF21

GND

22

PC0 (ADC0)23

PC1 (ADC1)24

PC2 (ADC2)25

PC3 (ADC3)26

PC4 (ADC4/SDA)27

PC5 (ADC5/SCL)28

IC1

ATmega8-16PI

X1

4MHz

C2

100n

C1

100n

C3

100n

C4

22p

C5

22p

GND

GND

GND

+5V

+5V

+5V

K1

GND

ST2

GND

3

GND

5

GND

6

Yout10

Xout12

Vs14

Vs15

GND

7

IC2

GND

070233 - 11

0

ADXL322

Figure 1. Besides the acceleration sensor and microcontroller there are very few other components required.

Tilt Gamepad • 57 Elektor blockbusters

Page 58: E-book-15-ElektorBlockbusters-uk

439/2007 - elektor electronics

pled alternately, the 2.56 V reference for the A/D converter is produced on-chip and decoupled by capacitor C3 on Pin 21 (AREF). The I/O pins have good sink/source current capability which together with selectable internal pull-up resistors means that there is no re-quirement for additional drivers for the output signals.

Simple circuitryIt can be seen in the circuit diagram in Figure 1 that apart from the microcon-troller and sensor there are very few additional components required. The layout of the double-sided PCB shown in Figure 2 is therefore quite simple.Figure 3 gives the flow chart describ-ing the main software functions. The microcontroller ADC port is sampled every 10 ms, raw values of acceleration are converted into tilt values which are then filtered. The signals output by the gamepad depend on the direction of tilt and tilt angle.The 6-way pin header (K1) is fitted to the PCB for all the connections to the gamepad. The circuit is powered directly from the USB interface (+5 Vand ground).

Putting it togetherThe finished PCB can be fitted into the casing of a standard PC gamepad if sufficient space is available. In prin-ciple any gamepad can be used pro-viding the direction buttons are ‘active Low’ i.e., when you press a button the output signal goes from a high to a low. The author used a ‘Firestorm Digital 3’ while in the Elektor Electronics lab a ‘MAXFIRE G-08X4’ from Genius hap-pened to be available for conversion (it must have been used earlier by one of our team for some serious research work…).In addition to the gamepad and fin-ished PCB a short length of 6-core ca-ble is required and possibly a small plastic enclosure for the finished PCB if it will not fit in the gamepad case. Do not insert the programmed micro-controller in its socket yet. The micro-controller can be ordered ready-pro-grammed from the Elektor Electron-ics website. Alternatively, the hex file (object code) can be downloaded from the same website at no cost if you pre-fer to program the device yourself. The original source files are protected by licences and copyrights and are not freely available.Assembly begins by first dismantling the gamepad; undo the screws at the

C5

C1K1

IC1

C2

C3

IC2

C4

X1

Figure 2. The double-sided PCB is supplied with the SMD-outline tilt sensor already mounted

(near the bottom of the board).

Components listCapacitorsC1,C2,C3 = 100nFC4,C5 = 22pF

SemiconductorsIC1 = Atmega8-16PI, programmed,

Elektor SHOP # 070233-41*IC2 = ADXL322

MiscellaneousK1 = 6-way SIL pinheaderX1 = 4MHz quartz crystalPCB with ADXL322 sensor fitted, Elektor

SHOP # 070233-91

* hex code file: free download # 070233-11.zip from www.elektor.com

Tilt Gamepad • 58 Elektor blockbusters

Page 59: E-book-15-ElektorBlockbusters-uk

PROJECTS GAMEPAD CONVERSION

44 elektor electronics - 9/2007

back of the unit which hold the two parts of the shell together. Once inside it is necessary to find out which parts of the circuit are connected to +5 Vand which are connected to ground. The simplest method is to trace wires from the USB connection, pin 1 (usu-ally black) is ground and pin 4 (usual-ly red) is +5 V. Similarly check out the wiring to the gamepad buttons; a close inspection reveals that each of the di-rection buttons have two contacts, one of which is usually connected to ground (as in the Thrustmaster game-pad but some use +5 V for this connec-tion) the other contact goes to the mi-crocontroller. This contact will be used later to solder wires to the new PCB connector K1 pins 2 to 5. If it is neces-sary to mount the PCB externally in a small plastic enclosure (as is the case with the “Firestorm Digital 3”), a hole will need to be drilled in the rear of the gamepad housing (5 mm diameter

PCB can be secured in the gamepad using hot glue (roughen the internal surface of the housing for good adhe-sion) or if an external enclosure is used it can be attached externally to the rear of the gamepad again with hot glue. Screw the two halves of the gamepad together.

The tilt gamepad is now finished! The PC has no way of knowing that the gamepad internals have changed so it’s not necessary to load any new soft-ware drivers. Revisit all your favour-ite games but this time experience a whole new level of intuitive control.

(070233-I)

should be sufficient) to run the multi-core cable through.Wiring between the tilt PCB connector K1 and gamepad can now begin by sol-dering the wires +5 V, ground and the four direction button contacts.The pin assignment for K1 is detailed on the circuit diagram in Figure 1.Pins 1 and 6 carry the power sup-ply while 2 to 5 are the digital output signals wired to the direction button contacts (active low, the idle state is high).The Table below shows the wiring connections in detail and the cable col-ours. Printed arrows on the PCB next to connector K1 indicate the direction in which the PCB should be moved to produce an output at that pin.Once the wiring is complete the pre-programmed microcontroller can now be fitted in its socket on the PCB. The

System Init

Reset Timer

Start Timer

Output

070233 - 12

no

yes

yes

no

SelectADC Channel

Start ADC

Filter andCalculate

ADCReady

?

Timer = 10 ms?

Figure 3. The software flow diagram. The sensor is sampled every 10 ms.

Gamepad/sensor board connectionsWiring between the gamepad and K1 on the sensor PCB using 6-core colour coded cable.

K1 GND Up Left Down Right +5 V

Cable Black Orange Yellow Green Blue Red

Gamepad Earth/Ground Up Left Down Right +5 V

Tilt Gamepad • 59 Elektor blockbusters

Page 60: E-book-15-ElektorBlockbusters-uk

Micro WebRemote measurement andcontrol is possible viathe Internet.Unfortunately,webserversusually sit inlarge,humminggreycabinets.That’s notthe idealsolution forkeeping aneye on yourrefrigerator,coffee machineor central heatingsystem. The ElektorElectronics MicroWebserver provides analternative.

Jürgen Wickenhäuser

Micro Webserver • 60 Elektor blockbusters

Page 61: E-book-15-ElektorBlockbusters-uk

esting details that are not essential fora ‘simple’ webserver. However, read-ers who want to know all the detailswill find what they’re looking for in theaccompanying software. The interfaceis without question unusually user-friendly. For example, the programvariables can be used directly in web-sites. It’s hardly possible to makethings any easier.The Micro Webserver is programmedusing the C language. But don’t letyourself be discouraged if you aren’tfamiliar with C, since this project is cer-tainly suitable for beginners as well.

ConnectionInternet and Ethernet are closelyrelated. Ethernet is a standard thatdefines the connection. The transmis-sion speed is normally 10 or 100Mbit/s, and it is automatically config-ured when the connection is estab-lished. We use the 10-Mbit/s variant inthis project, since it is more than ade-quate for an embedded webserver.We assume you already have an Ether-net network. The webserver can thusbe connected directly to a hub orswitch, so the Internet can beaccessed via Ethernet. There are alsoagreed conventions regarding howInternet communication takes place(via Ethernet, for instance). All of thisis specified in the TCP/IP protocol.Here we assume that the network towhich the Micro Webserver is con-nected can also ‘speak’ this protocol.From a technical perspective, there’sno reason why the Micro Webservercannot also be directly connected to aPC using a crossover cable. However,describing this in more detail isbeyond the scope of this article, since insome cases the PC settings must bechanged for such a connection.

Hardware

After all these introductory diversions,it’s time to get down to brass tacks.The hardware platform is the by nowwell-proven MSC1210 board (originallydescribed in the 2003 Summer Circuitsissue). If you do not already own acopy of this outstanding board, youcan obtain one from Elektor Electron-ics together with the extensiondescribed here (Figure 1).The extension is thus new. In principle,it’s simply a ‘custom’ network card forthe MSC board. This card is builtaround the CS8900A Ethernet driver IC(refer to the schematic diagram in Fig-ure 2). As usual with network cards,there are two LEDs (D1 and D2) to indi-cate the status of the network connec-tion. D1 flashes for 6 ms each time adata packet is received or transmitted,or if there is a collision between twopackets. The second LED indicateswhether the CS8900A is receivingproper link pulses. These pulses areused in Ethernet networks to synchro-nise transmitters and receivers, and D2will be on if this synchronisation issuccessful.The network IC also has a complete10Base-T transceiver. 10Base-T is thestandard for 10-Mbit/s Ethernet overtwisted-pair cable. The circuit requiresonly a few external components. Thetransformer just ahead of the RJ54 con-nector provides electrical isolation fromthe rest of the world. The printed circuit board (Figure 3)has a ‘prototyping’ area to provideextra space for user applications, inaddition to the space on the MSC1210board. Several spare signal lines areavailable in the leftmost row of the pro-totyping area (see Figure 2). Two extraLEDs and a pushbutton switch arealso placed on the LAN board. The

13

control and regulationvia the Internetserver

The Elektor Electronics Micro Web-server is a full-fledged node for Inter-net traffic, despite its quite modest

dimensions and complexity. It con-sists of a microcontroller board

with a network interface.Thanks to its compact con-

struction and the versatil-ity of the microcontroller

board, the Micro Web-server is an ideal

choice for measure-ment and controlapplications. Nat-urally, the factthat it can beread and oper-ated from any-where in theworld via theInternet is amajor bonus.Despite theseunprecedentedfeatures, then e c e s s a r yhardware isactually mini-

mal. In principle,two ICs are all

you need for acomplete web-

server. To avoid anymisunderstanding,

this is not some kind ofdemo or prototype, but a

fully functional devicesuitable for industrial appli-

cations, and its potential usesextend far beyond what we can

describe here.

Basic designThe underlying technology is rathercomplex. Consequently, in this articlewe must omit a large number of inter-

Micro Webserver • 61 Elektor blockbusters

Page 62: E-book-15-ElektorBlockbusters-uk

elektor electronics - 7-8/200414

Figure 1. The MSC1210 board with the network extension: a powerful pair!

Figure 2. The network card is built around the CS8900 network IC.

T1

HALO

11

10

14

15

16

8

7

6

9

3

2

1

K3

RX-

TX+

TX-

RX+

1

2

3

4

5

6

7

8

RJ45 LAN

C2

100n

C1

100n

C3

68p

R1

10

0

R2

24 9

R3

24 9

C7

100n

C8

100n

C9

100n

C4

100n

C5

100n

C6

100n

C10

100n

U+

R5

4k

7

R4

4k

99

X1

20MHz

R6

1k

R7

1k

D2D1

LANACTIVITY

LINKPULSES

AD0

AD1

AD2

AD3

AD4

AD5

AD6

AD7

AD0

AD1

AD2

AD3

AD4

AD5

AD6

AD7

ADR00

ADR01

ADR02

ADR03

ADR01

ADR02

ADR03

ADR00

R8

1k

R9

1k

D4 D3

USER

R10

1k

S1

CHIPSEL

IOCHRDY

REFRESH

MEMCS16

CS8900

DV

SS

1A

DV

SS

3A

DMACK0

DMACK1

DMACK2IOCS16

DMARQ2

DMARQ1

DMARQ0

SLEEP

DV

SS

1

DV

DD

1

DV

SS

2

DV

SS

3

DV

SS

4

AV

SS

0

AV

SS

1

AV

SS

2

AV

SS

3

AV

SS

4

DV

DD

2

DV

DD

3

DV

DD

4

AV

DD

1

AV

DD

2

AV

DD

3

RESET

CSOUT

XTAL1

XTAL1

IC1

SD15

SD14

SD13

SD12

SD11

SD10

SA10

SA11

SA12

SA13

SA14

SA15

SA16

SA17

SA18

SA19

TEST

SBHE

MEMR

MEMW

LINK

TXD+

TXD-

RXD+

RXD+

ELCS

EEDO

EEDI

EECS

EESK

IRQ3

IRQ2

IRQ1

IRQ0

RES

SD9

SD8

SD7

SD6

SD5

SD4

SD3

SD2

SD1

SD0

SA0

SA1

SA2

SA3

SA4

SA5

SA6

SA7

SA8

SA9

AEN

IOW

IOR

DO+

DO–

DI+

D1–

CI+

CI–

LAN100

HC1

10 23 55 57 70 89 86 94 96

22 56 69 90 85 95

16

14

12

18

19

20

21

24

25

26

27

74

73

72

71

68

67

66

65

37

38

39

40

41

42

43

44

45

46

47

48

50

51

52

53

54

58

59

60

63

75

62

61

76

36

64

49

29

28

34

33

83

84

79

80

81

82

99

78

87

88

91

92

17

35

30

31

32

11

13

15

77

93

97

98

9

8 1

7

2

5

6

3

4

USER

USER PAD

VC

C4

DG

ND

6

INT

1

INT

0

PO

RT

1_6

PO

RT

1_5

PO

RT

1_1

PO

RT

1_0

VIN_D2

DGND2

DGND3

DGND4

DGND5

INT1

INT0

VCC1

VCC2

VCC3

P37

P36

P17

P16

P15

P11

P10

P00

P01

P02

P03

P04

P05

PO6

P07

ALE

P27

P26

P25

P24

P23

P22

P21

P20

K1

Peripheral Bus

P1

1

P1

0

USERLED0LED1

RD

WR

INT1

INT0

NET_RES

P16

P1

5

P15

P11

P10

ADR15

P1

6

INT

0

INT

1

ADDRESSBUS

BUSDATA-

LAN RESET(ACTIVE HIGH)

044026 - 11

CS

DM

AL

ED

AU

I10

BT

INT

E2P

RO

M

TG43-1406N

Micro Webserver • 62 Elektor blockbusters

Page 63: E-book-15-ElektorBlockbusters-uk

placement of the connector for the linkto the ‘motherboard’ allows the exten-sion card to be located next to themotherboard or underneath it. In thelatter case, the two boards can sand-wiched together using standoffbushes.Although the design of this project isespecially simple, there is one thingthat must be mentioned. The currentconsumption of the LAN IC is100–120 mA, which is relatively highcompared with the current drawn bythe microcontroller. The 5-V supplyvoltage is taken from the MSC1210board. To prevent the voltage regulatoron that board from becoming over-heated, we strongly recommend thatthe entire circuit be powered from avoltage of 7.5 to 9 V, but definitely nohigher than this.

OnlineThere’s actually not much more to sayabout the hardware. Configuring theboard is fully described in the text box.Once you’ve gotten the server ‘up’, youcan start testing.This is where things start to get inter-esting. To start off, simply connect theboard to the network. LED D2 will becontinuously on if an Ethernet signal isdetected. This is a promising start, butthe real test comes next. It consists oftrying to ‘ping’ the server using theWindows Command Prompt window(DOS command window). On a PC con-nected to the network, type the follow-ing command in the command line:ping 192.168.1.156(of course, the IP address here must bethe address previously assigned to the

Webserver). LED D1 should start blink-ing as an indication that data is beingtransferred via the Ethernet, and areply from the server should appear inthe command win-dow.Ping is a simple pro-tocol that allows afew bytes to betransmitted andwaits for an ‘echo’.It’s a really handyway to quickly checka network connec-tion.If the ping test is OK,you can then accessthe webserver usinga web browser. In thebrowser window,enter the followingaddress:

http://192.168.1.156(use the address that has previouslybeen assigned to the webserver). Andthat’s it: what you see next comes fromthat little board (see Figure 5).In the terminal download window, youcan also see which page wasrequested.

How it worksWhat actually happened when yourequested the web page? First, youmade a connection to an IP address.Actually, it’s a bit more complicatedthan that: you made a connection to a‘socket’ at a particular address. Asocket is a sort of ‘connector’, in thiscase one that only fits web links. Eachsocket is also assigned a specific port

number. Port 80 is frequently used forwebservers. You can see this in theprogram line SOCKET_SETUP(i,SOCKET_TCP,80,FLAG_PASSIVE_OPEN).

The final parameterhere indicates thatthe socket is passive,which means it waitsfor requests fromclients. The socketsare created in a FORloop. The number ofsockets createddetermines howmany clients can beconnected to theserver at the sametime. As each socketcosts memory, thetotal number is lim-ited. The CS8900A ICused here also has abuffer (approximately

4 kB) for incoming Ethernet packets.That’s not especially large if severalusers want to connect to the server atthe same time, or if large items such asimages are requested. Actually, thisdoesn’t matter all that much, sinceTCP allows the occasional packet toremain unanswered. If necessary, theclient resends unanswered packets onits own initiative.After the sockets have been created,ELM_FLEX.C initiates the A/D con-verter of the microcontroller a few lineslater in the code. For more informationabout the A/D converter, see the com-panion Micro Webserver article ‘Mea-surement and Control via the Internet’in this issue.After this, the program enters a end-less FOR loop. In this loop, poll_web-

7-8/2004 - elektor electronics 15

Automatic online weather station:– temperature– precipitation– lightning detection– wind strength and direction– relative humidity– rain barrel level– light intensity

Web interface for home appliances and fixtures:– refrigerator or freezer temperature monitoring– remote control for coffee machine, central heating or lighting– controlling sun awnings or roller shutters– outside lighting– intruder detection– greenhouse climate control

Access control and registration in combinationwith:– badge readers– light barriers– door openers– RFID tags

Monitoring and controlling machinery:– rpm– voltage and current– temperature– liquid level– flow rate / discharge rate– pressure– valve control– relay control or PWM (servo) control

Terminal for a central database (in combinationwith an LC display and barcode reader)

Applications The Micro Webserver is ideal for the following applications:

Internet references[1] www.wickenhaeuser.com

μC/51 compiler with source code

[2] www.mikrocontroller.info/kabelsalat/Wiring diagram for a null-modem cable

[3] www.ti.com/msc MSC121x home page

[4] groups.yahoo.com/group/TI-MSCMSC121x users group. Definitely worth the effort.Free, but registration is required.

[5] groups.yahoo.com/group/TI-MSC/filesYou can find tools for the MSC121x here, such asthe original TI downloader.

[6] www.cirrus.com/en/pubs/proDatasheet/cs8900a-4.pdfData sheet for the CS8900A network driver

Micro Webserver • 63 Elektor blockbusters

Page 64: E-book-15-ElektorBlockbusters-uk

elektor electronics - 7-8/200416

COMPONENTSLISTResistors (SMD):R1 = 100 , shape 0603R2,R3 = 24 9, shape 0603R4 = 4k 99, 1 %, shape 0603R5,R10 = 4k 7, shape 0603R6-R9 = 1k , shape 0603

Capacitors (SMD):C1,C2,C4-C10 = 100nF, shape 0603,

ceramicC3 = 68pF, shape 0603, ceramic, NP0

Semiconductors (SMD):IC1 = CS8900A-CQ (5 V), shape

TQFP100D1-D4 = chip-LED, shape 0805Recommended colours: D1 green; D2

yellow; D3,D4 red

Miscellaneous:T1 = Ethernet transformer type TG43

(Halo) or ST7010T (Valor), see also ref.[6]

X1 = 20MHz quartz crystal, HC49_SMDcase

K1 = 34-way DIL pinheaderK2 = 8-way pinheaderK3 = RJ45 connector (screened)S1 = mini pushbutton

For software, bare PCBs and fullyassembled boards, see the ‘What you need’ box.

Figure 3. The network card for theMSC1210 board.

Figure 4. The web page sent bythe micro webserver.

Micro Webserver • 64 Elektor blockbusters

Page 65: E-book-15-ElektorBlockbusters-uk

7-8/2004 - elektor electronics 17

The Micro Webserver only works in a TCP/IP network. Just like all other computers in aTCP/IP network, the microcontroller is assigned a unique address, which is its IPaddress. Before you start programming the microcontroller, you must manually specifythis address, since the Micro Webserver does not work with automatic address assign-ment. The default IP address is set to 192.168.1.156. It belongs to a range of address-es that are specifically reserved for networks that are not directly connected to theInternet. Subscribers to ADSL or cable Internet use addresses in this range for their localnetworks. Addresses having the form 10.0.0.x also belong to this category. It may alsobe possible to request a ‘real’ Internet address for your Micro Webserver, but thatdepends on your provider. In any case, you must personally check which address rangeis used in your network and which addresses are available to be assigned to the server.

After choosing an address, you can turn your attention to the necessary programmingsoftware and C files. Part of the required source code (the part that implements theactual webserver) is included with the uC/51-compiler (from version 1.20 onwards). Afully functional demo version of this compiler can be downloaded free of charge fromthe author’s home page (see reference [1]). The only difference between the demo ver-sion and the registered version is that code size for the Micro Webserver is limited to16 kB, but that’s more than enough for this application. Sample source code for initial-ising the webserver and implementing web pages (including several sample pages) isincluded in the package.

After installing the uC compiler, you must first use MakeWiz to create a workspace. InMakeWiz, open the file ...\SRC\MSC1210\ELM_FLEX\ELM_FLEX.MAK. Then changesomething in the text (for example, add your own version number) so that the Savebutton will be enabled. Tick the ‘Write JFE-Workspace File’ check box and save the file(Figure 5).

Now you can start the JFE editor (with thanks to Jens Altmann). In JFE, use ‘OpenWorkspace’ to open the file ...\SRC\MSC1210\ELM_FLEX\ELM_FLEX.WSP. All of the filesbelonging to the project will appear in the editor window. Now you have to specify thepreviously determined IP address in the ELM_FLEX.C file. You can do so in the lineCOMPOSE_IP(my_ip, 192.168.1.156).

A workspace that has been created using MakeWiz causes three special buttons toappear in JFE: ‘MAKE’, ‘RE-MAKE’ and ‘DL.BAT’. The MAKE button causes the project tobe compiled, but it limits processing to the files that have actually been modified. The isthe usual (and fastest) way to generatethe hex file you need for programmingthe microcontroller. RE-MAKE must beused if something not present in theworkspace has been modified, such as aheader file (.h). This command causeseverything to be recompiled. Finally,DL.BAT causes the result to be sent to theMSC board. This actually amounts to sim-ply executing a batch file, to which JFEpasses a parameter. This parameter isalways the name of the target file, whichin this case is ELM_FLEX (with no exten-sion).

The specific command line that initiatesdownloading to the MSC board is statedin the batch file (which is also located inthe project folder). In this case, the com-mand line is download/F%1.hex /X11 /P1 /T/B9600.

Parameter P1 indicates that COM1 of thePC must be used for programming. Thiscan be changed if necessary.

So far, so good: you’ve modified the IPaddress in ELM_FLEX.C, you’ve compiledthe project, and your finger is just itch-ing to press DL.BAT — but hang on a

moment! Before you can download anything to the board, you have to acquire a copyof the original Texas Instruments downloader (Downloader.exe). You can obtain thisfrom the MSC group site at Yahoo (reference [4]), among other places, and it can beplaced in the project folder. If you wish, you can also place it in a more general loca-tion, but in that case you naturally have to specify its new location in DL.BAT.

Be sure to fit jumpers J1 and J2 on the MSC1210 board (J3 must remain open). If J1and J2 are not fitted, the board is protected against resetting and modifying thefirmware via the PC. Finally, you need a null modem cable to connect the board to thePC, but that should be obvious. After you’ve found a place for the downloader, modi-fied DL.BAT if necessary (to specify a different COM port or change the path to thedownloader), connected the board to the proper PC port, and powered up the board,you’re finally ready to click on DL.BAT in JFE.

If everything goes as it should, the MSC1210 board will return a short greeting mes-sage, and if ‘<NET FAILURE>’ is not included in this message, the Ethernet board hasbeen successfully recognised. In addition, one of the red LEDs on the MSC board shouldblink slowly.

After downloading the code, don’t forget to remove jumpers J1 and J2.

Figure 6. With JFE, all files are easily accessible.

Figure 5. Use MakeWiz to store the project.

Configuring the board

Micro Webserver • 65 Elektor blockbusters

Page 66: E-book-15-ElektorBlockbusters-uk

server() is called periodically. As longas the result returned by this call is ‘0’,other (user-written) routines can alsobe executed in this loop. However, it’simportant to ensure that user-writtenextensions do not take up too muchprocessor time, since the webserverwill otherwise become inaccessible.The FlexGate TCP/IP stack works withevents. The Micro Webserver onlyresponds to EVENT_HTTP_REQUEST(page request) andEVENT_SOCKET_IDLETIMER (whichhas a period of approximately 0.5 s). Ifa client wants to access a page, thename is first requested using web-page_name(). Following this, web-page_bind() is used to prepare the cor-

responding page for the reply. Pagesthat are to be externally available mustbe declared in advance as array externcode uchar (see ELM_FLEX.C).This completes the process if therequested page does not contain anydynamic data. However, dynamic datais exactly where the power of thishandy little device lies. An example ofdynamic data is measurement datacoming from the microcontroller board.Such data can easily be incorporatedinto a web page. And in the otherdirection, you can remotely control themicrocontroller outputs via a web page.To find out more about this, see thecompanion article ‘Measurement andControl via the Internet’ in this issue.

Naturally, there’s a lot more we couldsay about the Internet portion of thesoftware (the TCI/IP stack), but thatgoes beyond what we had in mind forthis article. If you want explore thisquestion in more detail, have a look atthe manual for the stack. You’ll find itin the folder ...SRC\FLEXGATE\ thatcomes with the microcontroller com-piler. In addition, Texas Instruments ispresently preparing an applicationnote for this project. The details willappear in due time on the TI website.

(044026-1)

elektor electronics - 7-8/200418

What you needThe Micro Webserver consists of:

– the MSC1210 ‘Precision Measurement Central’ board (seethe July/August 2003 issue of Elektor Electronics)

– the 10-Mbit Ethernet network card (RJ45, twisted pair)

– the μC compiler with the necessary software (ReadersServices order code 044026-11)

– the TI downloader program (Downloader.exe)

The MSC1210 microcontroller card and the associated net-work extension are available from Elektor Electronics.The μC compiler, including all the necessary source code,can be downloaded at no charge from www.wicken-haeuser.com or from the Elektor Electronics website.

The programming software for the MSC board(Downloader.exe) is available from reference [4]. Updateswill be available from the author’s website.

Prices:

– ready-made MSC1210 board: £69.00 (US$112.50)(assembled and tested; Readers Services order code030060-91)

– ready-made network extension for the MSC1210 board:£41.95 (US$73.95) (assembled and tested; ReadersServices order code 044026-91)

– combined package: assembled MSC1210 board, networkextension and all related Elektor Electronics articles ondiskette: only £103.50 (US$184.95) (Readers Servicesorder code 044026-92)

For die-hard DIYers, bare PCBs are also available for theMSC1210 board (Readers Services order code. 030060-11) and the network extension (Readers Services order code044026-11). Note that most of the components are SMDtypes, and some of them are very difficult to obtain as one-offs as well as solder by hand.

About the introductory illustration:This jumble of lines may appear chaotic, but itactually represents a reasonably well-organisedentity: the Internet. This ‘map’ was automaticallygenerated by a program that literally combs theInternet. In its travels, the program also came closeto the server where the Elektor Electronics website ishosted. See www.opte.org.

Indicators:

Cyan: Asia PacificPink: Europe, Middle East, Central Asia, AfrikaYellow: North AmericaBlue: Latin America and CaribbeanRed: RFC1918 IP AddressesBlack: Unknown

Micro Webserver • 66 Elektor blockbusters

Page 67: E-book-15-ElektorBlockbusters-uk

non reflected

reflected

Micro Webserver • 67 Elektor blockbusters

Page 68: E-book-15-ElektorBlockbusters-uk

PROJECTS SDR

14 elektor electronics - 5/2007

Software Defi ned With USB Interface

Burkhard Kainka

SD (software-defi ned) radio receivers use a bare minimum of hardware, relying instead on their software capabilities. This SDR project demonstrates what’s achievable, in this case a multi-purpose receiver covering all bands from 150 kHz to 30 MHz. It’s been optimised for receiving DRM and AM broadcasts but is also suitable for listening in to the world of amateur transmissions.

The designer’s aim for this project was to create a receiver displaying high li-nearity and phase accuracy. Develop-ment was focussed on the characte-ristics that were most important for a top-notch DRM receiver and the end result is a receiver with remarkable in-terference rejection characteristics. Re-ception of DRM stations using DREAM software produced signal-to-noise ratio (S/NR) values of well over 30 dB. The design principle of the receiver gua-rantees an extremely fl at fi lter-curve response. This works out rather well not only for DRM but also for the audio quality of AM broadcasts, which sound almost as good as VHF FM. It’s worth noting too that some transmitters that do not conform to the normal band-widths laid down for medium wave (9 kHz) and shortwave (10 kHz) as rigidly as perhaps they should. Whilst these stations produce no observable sound improvement for listeners using normal receivers (since their IF fi lters limit the bandwidth and in the process the fre-quency response too), this is not the case with SDR, where it’s no problem to select a wider bandwidth at will. It gets even better: in software receivers the fi ne-tuning capabilities of PC deco-der programs give you the capability of determining the desired bandwidth

with notch fi lters to the automatic le-vel control (ALC) settings along with selecting all the usual receive modes from AM by way of DRM and SSB to CW.Further refi nements can be added for SWL (shortwave listening) applica-tions. If for instance you wish to incre-ase the sensitivity on the upper ama-teur bands this is easily arranged by using two switchable antenna inputs and providing an optimised preselector circuit or preamplifi er in one of them. The receiver’s printed circuit board itself provides a pretty basic RF front end, which is nevertheless perfectly adequate for broadcast reception. A long wire antenna of adequate length will lift the strength of signals above atmospheric noise level to ensure you miss virtually nothing.

Hardware requirementsMost SDR programs [1] require the Win-dows XP platform to operate satisfacto-rily. The most important hardware ne-cessary then is an SDR-capable sound card. We have developed a small cir-cuit for testing sound cards, described elsewhere in this issue under the hea-ding ‘Developer Tips’. Without perfor-ming this test fi rst it’s utterly pointless

starting to make the SDR receiver!

All about USBThe receiver is controlled over a USB connection and powered with +5 V in the same way (no additional mains power supply needed). For the USB in-terface in the receiver circuit (Figure 1) we selected the FT232R from our Scot-tish friends at FTDI. This modern USB-to-serial converter works without the need for a quartz crystal, as it is equip-ped with an internal R-C oscillator of adequate stability. The module (IC4) is used here in its ‘bit-bang’ mode along the lines of a fast parallel port. Eight data lines are available for use and the-se can be driven in whichever way we choose. Two of the lines are used as an I²C Bus and control the frequency of the receiver. Three wires connect the input multiplexer to one of up to eight anten-na inputs with and without fi ltering. Two additional inputs serve to control the IF amplifi cation of the receiver. In this way the receiver operates entirely under remote control. Kiss good-bye to all those knobs and controls of bygone radio days…Please pay particular attention to de-coupling the power supply. One rea-son for this is because the USB chip

Elektor blockbusters

Page 69: E-book-15-ElektorBlockbusters-uk

155/2007 - elektor electronics

Radio

CBUS023

RI6

GND

7

CBUS122

RTS3

TXD1

DTR2

CTS11

3V3OUT17

VCCIO4

RXD5

DSR9

DCD10

CBUS213

CBUS314

CBUS412

GND

18

GND

21

TEST26

AGND

25

VCC

20

USBDM16

USBDP15

RESET19

OSCI27

OSCO28

IC4

FT232R

1234

5 6

K1

USB-B connector

GND

C8

10n

GND

L2VCC

C16

100n

L3

C7

100n

GND

3V3

R2 330

R3 330

C1

100n

GND16V

C4

4u7

GND

VSSL7

VSS

16

AVSS6

PDM/OE10

VDD

2

VDD

19

VDDL11VD

D14

AVDD4

VCXO/WP17

SCL13

SDA5

XIN

1

XOUT

20

CLOCK18

CLOCK29

CLOCK312

CLOCK415

CLOCK518

CLOCK63

IC3

CY27EE16ZE

3V3

GND

GND

X1

10MHz

C12

10p

C13

10p

3

D2 5

6

R1

S4

C

IC1A

11

D12 9

8

R13

S10

C

IC1B

14

7IC1C

L1

10uHC2

100n 16V

C3

4u7

GNDGND

VCC

GND

VCC

VCC

VCC

VCC

C5

100n

C6

100n

12

13 IC2A

43

5IC2B

89

6IC2C

1110

12 IC2D

14

7

IC2E

I1

I2

I3

Q1

Q2

Q3

A013

A114

A215

A312

A41

A55

A62

A74

INH6

COM3

VEE

7

GND

8

A11

B10

C9

VCC

16

IC6

74HC4051

C21

100n

GND

VCC_HF

GND

L6

2200uH

GND

C23

100nC25

100nC29220p

L5

47uH

R12470

GNDC32

100n

C31

100p

R15

470

GND

C38

100nR25

4.7

R241k

GND

C36

100n

TEST_CLK

TEST_CLK

T1

BF245

C30

100nR16

1M

R17

100k

R18

470

GND

C26

100n

GND

L4

10uH

VCC_HF

Q_SWQ_SW_N

R19100

I_SWI_SW_N

R7100

C19

100n

R610k

C22

2n2

GND

C24

2n2

R9

4k7

C27

100n

C33

100n

R1410k

C35

2n2

GND

C37

2n2

R21

4k7

C39

100n

5

67IC5B

810

9IC5C

1412

13

IC5D

R5100k

R13100k

R8100k

R10

10k

C28

100n

GND

2

31IC5A

R20100k

R22

10k

C40

100n

GND

4

11IC5E

1 2

13

IC7A

4 3

5

IC7B

8 9

6

IC7C

11 10

12

IC7D

14

7IC7E

R1127k

R2327k

C20

100n

C34

100n

GND

K2

GND

VCC

R1

100

16V

C9

4u7

C10

100n

C11

100n

R4100

VCC

16V

C14

470u16V

C15

4u7

C17

100n

C18

10n

VCC_HF

GND

PC1

K3

GND

GND

ANT

070039 - 11

IC1 = 74AC74IC2 = 74HC4066IC5 = TL084CNIC7 = 74HC4066

Figure 1. Diagram of the receiver circuit, which in fact comprises just a tuning oscillator and a mixer.

Elektor blockbusters

Page 70: E-book-15-ElektorBlockbusters-uk

PROJECTS SDR

16 elektor electronics - 5/2007

FT232R operates internally at the same frequency range that we are receiving through the antenna downlead and we don’t want any of this RF to leak across from one stage to another. That said, the decoupling within the chip itself is remarkably good and the residual RF on the control port lines is barely detectible. Consequently we can cont-rol the HC4051 RF input multiplexer di-rect from the control port lines, without traces of the processor clock appearing in the wanted signal region.Using its built-in 3.3 V voltage regu-lator, the FT232R provides the opera-ting supply for the programmable clo-ck generator CY27EE16ZE, avoiding the need for an additional voltage re-gulator. The rest of the circuit (Figure 1) operates exclusively on 5 V. Sever-al different smoothed and fi ltered vol-tages are produced, to guarantee good RF decoupling on one hand and to en-sure suppression of audio frequency interference on the other. This is parti-cularly crucial at the RF input stage of the receiver, from which the signal is fed via the mixer to the IF circuitry. For this reason a large electrolytic is provi-ded at this point (VCC_HF) to ensure proper ‘peace and quiet’.

Programmable VFOThe SDR calls for an oscillator frequen-cy running four times higher than that of the signal received, in order that the necessary phase fi ltering can be divi-ded by four. If we are aiming to receive signals up to 30 MHz, then the oscilla-tor needs to run right up to 120 MHz. DDS oscillators are very popular in HF projects today but at 120 MHz a DDS is dearer, more power-thirsty and far less controllable. Accordingly we shall look away from DDS oscillators and use a programmable clock oscillator with internal PLL here. Many Elektor Elec-tronics readers will remember the CY-27EE16ZE back from the February 2005 issue. This clock oscillator, developed specially for digital applications, per-forms equally well in RF circuitry. The frequency resolution does not quite match that of a DDS but the phase ac-curacy of the output signal achieves comparable results. Restricting pow-er consumption to a relatively modest amount is important with this project, since we must not draw too much cur-rent from the USB port.The chip is programmed over the I²C-Bus using lines SCL and SDA. The in-ternal VCO operates in the frequency range 100 to 400 MHz, stabilised by

An additional input (PC1) can be se-lected if you wish to connect external tuned input circuits or preamplifi ers. Fi-nally three more inputs are provided for future developments. The input fi lters on the printed circuit board are good to be getting on with and are certain-ly adequate for most applications. You can of course introduce steep low-pass fi ltering ahead of the fi lters provided if you want to be certain of blocking out overtone mixing in every possib-le situation. Or you might choose to fi t different resonant circuits, selected by input switching. The particular input that is active at any given time is connected to the common output COM (pin 3). Coupling capacitors are provided either side of the switch. A bias voltage of about 2.5 V is provided to the switch from the source connection of the BF245 via a 1-megohm resistor. This eliminates any distortion from large input signals that might arise when signals are limited by the protection diodes on the analo-gue inputs to the ICs. Input A7 delivers a calibration signal from Output 3 (Test-Clk) of the pro-grammable crystal oscillator. The oscil-lator produces a square-wave signal of 3.3 V peak-to-peak at 5 MHz. A signal voltage of around 5 mV at 5 MHz is produced at the voltage divider, cor-responding to a signal strength of S9 + 40 dB. This enables the fi eld strength meter created in software to be calibra-ted without any further expenditure. JFET BF245 on the output of the input multiplexer serves as an impedance transformer. This provides a relative-ly high impedance termination of 100 k for the RF signal, enabling for in-stance a high-Q resonant circuit to be connected even to input In2. At the low-impedance output of the source follower we arrange to have a voltage of circa 2.5 V, fed via the mixer and the following op-amp all the way to the output. It is important that no audio frequency signal remnants appear at the source connection and for this rea-son the ‘critical’ supply Vcc_HF is also fi ltered very thoroughly. The FET itself provides additional decoupling of the supply voltage, but we don’t want any signal escaping from the Gate either that might fall in the IF region below 24 kHz. This is why an RF choke is con-nected directly to the antenna input, to shunt for instance any 50 Hz mains hum signal.Leading off from the Source connection are two 100- resistors that go to the two mixers for the I and the Q signals.

means of the 10-MHz crystal and a PLL. Its output signal then goes via co-unters to the desired outputs. Here we select the clock output Clock5, where a VFO signal between 600 kHz and 120 MHz is available for further processing in the 74AC74 counter.The principle of the I-Q mixer has been described already in Elektor Electro-nics 12/2006. A two-stage mixer is cre-ated here from a total of four analogue switches inside an HC4066 IC. This is controlled by two phase-shifted oscil-lator signals, which themselves are produced with a 74HC74 counter. Sup-posing the programmable clock oscil-lator produces 24 MHz, then the mixer would need a drive of 6 MHz. The re-ceiver would in this case operate in a region of around ±24 kHz either side of the centre frequency of 6 MHz.Vital here is a phase shift of exactly 90 degrees between the two oscillator si-gnals. Any deviation will lead to redu-ced suppression of the image frequen-cies. A 74HC4053 or 74HC4052 integra-ted changeover switch device would not make a good choice for the analo-gue switch because the signal transit delays in the internal decoders would then cause different phase errors to appear in every frequency range. Our chosen solution using the rather more basic switches of an HC4066 retains all four phases in sync. Since the 74AC74 counter is confi gured as a synchronous counter we would not expect to fi nd any phase errors here either. In fact the receiver displays image frequency sup-pression of around 40 dB up to 15 MHz or so, although this value decreases beyond about 20 MHz (which we can tolerate given that these frequencies are not so heavily occupied).

Signal processingThe receiver is provided with several inputs, selected by the 74HC4051 input multiplexer (IC6). The antenna input ANT is fed by way of fi lters to the fi rst three inputs. The fi rst switch setting (wideband) uses only one input choke (L6), which shunts any audio frequen-cy signals at the input to ground. In the second position (Medium Wave) there is a low-pass fi lter with a boundary fre-quency of 1.6 MHz, using resistor R12 to attenuate excessive resonance. This fi lter suppresses interference to medi-um wave reception from overtone mi-xing with stations in the short wave range. The third position makes use of a simple R-C high-pass fi lter to attenu-ate strong medium wave signals.

Elektor blockbusters

Page 71: E-book-15-ElektorBlockbusters-uk

175/2007 - elektor electronics

They improve the symmetry of the mi-xers, the ‘on’ resistances of which let through a certain amount of leakage. The mixers themselves are HC4066 analogue switch ICs ganged as chan-geover switches. The voltage of these too is set around 2.5 V, allowing them to be controlled without overdriving up to about 5 V peak-to-peak.The IF amplifi er consists of two exact-

Figure 2. The SDR receiver board.

COMPONENTSLISTResistorsR1,R7,R19 = 100R2,R3 = 330R4 = 100R5,R8,R13,R17,R20 = 100kR6,R10,R14,R22 = 10kR9,R21 = 4k 7R11,R23 = 27kR12,R15,R18 = 470R16 = 1MR24 = 1kR25 = 4 7

CapacitorsC1,C2,C5,C6,C7,C10,C11,C16,C17,C1

9,C20,C21,C25-C28,C30,C32,C33,C34,C36,C38,C39,C40 = 100nF

C3,C4,C9,C15 = 4μF7 16V radialC8,C18 = 10nFC12,C13 = 10pFC14 = 470μF 16V radialC22,C24,C35,C37 = 2nF2C29 = 220pFC31 = 100pF

SemiconductorsIC1 = 74AC74IC2,IC7 = 74HC4066IC3 = CY27EE16 (Cypress)IC4 = FT232R (FTDI)IC5 = TL084CN with socket (see text)IC6 = 74HC4051T1 = BF245

InductorsL1-L4 = 10μHL5 = 47μHL6 = 2.2mH

MiscellaneousK1 = USB-B socket, PCB mountK2 = stereo jack socket, 3.5mm, PCB

mountK3 = 2-way PCB terminal block, lead

pitch 5mmPC1 = solder pinX1 = 10MHz quartz crystalReady-populated and tested PCB, order

code 070039-91Project software, free download

070039-11Supplementary document, free downloadPCB, bare, ref. 070039-1 from www.thep-

cbshop.com

Elektor blockbusters

Page 72: E-book-15-ElektorBlockbusters-uk

PROJECTS SDR

18 elektor electronics - 5/2007

ly equal branches that together pro-duce an attenuation of up to 40 dB at all times. When you are using 5 V sup-plies, the gain bandwidth (GBW) of the selected op-amp is important, in order to achieve tenfold amplifi cation without phase errors for signals around 20 kHz. In the author’s test samples a TL084 turned out to be adequate. If you provide a socket for IC5 you will be able to try other, faster op-amps.The input stage works as a differential amplifi er. In dimensioning the resistors what we are looking for is not the best common-mode suppression but rather an input resistance that’s as equal as possible across the inverting and non-inverting inputs. Tests show that good phase accuracy (and consequently high image-frequency suppression) depend on equal impedance existing on all four phases of the mixer. The input impe-dance amounts to around 5 k at all of the inputs. Note the load resistance of 4.7 k on the non-inverting input as opposed to 10 k on the inverting one. This is correct, since signal transit on this input gets dispersed in exact an-tiphase by inverse feedback, halving the input resistance to 5 k . In this way both inputs offer the same input resistance as close as matters.The 2.2 nF capacitors together with the mixer’s internal resistance and the

tion) chips FT232RL and CY27EE16, which unfortunately are available only in SSOP case format with a pin spa-cing of 0.65 mm. Figure 3 shows the laboratory prototype PCB with compo-nents fi tted.The best way to begin is by soldering the two surface-mount device (SMD) chips in place. It pays to start fi rst at the four corners, before soldering all the other pins generously. Superfl uous solder can be removed with desolder braid, followed by thorough checking with a magnifying glass to avoid un-welcome surprises later on.The components with wire leads will present no diffi culty. The circuit does not call for any special RF componen-ts or test points. Capacitors C12 and C13 should not be fi tted initially. The CY27EE16 has presettable internal capacitors that should enable you to achieve a frequency of exactly 10 MHz without diffi culty. C12 and C13 will be needed only if the crystal used requires greater loading capacity. Once all construction is complete you need to make a quick round-up with a multimeter checking for any short cir-cuits around the USB connections, as you certainly don’t want to damage the PC.

100 series resistors form simple low-pass fi lters with a limiting frequency of over 100 kHz, so as to keep remnants of RF well away from the audio frequen-cy stages. The limiting frequency lies far above the transfer frequency range, meaning that capacitor tolerances do not produce any discernible phase er-rors. You can use even ceramic disc ca-pacitors here. Tolerances between 10 and 20 % are not a problem with any of the capacitors in the signal path acting as high-pass elements with a limiting frequency of around 300 Hz.The fi nal stage has a tenfold gain (20 dB), which can, however, be reduced to unity gain by the analogue switches. A total of three attenuation steps are provided: 0 dB, –10 dB und –20 dB. To avoid it being driven too hard, the gain can be reduced in software. As the receiver’s input displays high re-sistance to being overdriven the atte-nuator is placed in the fi nal stage, so as to prevent overdriving of the output. This corresponds to gain control in an IF amplifi er.

ConstructionThe printed circuit board shown in Fi-gure 2 uses standard wire-ended com-ponents as far as possible, with the ex-ception of the LSI (large scale integra-

Figure 3. This lab sample board is not quite equivalent to the production version supplied through the Elektor SHOP.

Elektor blockbusters

Page 73: E-book-15-ElektorBlockbusters-uk

195/2007 - elektor electronics

Hook-up and alignment

Before connecting the receiver to the computer’s USB port for the fi rst time you will need to install the driver soft-ware for the FT232R. You can fi nd this on the manufacturer’s website (www.ftdichip.com/FTDrivers.htm) or alter-natively in the software download for this article. Installation using CDM_Setup.exe automatically removes any traces of older FTDI drivers on your computer. After this has been done Windows will fi nd the correct driver automatically as soon as the receiver is connected. The same process pro-vides the PC automatically with an additional virtual COM-port interface. For this you do not even need to know which COM number is allocated to the device, as it effectively sets up its own direct connection to the FT232R. FT-D2XX.dll controls the eight data lines of the chip as for a parallel port, eli-minating at the same time all timing problems. To save time the multiple le-vel changes involved in controlling the I2C bus are loaded conveniently into a buffer and then fed out to the data lines in short order. The program Elek-torSDR.exe enables you to control all functions of the receiver (Figure 4) and can be found in the download archive as an executable fi le together with the Delphi source code. Also available for download is a supplementary .pdf do-cument that describes initialisation and commissioning.

Decoder softwareNearly all signifi cant characteristics of the receiver are determined by settings in the decoder software on your PC. As the survey in [1] indicates, there are a number of different programs to choose from. You could perform your fi rst test with SDRadio [2] for example. After this you will discover additional possibili-ties in DREAM [3] or G8JCFSDR [4].Whichever program you select, it’s vital to set up the sound card correctly (this is described in the supplementary do-cument). Information on the programs can be found on the relevant Web pages and in the Elektor Electronics articles listed below. Further advice may be found on the author’s home-page (www.b-kainka.de) and will ap-pear also in due course on the project page at www.elektor-electronics.co.uk and, if necessary, in the Forum on the same website.

(070039-1)

Figure 4. Elektor Electronics SDR Tuning control program.

Figure 5. Four AM stations in tuning range spectrum, as displayed by the SDRadio program.

Web links:[1] www.nti-online.de/diraboxsdr.htm

[2] www.sdradio.org/

[3] http://sourceforge.net/projects/drm

[4] www.g8jcf.dyndns.org/

Literature:Burkhard Kainka: DREAM Team –Software for DRM reception, Elektor Electronics 4/2004, pp. 20 ff.

Wolfgang Hartmann and Burkhard Kainka: ‘Radio listening with Matlab—Diorama software DRM receiver’, Elektor Electronics 4/2006, pp. 76 ff.

Burkhard Kainka: I-Q: a highly intelligent approach to quality radio, Elektor Electronics 12/2006, pp. 38 ff.

Elektor blockbusters

Page 74: E-book-15-ElektorBlockbusters-uk

TECHNOLOGY WIRELESS

44 elektor electronics - 3/2007

WirelessiDwaRF: a network

Dr. Erik Lins and Christian Meinhardt

iDwaRF brings together a Cypress WirelessUSB transceiver and an Atmel AVR microcontroller to create a networkable 2.4 GHz radio module featuring a free protocol stack and development environment.

Besides standard applications such as mobile radio, WLAN and Bluetooth, highly-integrated low power radio de-vices open up many new possibilities,

including wireless sensor networks and even radio-controlled robotic foot-ball teams able to orchestrate an off-side trap in the blink of an eye! And, with iDwaRF, we can do all this with-out complex protocols or licensing problems.

An alternative to ZigBeeFor wireless sensor network applica-tions ZigBee [1] is often the protocol of choice. The protocol is relatively com-plicated, and only members of the Zig-Bee Alliance are permitted to use it in commercial products. Cypress [2] offers a simpler alternative in its WirelessUSB technology [3]. The devices are cheap and the radio protocol makes only mod-erate demands in terms of hardware and memory in the microcontroller. WirelessUSB supports wireless many-to-one links and is thus ideal for use in wireless sensor networks. The protocol details are freely available and can be used without restriction in combina-tion with Cypress radio chips.

iDwaRF

The iDwaRF-Net software that accom-panies the iDwaRF-168 module (Fig-ure 1) is a port of the Cypress Wire-lessUSB protocol to the ATmega168 AVR-family microcontroller [4]. The iDwaRF-168 module can be freely re-programmed and can equally well play the role of hub or sensor in a many-to-one wireless sensor network. It is easy to add extra application-specifi c functions.

WirelessUSB operates in the 2.4 GHz ISM band. Each WirelessUSB radio net-work uses a selection from a total of 79 channels: even when multiple Wireles-sUSB devices are operating simultane-ously the protocol will be able to fi nd a free channel to use.Transmission uses a robust DSSS (di-rect sequence spread spectrum) modu-lation scheme [5]. Even at a 10 % error rate the data can still be received cor-rectly, and if there should be long-term interference the protocol provides for

Figure 1. The iDwaRF radio module with 2.4 GHz WirelessUSB transceiver and ATmega168 AVR microcontroller.

Wireless USB in miniature • 74 Elektor blockbusters

Page 75: E-book-15-ElektorBlockbusters-uk

453/2007 - elektor electronics

USB in miniatureable WirelessUSB radio module

an automatic change of channel. Like Bluetooth, WirelessUSB comes in short-range (up to 10 m) and long-range (up to 50 m) versions. The latter is used in the iDwaRF-168 module.

Hub and sensorsAn iDwaRF module programmed to act as a hub forms the centre point of a star-topology many-to-one radio network, which can consist of many sensors (Figure 2). Normally the hub operates continuously and can be con-nected to a PC or another microcon-troller, acting as a host, using a se-rial link. For simple applications the iDwaRF module itself can be pro-grammed to carry out the required dedicated host functions.

Figure 2. The star-topology radio network consists of a hub and several sensors.

RF

IN46

RFOUT5

X13

38

X13IN35

X13OUT26

/PD33

/RE

SE

T14

PACTL34

DIO

20D

IOV

AL

19

IRQ

21

MO

SI

23

MIS

O24

SCK25

/SS

22

VCC6

VCC9

VC

C16

VCC28

VCC29

VCC32

VC

C41

VC

C42

VC

C44

VC

C45

GN

D13 E

NC1

NC2

NC3

NC4

NC7

NC8

NC10

NC11

NC12

NC

15

NC

17

NC

18

NC27

NC30

NC31

NC36

NC

37

NC

39N

C40

NC

43

NC

47N

C48

U1

CYWUSB6935-48LFX

1ANT2

ANT_WIGGLE_L

1

ANT1

ANT_WIGGLE_R

ISOMISOM

OSIMOSIM

SCK

SCK

SS/SS/

/PD

/INT0

/INT0

/WUSBRESET

/WUSBRESET

1234567891011121314

CON1

MIS

O

VC

C

SC

K

MO

SI

/RE

SE

T

GN

D

PO

RT

1

PO

RT

0

PO

RT

3

PO

RT

2

PO

RT

1

PO

RT

0

PO

RT

0

PO

RT

7

PO

RT

7

PO

RT

5

PO

RT

4

PORT6INT1 OC2B PD3

1

XCK T0 PD42

GND3

VCC4

GND5

VCC6

XTAL1 TOSC1 PB67

XTAL2 TOSC2 PB78

OC

0B T

1 P

D5

9

OC

0A A

IN0

PD

610

AIN

1 P

D7

11

CL

KO

ICP

PB

012

OC

1A P

B1

13

/SS

OC

1B P

B2

14

MO

SI O

C2

PB

315

MIS

O P

B4

16

PB5 SCK17

AVCC18

ADC619

AREF20

GND21

ADC722

PC0 ADC023

PC1 ADC124

PC

2 A

DC

225

PC

3 A

DC

326

PC

4 A

DC

4 S

DA

27P

C5

AD

C5

SC

L28

PC

6 /R

ES

ET

29P

D0

RX

D30

PD

1 T

XD

31P

D2

INT

032

U2ATmega168-20MI

PORT6

PO

RT

0

PO

RT

1

PO

RT

2

PO

RT

3

PO

RT

4

PO

RT

5

PO

RT

6

PO

RT

7

X13OUT

C1

1p8

C6

100n

C7

100n

C8

100n

C9

100n

C11

100n

C10

100n

VCCVCC

VCC

C2

NOLOAD

C4

10p

L1

3nH9

X1

13MHz

C12

100n

C14

22p

050402 - 11

X2

xxMHz

C13

22p

VCC

VCC

C15

100n

C5

10u

/RESET

VCC

VCC

Figure 3. Circuit diagram of the iDwaRF module.

Wireless USB in miniature • 75 Elektor blockbusters

Page 76: E-book-15-ElektorBlockbusters-uk

TECHNOLOGY WIRELESS

46 elektor electronics - 3/2007

A sensor unit consists of a suitably-programmed iDwaRF module with sensors attached. To save power we use the AVR’s internal RC oscillator. Also, the module is only activated at intervals (as determined by the ‘bea-con time’). Communications are initi-ated by the sensor and terminated by the hub; a reverse channel (transmit-ting information from hub to sensor) is also available.

Module printed circuit boardFigure 3 shows the circuit diagram of the iDwaRF-168 module. The Cy-press CYWUSB6935-LR transceiver is connected to an ATmega168 micro-controller over SPI, using the MISO, MOSI, SCK and /SS (chip select) sig-nals. An interrupt signal (/INT0) from the radio device indicates the recep-tion of data. The ATmega168 can put the radio chip into power-down mode using an I/O pin connected to the /PD signal, and can reset it using the /WUSBRESET signal. The radio chip needs just an external 13 MHz crystal (X1) and decoupling capacitors (C6 to C11) for operation. The transmit and receive antennas are separate from one another and integrated directly into the circuit board layout as mean-der lines (Figure 4). Having separate antennas gives greater range and sim-

Figure 4. The iDwaRF printed circuit board includes a printed antenna.

MISO

VCC

SCK

MOSI

RST

GND

PORT0

PORT1

PORT2

PORT3

PORT4

PORT5

PORT6

PORT7

GND

RST

MOSI

SCK

VCC

MISO

REGIN7

VDD6

GND3

VBUS8

D-5

D+4

RST9

SUSPEND12

SUSPEND11

RI2

DCD1

DTR28

DSR27

TXD26

RXD25

RTS24

CTS23

NC

10N

C13

NC

14N

C15

NC

16N

C17

NC

18N

C19

NC

20N

C21

NC

22

GN

D29

GN

D30

U2CP2102

D+

D-

1

2

3

4

5

9 876

CON2

USBMINIB

1

2

3

4

5

6

CON3

1

2

3

4

5

6

7

8

9

10

11

12

13

14

CON1

BYPSS1

IN4

GN

D3

OUT5

SNS6

ERR7

SH

D8

NC2

U1

LP2989IM-3.3C2see text

**

10n

C3

10u

050402 - 12

C1

10u

VCC

VbusR1

1k5

green

LED1

SW1

VCC

USB to UARTBridge C5

100n

C4

1u

Vbus

Figure 5. Circuit of the hub board.Figure 6. The iDwaRF module is mounted

on the hub printed circuit board.

1

2

BATT

Battery Clip 3xAAA 2479

PORT6

SI1

SCK2

RST3

CS4

WP5

VC

C6

GN

D7

SO8

U3

AT45DB081D-SSU

SDA1

SCL2

O.S.3

GN

D4

A25

A16

A07V

CC

8U2

LM75

SCK

OSIMISOM

RST

PORT2

PORT3

PORT0

PORT7

PORT1

MISO

VCC

SCK

MOSI

RST

GND

PORT0

PORT1

PORT2

PORT3

PORT4

PORT5

PORT6

PORT7

GND

RST

MOSI

SCK

VCC

MISO1

2

3

4

5

6

CON3

1

2

3

4

5

6

7

8

9

10

11

12

13

14

CON1

R1

1k5

green

LED1

VCC

SW1

BYPSS1

IN4

GN

D3

OUT5

SNS6

ERR7

SH

D8

NC2

U1

LP2989IM-3.3C2

10n

C3

10u

C1

10u

VCC

MISO

VCC

SCK

MOSI

RST

GND

PORT0

PORT1

PORT2

PORT3

PORT4

PORT5

PORT6

PORT7

1

2

3

4

5

6

7

8

9

10

11

12

13

14

CON2

R5

1M

R6

1M

R2

1k5

R3

1k5

R4

1k5

C5

100n

C4

100n

VCC

VCC

J2

LDR

R7

4k7

J1

Vbatt

VbattVCC

PORT5

PORT4

PORT7VCC

050402 - 13

see text

*

*

*

Figure 7. Circuit diagram of the node board with temperature and light sensors.

Wireless USB in miniature • 76 Elektor blockbusters

Page 77: E-book-15-ElektorBlockbusters-uk

473/2007 - elektor electronics

plifi es matching (L1, C1 and C4). The antennas are laid out in the manner recommended by Cypress.

The microcontroller is equipped with a crystal in an HC49 package, and so it is straightforward to change it for a different frequency. As supplied the ATmega168 is confi gured to use its in-ternal RC oscillator.

A 14-way header (CON1) brings out the ISP (in-system programming) signals of the ATmega168 (MOSI, MISO, SCK and /RST), power, and eight spare I/O port pins. Some of the header pins are connected to more than one signal on the microcontrol-ler to allow as many as possible of the peripheral functions of the device to be used. This means that you must ensure that any two microcontroller pins that are connected to the same header pin are never simultaneously confi gured as outputs, or damage to the microcontroller may result. Ta-ble 1 shows the CON1 pinout and signals in detail.

Application boardsIn the simplest wireless network sce-nario one iDwaRF-168 module is pro-grammed as a hub and one or more modules are programmed as sensors. It is of course necessary to build the necessary interfaces to the sensors themselves and connect them to the modules. To simplify building such systems we have developed three ap-plication boards, to each of which can be attached an iDwaRF-168 module: a hub board, a node board and a proto-typing board.

The hub board supports the iDwaRF module with a USB interface (the CP2102), a 3.3 V LDO voltage regula-tor, button and LED (Figure 5).

The node board is used to make a sen-sor unit using an iDwaRF module. The circuit (Figure 6) includes an LDR as a light sensor, an LM75 temperature sensor, an (optional) AT45DB801D seri-al fl ash memory, a button and an LED. Power is provided by three AAA cells and a 3.3 V LDO voltage regulator.

The two printed circuit boards (Fig-ure 7 and Figure 8) are chiefl y popu-lated using SMD components. Figure 9shows the boards with iDwaRF-168 modules fi tted.

Table 1. CON1 connection groupsiDwaRF-168 CON1(port pin)

First connection(ATmega168 pin number)

Second connection(ATmega168 pin number)

Third connection(ATmega168 pin number)

PORT0 OC0B / T1 / PD5 (9) AIN1 / PD7 (11) ADC3 / PC3 (26)

PORT1 OC0A / AIN0 / PD6 (10) ADC2 / PC2 (25) -

PORT2 SCL / ADC5 / PC5 (28) - -

PORT3 SDA / ADC4 / PC4 (27) - -

PORT4 TXD / PD1 (31) - -

PORT5 RXD / PD0 (30) - -

PORT6 INT1 / OC2B / PD3 (1) XCK / T0 / PD4 (2) -

PORT7 CLKO / ICP / PB0 (12) OC1A / PB1 (13) -

Figure 8. The node board converts the iDwaRF module into a complete sensor unit.

Figure 9. Node board (rear) and hub board (front) with iDwaRF radio modules fi tted.

Wireless USB in miniature • 77 Elektor blockbusters

Page 78: E-book-15-ElektorBlockbusters-uk

TECHNOLOGY WIRELESS

48 elektor electronics - 3/2007

lists for the circuit boards and layouts available for download from the Ele-ktor Electronics website.

SoftwareThe iDwaRF-Net software package [6] includes a library of fi rmware for use in hub and sensor modules with corre-sponding header fi les (in the ‘iDwaRF’ directory), along with a few ancillary functions, for example to support seri-al communications (‘USART’ directory). There are also four example programs which can either be used as they stand or form the basis for dedicated appli-cations. Table 2 gives more details of these example programs.

Each example program consists of hub source code (userMain_hub.c) and sensor source code (userMain_sensor.c). The fi rmware provides the facility to register so-called ‘callback’ func-tions, which the fi rmware calls regu-larly in the course of normal operation. These functions can be used for appli-cation-specifi c code. The most impor-tant callback functions are explained in the text box.

Ready, steady…Assembling the hardware is relatively straightforward. The SMD printed cir-cuit boards (the iDwaRF module, the node board and the hub board) are available as ready-made units (see the ‘Elektor Shop’ pages at the back of this issue). A kit of parts is available for the prototyping board. Separate-ly-ordered iDwaRF-168 modules are supplied unprogrammed and without header or crystal fi tted in order to give the user maximum fl exibility.

The fi rmware for programming a hub or sensor module is freely available [6]. Modules ordered bundled with a

The prototyping board has a gener-ous area for building your own cir-cuits and is suitable for creating more specialised applications using the iDwaRF-168 module. There are SMD pads on the reverse of the board. The only active component in the circuit (Figure 10) is the LDO voltage regula-tor, in a TO-92 or TO-220 package ac-cording to the expected current draw. As well as the regulator and socket to accept the iDwaRF-168 module there is an AVR programming connector, a battery holder and, as an alternative, a socket for a mains adaptor with a reverse polarity protection diode. The printed circuit board (Figure 11) is half-Eurocard sized and can be used in the place of a node board. For rea-sons of space we have made the parts

Table 2. Example programsempty Empty program: framework for new applications.

chat Creates a wireless serial connection between two host PCs, allowing ‘chatting’ between two terminal programs.

tutorialExample program that switches the LEDs on the hub and sensor modules on and off remotely when a button is pressed. The imple-mentation of this example is explained step-by-step in a separate ‘how to’ document (see text box).

terminalThis basic sensor network application supports the components on the node board or iDwaRFSensorBox. Data packets (including battery voltage, potentiometer setting, button state and temperature) from several sensors are displayed in plain ASCII text. The ter-minal program can also send data to individual sensors.

quad_adc This program reads four ADC channels and transmits the readings to the hub at regular intervals.

MISO

VCC

SCK

MOSI

RST

GND

PORT0

PORT1

PORT2

PORT3

PORT4

PORT5

PORT6

PORT7

GN

D

RS

T

MO

SI

SC

K

VC

C

MIS

O1 2 3 4 5 6

K4

1

2

3

4

5

6

7

8

9

10

11

12

13

14

K2

1

2

3

4

5

6

7

8

9

10

11

12

13

14

K3

1

2

BATT

Battery Clip 3xAAA 2479

D1

1N4001

1 3

2LF33CV

IC1LP2950

2

3

1

K1

25V

C1

1u25V

C2

1u

iDwaRF

AVRISP

EXT

VCC

VCC

050402 - 14

SOIC-24

SOT-23/6

SOT-23/6

VCC

Figure 10. Circuit diagram of the prototyping board for dedicated iDwaRF module applications.

Figure 11. The prototyping board has an experimentation area with SMD footprints on the reverse.

Wireless USB in miniature • 78 Elektor blockbusters

Page 79: E-book-15-ElektorBlockbusters-uk

493/2007 - elektor electronics

node or hub board come ready-pro-grammed. A crystal is always required for baud rate generation on the hub board (a 7.3728 MHz crystal is sup-plied as standard), and the microcon-troller must be suitably programmed for crystal operation. The correct val-ues for the ATmega168 with a crys-tal oscillator are: extended byte, 0xF9; high byte, 0xDF; and low byte, 0xFC. It is recommended to use the same values and same crystal frequency for the sensor, and the fi rmware is cur-rently set up to work on this assump-tion. If the frequency is to be changed (using a different crystal or the inter-nal RC oscillator) the relevant #defi ne in the fi rmware must be changed and the code compiled afresh.

The AVR ISP connectors have to be soldered on to the node board and hub board, and the node board also needs to be connected to the battery holder. Finally the iDwaRF module can be fi tted and (in the case of the node board) the batteries inserted. The USB connection on the hub board re-quires the corresponding CP2102 vir-tual COM port driver to be downloaded and installed [6]. Drivers are available for both Windows and Mac OS X. A CP210x module is provided as stand-

ard in current Linux kernels, allowing the iDwaRF module to be used with non-Windows PCs.

The pre-compiled hex fi les [6] for hub and sensor are downloaded using the six-pin AVR ISP connector. Note that the supply voltage for the iDwaRF module on the node and hub boards is only 3.3 V, and so care must be taken

to ensure that the programming adap-tor also works at this voltage. Sim-ple STK200-compatible programming adaptors that connect to the PC’s printer port, which draw power from the target device, do not always work reliably at 3.3 V. Modern USB program-ming adaptors (compatible with the STK500-V2) such as the CrispAVR-USB work without problems.

Table 3. Commands available in ‘terminal’ programCommand Description

rst Restarts the hub fi rmware. All sensors are unregistered and lose their ID codes, and must register again with the hub.

gps Returns an internal Cypress fi rmware state variable.

bonActivates automatic bind mode on the hub. New sensors are probed for using PN code 0 and channel 0. In normal use automatic bind mode is activated.

bof Deactivates automatic bind mode. New sensors can no longer register with the hub.

enuDisplays a list of the currently registered sensors on the hub. The list includes the sensor ID assigned during registration and the unique manufacturing ID stored in the radio chip.

clnCleans up the hub’s list of registered sensors. Sensors which have registered more than once with the hub and which have there-fore been assigned different ID codes are removed from the list and only their current ID code remains valid.

cnf

Confi gures network parameters. There are 8 different PN codes and channel subsets, and this command allows the hub to be swit-ched to a new PN code and channel. The facility to change channel number is for test purposes only, as the channel is changed automatically in normal operation. The PN code, however, remains fi xed. The format is

cnf <pncode> <channel>

where 0 < pncode < 9 and 0 < channel < 80. The cnf command automatically deletes all registered sensors from the list.

snd

Sends beacon time and other data to a sensor. The data packet is buffered in the hub and when the sensor in question next makesa transmission the packet is sent back in the back channel to the sensor. All parameters are given in decimal. The format is

snd <sensorid> <beacon time> <data0> <data1> <data2> <data3> ...

A beacon time of -1 indicates that the beacon time is not to be changed.

delRemoves a sensor from the list of registered sensors in the hub. The format is

del <sensorid>

hex Causes sensor data to be displayed in hex rather than as plain text.

Figure 12. Prototyping board with iDwaRF radio module plugged on.

Wireless USB in miniature • 79 Elektor blockbusters

Page 80: E-book-15-ElektorBlockbusters-uk

TECHNOLOGY WIRELESS

50 elektor electronics - 3/2007

... go!

The ‘terminal’ example program is the best one to use to demonstrate all the important functions of a wire-less sensor network. iDwaRF mod-ules programmed as sensors auto-matically connect to the module pro-grammed as the hub and transfer data. With one node board and a hub board connected to a PC it is possi-ble to see immediately on the PC’s

Now we can run a terminal program, set to the relevant port, and talk to the hub in plain ASCII. If there are no sen-sors there will initially be no reports from the hub. The hub is reset by typ-ing the command ‘rst’ and pressing ‘enter’: the hub will then emit its start-up message. It is best to confi gure the terminal program to expect CR+LF at the end of each line and to enable lo-cal echo, as the hub does not echo the characters it receives.

screen when light falls on or is shad-ed from the light sensor, when the button is pressed, or when the tem-perature sensor is warmed or cooled. Setup proceeds as follows.

Hub boardThe virtual COM port driver creates a virtual COM port when the USB cable is plugged in. The number of the port can be obtained from the Device Man-ager (reached from the Control Panel).

Data format

S5: ID 0 ldr 212 temp 22.5°C batt 2.9V button OFF (5 6 7 8 9 10) : 11

a) b) c) d) e) f) g) h)

Legend:

a) Packet type: S0 (BIND_REQUEST); S1 (BIND_RESPONSE); S2 (PING, hub only); S3 (ACK); S4 (DATA, hub only); S5 (DATA, sensor only)

b) Sensor ID

c) ADC value from the light intensity sensor

d) Temperature

e) Battery voltage

f) Button state (ON or OFF)

g) Six unused bytes displayed as decimal indices

h) Data byte count

The values from c) to g) above form the packet data payload. The standard packet size is set to 17 bytes, of which six are protocol overhead, leaving 11 bytes of payload.

The principal callback functionsIn the hub:cbSensorPacketReceived(): called when a packet is received from a sensor. Direct access to the current sensor data is possible, although if lengthy processing is to be carried out the data should be copied into a global buffer and the work done in the main program.

cbSerialDataReceived(): called when a byte is received over the serial interface. Usually the byte is simply stored in a global buffer and its re-ception signalled using a fl ag, so that more time-consuming processing can be carried out in the main program.

cbProcessRxData(): further processes the bytes received by cbSerialDataReceived(), for example to implement a complex communications pro-tocol with the host PC. In the ‘terminal’ example the commands entered on the host PC are parsed and processed in this function.

In the sensor:cbConfi gForSleep(): called shortly before the sensor switches into power-down mode. This allows for particular sensor devices to be switched off to reduce power consumption.

cbExitFromSleep(): called when the sensor leaves power-down mode. At this point particular sensor devices can be powered up again.

cbTxProcess(): assembles the data packet to be sent to the hub. At this point sensors can be read and the readings stored in the global trans-mit buffer. The current data packet is then automatically sent to the hub.

cbBackchannelProcess(): called with data received from the hub in the reverse channel. This can be used to create an output signal on the sensor, or to generate an analogue voltage using PWM. The ‘terminal’ example switches on the LED when a data packet is received.

Wireless USB in miniature • 80 Elektor blockbusters

Page 81: E-book-15-ElektorBlockbusters-uk

513/2007 - elektor electronics

SensorIf a sensor is switched on the data packets received will be displayed line-by-line in the terminal window. The first packet is called a ‘bind re-quest’ where the sensor registers with the hub and, in return, receives an ID code assignment and a value called the ‘beacon time’. This period, which has a default value of fi ve seconds, is the interval between the transmission of successive data packets. The format of the data packets is described in detail in the text box ‘Data format’. A brief fl ash of the LED on the sensor board shows when it is active; the LED is ex-tinguished when the sensor returns to power-down mode.

If the node board is moved to a warm-er location, or if the ambient light in-tensity changes, the data packets dis-played will refl ect the new sensor val-ues. If the button on the node board is pressed a data packet is transmitted immediately: this shows that it is pos-sible to react immediately to external events, without waiting for the preset beacon time to elapse.

Command lineCommands can be typed into the ter-minal window at any time. Typing ‘enu’ (‘enumerate’) lists the sensors that are registered with the hub, showing their ID code and unique serial number.

Our fi rst sensor will appear in this list with ID ‘0’. To send data to this sen-sor we use the ‘snd’ command. In its simplest form this has two parame-ters: ‘snd 0 40’ sends the value 40 to the sensor with ID code ‘0’. The fi rst data byte is always interpreted by the sensor as a new beacon time, in units of 125 ms. In this example, the value of 40 corresponds to the default beacon time of fi ve seconds. So, if we type ‘snd 0 8’ we will set the beacon time for sensor 0 to one second, and data packets from this sensor will be displayed in the terminal window at this rate. The command ‘snd 0 40 1’ sets the beacon time back to fi ve sec-onds and also sends an extra data byte with value ‘1’, which will cause the LED on the node board to light. In the terminal example the code in the sensor simply checks whether there is an extra data byte beyond the beacon time or not, and sets the LED on or off accordingly. The actual value of the extra byte is not taken into account. The complete set of commands pro-vided by the hub in the ‘terminal’ ex-

ample is listed in Table 3.If now a further sensor is activated another ‘bind request’ packet will ap-pear among the data packets being re-ceived from the fi rst sensor, followed by a series of data packets. The ‘enu’ command can be used to list the regis-tered sensors, and should now display two entries with ID codes ‘0’ and ‘1’. We can test the new sensor by adjust-ing its beacon time: ‘snd 1 8’ will set it to one second, and we should now receive packets from sensor 1 at fi ve times the frequency of those from sen-sor 0. If an ‘x’ is used in place of the ID code in the send command, the beacon times for all sensors are set simultane-ously. Using ‘snd x 40’ we can therefore reset the beacon times for both sensors to fi ve seconds.

If the data packets are to be proc-essed on the host PC, the ‘hex’ com-mand can be used to switch the dis-play from readable form to pure hex values. These can easily be read by another application, for example using the scanf() function.

Room for expansionThe supplied programs can form the basis of dedicated applications using iDwaRF modules: the possibilities are endless. Often a couple of extra com-ponents are all that is needed, for ex-ample to make measurements using an ADC, generate PWM waveforms, scan keys or drive an LCD.

The iDwaRF-Net software can in theory work with up to 255 sensors, although at present the limit is 32. For larger sensor networks the xHub is planned, using an ATmega128 with more fl ash memory and an external SRAM. An ex-ternal antenna will increase the range of the hub.

Users of the iDwaRF radio module [7] and the iDwaRF-Net fi rmware can use a forum [8] organised by the author. This is in addition to the forum on the Elektor Electronics website. Further ex-ample programs will of course appear for download at [6] as soon as they be-come available.

(050402-I)

References and links:[1] www.zigbee.org

[2] www.cypress.com

[3] Thomas Biel: ‘Wireless USB’, Elektor Electronics, September 2004, p. 8

[4] www.atmel.com/avr

[5] Stefan Tauschek: ‘Wireless Connectivity’, Elektor Electronics, February 2005, p. 14

[6] www.elektor-electronics.co.uk or www.chip45.com/iDwaRF-168_Downloads

[7] www.chip45.com/iDwaRF-168

[8] www.chip45.com/iDwaRF-Net

Wireless USB in miniature • 81 Elektor blockbusters

Page 82: E-book-15-ElektorBlockbusters-uk

A 16-bit Tom Th

elektor electronics - 2/200638

HANDS-ON MICROCONTROLLERS

Now it’s for real – from this issue youcan order a circuit board with anR8C/13 microcontroller and the neces-sary software, at price consisting ofP&P and handling only. The service isstrictly limited to stocks and pro-vided exclusively for Elektor Electron-ics readers in co-operation with Glyn.So if you want to grab an R8C starterkit, order it straight away — the online

method using our website is by far thefastest.There are three good reasons for usingthe Renesas R8C/Tiny family: first, itprovides 16-bit computing power at alow price; second, it comes with a freebut nevertheless very capable C com-piler; and third, no programming hard-ware is necessary, because code canbe easily downloaded to flash mem-

ory via the RS232 port. We alreadyintroduced the board and the soft-ware in the January 2006 issue. If youmissed that article, you can downloadit free of charge from the Elektor Elec-tronics website at www.elektor-elec-tronics.co.uk (select the Magazinetab, then January 2006). Our objectivein this article is to help you startusing the board.

Gunther Ewald and Burkhard Kainka

Thanks to the efforts of Elektor Electronics and Glyn, for the first time now a Europeanelectronics magazine supplies a complete microcontroller starter board and accompanyingsoftware CD-ROM at a very attractive price. We already introduced the Renesas R8C in the lastissue. Now it’s time to start using it.

A 16-bit Tom Thumb • 82 Elektor blockbusters

Page 83: E-book-15-ElektorBlockbusters-uk

humb

2/2006 - elektor electronics 39

Our R8C starter kit is available– now you can get going!

When installing the nec-essary software, followthe instructions exactly asgiven in order to ensurethat what you later seeon your PC matcheswhat we describe here.Install the KD30 moni-tor/debugger first, fol-lowed by the NC30 Ccompiler with the HEWdevelopment environ-ment and an update.Installation in this orderis important so the HEWwill find the debuggeralready installed and link it in properly. Next, install thedebugger package in order to integrate the debugger intothe development environment. Later on, you only need to startthe HEW in order to have everything together on yourscreen. Finally, you have to install the Renesas FlashDevelopment Toolkit (FDT), which enables you to downloadfinished programs to the microcontroller.

After you insert the CD, a product summary in PDF formatwill be displayed first. You should see the main directory ofthe CD after you close the product summary. Alternatively,you can right-click on the drive icon and select ‘Open’ inorder to skip the PDF intro. The most important directories onthe CD are \Software and \Sample_NC30. They contain allthe necessary programs (which should now be installed) andthe initial sample projects.

1. KD30The executable installer file KD30V410R1_E_20041203.exe.is located in the \Software\kd30400r1\ directory on theCD. Start the installation and confirm the default pathC:\MTOOL\.

2. NC30Run the setup file nc30wav530r02_2_ev.exe in the\Software\ nc30v530r0_hew\ directory on the CD. First youhave to select whether you want to install the Japanese ver-sion or the English version. Most of our readers will probablyprefer the English version. The program suggests C:\ProgramFiles\Renesas as the default installation path. You should con-firm this path.

A second default path is shown for the tool chain:C:\Renesas\NC30WA\V530R02. You should also accept thedefault path name, as well as all subsequent default path names.

At the end of the installation, an individual site code is dis-played. You can ignore it, because it is only necessary forregistering the software. If you purchase the full version of thecompiler, you will automatically receive a CD with your own

code for enabling thesoftware.

After you have installedthe HEW, you have torun the installer for theAutoUpdate program. Asshown in the figure, con-firm that you wish toreceive weekly updatesfrom the Renesas Toolswebsite. That enablesyou to keep your soft-ware ‘fresh’ all the time.If the PC on which yoursoftware is installed does

not have access to the Internet, you can cancel installation ofAutoUpdate without causing any problems. The most recentupdate file is on the CD, and it must be installed next.

After being installed, the updater immediately checks to seewhether there is anything new and automatically downloadsthe latest changes. The first update will then be installed auto-matically. The PC must then be restarted before you continue.

3. Update HEW This step is only necessary if you have not already down-loaded the latest update from the Internet and installed it. Runthe first HEW update from the CD by startinghewv40003u.exe in the\Software\HEW_V.4.00.03.001_Update directory on theCD. That will update your compiler to the latest version(Database Version 7.0). That is important, because the sam-ple projects have been generated for this version. Althoughyou can use the new version to load older projects, whichwill then be updated automatically, regressing to an olderversion of the compiler is not that easy.

4. Debugger packageRun the installer file m16cdebuggerv100r01.exe in the\Software\Debugger Package\ directory on the CD. Followthe instructions of the installer program and confirm youragreement to the licence conditions. Everything else is auto-matic. You must restart the computer after this installation.

5. Flash Development Toolkit Install the FDT by running the installer file fdtv304r00.exe inthe \Software\Flasher_FDT directory on the CD. Confirm alldefault settings. Everything else is automatic.

When everything has been installed, you will find theRenesas program group under Start / All Programs. The tworelevant programs in the group are High-performanceEmbedded Workshop and Flash Development Toolkit.

The software

A 16-bit Tom Thumb • 83 Elektor blockbusters

Page 84: E-book-15-ElektorBlockbusters-uk

The hardware

The low-profile PCB with pre-assem-bled SMD components is supplied withtwo pin headers that you must fit andsolder yourself (Figure 1). That yieldsa complete processor module in theformat of a 32-pin DIL IC (Figure 2).There is also space reserved on theboard for a 14-way pin header, but itdoes not have to fitted right awaybecause it is only needed for the E8debugger.

The actual microcontroller (the R8C/13)is contained in the 32-pin LQPF SMDpackage, which measures 7 by 7 mmand has a lead spacing of 0.8 mm. Themarking ‘R5F21134FP#U0’ reveals thatit is an R8C/13 with 16 KB of flashROM. We selected the R8C/13 becauseit has the same characteristics as its‘siblings’ (R8C/10, R8C/11 andR8C/12). The board also comes fittedwith a 20-MHz crystal and the neces-sary capacitors, as well as severalother capacitors and resistors. Alto-gether, this amounts to a completemicrocontroller system. Once a pro-gram has been loaded, all you have todo is connect a 3.3-V or 5-V supply volt-age and you’ve got a working system.Program code can be loaded using aserial interface; no special program-ming hardware is necessary. That’sbecause the microcontroller has adebug interface and a correspondingboot program that can be used to copythe software into the flash ROM.

First contactIn the next issue of Elektor Electronics,we will describe a complete develop-ment system with RS232 and USBinterfaces. But you naturally don’twant to wait that long to try out theboard. For that reason, we describe asolution here that only requires a fewcomponents from your parts bin:

• a source of 5-V power, preferably sta-bilised by a voltage regulator• an inverting level converter for con-nection to the RS232 port• a pushbutton reset switch• a mode switch to select the program-ming mode

The microcontroller board feeds out allthe microcontroller leads one to one.As we already mentioned, a crystal, afew capacitors and some resistors arefitted on the board. The schematic dia-gram in Figure 3 shows only the con-

elektor electronics - 2/200640

HANDS-ON MICROCONTROLLERS

R8C/13

RESET

RXD1

MODE

TXD1

VSS

VCC

P17

P16

P15

P14

P13

P12

P11

P10

P45 P33

P32

P31

P30

AN0

AN1

AN2

AN3

AN4

AN5

AN6

10

11

12

13

14

15

16 17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

321

2

3

4

5

6

7

8

9

1

2

3

4

5

6

7

8

9

27k

100k

4k7

10k

10k

78L05

100n 100n

BC548C

1N4004

TXD

BC558C

050179 - 2 - 11

RXD

SUB-D9

+9V

Figure 1. The hardware you can order from us at low cost forms a complete microcontroller system.

Figure 3. The circuit diagram of a minimal system for initial tests.

Figure 2. The fully assembled board with the pin headers fitted.

A 16-bit Tom Thumb • 84 Elektor blockbusters

Page 85: E-book-15-ElektorBlockbusters-uk

nections that are essential for a ‘quickstart’, so you can get your bearings asfast as possible. The connections notshown in the figure must alwaysremain open. Figure 4 shows an exper-imental setup on a prototyping board.The serial port of the PC is connectedhere via transistor inverters. Althougha MAX232 could be used just as wellfor this purpose, the transistors willprobably be easier to find in your partsbin. A BC548C NPN transistor invertsthe TXD signal from the PC and feedsit to the RXD1 input of the microcon-troller. This input does not have aninternal pull-up, so the collector resistoris essential. In the opposite direction,TXD1 drives a BC558C PNP transistor.The RXD input of the PC has its ownpull-down, so the collector resistor canbe omitted here.The MODE input of the microcon-troller determines whether the inter-nal boot program or a downloadeduser program is run after a reset. TheMODE input is pulled high by a 10-kresistor when the switch is open,which causes the user program to bestarted. If you want to load a programinto the flash memory, you first haveto close the switch in order to pullMODE low. Then you must brieflypress the Reset switch. That causesthe microcontroller to start up in thedebug mode, which allows new soft-ware to be loaded into the flash ROM.After the software has been trans-ferred, open the Mode switch andpress the Reset switch again. Thatcauses the downloaded program to bestarted. However, duty comes beforepleasure, and in this case the duty isinstalling the software on the PC.That’s described step-by-step in theinset. Follow the instructions exactlyas given in order to ensure that whatyou later see on your PC matcheswhat we describe here.

Ready, set, flash!The first thing you should do is to tryout the Flash Development Toolkit(FDT) by downloading a finished pro-gram to the microcontroller. For thetime being, we’ll skip the process ofdeveloping you own programs, so youcan enjoy some tangible results assoon as possible.

After installing the Renesas softwarepackage, you will find the FDT pro-gram in the Windows ‘Start’ menu. Theprogram is shown there in two ver-sions: a full version and a compact

‘Basic’ version. Start ‘Flash Develop-ment Toolkit Basic’ (Figure 5).You must configure several settingsthe first time you start the program.If necessary, you can access themlater on via the Options / New Set-tings menu. Select ‘R5F21134’ as themicrocontroller type, and select theupper of the two core protocol options(Figure 6).In the next window, select the serialinterface port from the rangeCOM1–COM4. The third window asksyou to specify a baud rate for the linkto the microcontroller. Enter ‘9600baud’ here (Figure 7).Finally, you have to specify whetheryou want to enable readout protectionfor the microcontroller. As the risk ofcriminal industrial espionage is rathersmall with the initial familiarisationprograms, you can dispense with anyform of protection. Save the settings asshown in Figure 8. That completes thepreparations.

Hurrah, it blinks!Now connect the board to the specifiedCOM port on your PC. Close the Modeswitch and briefly press the Resetswitch. The microcontroller will enterboot mode and wait for you to send itdata.The next step is to download a fully

compiled program to the microcon-troller. On the CD, you will find the‘Sample NC30’ folder with several sam-ple projects. That includes the projectfolder ‘Sample_NC30\ port_toggle’,which contains the folder ‘port_toggle\Release’. The file port_toggle.mot islocated in the latter folder. It is a pro-gram in Motorola hex format that canbe downloaded directly to the micro-controller.

Specify the path to this file, and thenstart the download process by select-ing ‘Program Flash’. The downloadtakes around two seconds. The flashmemory is first erased, and the newprogram is then copied over. If every-thing goes properly, the message‘Image successfully written to device’will be displayed. Open the Modeswitch and briefly press the Resetswitch. That will start the programthat you just downloaded.

The program toggles the first fourlines of Port 1 (P1_0 to P1_4) at a slowrate, so you can observe their statesusing a LED with a series resistor. Theports of the R8C and the other M16microcontrollers have a low imped-ance in the output direction, regard-less of whether they are in the high orlow state. That means you mustalways use a series resistor (1 k , for

2/2006 - elektor electronics 41

Figure 4. A prototype of the test system built on a lab prototyping board.

A 16-bit Tom Thumb • 85 Elektor blockbusters

Page 86: E-book-15-ElektorBlockbusters-uk

example) when connecting a LED tothem (Figure 9).All of the sample programs describedbelow can be copied to the microcon-troller in the manner just described. Ifthe R8C cannot be flashed due to acommunication error, it must be leftwithout power for one minute to erasethe internal RAM loader. This error canoccur if you have been working withthe debugger before attempting todownload a program.

The R8C as a musicianLike to try another hardware test?

Then download the ‘Jingle_Bells’Motorola file from the R8C project tothe microcontroller. Connect a small 8-

loudspeaker or a headphone with a1-k series resistor to the board (Fig-ure 10), and then start the microcon-troller. You will hear a simple melody.Incidentally, this program uses theinternal high-speed ring oscillator(8 MHz) and does not require the crys-tal oscillator. If you touch an oscillo-scope probe to the crystal lead Xin(pin 6) or Xout (pin 4), you will see thatno clock signal is present (in contrastto the situation with the port_toggleproject). As you can hear from the

absence of any sour notes coming fromthe speaker, the internal RC oscillatoris fully adequate for this task. Thatmeans you could flash the programinto an R8C/13, connect it to a piezo-electric speaker and a 3-V button cell,and hang it from your Christmas treeor insert it in a Christmas card.Now that you know the hardware isOK, your fingers are probably itchingto start programming something,aren’t they? OK, it’s time to start upthe integrated hardware developmentenvironment (HEW). In order to keepthings fairly simple at first, let’s startby making a few changes to an exist-ing project. We’ll also work without thedebugger to start with.

High CYou can use HEW to generate assem-bly-language projects. However, pro-gramming the R8C in assembly lan-guage is significantly more difficultthan programming it in C, becausethere are so many different data for-mats and addressing modes. The Ccompiler looks after all that for you. Youdon’t even have to know whether themicrocontroller is processing a word, abyte or a bit. In this case, C is easierthan assembly language even for peo-ple who are only used to working inassembly language. The unfamiliarnotation will quickly become secondnature after you work through a fewexamples, so there’s no need to beafraid of C!

First copy the entire ‘port_toggle’ proj-ect from the CD to your PC. When youstart a new project, use a directorysuch as C:\WorkSpace, which is alsothe default directory suggested byHEW. In the Renesas program group,start the ‘High-Performance Embed-ded Workshop’ program. A selectionwindow is displayed when the pro-gram starts, and you can specifywhether you want to generate a newproject or open an existing project.Use File/ Open Workspace to open theport_toggle file. All the files belongingto the project will then be shown at theleft. Click on port_toggle.c to open thesource code file. Everything shouldthen appear as shown in Figure 11.Next, you should try to compile theproject, just for the exercise. First youhave to decide whether you want togenerate a debug version or a releaseversion. You should work without thedebugger for now, which means youshould select the ‘Release’ option

elektor electronics - 2/200642

HANDS-ON MICROCONTROLLERS

Figure 5. The Flash Development Toolkit, Basic version.

Figure 6. Selecting the microcontroller type and transmission protocol.

A 16-bit Tom Thumb • 86 Elektor blockbusters

Page 87: E-book-15-ElektorBlockbusters-uk

under Build / Build Configurations.Then start the compilation by select-ing Build / Build All. The C source codewill be compiled, linked, and written tothe output directory \Release in theform of a Motorola hex file. The entireprocess is listed at the bottom of theBuild window. At the end, you’ll seethe longed-for message that signalssuccess:

Build Finished0 Errors, 1 Warning No errors – that’s very good! Warningsoccur relatively often and aren’t all thatdramatic. In this case, the warningreads: ‘Warning (ln30): License hasexpired, code limited to 64K (10000H)byte(s)’. You don’t have to worry aboutthat, because you’re using the free ver-sion of the compiler, and 64 kB is any-how more than R8C/13 can hold. If youwish, you can download the output fileto the microcontroller again and runthe program. It will work just as wellas the Motorola hex file on the CD.

Now let’s have a look at the sourcecode:

while (1) /* Loop */{p1_0 = 0;p1_1 = 0;p1_2 = 0;p1_3 = 0;for (t=0; t<50000; t++);p1_0 = 1;p1_1 = 1;p1_2 = 1;p1_3 = 1;for (t=0; t<50000; t++);}

The core of the program consists of asimple, self-explanatory loop. First theports are enabled, then there is a waitloop, then the bits are disabled, andfinally there is another wait. Even ifyou don’t have any experience with C,you can right away see where youcould make some changes. Forinstance, you could shorten the waitloops to make everything run a bitfaster. For example, you could set thecount to 25,000 instead of 50,000. Youcould also try reducing the count to 2and see how fast it runs then. You caneven remove the wait loops entirely byusing the comment sign ‘//’ to renderthem ineffective. Of course, you won’tbe able to use a LED any more tocheck the signals, but an oscilloscopewill show a high-frequency square-wave signal. Each time you modify the

2/2006 - elektor electronics 43

Figure 7. Selecting the baud rate.

Figure 8. Readout protection is unnecessary.

program, you must use Build All tocompile the program and then use FDTto download it to the microcontrolleragain.

A sense of timeNow we come to the crystal oscillatorof the microcontroller. The port_togglesample program uses the crystal oscil-lator, which runs at 20 MHz. Asalready mentioned, there are also twointernal RC oscillators with frequen-cies of 125 kHz and 8 MHz, respec-tively. In fact, the microcontrolleralways starts up with the low-speed

ring oscillator enabled. If you look atthe data sheet for the R8C/13, you willsee the complicated clock-generationarrangement for the R8C, with a totalof three oscillators and several optionaldivider stages.The port_toggle sample projectdemonstrates how to switch from the125-kHz oscillator to the crystal oscil-lator:

prc0 = 1; /* Protect off */cm13 = 1; /* Xin Xout */cm15 = 1; /* XCIN-XCOUT

drive capacity select bit : HIGH*/

A 16-bit Tom Thumb • 87 Elektor blockbusters

Page 88: E-book-15-ElektorBlockbusters-uk

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”);asm(“nop”);asm(“nop”);ocd2 = 0; /* Main clock

change */prc0 = 0; /* Protect on */

The above listing shows the relevantinstruction lines at the beginning ofthe source code. It’s necessary tochange a few control bits in SystemClock Control Registers 0 and 1, butthey are initially in protected mode.This protection is disabled in the firstline so the relevant control bits can bealtered. After the bits have been

switched, we have to wait a littlewhile for the oscillator to stabilise afterbeing started up. After this, the clocksource is changed and write protectionis re-enabled. From now on, all pro-grams will run at 20 MHz. If you now remove this entire block ofcode from the listing, including prc0 =1 and prc0 = 0, the oscillator will notbe changed and the microcontrollerwill continue operating at 125 kHz. Tomake it possible to observe the resultwithin a finite length of time, you mustalso shorten the wait loops by a factorof 100:

void main(void){

pd1 = 0x0F; /* Set Port 1.0 -1.3 be used for output*/

while (1) /* Loop */{p1_0 = 0;

elektor electronics - 2/200644

HANDS-ON MICROCONTROLLERS

P1- 01k

LED

050179 - 2 - 20

Figure 9. Connecting a LED to P1_0.

P1- 01k

050179 - 2 - 21

Figure 10. Connecting a loudspeaker to themicrocontroller.

Figure 11. The port_toggle project in the development environment.

p1_1 = 0;p1_2 = 0;p1_3 = 0;for (t=0; t<500; t++);p1_0 = 1;p1_1 = 1;p1_2 = 1;p1_3 = 1;for (t=0; t<500; t++);}

}

The LED will blink somewhat moreslowly now, but the microcontrollerwill run with very low power con-sumption.The internal high-speed ring oscillator,which runs at 8 MHz, provides a com-promise between really fast and reallyslow. The Jingle_Bells sample projectshows how you can use it. Copy thefollowing relevant instruction lines intoyour program:

prc0 = 1; // EnableHigh Speed Oscillator (8 MHz)

hr00 = 1;asm(“NOP”);asm(“NOP”);hr01 = 1;prc0 = 0;

You should also have a look at theTimer_Interrupt project. If you’re tryingto use a timer for the first time, you canof course pore through the R8C/13 datasheet, but it’s better to start with aworking bit of code from a sample pro-gram and then read the relevant por-tions of the data sheet while trying outyour own modifications. Besides timerinitialisation, the Timer_Interrupt sam-ple program shows how to implementan interrupt function in C. You’ll findeven more sample programs in theapplication notes on the CD.

If you’re now eager to generate yourown personal project, you can find thenecessary information on the ElektorElectronics website at www.elektor-electronics.co.uk (look for the R8C linkin the right-hand column). There youwill find a simple example thatexplains in step-by-step fashion howto generate your own application pro-gram without relying on an existingproject. And if you still have questions,a dedicated Forum topic for the R8Cstarter kit has been set up on the Elek-tor Electronics website.

(050179-2)

Referencewww.glyn.com

A 16-bit Tom Thumb • 88 Elektor blockbusters

Page 89: E-book-15-ElektorBlockbusters-uk

PROJECTS MICROCONTROLLERS

22 elektor - 11/2007

USB Flash BoardAn 8051-based system for rapid software Alexander Kniel

Flash microcontrollers are easy to program, which makes them suitable for rapid software development environments and educational uses. In the past, program code was usually downloaded via a serial interface, but nowadays many PCs (especially laptops) only have USB ports. Our versatile Flash Board provides a solution to this problem. It is built around an AT89C5131A, which is an extended 8051-family microcontroller with an 80C52 core and a Full Speed USB port. As a sort of bonus, the IC has a complete update interface for downloading new firmware. Atmel also provides suitable software in the form of its FLIP program, which is available free of charge.

The Flash Microcontroller Board ori-ginally published in December 2001 is well known to Elektor readers, and it has helped many readers get started in the world of microcontrol-lers. That’s hardly surprising, since microcontrollers with flash memory, such as the AT89C8252 used in the original Flash Board, are easy to pro-gram. As with many other similar boards used for educational purpo-ses, the code is downloaded from a development PC to the microcontrol-ler via a serial interface. Unfortuna-tely, the good old RS232 interface is becoming increasingly rare. Lapt-ops in particular often have only USB ports and no longer come with prin-ter ports or serial ports. If a teacher wants to give his students training boards that they can also program at home using a laptop, a different ap-proach is necessary.

The author, an electronics instruc-tor at a vocational/technical school in Heilbronn (Germany), thus developed a version of the Flash Board based on a modern microcontroller with a USB interface. For this purpose he selected the Atmel AT89C5131AM, which has an 80C52 core and thus belongs to the 8051 family, just like the AT89C8252. The IC incorporates an Full Speed USB

port, and it is specifically designed for use in USB devices such as printers, cameras, and so on. As a sort of bo-nus, the microcontroller has a complete update interface for downloading new firmware. This in particular enabled the author, who has a weakness for hardware and all sorts of programming languages, to build an extremely simp-le USB Flash Board because Atmel also provides suitable software in the form of its FLIP program, which is available free of charge. All you have to do is pro-vide the program code in a hex file and you’re ready to go.

Generation-2 Flash BoardMany copies of the first version of the new board developed by Alexander Kniel have already been built by stu-dents and used with laptop compu-ters. The board design was modified slightly in the Elektor lab, and among other things Elektor designer Chris Vossen added an LCD interface. The board thus follows in the footsteps of the 2001 version of the Elektor Flash Microcontroller Board and is suitable for not only learning how to program microcontrollers, but also for mature applications in device controllers, ro-bots, and many other areas.Everything revolves around the abo-

ve-mentioned AT89C5131AM, which is an extended member of the 8051 fa-mily. Its core is an 80C52X2 with six clocks per instruction cycle. Besides 32 KB of flash memory, the IC has 1024 bytes of extended RAM, additi-onal EEPROM, and many other useful peripherals. Another helpful feature is that the M version of the microcontrol-ler can also operate at 5 V, and a versi-on in the user-friendly PLCC52 packa-ge is available. However, probably the most important feature is the USB 1.1/ USB 2.0 Full Speed module (for the experts: with endpoint 0 for control transfers and six additional endpoints with up to 512 bytes of FIFO memo-ry). If you want to develop USB soft-ware, this gives you everything you could wish for, although you do need a bit of technical expertise. Everyone else can regard the microcontroller as a normal 8051 device that can be pro-grammed via USB.

The schematic diagram (Figure 1) shows a dual power supply that can draw power either from the USB bus or (with jumper JP4 fitted) via voltage regulator IC2 from an AC adapter con-nector K9. The D+ and D– pins of the

Figure 1. Schematic diagram of the USB Flash Board.

USB Flash Board • 89 Elektor blockbusters

Page 90: E-book-15-ElektorBlockbusters-uk

1 3

2

IC27805D10

1N4001

P2.23

P1.54

P1.65

P1.76

P2.39

P2.511

P2.614

P2.715

P2.410

P3.020

P3.129

P3.230

P3.331

P3.432

P3.533

P3.635

P3.739

X112

X213

VSS

41

P1.047

P1.148

P1.249

P1.350

P1.451

P0.052

P0.145

P0.244

P0.342

P0.440

P0.538

P0.637

P0.736

VDD

16

AVDD

17

P4.07

P4.18

EA26

ALE27

PSEN28

VREF24

D+23

D-22

PLLF21

AVSS

19

RESET43

UCAP18

UCAP

25

NC34

NC46

P2.01

P2.12

IC1AT89C5131

C11

22p

C10

22p

R41k5

R227R

R327R

R11

4k7

C1

100n1234

5 6

K2

R5

100R

C4

10n

C3

2n2

2

31

K9

16V

C12

1000u16V

C13

100u

C14

100n

D12

C2

100n

R12

1k5

D9

BAT46

1 23 45 6

K4R6

4k7

+5VR7

4k7

JP2R10

1k

P1.0P1.1 P1.2P1.3 P1.4P1.5 P1.6P1.7

+5V

P1.1P1.2

P1.4P1.5P1.6P1.7

P3.0P3.1P3.2P3.3P3.4P3.5P3.6P3.7

S5S3 S4 S6

C6

100n

P3.0P3.1 P3.2P3.3 P3.4

P3.6P3.5P3.7

C7

100n

1

2 3 4 5 6 7 8 9

R11k5

D1

P0.0P0.1P0.2P0.3P0.4P0.5P0.6P0.7

P0.6P0.4P0.2P0.0

P0.7P0.5P0.3P0.1

+5V

P0.0

D2

P0.1

D3

P0.2

D4

P0.3

D5

P0.4

D6

P0.5

D7

P0.6

D8

P0.7

JP1

+5V

P2.0P2.1P2.2P2.3P2.4P2.5P2.6P2.7

8 7 6 5

41 2 3

S2

P3.2P3.3

P3.4P3.5

P3.7P3.6

1

23456789

R910k

P1.3

16V

C9

1u

P3.0P3.1

+5V

D11

6V2

JP4

C15

100n

C16

100n

P2.0P2.1P2.2P2.3

+5V

C5

100n

P1

10k

P2.7

JP3

16V

C8

10u

+5V

P1.0

S1

1 23 45 67 89 10

K3

1 23 45 67 89 10

K8

1 23 45 67 89 10

K6123456789101113

1214

K7

+5V

P2.4

+5V

X1

24MHz

+5V

070125 - 11

2311/2007 - elektor

development

USB Flash Board • 90 Elektor blockbusters

Page 91: E-book-15-ElektorBlockbusters-uk

PROJECTS MICROCONTROLLERS

24 elektor - 11/2007

microcontroller are for the USB data lines. To activate the internal USB boot loader, a low signal level must be applied to PSEN via JP2 (jumper toward the edge of the board).

When reset switch S1 is pressed, the boot loader starts up and receives data via the USB port. Jumper posi-

It can be fitted directly on the PCB or mounted on a front panel.

Four full-fledged 8-bit portsThe microcontroller has four full-fledged 8-bit ports, each of which is accessible via a connector and/or as-signed a specific peripheral function. Port P0 is available on K3, and it also drives eight LEDs that can be con-nected to VDD (+5 V) via series re-sistors. Port P1 is freely usable and accessible via K6. Port P2 is wired to LCD connector K7. An LCD module can be operated in 4-bit mode via this connector, and a contrast adjustment trimpot is provided on the board. Fi-nally, port P3 is specifically intended to be used for inputs, and it can be accessed externally via K8. For testing user-developed programs, the board is fitted with pullup resistors, four pushbutton switches (P3.0…P3.3), and four DIP switches (P3.4…P3.7) on port 3. Switches normally require de-bouncing, which can usually be imple-mented in software. The P3.2 and P3.3 lines have supplementary hardware debouncing in the form of capacitors C6 and C7, since these lines are con-nected to the interrupt inputs of the microcontroller. We also mustn’t forget port P4 with the P4.0 and P4.1 lines, which form the I2C bus interface and are accessible via K4.

The bare PCB for the USB Flash Board (Figure 2) is available from the Elek-tor Shop under order number 070125-1. Alternatively, you can purchase a complete kit with all the componen-ts under order number 070125-71. As-sembling the board is not difficult. Be sure to avoid creating any shorts between D+, D– or the 5 V supply line and ground in the area around the USB socket. As there is no spe-cial protection for the D+, D- and 5-V supply lines, it’s a good idea to check this with an ohmmeter – but be sure to remove the microcontroller from its socket first. There is room for an ex-tra 100-nF ceramic capacitor beneath the IC socket, which should be fitted first. It provides optimal supply vol-tage decoupling.

Initial operationYou should use an AC adapter (8–12 V DC) for initial testing. Fit jumper JP4 to select this power source. LED D1 should light up now. If you have already connected an LCD module, it

tion JP3 must be closed (jumper to-ward IC2) to activate the USB port. This connects pullup resistor R4 to the D+ line, which indicates a Full Speed USB device to the PC. If you would like to have a more conveni-ent way to switch between run mode and download mode, you can connect a changeover switch to JP2 and JP3.

IC2

C11

C142

C10

S6

K9

1

K2

1

ONR3R4

2 3 4

S2

9 10

K8

C12

+

D10

3

C3+

R12 D9

JP4

D12

R10 JP

2

C13 R2

D11

6

C9C4

C2

X1

5

R5

+

JP3 IC1

C1

JP1C5

P1

C15

S5

S4

R9

R11

S3

S1

21

C7

C6

+

R1

C8

D2

2 101 9

D3 D5D4 D6 D8D7

2

K3

121

109

K6 D1

2

(C)

Ele

ktor

0701

25-1

R7R6

1

K7

14

K4

13

Figure 2. Assembling the circuit board should not present any problems.

Components listResistorsR1 = 1k 5 8-way SIL arrayR2,R3 = 27R4,R12 = 1k 5R5 = 100R6,R7,R11 = 4k 7R9 = 8-way 10k arrayR10 = 1kP1 = 10k potentiometer

CapacitorsC10,C11=22pFC3 = 2nF2C4 = 10nFC1,C2,C5,C6,C7,C14,C15,C16 = 100nFC8 = 10μF 16VC9 = 1μF 16VC12 = 1000μF 16VC13 = 100μF 25V

SemiconductorsD1-D8,D12 = LED, red, low-currentD9 = BAT46D10 = 1N4001D11 = zener diode 6V2IC1 = AT89C5131AMIC2 = 7805X1 = 12MHz quartz crystal

MiscellaneousJP1,JP4 = 2-way SIL pinheaderJP2,JP3 = 3-way SIL pinheaderK2 = USB-A socketK3,K6,K8 = 10-way boxheaderK4 = 6-way (2x3) pinheaderK7 = 14-way boxheaderK9 = mains appliance socket, PCB mountS1,S3-S6 = miniature pushbuttonPLCC socketPCB, # 070125-1 from Elektor SHOPKit of parts, # 070125-71 from Elektor

SHOP

USB Flash Board • 91 Elektor blockbusters

Page 92: E-book-15-ElektorBlockbusters-uk

2511/2007 - elektor

should display dark pixels in the top line. If necessary, adjust the contrast trimpot until both lines are clearly dis-tinguishable. The upper line will re-main dark until the board has been in-itialised with a program. If you have an oscilloscope, you can also check the 12-MHz clock signal on the crystal. This clearly shows that the microcontroller is running.

You have to download a program for the first real software test. For this purpose, you can use the Flexible In-System Programmer (FLIP) software, which you can download free of charge from Atmel’s home page (www.atmel.com). Enter ‘Flip’ as the search term to find FLIP 2.4.6 for Windows (4 MB, Version 2.4.6, updated May 2006). First extract the contents of archive file flip-2_4_6.zip to a separate folder and then run the Setup.exe file in that folder. Fol-low the installation instructions and accept the licence conditions and sug-gested installation location. You will then see a short list of instructions for what you have to do next (Figure 3). The program is installed by default in C:\Program Files\Atmel\FLIP 2.4.6\.

Now connect a cable to the USB con-nector and fit jumper JP2 in the ‘USB’ position (toward the edge of the board). To be on the safe side, press reset switch S1 and close JP3. This starts the USB download firmware, which waits for contact with the PC to be established. The program reports vendor ID 03EB and product ID 2FFD, which enable Windows to assign a sui-table driver. Windows will recognise a new device and ask you to select a suitable driver. Select the driver loca-ted in folder C:\Program Files\Atmel\FLIP 2.4.6\usb (see Figure 4). After it is installed, you will see the new de-vice in the Device Manager window. It can be recognised by its name ‘Jungo AT89C5130/AT89C5131’.

If something goes wrong during this process, you have to track down the problem. Possible problem sources in-clude incorrectly fitted jumpers. For instance, if you activate the USB port with JP3 (pullup connected to D+) but do not start the internal firmware (JP2 still in the ‘Run’ position or no reset executed after switching over), Win-dows will report a new device – but not the right one. By contrast, you might start the update firmware correctly but fit JP3 incorrectly. In this case, Win-dows will not recognise that a device

Figure 3. The free FLIP programming software displays a list of what you have to do to start using the board.

Figure 4. The microcontroller is recognised by Windows as a new device.

Figure 5. After you click Run, FLIP downloads the program to the flash memory of the microcontroller.

USB Flash Board • 92 Elektor blockbusters

Page 93: E-book-15-ElektorBlockbusters-uk

PROJECTS MICROCONTROLLERS

26 elektor - 11/2007

is connected, and thus no communica-tion will be established. After a bit of practice, you won’t have any problems making the right settings, and you can establish a communication session with the PC whenever you need it.

Program downloadNow launch FLIP. First you have to use F2, Device à Select, or the IC icon to select the correct IC (AT89C5131). Then use F3, Settings à Communica-tion à USB, or the cable icon to select and open the USB interface. Finally, you have to use F4 or File à Load Hex

If you want to download a new hex file after this test, you must first dis-connect the USB cable and then recon-nect it – and of course, with the right jumper settings and a Reset first. Af-ter this, you must establish the con-nection again in FLIP.

Alternatively, you can leave the USB cable connected and simply open JP3, which will also isolate the device from the USB without interrupting the supply voltage. In order to download a new program, you must first chan-ge the setting of JP2 again. The press Reset, wait two seconds, and fit JP3 again. This initialises the USB device. You will have to open the interface in FLIP again, after which you can start the download.

Programming with BASCOMThe BASCOM-51 Basic compiler is an ideal tool when you are just getting started with developing programs for the system, although you can also write programs for the microcontroller in C or assembly language. You can download a free demo version of BAS-COM-51 from the site of its producer, MCS Electronics (www.mcselec.com). The free version can generate up to 4 KB of code, which is sufficient for many applications.Figure 6 shows the main menu of the compiler. In order to ensure correct operation of the board, you must as-

File to load a suitable hex file. Select program file: 5131_TEST_ELEKTOR.HEX, which you can obtain along with the BASCOM AVR source code from the Elektor home page. Click the Run button (see Figure 5) to download the program code to the flash memo-ry. After this, you must change over JP2 and press the Reset button to run the program. Caution: the BLJB option is enabled automatically with a new microcontroller. You must deselect (uncheck) it the first dime you down-load a program, since otherwise it will not be possible to run the program af-ter it has been downloaded.

Figure 6. Main menu of the BASCOM compiler.

Hardware test in Bascom-51

‘Simple test for inputs,‘outputs and LCD‘**********************

Dim X As Byte

P1 = 0

ClsLcd “ 8051-Test “Wait 1LowerlineLcd “ Elektor “Wait 3

For X = 1 To 13Shiftlcd RightWaitms 200Next

ClsLcd “ Test Port 0 “LowerlineLcd “ Bit 2 exp 0 “

P0 = &B11111110Wait 1LowerlineLcd “ Bit 2 exp 1 “P0 = &B11111101Wait 1LowerlineLcd “ Bit 2 exp 2 “P0 = &B11111011Wait 1LowerlineLcd “ Bit 2 exp 3 “P0 = &B11110111Wait 1LowerlineLcd “ Bit 2 exp 4 “P0 = &B11101111Wait 1LowerlineLcd “ Bit 2 exp 5 “P0 = &B11011111Wait 1LowerlineLcd “ Bit 2 exp 6 “P0 = &B10111111Wait 1Lowerline

Lcd “ Bit 2 exp 7 “P0 = &B01111111Wait 1LowerlineLcd “ All Bits “P0 = &B00000000Wait 1

ClsLcd “ Test Port 3 “LowerlineLcd “ Test Port 0 (LED) “Wait 3

Status:P0 = P3X = P0ClsLcd “ Inputs “LowerlineLcd “Port 3 = “ ; X ; “ “Waitms 60Goto Status

End

USB Flash Board • 93 Elektor blockbusters

Page 94: E-book-15-ElektorBlockbusters-uk

2711/2007 - elektor

sign the LCD pins to port P2 under Options (Figure 7).

BASCOM supports configuration of different register files for individual 8051 derivatives. Although there are no specific settings for the AT89C5131, this microcontroller is largely compa-tible with the 8052, so you should use register file 8052.dat.

The listing shows the source code of the test program. It is easy to read and largely self-explanatory. After an intro-ductory message is displayed on the LCD, a running-light routine is execut-ed to check all the LEDs on Port P0. Following this, the inputs on port P3 are read in an endless loop and their states are copied to output port P0

andshown on the LCD. You can ac-tuate the DIP swit -

ches (S2) and pushbuttons

S3–S6 to check that they are proper-ly assigned to the

port pins. The as-sociated output

LED will light up for each

switch.The test

pro-gram

thus

exer-cises

practically all of the hardware.

A couple of ideasFinally, a couple of ideas for further

projects. The microcontroller has an internal EEPROM, similar to what is

found in the 89S8252 and the 89S8253. However, in this case it is governed by different control registers (SFRs). This means that you cannot escape a care-ful study of the data sheet if you want to use the supplementary hardware.Like the 8052, the AT89C5131 has ano-ther serial interface that can be used with BASCOM by instructions such as Print and Input. However, this re-quires connecting an additional line driver (such as a MAX232), since the USB Flash Board does not have a serial interface port. This opens the door to typical interface applications, which means that you can use the micro-controller as a PC-based measuring in-strument, counter or motor controller.Of course, the AT89C5131 can also do a lot more, including implementing a complete USB device. This is descri-bed in several application notes and accompanying source code on the At-mel website. The archive file c5131-usb-kbd-stand-alone-1_0_2.zip de-monstrates how to construct a USB keyboard.

With this USB microcontroller and the extensive software archive, you have essentially everything you need to de-velop your own USB applications.

(070999-1)

Figure 7. The assignment of the LCD pins to port P2 must be configured under Options.

USB Flash Board • 94 Elektor blockbusters

Page 95: E-book-15-ElektorBlockbusters-uk

Elektor blockbusters Artikeltitel • 95

5