PC Serial Design

28
Why have we chosen to use the serial port, when it is more complicated and offers fewer connections than the printer port? For a beginners’ course using the serial port has several advantages: - The serial port is well protected against accidental damage. Cables can safely be plugged in while the computer is on. - There is usually a spare serial port which can be used for experiments. - The serial port can deliver enough current to power a wide range of projects, and so a separate power supply is not required. This course is also easy on the pocket, which is important, not least for educational estab- lishments and those on youth employment programmes. Apart from the small printed circuit board, you will need just a few every- day components, such as pushbuttons, NPN transistors, resistors, LEDs, capacitors, diodes and an LDR. All the connections of the serial port are brought out to sockets on the circuit board and there is also a small proto- typing area for building experimental circuits. All the projects are programmed in Visual BASIC 5. The programs (available on floppy disk, order code 000074-11, or for download from www.elektor-electronics.co.uk) are clearly commented, so that you can easily BEGINNERS COURSE PC Serial Peripheral Design ( 1 ) Part 1: Introduction, course hardware, first program By B. Kainka At one time or another many readers may have thought about control- ling or monitoring equipment using their PC. Electronics projects using a PC need not be lavish or expensive: often the interfaces provided on the PC can be used directly. In this series of articles we present a range of projects using the serial (RS232) port, controlled using simple pro- grams written in Visual Basic.

description

PC RS232 Serial Peripheral Communications Design.

Transcript of PC Serial Design

Page 1: PC Serial Design

Why have we chosen to use the serial port,

when it is more complicated and offers fewer

connections than the printer port? For a

beginners’ course using the serial port has

several advantages:

- The serial port is well protected against

accidental damage. Cables can safely be

plugged in while the computer is on.

- There is usually a spare serial port which

can be used for experiments.

- The serial port can deliver enough current

to power a wide range of projects, and so a

separate power supply is not required.

This course is also easy on the pocket, which

is important, not least for educational estab-

lishments and those on youth employment

programmes. Apart from the small printed

circuit board, you will need just a few every-

day components, such as pushbuttons, NPN

transistors, resistors, LEDs, capacitors,

diodes and an LDR. All the connections of the

serial port are brought out to sockets on the

circuit board and there is also a small proto-

typing area for building experimental circuits.

All the projects are programmed in VisualBASIC 5. The programs (available on floppy

disk, order code 000074-11, or for download

from www.elektor-electronics.co.uk) are

clearly commented, so that you can easily

BEGINNERSCOURSE

PC Serial Peripheral Design (1)Part 1: Introduction, course hardware, first programBy B. Kainka

At one time or another many readers may have thought about control-ling or monitoring equipment using their PC. Electronics projects usinga PC need not be lavish or expensive: often the interfaces provided onthe PC can be used directly. In this series of articles we present a rangeof projects using the serial (RS232) port, controlled using simple pro-grams written in Visual Basic.

Page 2: PC Serial Design

change them to try out your own ideas. In

later instalments, we will deal with complex

topics such as real-time control and connec-

tion to external circuitry. As a bonus, readers

will be introduced to applications of various

sensor technologies, which arise naturally

through the course.

The printed circuit board

The projects are based on a simple circuit

board. As the circuit in Figure 1 shows, it is

a small prototyping board fitted with four SIL

socket strips and a 9-way sub-D socket. Two

of the four SIL sockets are connected to the

sub-D socket, while the other two are simply

connected to one another.

Figure 2 shows the component layout for the

circuit board, and the assembled board is

shown in Figure 3. Table 1 gives a summary

of the pinout of the 25-way and 9-way con-

nectors normally employed for serial ports,

showing the names and functions of all the

signals that make up the interface. A male

connector is invariably provided on the PC

side, and so we require a female connector: a

9-way extension cable can be used to con-

nect the PC to the circuit board described

here. If your PC is equipped with a 25-way

connector, you will need to use a suitable

adapter.

Data is normally transferred over the ser-

ial interface using the TXD (transmit data)

and RXD (receive data) signals. The other sig-

nals have auxiliary functions concerned with

setting up and controlling data transfer. They

are known as ‘handshake signals’, because

they are used to acknowledge transfer of data

between two pieces of equipment. A partic-

ularly useful feature of the handshake signals

is that their state can be read or written

directly.

The pin labelling on the circuit board fol-

lows that of the 9-way sub-D plug. Each pin

of this plug is taken to two SIL socket pins,

except for GND, which is taken to four. The

small prototyping area on the circuit board is

divided into five groups of connections with

four SIL socket pins in each. Four SIL sockets

with turned pins are used in total; two 20-pin

DIL sockets — which are easier to obtain —

can be used instead.

Visual BASIC

You will need a copy of Visual Basic, version 5

or 6, for this course. All source code is avail-

able from the Elektor Electronics website in

VB5 format. The programs can also be loaded

and compiled without modification using

VB6. If you do not have a copy of Visual Basic

BEGINNERSCOURSE

Figure 1. Circuit diagram of the experimental PCB.

Figure 2. Component layout for the experimental PCB.

1

2

3

4

5

6

7

8

9

K1 K2 K3 K4

DCD

RXD

TXD

DTR

GND

GND

RI

CTS

RTS

DSR

GND

RI

CTS

RTS

DSR

DCD

RXD

TXD

DTR

000074 - 11

000074-1 H1H2

IC1

IC2

K1

00

00

74

-1

10987654321DCDR

XDTXDD

TRG

NDD

SRR

TSC

TSR

IG

ND

000074-1

Figure 3. The assembled board.

Page 3: PC Serial Design

and balk at its price, you can obtain a free

version of VB5 from Microsoft: ‘Visual Basic

Control Creation’ VB5CCE is available on the

Internet at

http://msdn.microsoft.com/vbasic/downloads/cce/default.asp

Our first program: I/O test

And now, at last, to our first program. It’s a

simple test program which gives direct

access to all serial port connections (except

RXD). The three outputs can be tog-

gled with a click of the mouse, while

the four inputs are read and dis-

played. The program is configured to

use COM2 by default; however, it

will recognise when COM2 is in use

and automatically attempt to use

COM1 instead. It is assumed that

most PCs have a mouse connected

to COM1 and that COM2 is unused.

Frequently the connectors on PCs

are not correctly labelled: in that

case this program can help to iden-

tify them correctly. If you have two

spare COM ports, you can use COM1

or COM2 as you prefer.

What is ‘ON’, and what is ‘OFF’?

If you connect a voltmeter between

DTR and GND (ground), you will find

that ‘ON’ gives a positive voltage of

about 10 V, while ‘OFF’ gives a volt-

age of about –10V with respect to

GND. Now connect a wire between,

for example, the DTR output and the

DSR input. As soon as DTR is turned

BEGINNERSCOURSE

Figure 4. Visual Basic (VB5CCE) is available for download here.

Figure 5. Window showing direct access toserial port signals.

Table 1 Connector pinouts and signal names

Pin Pin Input/ Symbol Function25-way 9-way Output

2 3 Out TxD Transmit Data3 2 In RxD Receive Data4 7 Out RTS Request To Send5 8 In CTS Clear To Send6 6 In DSR Data Set Ready7 5 GND Ground8 1 In DCD Data Carrier Detect

20 4 Out DTR Data Terminal Ready22 9 In RI Ring Indicator

Page 4: PC Serial Design

on, the DSR input reports ‘ON’ too.

Our first practical application is to

poll a switch (Figure 6). In order to

read the state of the switch, the DTR

signal must be turned on. Now we

have a complete PC application: the

switch can be placed in some remote

location and it state will be relayed

to the PC. What that might represent

is up to you: you might, perhaps,

want to monitor whether that mouse-

trap in the cellar has been set off.

We round off this first instalment

with another neat little application.

Here a light-emitting diode is con-

nected to and controlled by the PC

(Figure 7). Many Elektor Electronicsreaders will protest loudly that one

should never connect an LED with-

out a current-limiting resistor. Here,

though, it is not necessary, as a resis-

tor is effectively built into the PC.

Another protest: in the

datasheets, the maximum allowable

reverse voltage of an LED is given as

3 V or 5 V. In this circuit, however,

reverse voltages of up to 10 V can

appear across the LED. Experience

has shown that this is not in practice

a problem. Even with a reverse volt-

age of 20 V no significant current

flows in most LEDs. But we should

provide a ‘clean’ solution: an addi-

tional silicon diode (for example, a

1N4148) will protect the LED from

excessive reverse voltages. The

diode can be connected either in

anti-parallel or in series with the

LED (Figure 8). As a rule of thumb,

for serious projects the reverse volt-

age should be limited to 5 V; for

experimental purposes we can allow

ourselves a little latitude.

(000074-1)

BEGINNERSCOURSE

Figure 6. A simple switch is connected for the first experiment.

S

DTR

DSR000074 - 15a

000074-1

K1 000074-1

10987654321DCD

RXDTXDDTRGNDDSRRTSCTSRIGND

000074 - 15bS

Figure 7. Equally simple: an LED is connected for the second project.

DTR

GND

LED

000074 - 16a

000074-1

K1 000074-1

10987654321DCD

RXDTXDDTRGNDDSRRTSCTSRIGND

000074 - 16bD

Figure 8. Two ways to protect the LED from excessive reverse voltage.

DTR

GND

LED

1N4148

000074 - 17a

DTR

GND

LED

1N4148

000074 - 17b

On Project Disk #000074-11:PORTS.BAS 845 03-28-00 5:31pANPEL.FRX 1,094 04-10-00 6:01pBLINK.FRX 1,094 04-10-00 6:43pCOUNTER1.FRX 1,094 05-04-00 6:49pCOUNTER2.FRX 1,094 05-04-00 7:14pCONTENTS.TXT 0 06-15-00 9:35aIOTEST.FRX 1,094 05-04-00 12:21pAMPEL.VBP 497 04-10-00 6:01pBLINK.VBP 497 04-10-00 6:43pCOUNTER1.VBP 499 05-04-00 6:49pCOUNTER2.VBP 499 05-04-00 7:14p

IOTEST.VBP 497 05-04-00 1:13pAMPEL.VBW 81 05-05-00 12:57pBLINK.VBW 80 05-05-00 4:26pCOUNTER2.VBW 80 05-05-00 4:27pIOTEST.BW 80 06-08-00 1:15pPORT.DLL 46,080 02-07-99 1:15pBLINK.FRM 3,488 04-10-00 6:43pCOUNTER1.FRM 3,422 05-04-00 6:49pCOUNTER2.FRM 6,683 05-04-00 7:14pIOTEST.FRM 5,317 05-04-00 12:21pANPEL.FRM 3,669 04-10-00 6:01p

22 file(s) 77,784 bytes

Page 5: PC Serial Design

In the first article in this series we introducedthe IOtest program. The majority of readerswith some programming experience will beinterested in how we access the serial inter-face using Visual Basic. Here we will use alibrary of program subroutines calledPORT.DLL written by H.-J.Berndt. This DLLfile is available from the Free Downloads sec-tion of the Elektor Electronics website athttp://www.elektor-electronics.co.uk. Forthose with no access to the Internet, the fileis also found on the diskette containing thecourse software (see Readers Servicespages).

In Visual Basic, all the procedures andfunctions defined in the DLL are declared andmust be in an external module. In our casethis is called PORTS.BAS (Listing 1).

The experienced (Visual Basic) user willprobably recognise the most commonly usedroutines for serial communications, e.g.,OPENCOM which is used to open the inter-face for communication and indicates that itis available to the program. SENDBYTE andREADBYTE are used to transfer data over theserial interface. For our purposes here, the

more important routines are thosethat access the control and statuslines of the interface. The proceduresDTR, RTS and TXD control these out-put signals and CTS, DSR, RI andDCD read the state of these inputsignals. One input line that you can-not read directly is RXD. This isbecause it would normally be usedto carry the received serial data.Also the PORT.DLL file contains rou-tines for time measurement that wewill be using later, as well as manyother functions for the other PC inter-faces (Parallel port, Joystick, Soundand Video).

I/Otest

The application program I/Otest isshown in Listing 2.The essential core of the program isthe timer procedureTimer1_Timer, which is automati-cally called at predetermined inter-vals. The check boxes 1 to 4 are acti-

BEGINNERSCOURSE

52 Elektor Electronics 10/2000

Part 2: Software

By B. Kainka

In this second part weconcentrate on software.We take a closer look at theIOtest program presented inthe first article and use simple program examplesin Visual Basic to control a model traffic light and a clock generator.

Figure 1. The traffic light LEDs.

DTR

RTS

TXD

GND

000074 - 2 - 11

PC Peripheral Design(2)

Page 6: PC Serial Design

vated and will show a tick when the corre-sponding input line is switched to a ‘1’. Thethree output lines are switched when theuser activates the corresponding check box.

The other parts of the program are usedto select and open the interface and we willlook at them a little later. We can see that theinterface will be initialised with a communi-cation rate of 1200 baud, no parity bit, 8 databits and 1 stop bit. For our purposes here,these communication parameters are entirelysuperfluous because we are only interestedin the control lines that form part of the inter-face. Windows will however configure theport as if it were to communicate with, forexample, a modem. But all we need to dohere is to read the input status lines andwrite to the output control lines.

Traffic Light controller

If you are new to Visual Basic it is a good ideato choose some hardware that you can actu-ally see working. For this reason a model traf-fic light with three LEDs was chosen (Fig-ure 1). The effects of current limiting andreverse voltage on the LEDs were discussed inthe first article of this series.

The model lamp is well suited to experi-menting for our first excursion into program-ming with Visual Basic. For the programdevelopment you will need to start with anew blank form, and using the mouse, selectand drag graphic control elements from thelist of tools onto the form (Figure 2). The sizeof each element and its position can be eas-ily altered. Each element has a completerange of properties that can be attached to it,including size, colour, text and much more.Those that you are not sure of yet can be sim-ply left as they are. For our application we usethe following elements:

- Two labels with the properties (the text)Caption = “fast” and “slow” respectively.

- A horizontal slider or scroll bar (HScrollBar)with the properties Min = 50, Max = 500and Position =100

- A timer (Timer) with the property Interval =100, i.e. 100 ms

- Two Option Buttons with the Caption =“COM1” and “COM2” respectively, the but-ton for COM2 is “true”

- The form itself contains the Caption = “Traf-fic Light”

Figure 3 gives an overview of the project. Theaforementioned module PORTS.BAS is alsoincluded in the project and contains all the

BEGINNERSCOURSE

5310/2000 Elektor Electronics

Listing 2User program IOtestPrivate Sub Form_Load()

i = OPENCOM(“COM2,1200,N,8,1”)

If i = 0 Then

i = OPENCOM(“COM1,1200,N,8,1”)

Option1.Value = True

End If

If i = 0 Then MsgBox (“COM Interface Error”)

TXD 1

RTS 1

DTR 1

TIMEINIT

End Sub

Private Sub Form_Unload(Cancel As Integer)

CLOSECOM

End Sub

Private Sub Option1_Click()

i = OPENCOM(“COM1,1200,N,8,1”)

If i = 0 Then MsgBox (“COM1 not available”)

TXD 1

RTS 1

DTR 1

End Sub

Private Sub Option2_Click()

i = OPENCOM(“COM2,1200,N,8,1”)

If i = 0 Then MsgBox (“COM2 not available”)

TXD 1

RTS 1

DTR 1

End Sub

Private Sub Timer1_Timer()

Check1.Value = CTS()

Check2.Value = DSR()

Check3.Value = DCD()

Check4.Value = RI()

If Check5.Value Then TXD 1 Else TXD 0

If Check6.Value Then DTR 1 Else DTR 0

If Check7.Value Then RTS 1 Else RTS 0

End Sub

Listing 1Declarations for PORT.DLL

Declare Function OPENCOM Lib “Port” (ByVal A$) As Integer

Declare Sub CLOSECOM Lib “Port” ()

Declare Sub SENDBYTE Lib “Port” (ByVal b%)

Declare Function READBYTE Lib “Port” () As Integer

Declare Sub DTR Lib “Port” (ByVal b%)

Declare Sub RTS Lib “Port” (ByVal b%)

Declare Sub TXD Lib “Port” (ByVal b%)

Declare Function CTS Lib “Port” () As Integer

Declare Function DSR Lib “Port” () As Integer

Declare Function RI Lib “Port” () As Integer

Declare Function DCD Lib “Port” () As Integer

Declare Sub DELAY Lib “Port” (ByVal b%)

Declare Sub TIMEINIT Lib “Port” ()

Declare Sub TIMEINITUS Lib “Port” ()

Declare Function TIMEREAD Lib “Port” () As Long

Declare Function TIMEREADUS Lib “Port” () As Long

Declare Sub DELAYUS Lib “Port” (ByVal l As Long)

Declare Sub REALTIME Lib “Port” (ByVal i As Boolean)

Page 7: PC Serial Design

In the normal course of eventsthe program will open COM2. Ifhowever you want to use COM1then you can point to the corre-sponding button and click. This willcause Windows to call the proce-dure Option1.Click which will openCOM1 and check for a successfulreturned status. This automaticselection and manual override hasalready been used in the IOtest pro-gram and will also used in theupcoming program examples. Itwould be a simple matter to addextra buttons to control the COM3and COM4 interface.

necessary declarations for PORT.DLL. Itneeds to linked with the software in each ofthe projects so that they can all have accessto the procedures and functions that areneeded to control the serial interface.

In a Visual Basic program, events areproduced by procedures that are isolatedfrom each other. The overall flow of the pro-gram is controlled by Windows. The proce-dure ‘Private Sub Form_Load()’ will be calledright at the beginning of the program (List-ing 3) This procedure contains all the instruc-tions needed to initialise the serial interface.In this case, the serial interface will be openand all the outputs of the interface will beswitched off. Lastly, the global variable

‘Time’ is reset to zero.The function OPENCOM in

PORT.DLL returns a value indicatingif the interface has been successfullyopened. It will not be possible toopen it if it is already in use byanother program. Initially the pro-gram will use this function to openCOM2. If the return value from thisfunction is 0 i.e. it is busy thenCOM1 will be opened. This will bedisplayed on the screen with thevalue of option button 1 (COM1)‘True’. If both COM1 and COM2 arebusy then a failure message will popup in a MessageBox.

BEGINNERSCOURSE

54 Elektor Electronics 10/2000

Listing 3Traffic lights programDim Time As Integer

Private Sub Form_Load()

i = OPENCOM(“COM2,1200,N,8,1”)

If i = 0 Then

i = OPENCOM(“COM1,1200,N,8,1”)

Option1.Value = True

End If

If i = 0 Then MsgBox (“COM Interface Error”)

TXD 0

RTS 0

DTR 0

Time = 0

End Sub

Private Sub Form_Unload(Cancel As Integer)

CLOSECOM

End Sub

Private Sub HScroll1_Change()

Timer1.Interval = HScroll1.Value

End Sub

Private Sub Option1_Click()

i = OPENCOM(“COM1,1200,N,8,1”)

If i = 0 Then MsgBox (“COM1 not available”)

TXD 1

RTS 1

DTR 1

End Sub

Private Sub Option2_Click()

i = OPENCOM(“COM2,1200,N,8,1”)

If i = 0 Then MsgBox (“COM2 not available”)

TXD 1

RTS 1

DTR 1

End Sub

Private Sub Timer1_Timer()

Time = Time + 1

If Time = 1 Then red

If Time = 40 Then redyellow

If Time = 50 Then green

If Time = 90 Then yellow

If Time = 100 Then Time = 0

End Sub

Sub red()

RTS 1

DTR 0

TXD 0

End Sub

Sub redyellow()

RTS 1

DTR 1

TXD 0

End Sub

Sub yellow()

RTS 0

DTR 1

TXD 0

End Sub

Sub green()

RTS 0

DTR 0

TXD 1

End Sub

Page 8: PC Serial Design

Blinker/Clock generatorThis next application is a blinker or clock gen-erator with adjustable frequency (Figure 5).The circuit is the same as for the traffic lightexperiment. This time, the TXD output is per-manently switched on while DTR and RTS areswitched in anti-phase, i.e., when one is on theother is off and vice versa. It is not too difficultto see how this program can be expanded toturn it into a mini running light display.

The software from the traffic light pro-gram is used again for this exercise. Thetimer procedure is, however, new (Listing 4).One difference here is that no additional pro-cedures are called to control the output lines,they are switched directly from inside ‘timer-procedure’.

The LEDs on the DTR and RTS lines shouldnow blink alternately. The speed of the blink-ing can be increased or decreased. As youincrease the speed you may notice that thetiming for each blink is not precisely regular.The reason for this is that Windows cannotmaintain a time interval of exactly 50 mil-liseconds because it is a multitasking oper-ating system many other processes will berunning at the same time. For this reasonWindows is generally considered to be notcapable of ‘real time’ operation. However,there are some tricks and techniques that wecan use and we shall be investigating themin the coming articles.

(00074-2e)

dure can be called to find out if aspecific period has elapsed before,for example, the traffic light LEDsare changed. The speed of switch-ing has been chosen arbitrarily andcan be easily altered. The IF state-ments are used to compare thetime values and switch the corre-sponding LED.

The form (Figure 4) also con-tains a horizontal slider or scrollbar. This slider is used to alter thespeed of the traffic light changing.As soon as the slider is moved, theprocedure Hscroll1.Change iscalled. This procedure will changethe interval in the timer corre-sponding to the actual position(Value) of the slider control. Theslider is calibrated from 50 to 500;the timer can therefore be altered inthe range from 50 ms to 500 ms.

BEGINNERSCOURSE

5510/2000 Elektor Electronics

Figure 2. The traffic light controllerform.

Figure 3. Project overview.

Figure 4. The traffic light programduring run time.

Figure 5. The Blinker Program.

Listing 4Timerprocedure for blink program

Private Sub Timer1_Timer()

Time = Time + 1

If Time = 1 Then

RTS 1

DTR 0

End If

If Time = 2 Then

RTS 0

DTR 1

End If

If Time = 2 Then Time = 0

End Sub

For the traffic light controller wewill need some timer function tointroduce a delay between chang-ing the lights. In the DLL there is,for example, a procedure calledDELAY. However, unlike program-ming in DOS, individual Windowsprograms do not have the entireprocessing time devoted to them. Itwould be pointless to write a pro-cedure containing a simple timingloop to give us the delays that weneed for the traffic light. Instead,the traffic light timer will be eventcontrolled. For this we will use aWindows timer. The timer period isset to 100 ms. The procedure will becalled every 100 ms.

In the timer procedure there isa variable called “Time” which isincremented and gives the time intenths of a second, so the proce-

Page 9: PC Serial Design

We have already seen in this course that theoutput signals of the RS-232 interface swingbetween –10 V and +10 V. However,because the output current is limited, it issafe to connect an LED directly. But whatexactly are the characteristics of the out-puts? We shall attempt to answer this ques-tion now.

In general, manufacturers of PC equip-ment follow the RS-232 standard, in whichthe voltage levels used to send data arespecified. It was originally specified that

BEGINNERSCOURSE

62 Elektor Electronics 11/2000

PC Serial Peripheral Design (3)

By B. Kainka

In this third part we look at theoutput signals of the RS-232 interface.In order to control devices with these out-put signals, it is necessary to know what can (andwhat cannot!) be expected of the output drivers: thisknowledge can then be used in our experiments.

the output voltages should be±15 V, while at the inputs a signalof at least ±3 V is required. Voltagesbelow –3 V are considered to be alogic ‘1’, and voltages above +3 Vare considered logic ‘0’. Since theoutputs deliver ±15 V, and theinputs require only ±3 V, reliabledata transfer is assured even overlong cables. Noise is much less of aproblem than it is with for examplethe TTL logic levels of 0 V and 5 V.

The standard in theoryand practiceModern PCs no longer adhere to therequirement to generate output volt-ages of ±15 V. The PC’s power sup-ply produces +12 V and –12 V, whichare used instead. The ultimate volt-age is somewhat lower than thisagain: this is due to the output dri-vers used. On separate interfacecards the 1488 driver and 1489

Page 10: PC Serial Design

receiver devices are generally used:these have set a de facto standardfor the behaviour of RS-232 inter-faces. Figure 1 shows the circuit ofthe driver in the IC. It is clear howthe current limiting (set at 10 mAaccording to the datasheet) is pro-vided. If the output is short-circuited,no more than 10 mA can flow. It canalso be seen that 12 V cannot beexpected at the output even when a12 V power supply is used: the volt-age drop of the output stage is suchthat only about 10 V will be pro-duced.

Many PCs are now built withmore integrated components, withoutput drivers already included,which can produce rather differentresults. It is interesting to determinethe exact voltages and currents

available from a particular PC. Thetrend among PC manufacturers isalways faster, bigger, better: thatmeans, as far as the RS-232 interfaceis concerned, higher baud rates overlonger cables with greater reliability.To ensure that the higher capaci-tance of longer cables does not havetoo great an adverse effect on thepulse shape, the maximum outputcurrent must be increased. The out-puts of more recent PCs therefore arecapable of delivering around 20 mArather than 10 mA. A total of up to60 mA can be drawn from the inter-face. That is handy for our experi-ments, and is another reason forwanting to make accurate measure-ments. On some PCs output voltagesof ±12 V can indeed be found: thesepresumably use MOSFETs in theirdriver output stages.

Measuring the outputcharacteristicsThe output characteristics can bemeasured very roughly using, forexample, a digital multimeter. Fig-ure 2 shows how to measure theopen-circuit voltage and short-circuitcurrent. ‘Short-circuit’ sounds ratherdangerous, but because of its cur-rent limiting the RS-232 interface willnot be damaged.The author’s PC measures as fol-lows:

BEGINNERSCOURSE

6311/2000 Elektor Electronics

Table 1R [kΩ] I [mA] U [V]infinite 0 10.9

22 0.48 10.610 1,04 10,44.7 2.12 102.2 4.18 9.21 7.8 7.8

0.47 12.55 5.90.33 14.84 4,.90.01 25 0.25

Figure 1. Schematic of the 1488 (source: Motorola)Figure 2. Measuring the open-circuit voltage(2a) and the short-circuit current (2b).

Figure 3. Measurements with variable load.

Figure 4. Characteristic curve for one output.

6k

2

3k

6

10

k

6k

2

70Ω

7k

0

70Ω

300Ω

VEE

VCC

14

4, 9, 12, 2

5, 10, 13

7

1

6, 8, 11, 3

000074 - 3 - 11

DTR

GND

V

000074 - 3 - 12a

DTR

GND

A

000074 - 3 - 12b

a

b

DTR

GND

V

A

10k

000074 - 3 - 13a

DTR

GND

V

0 ... 22k

000074 - 3 - 13b

a

b

12

10

8

6

4

2

00 5 10 15 20 25

000074 - 4 - 14

1kΩ

LED

I / mA

U / V

Page 11: PC Serial Design

Open-circuit voltage: U0 = –10.9 V (off),U0=+10.9 V (on)Short-circuit current: Imax = –22.4 mA (off),Imax=24.4 mA (on)

A number of measurements must be takenin order to get more exact data for a particularPC: the voltage and current must be mea-

sured for a range of loads. A poten-tiometer (say 10 kΩ) or a set of fixedresistors of various values can beused as a load. If two meters areavailable, the voltage and currentcan be measured simultaneously(Figure 3a); if only one, the voltagecan be measured, and then, as longas the resistor value is known, thecurrent can be calculated (Fig-ure 3b). For the example here, weused a set of standard resistors. Thevoltage was measured and the cur-rent calculated using the formulaI=U/R. The results can be seen inTable 1.

Figure 4 shows how the outputvoltage decreases under increasingload. The lowest-valued resistor, at10 Ω, gives practically a short-circuit,but a voltage can still be measured.The graph shows, to a first approxi-mation, that the voltage falls linearlywith increasing current. The internalresistance of the output can be cal-culated from the gradient of thegraph to be about 430 Ω. A modernbright LED has a forward voltagedrop of about 2.2 V. From the graphwe can read off the current: about20 mA. This is about the maximumallowable continuous current for anormal LED. So our measurementsshow that we can connect an LEDwithout a series resistor.

We used Microsoft Excel toanalyse the measurements. If youwish, you can carry out the corre-sponding experiments for your ownPC, which makes a good exercise inmeasurement and analysis; or youcan move straight on to the follow-ing experiments.

Uses for the serial interfaceIf the interface can drive LEDsdirectly, the current must also beenough for other purposes. As wehave already stated, up to approxi-mately 60 mA can be drawn from theinterface. We look at a few applica-tions here.

The following practical applica-tion is a small battery charger oper-ating from the serial interface. In thecircuit shown in Figure 5 the charg-ing current is about 30 mA. That isadequate for small batteries or fortrickle charging. We will work witha negative output voltage: the

advantage is that the circuit worksimmediately the PC is switched on,without having to run a program. Ifit is desired to use the oppositepolarity, the diodes can be reversedand the outputs switched to +10 Vin software. You could also controlcharging automatically in software.

Another example of a device thatcan be driven directly from the serialinterface is a small DC motor. Asmooth-running motor, such as theones found in cassette recorders, canbe used, and will run satisfactorilyon 30 mA. To obtain this current,several outputs are connectedtogether to drive the motor. With asmall modification to the ‘flasher’program two outputs can be made toswitch simultaneously. The motorcan then be made to run in eitherdirection.Small relays can also be connecteddirectly to the interface (Figure 6). Adiode is normally required to ensurethat the relay drops out when thepolarity is reversed.

Transistor switching stages Relays can be used to switch cur-rents greater than that required byLEDs. Cheaper, more elegant andless extravangant is a transistorstage. Figure 7 shows how a100 mA bulb can be switched, usingan external power supply. The tran-sistor used is a BC548. The principleof the switching stage is very sim-ple: the interface delivers a relativelysmall base current to the transistorwhich is amplified, so that the col-lector current is sufficient to drivethe lamp.

How are the components for theswitching stage selected? The mostimportant considerations will be dis-cussed briefly here. The operatingcurrent of the bulb is 100 mA. Thiscan be provided by a BC548 withoutdifficulty: the maximum collector cur-rent allowed is 300 mA. If the lampcurrent is measured at the momentit is switched on, it will be foundthat it is considerably greater. Whenthe bulb is cold it has a resistance ofabout 1/10 of that when it is operat-ing. In theory, then, an instanta-neous current of 1 A will flow. Inpractice, however, the currentswitched by the transistor is limited.

BEGINNERSCOURSE

64 Elektor Electronics 11/2000

GND

100Ω

4V8NiCd

000074 - 3 - 15

TXD

DTR

RTS

- 10V

Figure 5. Charging a battery from the RS-232interface.

DTR

GND

000074 - 3 - 16

Figure 6. Connecting a relay.

DTR

GND

2k2

1N4148

BC548

6V

100mA

4V5...6V

000074 - 3 - 17

Figure 7. Connecting a transistor switchingstage.

Page 12: PC Serial Design

Using a special multiplier circuit, a DC volt-age of about 20 V can be obtained; using amultiplier cascade a factor of 4 can beachieved, giving about 40 V. The circuit con-sists of four capacitors and four diodes (Fig-ure 9). Here LEDs are used so that the cir-cuit’s operation can be seen directly.

When the program is first run, the LEDsflash relatively brightly. The brightnessdecreases gradually to practically nothing,when the capacitors have charged to theirfinal voltages. A voltage of 40 V can be mea-sured at the output of the circuit. If the capac-itors are discharged using a 1 kΩ resistoracross the output, the process starts againfrom the beginning.

This circuit is an example of how LEDs canbe ‘stressed’ by high voltages. This is fine forour experimental purposes, since experienceshows that LEDs can cope with the high volt-ages without difficulty. One should be aware,however, that such circuits hardly representexemplary engineering practice; for profes-sional applications, silicon diodes (such asthe 1N4148) should of course be used.

(00074-3)

The bulb filament warms up afteronly a few milliseconds and so theoverload is brief enough to be with-stood. If you are not sufficiently reas-sured by this, you can substitute aBC338 which can withstand a peakcurrent of 800 mA.

The 2.2 kΩ base resistor will havea potential of around 10 V across it.When the output is on, the base cur-rent will be about 4.5 mA. TheBC548 is available in three gaingroups with gains of between 110and 800. Usually the BC548C is used,with a gain of between 420 and 800.In the pessimistic case a base cur-rent of 100 mA/400 = 0.25 mA isrequired; the actual base currentwith a 2.2 kΩ base resistor is com-fortably more than this. Note, how-ever, that the gain falls at higher col-lector currents. In any case, the tran-sistor will be driven well intosaturation, guaranteeing the small-est possible voltage drop betweenemitter and collector and keepingpower dissipation low both duringoperation and at the instant the tran-sistor is switched on.

As can be seen, the choice of baseresistor is not arrived at by exact cal-culation, but rather by estimation,since normally the gain of the tran-sistor is not known precisely. It isinteresting to try various base resis-tors to discover over what range rea-sonable results are obtained. Withtoo high a value, the transistor willnot be driven fully into saturation;then the voltage drop becomesgreater and the transistor becomesnoticeably warm. Also, a resistorwhich gives satisfactory results inthe ‘on’ state can nevertheless notbe able to provide sufficient drive atthe instant of turn-on. The lampappears to turn on slowly, duringwhich time there is considerablepower dissipated in the transistor.With too low a base resistor power iswasted in the control circuit, leadingalso to higher dissipation and possi-bly to overloading the base-emitterdiode by exceeding the maximumallowable base current. The absolutemaximum allowable base current isgiven in the datasheet.

In the circuit diagram a diode isshown connected in reversebetween the base and emitter of thetransistor. This prevents excessivenegative voltages appearing at the

base. The maximum reverse voltageof the base-emitter diode generallylies at around –5 V. Breakdownoccurs at about –9 V, when a consid-erable reverse current flows. Thetransistor behaves like a Zener diodewith a voltage of about 9 V. Since inthe ‘off’ state the voltage will bearound –10 V, it must be limited.With the diode fitted, the base volt-age cannot fall below –0.6 V. It is aworthwhile experiment to investi-gate the effect of omitting the diode.A reverse current indeed flows, butthe transistor nevertheless does notconduct: the lamp remains off. Thecircuit works even without thediode. It is said that a continuousreverse current over time impairs thenoise performance of the transistor;but that will not be a problem here.As so often, it makes a differencewhether one is experimenting ordesigning a circuit in earnest; in thelatter case, the diode belongs in thecircuit.

AC experiments

The flasher program (Flasher.vbp)produces an alternating voltage onthe DTR and RTS outputs, whose fre-quency can be adjusted up to a limitof about 10 Hz. This lets us try somesimple experiments with alternatingcurrent. As is well known, a capacitorappears as a resistor to alternatingcurrent, conducting the current betterat higher frequencies. This can bedemonstrated using the circuit ofFigure 8. Here a capacitor is con-structed from two electrolytics con-nected back-to-back to enable oper-ation with an alternating voltage.This arrangement is sometimes usedin driving loudspeakers.

If the flasher program is set to alow frequency, the LEDs alternatelyflash briefly. At each transition thecapacitor is recharged. The currentthen falls to zero as the voltageacross the capacitor approaches thevoltage on DTR. If the frequency isincreased, the flashes become morefrequent and the average brightnessof the LEDs also increases. Thecapacitor presents a lower resis-tance to the alternating current, andso the (average) current increases.

The alternating voltage producedhas a peak value of about 10 V. Thepeak-to-peak voltage is around 20 V.

BEGINNERSCOURSE

6511/2000 Elektor Electronics

DTR

GND

100µ16V

100µ16V

000074 - 3 - 18

Figure 8. Capacitors as AC resistors.

DTR

GND

V

000074 - 3 - 194x 100µ / 16V

Figure 9. 40 Volts from the serial interface.

Page 13: PC Serial Design

Typical RS-232 interface cards use atype 1489 receiver (Figure 1). ThisIC requires a single 5 V power sup-ply. The schematic shows a simpleswitching stage consisting of threetransistors. As can be seen, the

BEGINNERSCOURSE

66 Elektor Electronics 12/2000

PC Serial PeripheralDesign (4)By B. Kainka

So far we have studied the characteristics of the RS-232 outputs in detail.Now it is the turn of the inputs. The standard demands that an input voltage

of more than +3 V is considered as‘high’, while a voltage lower than

–3 V is considered as ‘low’.Between these voltages the level

is not defined.

Figure 1. Schematic of 1489 (source: Motorola).

1k

7

5k

0

9k

0

10

k

3k8

R

1

2

14

3

7

FResponse Control

Input

GND

Output

VCC

000074 - 4 - 11

MC1489 MC1489A

6k7 1k6R F

Page 14: PC Serial Design

always be detected correctly. However, if anLED is connected, the results may be differ-ent: it can happen that the LED will glow, butthe input will still read as zero.For some experiments it is important to knowthe input current rather than the thresholdvoltage. Here again we can make some sim-ple measurements (Figure 4), and, again, weobserve a hysteresis. We measured:Upper threshold: 0.18 mALower threshold: 0.36 mA

From these results we can deduce that an RS-232 output can easily drive, in parallel, moreinputs than the four available. From the volt-ages and currents measured we can calculatean input resistance of 5.6 kΩ. This resultseems plausible, looking at the schematic ofthe 1489.

An important result from these mea-surements is that a negative voltage is notrequired for an input to read as zero, eventhough the RS-232 standard prescribes avoltage below –3 V. Many experiments cantherefore be carried out with only a singlepower supply. There may, of course, be theodd PC which behaves differently from ourexample. In particular, some laptopsrequire negative input voltages. This mustbe taken into account in some of ourexperiments.

threshold voltage will not be verydifferent from the base-emitterthreshold of about 0.6 V. Taking intoaccount the voltage divider at theinput (consisting of a 3.8 kΩ and a10 kΩ resistor) we arrive at a figureof about 0.8 V. A further resistor RFlinks the output of the second tran-sistor stage back to the base of thefirst, providing feedback. The circuittherefore behaves as a Schmitt trig-ger. There are therefore two switch-ing thresholds, one when the inputvoltage is rising and one when it isfalling. With the input in betweenthese two levels the output willremain in its previous state. Accord-ing to the datasheet the lowerthreshold for the 1489 is 1 V, whilethe higher is 1.25 V, a difference of0.25 V. The 1489A, in contrast, has alower resistor RF, giving thresholdsof 1 V and 1.95 V.

MeasurementsThe 1489 sets the de facto standardfor RS-232 inputs. In modern PCs thereceiver is normally integrated into amore complex IC, giving the manu-facturer the choice of adhering to thequasi-standard, or to interpret theRS-232 standard differently. It istherefore interesting to determinethe exact behaviour of the inputs ona particular PC. For this, anadjustable voltage source isrequired: this does not mean that wewill need a piece of laboratory equip-ment, since the interface itself pro-vides the voltages we shall need. Asimple potentiometer suffices to helpmake our measurements (Figure 2).

The IOTEST program from thefirst instalment of this series is usedto make the measurements. The RTSsignal is turned on, and the DCD sig-nal is monitored (Figure 3). Readingsare taken from the voltmeter as thepotentiometer is adjusted. Theauthor’s PC gave the followingresults:Lower threshold: 1.0 VUpper threshold: 2.0 V

The input circuit in the PC is there-fore a 1489A rather than a 1489.

These measurements can berepeated for all four inputs on theserial interface, and similar readingswill be obtained. Knowing the upperthreshold is useful for some possibleapplications. For example, it is notpossible to detect a 1.5 V batteryconnected to an input, whereas adirect connection between an RS-232output and an RS-232 input will

BEGINNERSCOURSE

6712/2000 Elektor Electronics

Figure 2. Measuring the inputthresholds.

V

RTS

DTR

22k

DCD

GND000074 - 4 - 12

+10V

–10V

Figure 3. Observing the state of theinputs.

Figure 4. Measuring the input current.

RTS

DTR

22k

DCD

GND

+10V

–10VA

000074 - 4 - 14

Listing 1The Counter1 program

Dim DSRold, Counter1

Private Sub Form_Load()

i = OPENCOM(“COM2,1200,N,8,1”)

If i = 0 Then

i = OPENCOM(“COM1,1200,N,8,1”)

Option1.Value = True

End If

If i = 0 Then MsgBox (“COM

Interface Error”)

TXD 1

RTS 1

DTR 1

Counter1 = 0

DSRold = DSR()

Timer1.Interval = 20

End Sub

Private Sub Timer1_Timer()

DSRNew = DSR()

If DSRNew > DSRold Then

Counter1 = Counter1 + 1

Label1.Caption =

Str$(Counter1)

End If

DSRold = DSRNew

End Sub

Page 15: PC Serial Design

Pulse counterBuilding a counter in digital hard-ware is a relatively complicated job.When a PC is available, however, itis easy. Here a pulse counter is con-structed in Visual Basic. The DSRsignal serves as an input: a simplepush-button can be used to providepulses. Any other sensor could beused, as long as it can provide thecorrect voltage.

Listing 1 shows the programCounter1; the results on the screenare shown in Figure 7. Two globalvariables are used. DSRold stores theprevious state of the DSR signal andCounter1 stores the count. The twovariables are initialised in the firstroutine. The counter is set to zero,and DSRold is loaded with the stateof the DSR signal. The outputs arealso all turned on. This allows any ofthe outputs to be connected to theDSR input to provide a count signal.

The actual counting is done in thetimer routine. Windows calls this rou-tine roughly once every 20 ms. Eachtime the state of the DSR input iscompared with the state on the pre-vious call. If the new state is greaterthan the old state, a change from 0 to1 must have happened: in otherwords, a rising edge. These edgesare counted by incrementing the vari-able Counter1 by one each time. Thevalue on the screen is only refreshedwhen the variable changes.The pulses are counted reliablywhether the button is pressedrapidly or slowly, up to about 5pulses per second. When the pulserate is faster than this, however, it

will be found that some pulses maybe missed. The exact limit dependson the PC. With a timer interval of20 ms a signal with low and highperiods of 20 ms should theoreticallybe read correctly. A total period of40 ms corresponds to a frequency of25 Hz (25 pulses per second). How-ever, problems are observed at lowerfrequencies than this. From this wededuce that Windows cannot reli-ably maintain a timer interval of20 ms. A similar observation wasmade when we discussed the LEDflasher program. Even with a timerinterval of 50 ms definite irregularitycan be seen.This counter program is certainlynot the fastest possible. Further-more, we can easily construct a four-way counter, as shown in Figure 8:we simply need to write out thecode four times. Each time a differ-ent input is read and processed.Listing 2 shows the modified timerroutine.

(000074-4)

BEGINNERSCOURSE

68 Elektor Electronics 12/2000

Figure 7. The Counter1 program.

Figure 8. The four-way counter Counter2.

Listing 2Pulse counter with four inputs

Private Sub Timer1_Timer()

DCDnew = DCD()

DSRnew = DSR()

CTSnew = CTS()

RInew = RI()

If DCDnew > DCDold Then

Counter1 = Counter1 + 1

Label1.Caption =

Str$(Counter1)

End If

If DSRnew > DSRold Then

Counter2 = Counter2 + 1

Label2.Caption =

Str$(Counter2)

End If

If CTSnew > CTSold Then

Counter3 = Counter3 + 1

Label3.Caption =

Str$(Counter3)

End If

If RInew > RIRold Then

Counter4 = Counter4 + 1

Label4.Caption =

Str$(Counter4)

End If

DCDold = DCDnew

DSRold = DSRnew

CTSold = CTSnew

RIold = RInew

End Sub

Figure 6. Three buttons can be fitteddirectly to the circuit board.

000074-1

K1

000074-1

10987654321DCDRXDTXDDTRGNDDSRRTSCTSRIGND

000074 - 4 - 16

3x S

Figure 5. Up to four switches can beconnected.

000074 - 4 - 15

+10VDTR

RI

CTS

DSR

DCD

Reading the state of a switchIt is easy to use the serial interface to readthe state of up to four switches (Figure 5).One output, for example DTR, is required: thisis set high, in order to generate the requiredvoltage. The switches can be connected viaa cable of practically any length. Up to threetypical ‘reset-switches’ can be fitted to thecircuit board (Figure 6), in which case threeinput signals are used.

Page 16: PC Serial Design

nected between an output that hasbeen set high and an input, there areonly two possible results: either theresistor is sufficiently small that aclear logic one is read at the input, orit is not. If more precision is required,a new approach is needed.

Charging and discharging

If computers are good at one thing,it is counting. We can use this tomeasure time: a program simplycounts the seconds (or milliseconds)that pass until a certain event hap-pens, for example when an inputchanges state. If we can convert ananalogue quantity such as a resis-tance into a time period, then it willbe easy to measure it with a com-puter. In this example, we can usean RC network. Figure 1 shows acapacitor C charged and dischargedthrough a resistor R. A time constantT is associated with an RC network:

T = RC.

Here T is the time taken for the volt-age across the capacitor to reach63.2 % (=1-1/e) of its final value. Thiscan be derived from the exponentialcharging characteristic, shown inFigure 2. We shall not go into thedetails of the physics here: it isenough to know that the time takento charge to a given voltage isdirectly proportional to the capaci-tance and to the value of the resistor.

For a 100 µF capacitor and a 1 kΩresistor we have:

T = 1000 Ω × 0.0001 F = 0.1 s =100 ms

A doubling of the resistance leads toa doubling of the charging time. Thesame goes for a doubling of thecapacitance. So, we can measure thecharging time and deduce the valueof either one of the resistor or thecapacitor, if the value of the other isknown. All that is needed is a pro-gram that replaces the switch in Fig-ure 1. Figure 3 shows a simple circuitwhere the capacitor is connected notto ground but to the TXD output.There is a good reason for this: if anelectrolytic capacitor is used, it mustnever be charged with the wrongpolarity, and this is guaranteed aslong as TXD remains at –10 V.

The circuit charges and dis-charges the capacitor via DTR anduses the DSR signal as an input todetermine when the set voltage isreached. The threshold voltage willbe around 1.5 V. Comparing this withthe overall voltage range of –10 V to+10 V, we see that the threshold isabout 11.5 V/20 V = 0.575 = 57.5 %of the final voltage. This is not too farfrom our value of 63.2 % given abovefor the time constant. In any case,the error factor introduced is con-stant and can be compensated forlater. There are other sources of error,which we discuss below.

BEGINNERSCOURSE

26 Elektor Electronics 1/2001

PC Serial PeripheralDesign (5)Analogue measurements By B. Kainka

So far in this series we have used the PC only with digital signals: switching,monitoring and counting. Now we turn to the analogue domain: our programswill understand not just ‘yes’ and ‘no’, but ‘larger’ and ‘smaller’.

Figure 1. Charging and discharging a capacitor

R

C

000074 - 5 - 11

Figure 2. Charge/discharge curves anddefinition of the time constant T

T

000074 - 5 - 12

T

If a voltage is applied to a serial port input, itwill be read as either a logic Low (0) or a logicHigh (1). The PC cannot determine the actualvoltage present. Likewise, if a resistor is con-

Page 17: PC Serial Design

Counting timeThe time measurement takes placein a ‘while’ loop as shown in List-ing 1. The loop runs until either DSRbecomes set or the count reaches1.5 seconds (timeout). The measure-ment loop includes the commandDoEvents: this allows Windows toprocess other events that may beoccurring in the system. During mea-surements the user can still use themouse and other applications, andindeed stop the program itself. Thisis reassuring for the user, especiallywhen bugs in the program cause itto function incorrectly. In general itis always necessary, when program-ming loops, to consider how the loopcan be forced to terminate. Other-wise if the program gets into an infi-nite loop the PC will need to bereset, either by switching it off andon again, or by using the familiarCtrl-Alt-Del chord. Adding aDoEvents call makes the loop safe;but this has a cost in timing accu-racy, adding an uncertainty ofaround 1 to 3 milliseconds to themeasured time.

µF not ms

If the units ‘ms’ in the window inFigure 4 are replaced by ‘µF’, thevalue shown is not too far off the true

one. As we said above, a 100 µFcapacitor and a 1 kΩ resistor give atime constant of 100 ms. Similarly,with a 10 µF capacitor we have atime constant of 10 ms. This can betested by trying various capacitorsfrom the junk box. Often there will bequite a large discrepancy betweenthe value measured and the valueprinted on the capacitor: this isdown to the large tolerance (as muchas 50 %) quoted for electrolytics. Thecapacitance of an electrolytic oftenchanges if it is stored for a long time.

The measurements are less accu-rate for very large electrolytic capac-itors, with values of say around1000 µF. The indicated value will betoo small. The reason for this lies inthe program: the charged capacitormust be discharged, which alsorequires time. Our program uses atimer with a period of two seconds:one second is used for charging thecapacitor up to the input thresholdvoltage; the remaining second, how-ever, is not enough to discharge thecapacitor completely. The nextcharge therefore takes less time.There is a simple solution: a diodecan be used to accelerate the dis-charge cycle. Figure 5 shows the cir-cuit diagram, and Figure 6 showshow it can be constructed. With thismodification to the circuit we can

BEGINNERSCOURSE

271/2001 Elektor Electronics

Listing 1. Measuring the time constant in millisecondsPrivate Sub Form_Load()

i = OPENCOM(“COM2,1200,N,8,1”)

If i = 0 Then

i = OPENCOM(“COM1,1200,N,8,1”)

Option1.Value = True

End If

If i = 0 Then MsgBox (“COM Interface Error”)

TXD 0

RTS 0

DTR 0

Counter1 = 0

Timer1.Interval = 2000

End Sub

Private Sub Form_Unload(Cancel As Integer)

CLOSECOM

End Sub

Private Sub Timer1_Timer()

DTR 1

TIMEINIT

While (DSR() = 0) And (TIMEREAD() < 1501)

DoEvents

Wend

Label1.Caption = Str$(TIMEREAD()) + “ ms”

DTR 0

End Sub

Figure 3. Automatic charging from the PC

DTR

DSR

TXD

R

1k

C

100µ

–10V000074 - 5 - 13

Figure 4. Measurement with 100 µF and 1 kΩ

Figure 5. Improved capacitance measurementcircuit

DTR

DSR

TXD–10V

R

1k

D

1N4148

C

1...100µ

000074 - 5 - 15

Figure 6. Construction details.

000074-1

K1 000074-1

10987654321DCD

RXDTXDDTRGNDDSRRTSCTSRIGND

000074 - 5 - 16

47µ

C

D

1N4148

R1k

Page 18: PC Serial Design

reliably measure capacitors up toabout 1500 µF. Larger values are pos-sible if more time is allowed by mak-ing the appropriate changes to theprogram. The timeout value in themeasurement routine and the overalltimer period must both be increased,so that the program waits longenough for the measurement to becompleted.

What about capacitors smallerthan 1 µF? In principle the chargingresistor could be increased. How-ever, a problem then arises: theimpedance of the DSP input (around3 kΩ) introduces measurement errorsthat get more and more severe as thevalue of the charging resistor is

increased. This problem could forexample be overcome using an oper-ational amplifier with a high inputimpedance, but this is outside thescope of this series.

Software enhancements

It is much more interesting to try toget around these limitations in soft-ware. In particular it is possible touse a timer with a resolution of onemicrosecond. This increases the res-olution of the capacitance measure-ment one thousandfold, allowingmeasurements in nanofarads (Fig-ure 7). Library PORT.DLL providesfunctions TIMEINITUS and

BEGINNERSCOURSE

28 Elektor Electronics 1/2001

Figure 7. Capacitance display in nF

Figure 8. Circuit 1 with 10 kΩ potentiometer.

DTR

DSR

TXD–10V

R

1...22k

D

1N4148

C

47µ

000074 - 5 - 18

Figure 9. Measuring the charging time tomicrosecond resolution

Figure 10. Charging time plotted againstcharging resistance

00 5 10 15 20 25

100

200

300

400

500

600

700

T(ms)

R (kΩ) 000074 - 5 - 20

Listing 2. Modifications for program Cmeas2.frm

Private Sub Timer1_Timer()

F = 1.19

DTR 1

REALTIME (True)

TIMEINITUS

While (DSR() = 0) And (TIMEREADUS() < 1500000)

Wend

T = TIMEREADUS() * F

REALTIME (False)

T = Int(T)

Label1.Caption = Str$(T) + “ nF”

DTR 0

End Sub

Listing 3. Measuring the time constant in microseconds

Private Sub Timer1_Timer()

DTR 1

REALTIME (True)

TIMEINITUS

While (DSR() = 0) And (TIMEREADUS() < 1500000)

Wend

t = TIMEREADUS()

REALTIME (False)

Label1.Caption = Str$(t) + “ us”

DTR 0

End Sub

Listing 4. Determining the charging resistancePrivate Sub Timer1_Timer()

DTR 1

REALTIME (True)

TIMEINITUS

While (DSR() = 0) And (TIMEREADUS() < 1500000)

Wend

T = TIMEREADUS()

T = T * 1.0000000001

R = 2200 + 7800 * (T - 76300) / (294600 - 76300)

REALTIME (False)

R = Int(R)

Label1.Caption = Str$(R) + “ Ohm”

DTR 0

End Sub

Page 19: PC Serial Design

The reasons for deviation from the ideallinear curve are the same as were found inmeasuring capacitance. With very smallcharging resistances we get an error due tothe non-linear internal resistance of the DTRoutput driver; with large resistances (sayaround 22 kΩ) the low impedance of the DSRinput causes error.

The data obtained can be converted intoan explicit equation which will let us calcu-late a resistance with high accuracy. Listing 4shows the measurement routine for resis-tance. The calculation in question reads:

R = 2200 + 7800 * (T - 76300) / (294600 -76300)

Using this formula we can obtain a measure-ment accuracy of around 1 % in the range1.5 kΩ to 15 kΩ. It should be borne in mind,however, that this function, specific to a par-ticular PC, will not give the same accuracy ona different machine. The various measure-ments and calculations must be carried outafresh for each PC. It is sufficient to measurethe charging times for two resistors, say2.2 kΩ and 10 kΩ and substitute these in theformula. Failing this, it is possible simply toconsider where the greatest sources of errorlie: in this case our attention turns immedi-ately to the electrolytic capacitor. Electrolyt-ics often have a capacitance very differentfrom the value printed on them, which has asignificant effect on the charging time for agiven resistance. If a suitable correction fac-tor is inserted in the line

T = T * 1.0000000001

then this error will be compensated for, andreasonably usable results (see Figure 11) canbe obtained. A correction factor of greaterthan or less than one will be required accord-ing to whether the capacitor has a valuelower or higher than nominal.

(00074-5)

TIMEREADUS for this purpose,where ‘US’ stands for microseconds(µs). These functions are used inListing 2.

When we consider making mea-surements in microseconds, we mustlook at the effect of Windows on thetiming accuracy. In principle otherprocess running in parallel can inter-rupt the measurement program andcause large inaccuracies. This can beprevented by raising the priority ofthe measurement task, for which aspecial function is provided inPORT.DLL. Using REALTIME (True)we can obtain greater reliability. It isessential to set REALTIME (False)after the measurement has beentaken. The exact accuracy achieveddepends on the PC: with a 200 MHzPentium MMX we measured varia-tions of about 50 µs in the measuredvalue; with a faster PC this may bereduced. If the same experiment iscarried out in Delphi, the timingaccuracy is about 20 times better.The method is described in the Elek-tor Electronics book ‘PC Interfacesunder Windows’, to be publishedsoon). It is nonetheless impressivethat an interpreted language such asVisual Basic can achieve such timingaccuracy.

Alongside these changes to theprogram, we can also improve thebasic accuracy of the measurements.We have already seen two sources oferror in the simple equation t/ms =C/µF, namely the threshold voltagebeing slightly too low and the inputimpedance of the DSR signal. Thereis a third source of error: the DTR out-put does not switch exactly between-10 V and +10 V, but has an internalresistance of roughly 430 Ω. Thecharging resistance is therefore ineffect about 1430 Ω. Further, thisinternal resistance is non-linearlydependent on the current. The TXDoutput also has an internal resis-tance, making the voltage on thecapacitor slightly higher thanexpected. The effects are too compli-cated to be analysed mathematically,and so we take the course preferredby experienced engineers in the faceof a complicated calculation: test;measure; calibrate. All the errors canbe condensed into a single correctionfactor F which can be determinedwith a calibration measurement. Forthis we require a capacitor whose

value is accurately known (or whichcan be accurately measured). Thenthe correction factor can be adjusteduntil the reading is correct. On theauthor’s PC the value of F was foundto be 1.19; this value can of course beused on any PC, but there will beindividual variations from machine tomachine which can only be compen-sated for by determining the correctvalue of F in each case.

Resistance measurement

We can measure resistance usingthe same method; this is similar tothe way that potentiometers areread by PC games cards. The circuitfor measuring resistance is shown inFigure 8 and is essentially the sameas the capacitance-measuring cir-cuit. Here, however, we use a fixedcapacitor and work with variousresistor values.

To test this circuit we use the pro-gram (Listing 3) which measures thecharging time to the highest accu-racy. We use again the techniquedescribed above for measuring smallcapacitors: REALTIME (True) givesus good timing accuracy. Figure 9shows how the results appear on thescreen.

The circuit can be tested usingmetal film resistors with a toleranceof 1 %. Measurements with an accu-rate ohmmeter indicate that in gen-eral the tolerance of such resistors israther better. A set of tests usingC=47 µF gave the following results:

R/kΩ T/ms0 33.7

0.1 340.22 34.50.56 37.9

1 45.52.2 76.34.7 147.56.8 204.98.2 245.910 294.615 433.722 661.2

From the numbers alone a strong lin-ear dependency can be seen. Anexact determination of the linearityis possible using a graph: an analy-sis using Excel produced the curveshown in Figure 10. It can be seenthat linearity is good betweenaround 2.2 kΩ and 10 kΩ.

BEGINNERSCOURSE

291/2001 Elektor Electronics

Figure 11. Measurement using a 15 kΩ resistor.

Page 20: PC Serial Design

The best demonstration involves alight-dependent resistor (LDR). Fig-ure 1 shows a simple light-measur-ing circuit; Figure 2 shows how itmight be constructed. In this casewe are frequently interested in howthe reading changes over time, andthis is best shown on a graph.

Light measurement

In order to produce a graph on thescreen using Visual Basic, we needto use a so-called PictureBox, whichcan be dragged from the form’s tool-bar. It is very important to set thecorrect size. Visual Basic can use avariety of units and here we want tomeasure the size in pixels. TheScaleMode property should be set to‘3 - pixel’, and the box can be

BEGINNERSCOURSE

32 Elektor Electronics 2/2001

PC Serial Peripheral Design (6)Measurements with sensors

By B. Kainka

In the previous instalment we measured capaci-tances and resistances. You may have wonderedif this was all worth the effort, when accurateand inexpensive digital multimeters are readilyavailable, but we shall see that we are able totake readings from a wide variety of sensors bymeasuring their resistance.

Page 21: PC Serial Design

BEGINNERSCOURSE

332/2001 Elektor Electronics

Listing 1. Resistance PlotterDim y1, y2, x1, x2, n

Private Sub Form_Load()

i = OPENCOM(“COM2,1200,N,8,1”)

If i = 0 Then

i = OPENCOM(“COM1,1200,N,8,1”)

Option1.Value = True

End If

If i = 0 Then MsgBox (“COM Interface Error”)

TXD 0

RTS 0

DTR 0

Counter1 = 0

Timer1.Interval = 1000

n = 0

End Sub

Private Sub Form_Unload(Cancel As Integer)

CLOSECOM

End Sub

Private Sub Option1_Click()

i = OPENCOM(“COM1,1200,N,8,1”)

If i = 0 Then MsgBox (“COM1 not available”)

End Sub

Private Sub Option2_Click()

i = OPENCOM(“COM2,1200,N,8,1”)

If i = 0 Then MsgBox (“COM2 not available”)

End Sub

Private Sub Timer1_Timer()

DTR 1

REALTIME (True)

TIMEINITUS

While (DSR() = 0) And (TIMEREADUS() < 900000)

Wend

T = TIMEREADUS()

DTR 0

T = T * 0.932

R = 2200 + 7800 * (T - 76300) / (294600 - 76300)

REALTIME (False)

R = Int(R)

Label1.Caption = Str$(R) + “ Ohm”

y2 = 300 - R / 100

If n = 0 Then y1 = y2

x1 = n

n = n + 5

x2 = n

Picture1.Line (x1, y1)-(x2, y2)

y1 = y2

End Sub

Figure 1. Measurement using a light-dependentresistor

DTR

DSR

TXD–10V

D

1N4148

C

47µ

LDR

000074 - 6 - 11

Figure 3. Results from the LDR measurement

Figure 4. Amplifier for measuring skin resistance

DTR

DSR

TXD–10V

D

1N4148

C

47µ

T

R1

27k

R2

27k

000074 - 6 - 14

BC548

Figure 2. Construction of the LDR circuit

000074-1

K1 000074-1

10987654321DCD

RXDTXDDTRGNDDSRRTSCTSRIGND

000074 - 6 - 12

47µ

C

D

1N4148

LDR

dragged out to the correct size usingthe mouse. For the present example(plotter1.frm) a PictureBox 300 by500 points is required.

We can draw in the PictureBoxusing the Line command: see List-ing 1 for an example. The plot isdrawn over a period of 100 seconds,the x-coordinate advancing by 5 pix-els as each reading is taken. Aglobal variable n must be speciallydeclared to store the current positionacross calls to the timer procedure.On the y-axis resistance (R/100) isplotted, with a maximum value of

300 (30000 Ω=30 kΩ). Every second anew value is plotted in the graph inFigure 3 and a new line segment isdrawn from the last point to the newone. The old coordinate values mustbe stored, and global variables areused for this purpose.

Skin resistance measurementsAnother interesting ‘sensor’ is thehuman skin: a pair of bare wires canbe wound around two fingers. Theresistance of the skin is not constant,

Page 22: PC Serial Design

but varies according to its moisture levels.When people lie, they sweat: so we can builda lie detector by determining when the skinresistance falls. The problem is that skinresistance is typically rather higher than themaximum value we can measure with our cir-cuit: we need to use a transistor for amplifi-cation (Figure 4, Figure 5).

An NPN transistor amplifies the small cur-rent flowing through the skin, allowing oursimple A/D converter to measure relatively

high resistances. The input to thecircuit is protected by two additionalresistors, so that the measured resis-tance will not be too small even ifthe wires are shorted. The readingobtained depends on the contactarea of the wires and the moisturelevel of the skin. The results can beviewed using the resistance plotterprogram.

Temperature measurementTemperature can also be measuredusing our resistance measuring cir-cuit. The circuit of Figure 6 showshow easy it is to connect a 10 kΩNTC thermistor to build a very sim-ple yet perfectly usable thermome-ter.

The resistance characteristic of anNTC thermistor can be approxi-mated by an exponential curve. Inthe following formula, T is theabsolute temperature in Kelvin(T/°C + 273), while B is a value, typ-ically between 2000 and 500 Kelvin,provided by the thermistor manufac-turer. In fact the value of B is not per-fectly constant but rises graduallywith temperature: for this reason thevalue B25/85 is often quoted, where

calibration has been performed at25°C and 85°C.

An NTC thermistor is therefore spec-ified to a first approximation by twovalues: B and the thermistor’s nomi-nal resistance R25. For a typical10 kΩ NTC thermistor the value of Bmight be 4300 K. Rearranging theexpression above and substitutingR25 = 10 kΩ we can derive the fol-lowing line of Visual Basic to calcu-late the value of T in Celsius:

Temp = 1 / (Log(R / 10000) / 4300 +1 / 298) – 273

The VB ‘Log’ function calculates thenatural logarithm, often abbreviatedto ‘ln’ in mathematics textbooks.

In the program shown in Listing 2we first carry out a resistance mea-surement and then convert the mea-sured value into temperature. Theresults appear to one decimal placeas shown in Figure 7. Finally, List-ing 3 shows how to convert thereading from the Celsius scale intoFahrenheit.

(000074-6)

R T R eB

T K( ) = ⋅⋅ −

25

1 1298

BEGINNERSCOURSE

34 Elektor Electronics 2/2001

Figure 6. Connecting an NTC thermistor

DTR

DSR

TXD–10V

D

1N4148

C

47µ

NTC

10k-Θ

000074 - 6 - 16

Figure 7. Temperature display

Listing 3. Conversion to the Fahrenheit scaleAlthough the German physicist Gabriel Daniel Fahrenheit died in 1736, somepeople are still more comfortable working with temperatures measured inFahrenheit. They need only change a couple of lines of the program, as follows:

Temp = 32 + (Temp / 100 * 180)

Temp = Int(Temp * 10) / 10

Label1.Caption = Str$(Temp) + “ F”

Listing 2. Extensions for temperature measurementPrivate Sub Timer1_Timer()

DTR 1

REALTIME (True)

TIMEINITUS

While (DSR() = 0) And (TIMEREADUS() < 1500000)

Wend

T = TIMEREADUS()

T = T * 1.0000000001

R = 2200 + 7800 * (T - 76300) / (294600 - 76300)

REALTIME (False)

R = Int(R)

Temp = 1 / (Log(R / 10000) / 4300 + 1 / 298) - 273

Temp = Int(Temp * 10) / 10

Label1.Caption = Str$(Temp) + “°C”

DTR 0

End Sub

Figure 5. Measuring skin resistance

000074-1

K1 000074-1

10987654321DCD

RXDTXDDTRGNDDSRRTSCTSRIGND

000074 - 6 - 15

47µ

CT

D = 1N4148

R2

27k

R1

27k

BC548

Page 23: PC Serial Design

A real A/D converter with a voltageinput can be constructed using a sin-gle transistor. The transistor in Fig-ure 1 operates as a comparator, com-paring the voltage on the capacitorwith a reference value, here 0.7 V.The capacitor is alternately chargedand discharged by the DTR outputvia a resistor, in such a way that thevoltage across it is always near tothe comparator reference. Depend-ing on the input voltage the outputwill need to be turned on more orless frequently in order to establishthe desired voltage. The count ofthese events leads to the convertedvalue. Figure 2 shows how the cir-cuit can be constructed.

A/D converter program

The program in Listing 1 contains aloop which attempts to keep thevoltage across the capacitor as closeas possible to the comparator refer-ence voltage. Information on thevoltage across the capacitor is avail-able on the RI input: if the voltagelies above the switching threshold ofthe transistor (about 0.7 V), a collec-tor current flows and the voltage on

RI falls. Conversely a lower capaci-tor voltage turns off the transistorand RI goes high. The measurementloop must drive the voltage on DTRin the opposite direction: when thevoltage is too low, DTR must beturned on; when it is too low, DTRmust be turned off, setting the out-put voltage to –10 V. It is importantthat the switching happens at pre-cisely regular intervals, for exampleexactly one per millisecond. Thenumber of millisecond periods forwhich DTR is turned on must becounted. If no input voltage is pre-sent, we might expect that the posi-tive and negative states of DTRwould be equally common, makingthe averaged voltage across thecapacitor zero. If we look a littlemore closely, however, we see thatwe need to consider the thresholdvoltage of the transistor (about0.7 V), and so the positive state willbe slightly more frequent. With anapplied voltage the ratios change.The charging current from the DTRsignal must compensate for thecharging current from the input.

A negative input voltage leads tomore positive DTR states, and con-

BEGINNERS’COURSE

22 Elektor Electronics 3/2001

PC Serial PeripheralDesign (7)voltage measurement

By B. Kainka

In previous articles in this series we have described an A/D converterbased on a counter. A ‘real’ A/D converter, however, converts a voltage intoa measured value. Usually, this is thought to require an IC; however, aswe shall see, a much simpler alternative is available.

Figure 1. The simple A/D converter

T

R1

1k

R3

27

k

R21k

R427k

C

47µ

GND

RTS

DTR

000074 - 7 - 11

+10V

–6 ...+10V

R I

Figure 2. Voltage measurement with the simpleA/D converter.

000074-1

K1 000074-1

10987654321DCD

RXDTXDDTRGNDDSRRTSCTSRIGND

000074 - 7 - 12

C

T BC548

47µ

R1

R2

R3

R4

Page 24: PC Serial Design

Input Display

open 1180 V 110–3.6 V 68+3.6 V 152

We can see that an open-circuit input doesnot display zero, but a rather higher value.Comparing the measurement results for thevoltages -3.6 V, 0 V and +3.6 V, we can imme-diately see that the difference between thenegative voltage and zero is 42, as is the dif-ference between the positive voltage andzero. This is encouraging, since it indicatesthat the converter is linear.

The digital values can now be convertedinto voltages. The following calculation doesthe trick:

Voltage = (Display – 110)/11.2

This expression contains the measured zerovalue and a multiplicative factor giving thenumber of digital steps per Volt. Both thesevalues will vary from circuit to circuit. It istherefore worthwhile calibrating the circuit.Program AD2.frm (Listing 2) provides twoslider controls which start off at preset val-ues. The left-hand slider, with a range of 105to 115 and an initial setting of 110, sets thezero offset. The right-hand slider, with arange of 124 down to 100 and an initial set-ting of 112, sets the slope. To use the programfirst short the input leads together and setthe zero offset slider appropriately. Then aknown voltage must be applied to the input,and the display set to the correct value usingthe right-hand slider. The A/D converter con-structed here uses as a reference the voltageon the DTR output, which is not particularly

versely, a positive voltage leads tomore negative DTR states.

The program starts by settingDTR to 1. This is important to ensurethat the capacitor is not chargedwith the wrong polarity. The voltageacross the capacitor does not riseabove about 1 V, however, becausethe base-emitter diode in the tran-sistor starts to conduct. In this qui-escent state the transistor is fullyturned on. In the measurement pro-cedure proper, Timer1.Timer, a newmeasurement is carried out ever500 ms. Initially DTR is turned offuntil RI changes state for the firsttime. At this point the voltage acrossthe capacitor is equal to the thresh-

old voltage of the transistor. Thisfirst loop has a timeout condition totrap errors and runs for at most300 ms.

The main measurement loop isexecuted exactly 255 times, duringwhich the number of cases whereDTR is low is counted. The measure-ment always lasts 255 ms and pro-duces 256 different possible resultsfrom 0 to 255 (Figure 3). This givesthe same resolution as an 8-bit A/Dconverter.

Testing and calibration

Our first test delivered the followingresults:

BEGINNERS’COURSE

233/2001 Elektor Electronics

Listing 1. Conversion of an 8 bit valuePrivate Sub Form_Load()i = OPENCOM(“COM2,1200,N,8,1”)If i = 0 Then

i = OPENCOM(“COM1,1200,N,8,1”)Option1.Value = True

End IfIf i = 0 Then MsgBox (“COM Interface Error”)RTS 1DTR 1Counter1 = 0Timer1.Interval = 500End Sub

Private Sub Form_Unload(Cancel As Integer)CLOSECOMEnd Sub

Private Sub Option1_Click()i = OPENCOM(“COM1,1200,N,8,1”)If i = 0 Then MsgBox (“COM1 not available”)RTS 1DTR 1End Sub

Private Sub Option2_Click()i = OPENCOM(“COM2,1200,N,8,1”)If i = 0 Then MsgBox (“COM2 not available”)RTS 1DTR 1End Sub

Private Sub Timer1_Timer()RTS 1DTR 0U = 0TIMEINITWhile (RI() = 0) And (TIMEREAD() < 300)WendTIMEINITFor n = 1 To 255If RI() = 1 Then DTR 1 Else DTR 0: U = U + 1While TIMEREAD() < nWend

Next nDTR 1Label1.Caption = Str$(U) + “ “

End Sub

Figure 3. Display of digitised value.

Page 25: PC Serial Design

reliable. Recalibration is therefore often nec-essary. Figure 4 shows the program in action.

This simple A/D converter is reasonablyaccurate and reliable. The resolution is about0.1 V, and the measurement range is about–6 V to +9 V. This can already find practicalapplication, for example in testing batteries,and becomes all the more useful when theinput voltage can be plotted (Listing 3).There are many other applications. Figure 5shows the measured voltage across a capac-itor being briefly negatively and positivelycharged. The characteristic exponential dis-charge curves can be clearly seen.

Hardware improvements

When the possible sources of error in our sim-ple A/D converter are considered, we can seethat there are practically no aspects that can-not be improved.

– The basic accuracy depends on the voltageon the serial interface. It would be better touse a proper voltage reference, althoughthat would make the circuit rather morecomplicated.

– The switching threshold of a comparator

constructed from a simple NPNtransistor is not 0 V, bit ratherabout 0.7 V. The exact valuedepends on the chosen transistorand on temperature. A tempera-ture variation of one degree Celsiuschanges the threshold by about2 mV.

– The ratio of the two 27 kΩ resistorsaffects the measurement; but if 5 %tolerance types are used, the con-tribution will be dominated by theother sources of error.

– The measurement results do NOTdepend on the exact value of thecapacitor. This is a particularadvantage of this measurementmethod. Even if a 100 µF capacitor

is used in place of the 47 µF capac-itor, the results are not affected.

It is relatively straightforward toimprove on the design of the com-parator (Figure 6). Instead of a sin-gle transistor, two are used. The pairof NPN transistors forms a differen-tial amplifier, similar to the inputstage of an operational amplifier. Inthis way the DC base-emitter volt-age is reduced to a few millivolts.Temperature variation is no longer aproblem because the two transistorsare affected to the same extent. Thetotal emitter current through the4.7 kΩ resistor is about 2 mA. Whenthe input voltage is zero the current is

BEGINNERS’COURSE

24 Elektor Electronics 3/2001

Listing 2. The modified Timer procedure in AD2.frmPrivate Sub Timer1_Timer()RTS 1DTR 0U = 0REALTIME (True)TIMEINITWhile (RI() = 0) And (TIMEREAD() < 300)WendTIMEINITFor n = 1 To 255If RI() = 1 Then DTR 1 Else DTR 0: U = U + 1While TIMEREAD() < nWend

Next nREALTIME (False)U = (U - HScroll1.Value) / HScroll2.Value * 10U = Int(U * 10) / 10DTR 1Label1.Caption = Str$(U) + “ V”

End Sub

Figure 4. A complete voltmeter.

T1

R1

10

k

R3

27

k

R4

27k

C

47µ

GND

RTS

DTR

+10V

DSR

T2

R2

4k

7

TXD000074 - 7 - 16

D–10 ...+10V

–10V

Figure 6. The improved comparator.

Figure 5. Voltage plotter Plotter2.frm.

Page 26: PC Serial Design

input transistor no longer limits the voltageacross the capacitor during intervals betweenmeasurements, and so this voltage will rise.For this reason a silicon diode is included tolimit the voltage to 0.6 V. The effect of all ofthese changes is that an open-circuit inputgives a reading of zero, and that the mea-surement range is extended to 10 V witheither polarity. Figure 7 shows the construc-tion of the improved converter.

Software optimisations

Changes are also needed in the software.First it must be taken into account that theDSR input signal is read in the invertedsense: the input is high when the capacitorvoltage is above the threshold voltage. Theimproved characteristics of the measurementcircuit also make it worthwhile to increasethe accuracy of the measurements. The mainloop is now executed 1000 times. Listing 4shows the results. With a total input range of20 V we have a resolution on 0.02 V. As seenin Figure 8, a further decimal place can beshown on the display.

(000074-7)

divided equally between the twotransistors. The voltage drop acrossthe collector resistor of the secondtransistor is about 10 V, and so the

collector voltage remains aroundzero and close to the switchingthreshold of the DSR input.

Unlike in the original circuit, the

BEGINNERS’COURSE

253/2001 Elektor Electronics

Listing 4. Measurement routine with 1000 quantisation stepsPrivate Sub Timer1_Timer()RTS 1DTR 0U = 0REALTIME (True)TIMEINITWhile (DSR() = 1) And (TIMEREAD() < 300)WendTIMEINITFor n = 1 To 1000If DSR() = 0 Then DTR 1 Else DTR 0: U = U + 1While TIMEREAD() < nWend

Next nREALTIME (False)U = (U - HScroll1.Value) / HScroll2.Value * 10U = Int(U * 100) / 100DTR 1Label1.Caption = Str$(U) + “ V”

End SubEnd Sub

Listing 3. Plotter procedures Plotter2.frm

Dim y1, y2, x1, x2, n

Private Sub Command1_Click()n = 0End Sub

Private Sub Timer1_Timer()RTS 1DTR 0U = 0REALTIME (True)TIMEINITWhile (RI() = 0) And (TIMEREAD() < 300)WendTIMEINITFor i = 1 To 255If RI() = 1 Then DTR 1 Else DTR 0: U = U + 1While TIMEREAD() < iWend

Next iREALTIME (False)U = (U - HScroll1.Value) / HScroll2.Value * 10DTR 1y2 = 100 - U * 10If n = 0 Then y1 = y2: Picture1.Clsx1 = n

n = n + 5x2 = nPicture1.Line (x1, y1)-(x2, y2)y1 = y2

End Sub

000074-1

K1 000074-1

10987654321DCD

RXDTXDDTRGNDDSRRTSCTSRIGND

000074 - 7 - 17

47µ

CT2

T1

D

R4

R3

R1

R2

Figure 7. Construction of the improvedcomparator on the prototyping board.

Figure 8. Result displayed to two decimalplaces.

Page 27: PC Serial Design

HandsOn Technologyhttp://www.handsontec.com

ISP to ICP Programming Bridge: HT-ICP200In-Circuit-Programming (ICP) for P89LPC900 Series of 8051 Flash μControllers. ICP uses a serial shift protocol that requires 5 pins to program: PCL, PDA, Reset, VDD and VSS.

ICP is different from ISP (In System Programming) because it is done completely by the microcontroller’s hardware and does not require a boot loader.

Program whole series of P89LPC900 µController from NXP Semiconductors…

USB-RS232 Interface Card: HT-MP213A compact solution for missing ports…

Thanks to a special integrated circuit from Silicon Laboratories, computer peripherals with an RS232 interface are easily connected to a USB port. This simple solution is ideal if a peripheral does not have a USB port, your notebook PC has no free RS232 port available, or none at all !

Classic P89C51 Development/Programmer Board: HT-MC-02HT-MC-02 is an ideal platform for small to medium scale embedded systems development and quick 8051 embedded design prototyping.

HT-MC-02 can be used as stand-alone 8051μCFlash programmer or as a development, prototyping, industry and educational platform.

For professional, hobbyists…

Page 28: PC Serial Design

Products Catalog2011

…from engineers to engineers

50W Audio Power Amplifier HT-AV50W50+ watts from a 12V battery power supply !!

This integrated power output amplifier consists of little more than one integrated circuit. It is intended especially for use in motor vehicles and other battery operated applications. Although it appears simple and hardly worth looking at, the amplifier can produce an appreciable audio power output !

High power output through Class-H operation