Sunteți pe pagina 1din 53

HowToProgramthe

Z80PeripheryTutorial
Doc.Version201308231
Author:MarioBlunk

Abstract:GuidelinetoprogramZ80familydevicesinatutoriallikemanner.Assembly
programcodeexamplesgiven.
Keywords:CPU,SIO,CTC,PIO,counter,timer,IC,serial,terminal,nullmodem,flow
control,baudrate,vectortable,interruptserviceroutine,mainlineprogram,loop,
instruction,executiontime,mathematics,pulsewidth,jitter,oscilloscope,PWM,
modulation,equivalentstable,minicom,hyperterminal,timeconstant

Blunkelectronicatwww.trainz.de

Contents
1TheZ80SIO.......................................................................................................................5
1.1TerminalMode.............................................................................................................5
1.1.1DesiredCommunicationMechanism....................................................................5
1.1.2SIODeviceStructureandexternalwiring............................................................6
1.1.2.1Wiring.............................................................................................................6
1.1.3Programming........................................................................................................8
1.1.3.1Header...........................................................................................................8
1.1.3.2InterruptVectorTable....................................................................................8
1.1.3.3InitializingtheSIO.........................................................................................9
1.1.3.4InitializingtheCTC......................................................................................10
1.1.3.5InitializingtheCPU......................................................................................10
1.1.3.6HardwareFlowControl................................................................................11
1.1.3.7DisablingSIORXchannel...........................................................................11
1.1.3.8InterruptServiceRoutines...........................................................................12
1.1.3.9Transmissionofacharactertothehost......................................................14
1.2FileTransferMode.....................................................................................................15
1.2.1DesiredCommunicationMechanism.................................................................15
1.2.2Programming......................................................................................................16
1.2.2.1Header........................................................................................................16
1.2.2.2InterruptVectorTable..................................................................................16
1.2.2.3InitializingtheCTC......................................................................................17
1.2.2.4InitializingtheCPU.....................................................................................17
1.2.2.5XModemFileTransfer................................................................................17
1.2.2.5.1Hosttriggeredtransferandsetup........................................................17
1.2.2.5.2Subroutines.........................................................................................21
2TheZ80CTC...................................................................................................................22
2.1DesiredMechanism..................................................................................................22
2.2CTCDeviceStructureandexternalwiring................................................................22
2.2.1Wiring.................................................................................................................22
2.3Programming.............................................................................................................24
2.3.1Header...............................................................................................................24
2.3.2Interrupttable.....................................................................................................24
2.3.3InitializingtheCTC............................................................................................25
2.3.4InitializingtheCPU............................................................................................26
2.3.5Interruptroutine.................................................................................................26
3TheZ80PIO.....................................................................................................................27
3.1WhatdoweneedfortheICprotocol?....................................................................27
3.2TheOpenDrainProblem.........................................................................................28
3.3Wiring........................................................................................................................29
3.4Programming............................................................................................................29
3.4.1Header...............................................................................................................29
3.4.2InitializingthePIO..............................................................................................30
3.4.3MainRoutines....................................................................................................31
3.4.3.1BusReset...................................................................................................31
3.4.3.2BusStartandStop.....................................................................................31
Blunkelectronicatwww.trainz.de

3.4.3.3Sending......................................................................................................32
3.4.3.4Receiving....................................................................................................33
3.4.4Subroutines.......................................................................................................34
3.4.4.1SCLCycle...................................................................................................34
3.4.4.2SetSDAasinputoroutput.........................................................................35
3.4.4.3SetSCLasoutputorinput.........................................................................36
3.4.4.4Sendabyte................................................................................................37
4ProgrammingPulseWidthModulation(PWM)................................................................38
4.1TheProgramAlgorithm.............................................................................................39
4.2TheMath...................................................................................................................42
4.3TheZ80AssemblyCode..........................................................................................44
4.4Results......................................................................................................................44
4.5IntegratingCircuitry...................................................................................................47
5Z80ICequivalentstable..................................................................................................48
6References.......................................................................................................................49
7UsefulLinks......................................................................................................................50
8FurtherReading...............................................................................................................53
9Disclaimer.........................................................................................................................53

Blunkelectronicatwww.trainz.de

Preface
ThisdocumentaimstomaketheZ80processorsystempopularagainsincealotof
valuableliteratureandexpertisehasvanishedfromthepublicbecauseofmore
sophisticatedprocessorarchitecturesofthepresent.
Thisdocumentdoesnotaimtobringbackgoodoldtimes.
TheofficialZiLOGdatasheets[1]and[2]giveagoodoverallviewofallthefeaturesofthe
peripheraldevicesbutlackatutoriallikeapproachandprogrammingexamplesin
assemblylanguage.
RemarkablyZiLOGstillproducestheICsoftheZ80familysincethelateseventies!

Thereisnospecialfocusonhardwareissueslikedeviceselection,pincharacteristicsor
ratings.PleaserefertotheofficialZiLOGdatasheetsatwww.zilog.comorwww.z80.info.
SpecialthanksgotoZiLOGfortheirdatasheetsIusedforgraphicalillustrationswithinthis
document.
Thecodeexamplesshownhereprovidebyfarnotthebestperformanceandrobustness.
ThereforeIappreciateeveryhintorcriticstoimprovethequalityofthisdocument.

Blunkelectronicatwww.trainz.de

1 TheZ80SIO
TheZ80SIOisthemostpowerfulI/OdeviceoftheZ80productfamily.Partoneofthis
sectiondescribeshowtoprogramtheSIOsothatitcommunicateswithaPCin
asynchronousterminalmodewhereasparttwofocusesontheblocktransfermodeused
forfiletransmission.AlsoslightlytouchedinthisdocumentistheCTCprogrammingand
implementationofaninterruptmechanism.

1.1 TerminalMode
1.1.1DesiredCommunicationMechanism
WewanttoprogramtheSIOforasynchronousRS232terminalmodewiththese
parameters:
Baudrate:

9600Baud/sec

Stopbits:

Startbits:

Characterlength:
Parity:

8bit

none

Interminalmodethehostcomputer(inourcasethePCwithanyterminalprogramlike
MinicomorHyperTerminalandanRS232interface)communicateswiththeclient(the
Z80SIO)characterbasedviaasocalledNullModemCable.Thehosttransmitsoneor
morecharacterstotheclient,whereupontheclientechoesthischaracterbacktothehost
andprocessesit.Thehostdisplaystheechoedcharacteronitsscreen.Ifthehostdoes
notheartheechoedcharacterthecommunicationisfaulty.
Specialattentionistobepaidtotheflowcontrolschemewhichishardwarebased.In
generalthisiscalledRTSCTSorjusthardwareflowcontrol.Thismethodallows
transmissionofall8bitcharacters(socalledbinarymode)andpreventsoverrunningof
oneofthepeersincaseonofthemistoslow.InthisdocumentIassumethehostPCis
muchfasterthantheclient.

Blunkelectronicatwww.trainz.de

Thewiringofthenullmodemcableusedherehasfollowingconnectionsbetweenits
female9pinDSubconnectors:
14/41

crosswiredDTRandDCD

23/32

crosswiredTxDandRxD

55

signalground(GND)

78/87

crosswirdRTCandCTS

99

ringindicator(RI,notusedhere)

1.1.2

SIODeviceStructureandexternalwiring

Figure1(takenfrom[2])showstheblockdiagramofthedevicewiththeblocksandsignals
neededforourexampleoutlinedinred.Figure2(takenfrom[2])showsthedatapaths
withintheSIO.Markedinredaretheblocksweneedforasynchronousmode.
1.1.2.1 Wiring

Dataandcontrol:

ThesearetheZ80bussignalsD[7:0],A[1:0],/RD,/IOREQ,
/RESET,/CEandCLK.

InterruptControlLines:

/M1,/INTconnectedtoCPU,IEIandIEOdaisychainedtoother
periphery

SerialData:

TxDandRxDgoingtowardshostcomputer 1

ChannelClocks:

TxCAandRxCAdrivenbyCTCchanneloutputTO0

ModemorotherControls: CTS,RTS,DTR,DCDusedforhardwareflowcontrol
miscellaneous:

/SYNCnotused,pulledhighby10kresistor
/Wait/Readycomesoutofthedevice.Itistobeconnectedto
theWAITInputoftheZ80CPU.ByassertingthissignaltheSIO
tellstheCPUtowaituntiltheSIOhascompletedacharacter
transfer.Forthisexamplewedonotmakeuseofthis
connection.

1 UsuallythesesignalsarenotconnecteddirectlytothehostbutviadiverdeviceslikeMAX232,1488,1489
orsimilarlevelconverters.
Blunkelectronicatwww.trainz.de

Figure1:BlockDiagram

Figure2:DataPath

Blunkelectronicatwww.trainz.de

1.1.3

Programming

Treeproblemshavetobesolved:

initializingtheSIO
implementingtheinterruptmechanism
echoingthereceivedcharacter
transmittingacharacter
turningon/offtheSIORXchannelincertainsituations

1.1.3.1 Header

Theheadershowbelowdefinesthehardwareaddressesofthedataandcontrolportof
yourSIOandtheaddressofyourCTCchannel0.Myhardwarehereusestheaddresses
0x4,0x6and0x0.

SIO_A_D
SIO_A_C
CH0

equ
equ
equ

4h
6h
0h

Text1:header

1.1.3.2 InterruptVectorTable

EverytimetheSIOreceivesacharacteritrequestsaninterruptcausingtheCPUtojump
tothememoryaddressspecifiedbythetermRX_CHA_AVAILABLE.Specialreceive
conditionslikereceiverbufferoverruncauseajumptolocationSPEC_RX_CONDITION.

INT_VEC:
org
DEFW
org
DEFW

0Ch
RX_CHA_AVAILABLE
0Eh
SPEC_RX_CONDITON

Text2:SIOinterruptvectortable

Blunkelectronicatwww.trainz.de

1.1.3.3 InitializingtheSIO

FirstwehavetoconfiguretheSIOusingthesequenceshowninText3.Fordetailed
informationonthepurposeofcertainregistersandcontrolbitspleasereadtheSIO
datasheet.WeoperatetheSIOininterruptmodeinterruptonallreceivedcharacters.

SIO_A_RESET:
;setupTXandRX:
ld
a,00110000b
out
(SIO_A_C),A

;writeintoWR0:errorreset,selectWR0

ld
out

a,018h
(SIO_A_C),A

;writeintoWR0:channelreset

ld
out
ld
out

a,004h
(SIO_A_C),A
a,44h
(SIO_A_C),A

;writeintoWR0:selectWR4

ld
out
ld
out

a,005h
(SIO_A_C),A
a,0E8h
(SIO_A_C),A

;writeintoWR0:selectWR5

ld
out
ld
out

a,01h
(SIO_B_C),A
a,00000100b
(SIO_B_C),A

;writeintoWR0:selectWR1

ld
out
ld

a,02h
(SIO_B_C),A
a,0h

;writeintoWR0:selectWR2

out

(SIO_B_C),A

ld
out
ld

a,01h
(SIO_A_C),A
a,00011000b

out

(SIO_A_C),A

;44hwriteintoWR4:clkx16,1stopbit,noparity

;DTRactive,TX8bit,BREAKoff,TXon,RTSinactive

;nointerruptinCHB,specialRXconditionaffectsvect

;writeintoWR2:cmdlineintvect(seeintvectable)
;bitsD3,D2,D1arechangedaccordingtoRXcondition
;writeintoWR0:selectWR1
;interruptonallRXcharacters,parityisnotaspecRXcondition
;bufferoverrunisaspecRXcondition

SIO_A_EI:
;enableSIOchannelARX
ld
a,003h
;writeintoWR0:selectWR3
out
(SIO_A_C),A
ld
a,0C1h
;RX8bit,autoenableoff,RXon
out
(SIO_A_C),A
;ChannelARXactive
RET

Text3:configuretheSIO

Blunkelectronicatwww.trainz.de

1.1.3.4 InitializingtheCTC

TheCTCchannel0providesthereceiveandtransmitclockfortheSIO.
INI_CTC:
;initCH0
;CH0providesSIOARX/TXclock
ld

A,00000111b

out
ld
out

(CH0),A
A,2h
(CH0),A

;intoff,timeron,prescaler=16,don'tcareext.TRGedge,
;starttimeronloadingconstant,timeconstantfollows
;swrstactive,thisisactrlcmd
;timeconstantdefined
;andloadedintochannel0
;TO0outputsfrequency=CLK/2/16/(timeconstant)/2
;whichresultsin9600bitspersec

Text4:configuringtheCTCchannel0

1.1.3.5 InitializingtheCPU

TheCPUistorunininterruptmode2.SeeText5below.Thishastobedoneafter
initializingSIOandCTC.
INT_INI:

ld
ld
im
ei

A,0
I,A
2

;loadIregwithzero
;setintmode2
;enableinterupt

Text5:setuptheCPUinterruptmode2

Blunkelectronicatwww.trainz.de

10

1.1.3.6 HardwareFlowControl

InordertosignalthehostwhethertheclientisreadyornottoreceiveacharactertheRTS
linecomingoutoftheclient(anddrivingtowardsthehost)needstobeswitched.Asearlier
saidIassumethehostismuchfasterthantheclient,thatwhyIdonotimplementaroutine
tochecktheCTSlinecomingfromthehost.
A_RTS_OFF:
ld
out
ld
out
ret

a,005h
(SIO_A_C),A
a,0E8h
(SIO_A_C),A

;writeintoWR0:selectWR5

A_RTS_ON:
ld
out
ld
out
ret

a,005h
(SIO_A_C),A
a,0EAh
(SIO_A_C),A

;writeintoWR0:selectWR5

;DTRactive,TX8bit,BREAKoff,TXon,RTSinactive

;DTRactive,TX8bit,BREAKoff,TXon,RTSactive

Text6:signalingthehostgoornogoforreception

1.1.3.7 DisablingSIORXchannel

Whencertainconditionsariseitmightbyimportanttodisablethereceivechannelofthe
SIO(seeroutineinText7).

SIO_A_DI:
;disableSIOchannelARX
ld
a,003h
;writeintoWR0:selectWR3
out
(SIO_A_C),A
ld
a,0C0h
;RX8bit,autoenableoff,RXoff
out
(SIO_A_C),A
;ChannelARXinactive
ret

Text7:DisablingtheSIO

Blunkelectronicatwww.trainz.de

11

1.1.3.8 InterruptServiceRoutines

UponreceptionofacharactertheroutineRX_CHA_AVAILABLEshowninText8is
executed.Hereyougetthecharactersetbythehost.
Note:InthisexamplewebackuponlyregisterAF.Dependingonyourapplicationyou
mightberequiredtobackupmoreregisterslikeHL,DE,CD,...
RoutineSPEC_RX_CONDITIONisexecuteduponaspecialreceiveconditionlikebuffer
overrun.InmyexampletheCPUistojumpatthewarmstartlocation0x0000.
RX_CHA_AVAILABLE:
push
call
in

AF
A_RTS_OFF
A,(SIO_A_D)

;backupAF
;readRXcharacterintoA

;examinereceivedcharacter:
cp
0Dh
;waslastRXcharaCR?
jp
z,RX_CR
cp
08h
;waslastRXcharaBS?
jp
z,RX_BS
cp
7Fh
;waslastRXcharaDEL?
jp
z,RX_BS
;echoanyotherreceivedcharacterbacktohost
out
(SIO_A_D),A
;dosomethingusefulwiththereceivedcharacterhere!
call
call
jp

TX_EMP
RX_EMP
EO_CH_AV

;flushreceivebuffer

RX_CR:
;dosomethingoncarriagereturnreceptionhere
jp
EO_CH_AV
RX_BS:
;dosomethingonbackspacereceptionhere
jp
EO_CH_AV
EO_CH_AV:
ei
call
pop
Reti

A_RTS_ON
AF

;seecommentsbelow
;seecommentsbelow
;restoreAF

SPEC_RX_CONDITON:
jp
0000h

Text8:characterreceivedroutine

Blunkelectronicatwww.trainz.de

12

Note:ThecodewritteninredmightberequiredifyouwanttheCPUtobereadyfor
anotherinterrupt(ei)andtogivethehostagoforanothertransmission(callA_RTS_ON).
Irecommendtoputthesetwolinesnotherebutinyourmainprogramroutinethat
processesthecharactersreceivedbytheSIO.Thiswayyouprocessonecharacterafter
anotherandavoidoverrunningyourSIORXbuffer.
Text9showstheroutinetoflushthereceivebuffer.Thisisimportantifthehostsends
morethanonecharacteruponpressingakeylikeESCorcursorup/downkeys.The
routineofText8echoesjustthefirstreceivedcharacterbacktothehost,butbycalling
RX_EMPallcharactersfollowingthefirstonegetflushedintothevoid.

RX_EMP:
;checkforRXbufferempty
;modifiesA
sub
a
;cleara,writeintoWR0:selectRR0
out
(SIO_A_C),A
in
A,(SIO_A_C)
;readRRx
bit
0,A
ret
z
;ifanyrxcharleftinrxbuffer
in
A,(SIO_A_D) ;readthatchar
jp
RX_EMP

Text9:flushingthereceivebuffer

Blunkelectronicatwww.trainz.de

13

1.1.3.9 Transmissionofacharactertothehost

Ingeneraltransmittingofacharacterisdonebythesinglecommand
out (SIO_A_D),A
aswritteninText8.Tomakesurethecharacterhasbeensentcompletelythetransmit
bufferneedstobecheckedifitisempty.Thegeneralroutinetoachievethisisshownin
Text10.
TX_EMP:
;checkforTXbufferempty
sub
a
inc
a
out
(SIO_A_C),A
in
A,(SIO_A_C)
bit
0,A
jp
z,TX_EMP
ret

;cleara,writeintoWR0:selectRR0
;selectRR1
;readRRx

Text10:transmittingacharactertohost

Blunkelectronicatwww.trainz.de

14

1.2 FileTransferMode
1.2.1

DesiredCommunicationMechanism

WewanttoprogramtheSIOforasynchronousRS232XModemprotocolwiththese
parameters:
Baudrate:

9600Baud/sec

Stopbits:

Startbits:

Characterlength:
Parity:

8bit

none

Indifferencetothecharacterbasedmodedescribedinsection1.1(TerminalMode)
blocksof128bytesizearetobetransferredovertheNullModemCablefromthehostPC
totheclient,theZ80machine.IchoosetheXModemprotocolduetoitsrobustnessand
easyfeasibility.TypicalterminalprogramslikeHyperTerminal,KermitorMinicomdo
supporttheXModemprotocol.
Ofcourseyoucanalsotransferafileviacharacterbasedmodebutthetransferwilltake
muchmoretime.
Regardingthedevicestructure,NullModemCable,wiringandflowcontrolpleasereferto
section1.1.1onpage5and1.1.2onpage6.
AweblinktothedescriptionoftheXModemprotocolcanbefoundinsection7onpage
50.
Note:ForthismodetheconnectionoftheCPUpin/WAITandtheSIOpin
/Wait/Readyisrequired.Pleaseseesection1.1.2.1onpage6.

Blunkelectronicatwww.trainz.de

15

1.2.2

Programming

Fourproblemshavetobesolved:initializingtheSIO,implementingtheinterrupt
mechanism,requestingthehosttostarttheXModemtransferandloadthefiletoacertain
RAMlocation.
1.2.2.1 Header

Theheadershowbelowdefinesthehardwareaddressesofthedataandcontrolportof
yourSIOandtheaddressofyourCTCchannel0.Myhardwarehereusestheaddresses
0x4,0x6and0x0.FurtheronthereisaRAMlocationsdefinedforcountingbadblocks
whilethefileisbeingtransferred.

SIO_A_D
SIO_A_C
CH0

equ
equ
equ

4h
6h
0h

temp0

equ

1015h

;holdsnumberof
;unsuccessfulblocktransfers/blockduringdownload

Text11:header

1.2.2.2InterruptVectorTable

EverytimetheSIOreceivesthefirstbyteofablockitrequestsaninterruptcausingthe
CPUtojumptothememoryaddressspecifiedbythetermBYTE_AVAILABLE.Thisisthe
interruptmode:interruptonfirstcharacter.Specialreceiveconditionslikereceiverbuffer
overruncauseajumptolocationSPEC_BYTE_COND.Thelattercaseabortsthetransfer.

INT_VEC:
org
DEFW
org
DEFW

1Ch
BYTE_AVAILABLE
1Eh
SPEC_BYTE_COND

Text12:SIOinterruptvectortable

Blunkelectronicatwww.trainz.de

16

1.2.2.3InitializingtheCTC

Pleasereadsection1.1.3.4onpage10.
1.2.2.4InitializingtheCPU

Pleasereadsection1.1.3.5onpage10.
1.2.2.5XModemFileTransfer

Theassemblycodeofthismoduleisdescribedinthefollowingsections.Duetoits
complexityIsplititintopartsshowninText13,14and15whosesuccessionmustnotbe
mixed.Fordetailedinformationonthepurposeofcertainregistersandcontrolbitsplease
readtheSIOdatasheet.
1.2.2.5.1

Hosttriggeredtransferandsetup

ThehostPCinitiatesthetransfer.UsingMinicomforexampleyoupressCTRLAStoget
intoamenuwhereyouselectthexmodemprotocolandafterwardintothefilemenuto
selectthefiletobesenttotheclient.TheprocedureissimilarwithHyperTerminal.
AfterthatthehostwaitsforaNAKcharactersentbytheclient.
NowyoushouldrunthecodeshownbelowinText13onyourZ80machine.Thiscode
initializestheSIOforinterruptmodeinterruptonfirstreceivedcharacter.

;setupTXandRX:
ld
out

a,018h
(SIO_A_C),A

;writeintoWR0:channelreset

ld
out
ld
out

a,004h
(SIO_A_C),A
a,44h
(SIO_A_C),A

;writeintoWR0:selectWR4

ld
out
ld
out

a,005h
(SIO_A_C),A
a,0E8h
(SIO_A_C),A

;writeintoWR0:selectWR5

ld
out
ld
out

a,01h
(SIO_B_C),A
a,00000100b
(SIO_B_C),A

;writeintoWR0:selectWR1

ld
out
ld
out

a,02h
(SIO_B_C),A
a,10h
(SIO_B_C),A

;writeintoWR0:selectWR2

;44hwriteintoWR4:clkx16,1stopbit,noparity

;DTRactive,TX8bit,BREAKoff,TXon,RTSinactive

;nointerruptinCHB,specialRXconditionaffectsvect

;writeintoWR2:cmdlineintvect(seeintvectable)
;bitsD3,D2,D1arechangedaccordingtoRXcondition

Text13:setup1

Blunkelectronicatwww.trainz.de

17

Nowwedosomesettingsforbadblockcounting,thefirstblocknumbertoexpectandthe
RAMdestinationaddressofthefiletoreceivefromthehost.SeeText14.Thedestination
addresssettingisredcolored.FromthisRAMlocationonwardsthefileistobestored.Im
myexampleIuseaddress0x8000.Dependingonyourapplicationyoushouldchangethis
value.
sub
ld
ld
ld

A
(temp0),A
C,1h
HL,8000h

call
call

SIO_A_EI
A_RTS_ON

call

TX_NAK

;resetbadblockscounter
;Choldsfirstblocknrtoexpect
;setlowerdestinationaddressoffile

;NAKindicatesreadyfortransmissiontohost

Text14:setup2

Text15showsthecodesectionthatpreparestheCPUforthereceptionofthefirstbyteof
adatablock.ThelinecoloredredmakestheCPUwaitingforaninterruptwhichiscaused
bytheSIO.ThebelonginginterruptserviceroutineisshowninText16.
Onceablockhasbeenreceived,thechecksumisverifiedandpossiblebadblocks
counted.Thesamedatablockistransferredmaximal10timeswhereuponthetransferis
aborted.

Blunkelectronicatwww.trainz.de

18

REC_BLOCK:
;setblocktransfermode
ld
a,21h
out
(SIO_A_C),A
ld
a,10101000b
out
(SIO_A_C),A
ei
call
halt
call
ld
out
ld
out

A_RTS_ON

;writeintoWR0cmd4andselectWR1
;waitactive,interruptonfirstRXcharacter
;bufferoverrunisaspecRXcondition

;awaitfirstrxchar

A_RTS_OFF
a,01h
(SIO_A_C),A
a,00101000b
(SIO_A_C),A

;writeintoWR0:selectWR1
;waitfunctioninactive

;checkreturncodeofblockreception(eholdsreturncode)
ld
a,e
cp
0
;blockfinished,noerror
jp
z,l_210
cp
2
;eotfound
jp
z,l_211
cp
3
;chksumerror
jp
z,l_613
ld
a,10h
jp
l_612
l_210:

call
inc
sub
ld
jp

TX_ACK
c
A
(temp0),A
REC_BLOCK

;whennoerror
;preparenextblocktoreceive

l_211:

call
ld
jp

TX_ACK
A,01h
l_612

;oneot

l_613:

call
scf
ccf
ld
sbc

TX_NAK

;onchksumerror

DE,0080h
HL,DE

;clearcarryflag
;subtract80h
;fromHL,soHLisresettoblockstartaddress

ld
inc
ld
cp
jp
jp

A,(temp0)
A
(temp0),A
09h
z,l_612
REC_BLOCK

;clearbadblockcounter

;countbadblocksintemp0

;abortdownloadafter9attemptstotransferablock
;repeatblockreception

l_612:
DLD_END:
ret

Text15:ReceiveDataBlock

Blunkelectronicatwww.trainz.de

19

BYTE_AVAILABLE:
EXP_SOH_EOT:
in
l_205: cp
jp
cp
jp
ld
reti

A,(SIO_A_D)
01h
z,EXP_BLK_NR
04h
nz,l_2020
e,2h

;awaitblocknumber
EXP_BLK_NR:
in
A,(SIO_A_D)
cp
C
jp
nz,l_2020

;readRXbyteintoA
;checkforSOH
;checkforEOT

;readRXbyteintoA
;checkformatchofblocknr

;awaitcomplementofblocknumber
ld
A,C
;copyblocknrtoexpectintoA
CPL
;andcplA
ld
E,A
;Eholdscplofblocknrtoexpect
EXP_CPL_BLK_NR:
in
A,(SIO_A_D)
cp
E
jp
nz,l_2020

;readRXbyteintoA
;checkforcplofblocknr

;awaitdatablock
ld
D,0h
ld
B,80h
EXP_DATA:
in
ld
add
ld
inc
djnz

;startvalueofchecksum
;definesblocksize128byte

A,(SIO_A_D)
(HL),A
A,D
D,A
HL
EXP_DATA

;readRXbyteintoA
;update
;checksuminD
;destaddress+1
;loopuntilblockfinished

EXP_CHK_SUM:
in
A,(SIO_A_D)
;
ld
a,045h
cp
D
jp
z,l_2021
ld
e,3h
reti
l_2020: ld
RETI
l_2021: ld
RETI

;readRXbyteintoA
;fordebugonly
;checkforchecksummatch

E,1h
E,0h

;returnwhenblockreceivedcompletely

;IntroutineonRXoverflow
SPEC_BYTE_COND:
ld
HL,DLD_END
push
HL
reti

;incaseofRXoverflowprepareabortoftransfer

Text16:InterruptServiceRoutine
Blunkelectronicatwww.trainz.de

20

1.2.2.5.2

Subroutines

ImportantfortheXModemprotocolisthesendingoftheAcknowledgeandtheNot
Acknowledgecharactertothehostmachine.Forallotherroutinesusedinthecodeabove
pleaserefertosections1.1.3.3onpage9and1.1.3.6onpage11.

TX_NAK:
ld
out
call
RET

a,15h
;sendNAK15htohost
(SIO_A_D),A
TX_EMP

TX_ACK:
ld
out
call
RET

a,6h
;sendAKtohost
(SIO_A_D),A
TX_EMP

Text17:Acknowledge/NotAcknowledge

Blunkelectronicatwww.trainz.de

21

2 TheZ80CTC
TheZ80CTCprovidesfeaturestorealizevariouscountingandtimingmechanismswithin
theZ80computersystem.Thedatasheetgivesagoodoverallviewofallthefeaturesof
thisdevicebutlacksatutoriallikeapproachandprogrammingexamplesinassembly
language.
ThissectiondescribeshowtoprogramtheCTCandtheassociatedinterruptstructureso
thatakindofheartbeatisgenerated.Thisbeatcanbeusedtomakeadisplayless
embeddedcomputergivingalifesigneverycoupleofseconds.Furthermorethecode
examplesshownherecanbeimprovedtomakeasystemclock.

2.1 DesiredMechanism
Imagineanembeddedcomputer,basedonthefamousZ80CPU,whichhasnodisplay
meansbutasingleLED.Immediatelyafterpoweruptheboardhastogivealifesignby
flashingtheLEDeverytsecondsasakindofaheartbeat.
Themainprogramrunningontheboardshallnotbeaffectedbytheheartbeatfunction,
exceptit'sinterruptioneverytsecondsofcourse.

2.2 CTCDeviceStructureandexternalwiring
Figure3(takenfrom[2])showstheblockdiagramoftheCTCdevicewithits4
timer/counterchannelsandthetwochannelsweneedmarkedred.Figure4(takenfrom
[2])showsthestructureofasinglechannel.
Note:Theoutputofchannel3isnotconnectedtoanypin.

2.2.1

Wiring

Dataandcontrol:

ThesearetheZ80bussignalsD[7:0],A[1:0]orCS[1:0],/RD,
/IOREQ,/CE,/RESETandCLK.

InterruptControlLines:

/M1,/INTconnectedtoCPU,IEIandIEOdaisychainedtoother
periphery

Outputs:

zerocountsignalsTO[2:0],TO2iswiredtoTRG3

Inputs:

counterinputsTRG[3:0]

Blunkelectronicatwww.trainz.de

22

Figure3:CTCBlockDiagram

Figure4:ChannelStructure

Blunkelectronicatwww.trainz.de

23

2.3 Programming
Treeproblemshavetobesolved:
initializingtheCTC
implementingtheinterruptmechanism
writinganinterruptserviceroutinethathandlestheflashingoftheLED

2.3.1

Header

Theheadershownbelowdefinesthehardwareaddressesofthecontrolportofyourfour
CTCchannels0to3.Inmycaseheretheaddressesequalthechannelnumber.
CH0
CH1
CH2
CH3

equ
equ
equ
equ

0h
1h
2h
3h

Text18:header

2.3.2

Interrupttable

EverytimeCTCchannel3countequalszeroaninterruptistriggeredcausingtheCPUto
jumptothememoryaddressspecifiedbythetermCT3_ZERO.

org
DEFW

16h
CT3_ZERO

Text19:CTCinterruptvectortable

Blunkelectronicatwww.trainz.de

24

2.3.3

InitializingtheCTC

FirstwehavetoconfiguretheCTCchannelsasshowninText20.Wedon'tneedchannel
0and1.Theyareonhold.WeoperatetheCTCchannel2asfrequencydividerwhich
scalestheCPUclockof5MHzdownbyfactor256*256.TheoutputTO2ofchannel2
drivesinputTRG3ofchannel3whichfurtherdividesbyfactorAFh.Thiscauseschannel3
tozerocountatafrequencyofapproximately0.44Hz.Sotheinterruptoccursevery2.3
seconds.
Fordetailedinformationonthepurposeofcertainregistersandcontrolbitspleasereadthe
CTCdatasheet.

INI_CTC:
;initCH0and1
ld
A,00000011b
out
out

(CH0),A
(CH1),A

;intoff,timeron,prescaler=16,don'tcareext.TRGedge,
;starttimeronloadingconstant,notimeconstantfollows
;swrstactive,thisisactrlcmd
;CH0isonholdnow
;CH1isonholdnow

;initCH2
;CH2dividesCPUCLKby(256*256)providingaclocksignalatTO2.TO2isconnectedtoTRG3.
ld
A,00100111b
;intoff,timeron,prescaler=256,noext.start,
;startuponloadingtimeconstant,timeconstantfollows
;swreset,thisisactrlcmd
out
(CH2),A
ld
A,0FFh
;timeconstant255ddefined
out
(CH2),A
;andloadedintochannel2
;T02outputsf=CPU_CLK/(256*256)
;initCH3
;inputTRGofCH3issuppliedbyclocksignalfromTO2
;CH3dividesTO2clockbyAFh
;CH3interuptsCPUappr.every2sectoserviceintroutineCT3_ZERO(flashesLED)
ld
A,11000111b
;inton,counteron,prescalerdon'tcare,edgedon'tcare,
;timetriggerdon'tcare,timeconstantfollows
;swreset,thisisactrlcmd
out
(CH3),A
ld
A,0AFh
;timeconstantAFhdefined
out
(CH3),A
;andloadedintochannel3
ld
out

A,10h
(CH0),A

;itvectordefinedinbit73,bit21don'tcare,bit0=0
;andloadedintochannel0

Text20:configuretheCTC

Blunkelectronicatwww.trainz.de

25

2.3.4

InitializingtheCPU

TheCPUistorunininterruptmode2.SeeText21below.Thissettinghastobedone
afterinitializingtheCTC.
INT_INI:
ld
ld
im
ei

A,0
I,A
2

;loadIregwithzero
;setintmode2
;enableinterupt

Text21:setuptheCPUinterruptmode2

2.3.5

Interruptroutine

Uponzerocountofchannel3theroutineCT3_ZEROasshowninText18isexecuted.
HereyouputthecodethatswitchestheLEDonandoff.
Note:InthisexamplewebackuponlyregisterAF.Dependingonyourapplicationyou
mightberequiredtobackupmoreregisterslikeHL,DE,CD,

CT3_ZERO:
;flashesLED
push
AF

;backupregistersAandF

;nowaddressyourperipherythatturnstheLEDon/offe.g.aDFlipFlop
pop
EI
reti

AF

;restoreregistersAandF
;reenableinterrups

Text22:CT3zerocountroutine

Blunkelectronicatwww.trainz.de

26

3 TheZ80PIO
TheICprotocolallowsthecommunicationofvariousdeviceslikeADC,DAC,expanders,
memoriesandalotmoreviaa2wirebuswhichsavesboardspacetoagreatextent.The
Z80PIOdevicecanbeprogrammedsothatitbecomestheICbusmaster.Thedetailsof
theICprotocolcanbefoundathttp://en.wikipedia.org/wiki/IC.
WithinthisdocumentthereisnospecialfocusonprogrammingofthePIOnoronhardware
issueslikedeviceselection,pincharacteristicsorratings.TheZ80PIOdeviceandiswell
documentedbytheofficialZiLOGdatasheetsatwww.zilog.comorwww.z80.info.Please
readalsothedatasheetsprovidedbyrespectiveICdevicemanufacturers.

3.1 WhatdoweneedfortheICprotocol?
Theaimaresomemajorroutineswritteninassemblycode:
sendinganybyteontotheICbus
receivinganybytefromthebus
resettingthebus
startingandstoppingthebus
TheICbusisconnectedtoPIOportBwithB0drivingSCL,andB1drivingandreading
SDAasshowninFigure5.

Blunkelectronicatwww.trainz.de

27

3.2 TheOpenDrainProblem
AtypicalICmasterhasopendrainpins.TheZ80PIOdoesnothaveopendrainoutputs
onitsportsAandB.Insteadtheyareofpushpullcharacteristicwhichrequirestwo
additionalseriesresistorsR3andR4asshowninFigure5.R1andR2aremandatoryfor
anICmaster2.

Figure5:externalresistors
R3andR4serveasoverloadprotectionforthePIOandtheslavesincaseboththemaster
andoneoftheslavesdriveontotheSCLorSDAnet.Thevaluesof10kforR1/R2and160
OhmsforR3/R4areonlyroughestimationsandshouldbemodifiedaccordingtoyour
application.

2 SomeICmastersmayhavetheseresistorsbuiltin.
Blunkelectronicatwww.trainz.de

28

3.3 Wiring
ThegeneralrulesoftheZ80bussystemapplyasfollows:
Dataandcontrol:

ThesearetheZ80bussignalsD[7:0],A[1:0]orCONTSELand
PORTSEL,/RD,/IOREQ,/CEandCLK.

InterruptControlLines:

/INTconnectedtoCPU,IEIandIEOdaisychainedtoother
periphery

In/Outputs:

A[7:0],B[7:0],/ASTRB,/BSTRB,ARDY,BRDY

Note1:IrecommendtheANDingoftheCPUResetandtheCPUM1signaltoformthe
PIOM1signal.ThismakesthePIOstartingupproperlyuponsystemreset(pleasesee
Figure5).
Note2:AllunusedpinsofportAandBshouldbepulledupby10kresistorstoavoidthem
floatingwhenprogrammedasinputs.

3.4 Programming
3.4.1

Header

Theheadershownbelowdefinesthehardwareaddressesofthecontrolanddataportof
yourPIO.Inmycaseheretheyare9andBh.FurthermoretherearetwoRAMlocations
reservedtostorecurrentmodeandI/Oconfiguration.

PIO_B_D
PIO_B_C

equ
equ

9h
0Bh

PIO_B_MODE
PIO_B_IO_CONF

equ
equ

1005h
1006h

;holdscurrentPIOBmode
;holdscurrentIOconfigurationofPIOB

Text23:header

Blunkelectronicatwww.trainz.de

29

3.4.2

InitializingthePIO

Text24showstheactionsneeded:
settingportBinbitmode.
settingpinsB0andB1ininputmode.
loadingtheoutputregisterwithFCh(abinary11111100).
Laterintheprogramwedothefollowing:
EverytimepinB0orB1issettooutputmodethevalueszeroheldbytheoutputregisteris
passedthroughtothepin.Thiscausesahardlowonthepin.IfthepinB0orB1issetto
inputmode,itreleasesthelinewhereuponitispulledhighbythepullresistorsR1orR2.
SowecontrolthelogicalleveloftheSDAorSCLlinesonlybytheI/Oconfiguration
registerofthePIOportB.

INI_PIO:
;initPIOportB
ld
ld
out

A,0CFh
(PIO_B_MODE),A
(PIO_B_C),A

;setPIOBtobitmode
;updateglobalPIOBmodestatusvariable

ld
ld
out

a,0FFh
(PIO_B_IO_CONF),A
(PIO_B_C),A

;setD7..0toinputmode
;updateglobalPIOBIOstatusvariable
;writeIOconfigurationintoPIOB

ld

A,0FCh

out

(PIO_B_D),A

;ifdirectionofB1orB0changestooutput
;thepinwilldriveL
;loadPIOBoutputregister

Text24:configurethePIOportB

Blunkelectronicatwww.trainz.de

30

3.4.3

MainRoutines

3.4.3.1BusReset

Inordertogetallslavesproperreset,thefollowingcodeisrecommended.SCLisclocked
10timeswhileSDAisheldH.
RST_I2C:
;modifiesA,B,D
;leavesSDA=HandSCL=H
l_77:

ld
call
djnz
call
ret

B,0Ah
SCL_CYCLE
l_77
SCL_IN

;do10SCLcycleswhileSDAisH

Text25:busreset

3.4.3.2BusStartandStop

TheICbusprotocolrequiresacertainstartandstopsequence.Text26showsthecode.

I2C_START:
;startsI2Cbus
call
call
ret

SDA_OUT
SCL_OUT

;SDA=L
;SCL=L

I2C_STOP:
;stopsI2Cbus
call
call
call
ret

SDA_OUT
SCL_IN
SDA_IN

Text26:startandstoproutines

Blunkelectronicatwww.trainz.de

31

3.4.3.3Sending

ThecodeshowninText23istheroutineI2C_txwhichsendsabyteontothebus.Thebyte
tosendhastobeintheaccumulator(orCPUregisterA)priortocallingthisroutine.This
routinefirstsendsthesatabyte(bycallingsend_byte),thenchecksfortheacknowledge
bitsentbyaslave.Ifnoacknowledgebitisfoundtheroutineleavesthecarryflagset.

I2C_tx:
;bytetosendprovidesaccumulator
;returnswithcarryclearedifacknbitnotfound
;modifiesA,B,C,D,HL
call
bit
scf
ret

send_byte
1,D

;testDregisterforacknowledgebit

;returnifaknbit=Lwithcarryset

;whenACKerrorstopbus
call
I2C_STOP
scf
ccf
ret
;returnifaknbit=Hwithcarrycleared

Text27:sendroutine

Blunkelectronicatwww.trainz.de

32

3.4.3.4Receiving

Theroutinetoreceiveabytefromaslaveisshownbelow.Thebytereceivedfromthe
slaveisreturnedintheaccumulator.

I2C_RX:
;modifiesA,B,D
;returnswithslavedatabyteinA
;leavesSCL=LandSDA=H
l_66:

L_found:ccf
H_found:

ld
in
scf
bit
jp

B,8h
A,(PIO_B_D)

rl
call
djnz
call

C
SCL_CYCLE
l_66
SCL_CYCLE

1,A
nz,H_found

;sendNAKtoslave

;slavebytereadyinC
ld
A,C
ret

Text28:receiveroutine

Blunkelectronicatwww.trainz.de

33

3.4.4

Subroutines

Themainroutinesdescribedabovefrequentlycallothercodewhichweseeinthefollowing
sections.Theseroutinesarewrittenwiththeseprimaryobjectives:
memorysaving
modularity
easytounderstand(hopefully)
Theexecutionspeedisofsecondaryimportancehere.

3.4.4.1SCLCycle

EverybittransferredviatheSDAlinemustbeaccompaniedbyaLHLsequenceofthe
SCLline.Thefollowingroutineaccomplishesthat.AfterSCLgoingHtheSDAlineis
sampled3.

SCL_CYCLE:
;modifiesA
;returnsDwhereinbit1representsstatusofSDAwhileSCLwasH
;leavesSCL=L
call
call

SCL_OUT
SCL_IN

;lookforacknbit
in
A,(PIO_B_D)
ld
D,A
call
SCL_OUT
ret

Text29:SCLcycle

3Onlythe9thsampleofabytetransferisimportantregardingtheacknowledgebit.
Blunkelectronicatwww.trainz.de

34

3.4.4.2SetSDAasinputoroutput

AsmentionedearlierthedirectionsettingofB1determineswhetheraHorLisdrivenon
theline.SoifyouwantaHonSDArunroutineSDA_INifyouneedanLrunSDA_OUT.
SDA_IN:
;modifiesA

;reloadsPIOBmode
ld
out

A,(PIO_B_MODE)
(PIO_B_C),A

;changedirectionofSDAtoinput
ld
A,(PIO_B_IO_CONF)
set
1,A
out
(PIO_B_C),A
ld
(PIO_B_IO_CONF),A
ret

SDA_OUT:
;modifiesA
;reloadsPIOBmode
ld
out

A,(PIO_B_MODE)
(PIO_B_C),A

;changedirectionofSDAtooutput
ld
A,(PIO_B_IO_CONF)
res
1,A
out
(PIO_B_C),A
ld
(PIO_B_IO_CONF),A
ret

Text30:setSDAasoutputorinput

Note:IfyourSDAlineisstuckatloworhighforsomereason,theroutineshownherewill
notdetectthismalfunction.AnimmediatereadingbackofSDAcanbeimplementedeasily.

Blunkelectronicatwww.trainz.de

35

3.4.4.3SetSCLasoutputorinput

SimilartoSDAtheSCLlineiscontrolledbythedirectionofpinB0.IfyouwantaHonSCL
runroutineSCL_INifyouneedanLrunSCL_OUT.

SCL_IN:
;modifiesA
;reloadsPIOBmode
ld
A,(PIO_B_MODE)
out
(PIO_B_C),A
;changedirectionofSCLtoinput
ld
A,(PIO_B_IO_CONF)
set
0,A
out
(PIO_B_C),A
ld
(PIO_B_IO_CONF),A
ret

SCL_OUT:
;modifiesA
;reloadsPIOBmode
ld
A,(PIO_B_MODE)
out
(PIO_B_C),A
;changedirectionofSCLtooutput
ld
A,(PIO_B_IO_CONF)
res
0,A
out
(PIO_B_C),A
ld
(PIO_B_IO_CONF),A
ret

Text31:setSCLasoutputorinput

Note:IfyourSCLlineisstuckatloworhighforsomereason,theroutineshownherewill
notdetectthismalfunction.AnimmediatereadingbackofSCLcanbeimplementedeasily.

Blunkelectronicatwww.trainz.de

36

3.4.4.4Sendabyte

Thisroutineperformstheclockingoutofthedatabyte.
Note:Donotconfusethisroutinewiththeoneshowninsection3.4.3.3.Send_byteis
calledby2C_tx.

send_byte:
;requiresbytetobesentinA
;returnswithbit1ofDholdingstatusofACKNbit
;leavesSCL=LandSDA=H
;modifiesA,B,C,D

l_74:
SDA_L:
SDA_H:
l_75:

ld
ld
sla
jp
call
jp
call
call
djnz
call
call
ret

B,8h
C,A
C
c,SDA_H
SDA_OUT
l_75
SDA_IN
SCL_CYCLE
l_74
SDA_IN
SCL_CYCLE

;8bitsaretobeclockedout
;copytoCreg
;shiftMSBofCintocarry
;whenL
;pullSDAlow
;releaseSDAtoletitgohigh
;doSCLcycle(LHL)
;processnextbitofCreg
;releaseSDAtoletitgohigh
;doSCLcycle(LHL),bit1ofDholdsacknbit

Text32:sendbyte

Blunkelectronicatwww.trainz.de

37

4 ProgrammingPulseWidthModulation(PWM)
Pulsewidthmodulation(PWM)ifbasedonadigitalhardwareingeneralcanberegarded
asaDigitalAnalogConverter(DAC):Adigitalvalue,letssayabyte,isconvertedintoa
PWMsignalwherethepulsewidthrepresentsthebytebeinginput.
Figure6depictstwoexamples,oneforthevalue32d/20h(dashedline)andanotherfor
value224d/E0h(continuousline).Thesignalperiodends(atT)wherethesamplecount
reaches256d(or100h),whereuponthecyclestartsalloveragain.

Figure6:PWMoutputdiagram
Withanintegratorcircuitrythissignalcaneasilybesmoothedtoarealanalogvoltageor
current(seesection4.5onpage47).
Thefollowingdiscussionismoreoftheoreticalnaturewithlimitedpracticalbenefitsas
therearesmartersolutionsavailabletodaytogenerateaPWMsignali.e.CPLDs
programmedinVerilogHDL.Thebasicquestionsofthisdiscussionare:
IsitpossibletogenerateaPWMentirelyCPUbased?
Whichaccuracycanbeachieved?
TheCPUusedhereisofcoursethefamousZ80processortogetherwithitsperipheral
CTCandPIOunits.

Blunkelectronicatwww.trainz.de

38

4.1 TheProgramAlgorithm
Asaprogramalgorithmdescribesaprocedureonahighlevel,itcanbeappliedtoevery
hardwareplatformandeveryprogramminglanguage.Heresomeexamplestooutlinethe
range:
Z80CPUprogrammedinassembly
midrangeprocessors/microcontrollersandprogramminglanguages
TSC695FSPARCprocessorprogrammedinAda
Table1liststhevariablesusedforaCPUdrivenPWM.Figure7showswhattodoto
initialize,Figure8showstheessentialinterruptserviceroutine(ISR).
Butfirsttheinitsequence:
1) UponCPUresettheperipheralsandtheCPUinterruptmodeneedtobeinitialized
(yellowbox).
2) OnepinofthePIOorGPIOsmustbesetasoutput.
3) TheCTCmustbesettorequestaninterruptataconstantrateeveryxmillior
nanoseconds.Eachrequestsrepresentsatimeslotwhereinasamplecountergets
incremented(seeFigure6onpage38).
4) ThenthevaluesbelongingtothePWMneedtobeassignedwithainitvalue.Sowe
haveasafestartingpointwhentheinterruptgetsenabled(greenbox).
5) Usuallythemainlineprogramloopistobeenteredafterward.
Variable

Meaning

Remarks

dac_ch0

valuetobeconvertedintoananalog integer(i.e.8bit)
pulsewidth

sample_counter

countsthesamplesofaperiod

modulusnumber,overflow
indicatesanewperiod

buffer

outputbuffer

latchestheoutputsignal
betweenupdates

out_port

outputport

usuallyarealhardware
outputlikeGPIOorPIO

Table1:variablesusedforaPWM
Everytime,thecounteroftheCTCunitreacheszerocount,theISRshowninFigure8
getsexecuted.UsuallytheCTCsignalsthiseventbyassertinganinterruptrequestsignal,
whereupontheCPUstartsexecutingtheISR.

Blunkelectronicatwww.trainz.de

39

Importanttopointout:
1. TheCTCmusthavethehighestinterruptpriorityaspossible. 4
2. TheISRmustfinishbeforethenextzerocountoftheCTC.
Figure8:
1. TheISRexecutiontimeisnotconstant,asitcontainsbranchesdependingonthe
contentsofsomevaluesbeingtested.Soitisreasonabletoupdateout_portright
atthebeginningoftheISR(yellowbox).Theout_portsignalisupdatedinreal
time.
2. Nowifthesamples_counterequalsthe dac_ch0variable(reddiamond)abitx
issetinthebuffer.Ifthereisnomatch,thebufferbitisuntouched.The
samples_counterstartswithzero,sothegreaterdac_ch0is,thelaterthe
bufferbitwillbeset.
3. Nextthesamples_counterisincremented(graybox).Ifthesamples_counter
overflows,meansallitsbitsflipbacktozero,thebufferbitgetscleared.Thisis
themomentwherethePWMsignalperiodends.Otherwisethebufferbitisleftas
itis.
4. Returnfrominterrupt(RETI).
5. ThenexttimetheISRgetsexecuted,theout_portwillbeupdatedbythemost
recentstateofthebufferbit.Seeactionpoint1.

4 Alowerpriorityispossible,butdecreasestheoutputaccuracysignificantly.
Blunkelectronicatwww.trainz.de

40

INIT PIO
INIT CTC
INIT Interrupts

out_port := buffer

sample_counter = dac_ch0 ?
INIT VARIABLES:
dac_ch0 = 0
sample_counter = 0
buffer = 0
out_port = 0

set bit x in buffer

samples_counter + 1
ENABLE INTERRUPTS
sample_counter = 0 ?
Main Line Program

Figure7:generalinit
sequence

clear bit x in buffer

return from interrupt

Figure8:generalISR

Blunkelectronicatwww.trainz.de

41

4.2 TheMath
Lifewithoutmathematicsisfuzzyandboring.
ThemostimportantconstraintsofthePWMoutputsignalare:
1. Frequency f o andPeriod T o
2. Resolution R
3. Stability/Accuracy
Inthisexample f o isgivenwith50Hz. R istobe256steps(8bit).
1. Thisyieldsasamplingfrequencyof
f s=50 Hz256

f s=12.8 kHz
2. SotheCTCmustbeprogrammedtoreachzerocountatarateof:
t s=

1
fs

t s=

1
kHz
12.8

t s=78.1 s
SotheISRwillbeexecutedevery78.1microseconds.Thisimpliesthatthetotal
ISRexecutiontimeitselfmustbelessthan78.1microseconds.
3. Usuallythetime T m requiredtoexecuteamachineinstructionisexpressedasa
multipleoftheCPUclockperiod T cpu .ForexampletheZ80instruction
SET 0,(IX+0)
takes23CPUclocks.Hence T m forthisinstructionis23.
ToexpressthemaximumtotalexecutiontimeoftheISRtheseequationsapply:
T cpu=

1
f cpu

TheISRinworstcasemustrequirelessthan N C periods:
Nc <

ts
T cpu

WhenprogrammingtheISR,thesumoftheindividual T m valuesofthemachine
instructionsmustnotexceed N C .
4. Thestabilityisimpairedbythefact,thattheCPUservicesaninterruptnot
immediatelybutfinishestheinstructionofthemainlineprogrambeingexecuted
currentlyfirst.Sothedelay t d betweentheinterruptrequested(bytheCTC)and
Blunkelectronicatwww.trainz.de

42

theupdateofthePWMoutput(bytheISR)varies.Theshortestinstructionofthe
CPUinstructionsetdictatestheminimumdelay,thelongestinstructionthe
maximumdelay.SeetheCPUinstructionsetforCPUspecificratings.
AsfarastheZ80CPUisconcerned, T m rangesfrom4(shortestinstruction)to23
(longestinstruction).
4T m 23
Sothedelayinsecondsranges:
4T cpu < t d <23T cpu
IftheZ80CPUclockis5MhzthePWMsignalupdatewilljitterby3.8sbetween
0.8and4.6s,indicatedwitharedarrowsinFigure9andFigure10.

Figure9:PWMoutputjitter

Blunkelectronicatwww.trainz.de

43

4.3 TheZ80AssemblyCode
Theprogramcodeusedforthisexperimentcanbefoundhere:
http://www.trainz.de/trainz/sw/applications/pwm/dac_1_channel.asm
Thistinyprogramhasamainloopwheretheshortestandthelongestmachineinstructions
oftheZ80areusedinordertoexpandthestochasticjittertoitsmaximum.
TheISRrequirestuning,inordertoreducethetotalexecutiontime.Theless N C gets,
thehigher f o maybecome.Inthecurrentstateofthissmalltestprogramthetotal
executiontime t ISR oftheISRis198cycles,orinotherwords198timestheCPUclock
period T cpu :
t ISR =198T CPU

t ISR =198(

1
)
5MHz

t ISR =39.6s
whichiswellbelowthemaximumallottedtime t S of78.8s.

4.4 Results
Table2showssomeresultsofthePWMexperimentwiththegivenparametersonlight
bluebackground.Themeasurementsof t width confirmtheexpectedjitterofabout3.8s
(seesection4.2,page42,point4).Noteworthyisthatthepulsewidth t width isalwaysa
multipleof t s=78.1 s whichiseasytoseewithverysmallpulsewidths.
Themeasurementsongraybackgroundareoflimitedaccuracysincetheoscilloscope
usedhereroundsuptotenthsofmilliseconds.However,theachievablemeanvoltage
U mean resultsaremostaccurate.
ThePWMoutputfrequency f o is50.9Hz.
Theresolution R ofthisquasiDACis8bit.

Blunkelectronicatwww.trainz.de

44

f cpu =5 MHz
f o =51 Hz
U h =4.96V
dac_ch0
hexadecimal

t width.min

t width.max

U mean.min

U mean.max

[ms]

[ms]

[V]

[V]

1
2
3
20
40
80
C0
FE
FF
Table2:Results

0.0743
0.152
0.23
2.45
4.9
9.8
14.7
19.5
19.55

0.077
0.155
0.233
2.5
4.95
9.85
14.75
19.55
19.6

0.0084

0.022

0.053
0.727
1.46
2.48
3.5
4.93
4.96

0.068
0.734
1.475
2.49
3.516
4.94
4.97

Figure10showsascopescreenshotwiththejittermarkedbyredarrows.Theyellow
pointersindicatethestartofthesignalperiod.

Blunkelectronicatwww.trainz.de

45

Figure10:OscilloscopeScreenshot(PWMinputvalue32d/20h)
Forapplicationswhereaccuracyandstabilityarenocriticalissues,thisapproachmay
serveforcontrolof:
BrightnessofLEDsorlamps
Motors
Brakes
Magnets
...

Blunkelectronicatwww.trainz.de

46

4.5 IntegratingCircuitry
Themeanvoltage U mean inTable2page45hasbeencomputedbytheoscilloscope(see
alsoFigure10page46).InordertoobtainarealanalogoutputsignalfromthePWM
signal,anintegratorcircuitryisrequired.Thiscircuitrybasicallymusthaveaswitched
referencevoltageandatleastasimpleRCLowPassfilter(orbetteranopampbased
integrator)withasufficienthightimeconstant.
Figure11depictsapossiblecircuitrytakenfrom[3].Thetimeconstanthereis
t=R7 C4

t=1MOhms680nF
t=0.68s
andappliesfortheapplicationdescribedin[3]:
R=4096 ,(12bit)
f s=70kHz
T o=60ms
Soasaruleofthumb,thefiltertimeconstant t shouldbe10timesthePWMsignal
period T o .Toaccommodatetoourfiguresgiveninsection4.2page42,theR7andC4
shouldbereplacedby1MOhmsand0.2Fwhichequalsa0.2stimeconstant.
Thegreaterthetimeconstant,thegreaterthesettletimefortheoutput!

Figure11:IntegratorCircuitry
TheICsusedherearetheclassicalvoltageregulatorA723andtheFETopampTL080
(additionaloffsetcompensationmayberequired).

Blunkelectronicatwww.trainz.de

47

5 Z80ICequivalentstable
AnoverviewofICsofthefamousZ80familygivesTable3.
device

equivalenttype

Z80CPU

BU18400APS(ROHM)
D780C1(NEC)
KP1858BM1/2/3/KR1858BM1/2/3(USSR)
LH0080(Sharp)
MK3880x(Mostek)
T34VM1/T34BM1(USSR)
TMPZ84C00AP8(Toshiba)
UA880/UB880/VB880D(MME)
Z0840004(ZiLOG)
Z0840006(ZiLOG)
Z80ACPUD1(SGSAtes)
Z84C00AB6(SGSThomson)
Z84C00(ZiLOG)
Z8400A(Goldstar)
U84C00(MME)

Z80SIO

UA8560,UB8560(MME)
Z0844004(ZiLOG)
Z8440AB1(ST)
Z0844006(ZiLOG)
Z84C40(ZiLOG)
U84C40(MME)

Z80PIO

Z0842004/6(ZiLOG)
UA855/UB855(MME)
Z84C20(ZiLOG)
U84C20(MME)

Z80CTC

Z84C30(ZiLOG)
U84C30(MME)
UA857/UB857(MME)

Table3:Z80equivalents

Blunkelectronicatwww.trainz.de

48

6 References
1. ZiLOG,Z80FamilyCPUUserManualUM0080050205
2. ZiLOG,Z80FamilyCPUPeripheralsUserManualUM0081010601
3. KhnelC,ADundDAUmsetzerfrden
Amateur,Berlin1986,page65,German,
ISBN3327000972

Blunkelectronicatwww.trainz.de

49

7 UsefulLinks
(1) Findupdatesofthistutorialathttp://www.trainz.de
(2) CadSoftEAGLETrainingandConsultingareasonablewayto
reasonableworkathttp://www.trainz.de

(3) AnEAGLEconfigurationscripteagle.scr.Units,grid,linewith,textsize,font,drills
andmorewelldefinedandcleanedup
(4) EAGLEanaffordableandveryefficient
schematicsandlayouttoolat
http://www.cadsoftusa.com

(5) AGerberDataViewerandEditorathttp://www.pentalogix.com
GermanSalesandSupportOffice:
Helmut Mendritzki
Software-Beratung-Vertrieb
Dahlienhof 1
25462 RELLINGEN
GERMANY
Tel.: +49 (0) 4101 - 20 60 51
Fax: +49 (0) 4101 - 20 60 53
Mobile: +49 (0) 171 - 2155852
eMail: mendritzki@aol.com

Blunkelectronicatwww.trainz.de

50

(6) WhatisBoundaryScan?
(7) LookingforaleanBoundaryScanTestSystem?Pleasehavealookhere!

(8) DebugSPI,IC,BoundaryScan/JTAGandotherhardwarewiththeLogicScanner
athttp://www.trainz.de/logic_scanner/Logic_Scanner_UM.pdf

Blunkelectronicatwww.trainz.de

51

(9) Theofficealternative:LibreOfficeat
http://www.libreoffice.org

(10) AcompleteembeddedZ80systemplusassemblerforLinuxandUNIXcanbe
foundathttp://www.trainz.de/trainz
(11) ThepowerfulcommunicationtoolKermitathttp://www.columbia.edu/kermit/
(12) Z80VerilogandVHDLCoresathttp://www.castinc.comandhttp://opencores.org
(13) TheZ80interruptstructureat
http://www.trainz.de/trainz/doc/z80interrupts_rewritten.pdf
(14) TheXModemProtocolReferencebyChuckForsbergat
http://www.trainz.de/trainz/pdf/xymodem.pdf
(15) MoreZ80stuffathttp://www.z80.info

Blunkelectronicatwww.trainz.de

52

8 FurtherReading
Irecommendtoreadthesebooks:
UsingCKermit/FrankdaCruz,ChristineM.Gianone/
ISBN1555581080(english)

CKermit:EinfhrungundReferenz/FrankdaCruz,ChristineM.Gianone/
ISBN3882290234(german)

9 Disclaimer
Thistutorialisbelievedtobeaccurateandreliable.Idonotassumeresponsibilityforany
errorswhichmayappearinthisdocument.Ireservetherighttochangeitatanytime
withoutnotice,anddonotmakeanycommitmenttoupdatetheinformationcontained
herein.

MyBossisaJewishCarpenter

Blunkelectronic/Owner:Dipl.Ing.MarioBlunk/Buchfinkenweg5/99097Erfurt/Germany+4917629045855/http://www.trainz.de
2013MarioBlunk

PrintedinGermany

Blunkelectronicatwww.trainz.de

53

S-ar putea să vă placă și