Vous êtes sur la page 1sur 20

8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers

http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 1/20
TOC Introduction Ch. 1 Ch. 2 Ch. 3 Ch 4. Ch. 5 Ch. 6 Ch. 7 Ch. 8 Ch. 9 App. A App. B App. C
Book:PICMicrocontrollers
Chapter6:SerialCommunicationModules
EUSART
TheEnhancedUniversalSynchronousAsynchronousReceiverTransmitter(EUSART)moduleisaserialI/Ocommunicationperipheral.Itis
alsoknownasSerialCommunicationsInterface(SCI).Itcontainsallclockgenerators,shiftregistersanddatabuffersnecessarytoperforman
inputoroutputserialdatatransferindependentlyofthedeviceprogramexecution.Asitsnamestates,apartfromtheusageofclockfor
synchronization,thismodulecanalsoestablishasynchronousconnection,whichmakesitirreplaceableinsomeapplications.
Forexample,intheeventthatitisdifficultor
impossibletoprovidespecialchannelsforclock
anddatatransfer(forexample,radioremotecontrol
orinfrared),theEUSARTmodulepresentsitselfas
aconvenientsolution.
Fig.61RemoteControlandPlane
TheEUSARTsystemintegratedintothePIC16F887microcontrollerhasthefollowingfeatures:
Fullduplexasynchronoustransmitandreceive
Programmable8or9bitcharacterlength
Addressdetectionin9bitmode
Inputbufferoverrunerrordetectionand
Halfduplexcommunicationinsynchronousmode(masterorslave).
EUSARTAsynchronousMode
TheEUSARTtransmitsandreceivesdatausingstandardnonreturntozero(NRZ)format.Asseeninfigure62below,thismodedoesnot
useclocksignal,whilethedataformatbeingtransferredisverysimple:
Fig.62EUSARTAsynchronousMode
Briefly,eachdataistransferredinthefollowingway:
Inidlestate,datalinehashighlogiclevel(1)
EachdatatransmissionstartswithSTARTbitwhichisalwaysazero(0)
Eachdatais8or9bitwide(LSBbitisfirsttransferred)and
EachdatatransmissionendswithSTOPbitwhichalwayshaslogiclevelwhichisalwaysaone(1).
EUSARTAsynchronousTransmitter
FeaturedDevelopmentTools
FreeOnlineBooks
EasyPICv7DevelopmentSystem
EasyPICv7istopsellingPIC
DevelopmentBoardfor250Microchip
PICMCUsinDIPpackaging.Itfeatures
USB2.0programmer/debuggerandover
17essentialmodulesnecessaryin
development.Boardcomeswith
PIC18F45K22.[moreinfo]
Book:PICMicrocontrollers
ProgramminginC
Whataremicrocontrollers,anyway?
Electroniccomponentsbuiltintoone
singlechipcapableofcontrollingasmall
submarine,acraneoranelevator
anything.Itsuptoyoutodecidewhat
youwantthemtodo.Youjusthaveto
writeaprogramanddumpitintothe
microcontroller.[moreinfo]
Login | Cart (0)
Products Solutions Store Distributors Libstock Contact Us search here
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 2/20
Fig.63EUSARTAsynchronousTransmitter
InordertoenabledatatransmissionviaEUSARTmodule,itisnecessarytoconfigureittooperateasatransmitter.Inotherwords,itis
necessarytodefinethestateofthefollowingbits:
TXEN=1EUSARTtransmitterisenabledbysettingthisbitoftheTXSTAregister
SYNC=0EUSARTisconfiguredtooperateinasynchronousmodebyclearingthisbitoftheTXSTAregisterand
SPEN=1BysettingthisbitoftheRCSTAregister,EUSARTisenabledandtheTX/CKpinisautomaticallyconfiguredasoutput.Ifthisbitis
simultaneouslyusedforsomeanalogfunction,itmustbedisabledbyclearingthecorrespondingbitoftheANSELregister.
ThecentralpartoftheEUSARTtransmitteristheshiftregisterTSRwhichisnotdirectlyaccessiblebytheuser.Inordertostarttransmission,
themodulemustbeenabledbysettingtheTXENbitoftheTXSTAregister.DatatobesentshouldbewrittentotheTXREGregister,which
willcausethefollowingsequenceofevents:
BytewillbeimmediatelytransferredtotheshiftregisterTSR
TXREGregisterremainsempty,whichisindicatedbysettingflagbitTXIFofthePIR1register.IftheTXIEbitofthe
PIE1registerisset,aninterruptwillbegenerated.Besides,theflagissetregardlessofwhetheraninterruptis
enabledornot.Also,itcannotbeclearedbysoftware,butbywritingnewdatatotheTXREGregister
Controlelectronics"pushes"datatowardtheTXpininrhythmwithinternalclock:STARTbit(0)...data...STOPbit
(1)
WhenthelastbitleavestheTSRregister,theTRMTbitoftheTXSTAregisterisautomaticallysetand
IftheTXREGregisterhasreceivedanewcharacterdatainthemeantime,thewholeprocedureisrepeated
immediatelyaftertheSTOPbitofthepreviouscharacterhasbeentransmitted.
Sending9bitdataisenabledbysettingtheTX9bitoftheTXSTAregister.TheTX9DbitoftheTXSTAregisteristheninthandMost
Significantdatabit.Whentransferring9bitdata,theTX9Ddatabitmustbewrittenbeforewritingthe8leastsignificantbitsintotheTXREG
register.AllninebitsofdatawillbetransferredtotheTSRshiftregisterimmediatelyaftertheTXREGwriteiscomplete.
EUSARTAsynchronousReceiver
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 3/20
Fig.64EUSARTAsynchronousReceiver
SimilartotheactivationofEUSARTtransmitter,inordertoenablethereceiveritisnecessarytodefinethefollowingbits:
CREN=1EUSARTreceiverisenabledbysettingthisbitoftheRCSTAregister
SYNC=0EUSARTisconfiguredtooperateinasynchronousmodebyclearingthisbitstoredintheTXSTAregisterand
SPEN=1BysettingthisbitoftheRCSTAregister,EUSARTisenabledandtheRX/DTpinisautomaticallyconfiguredasinput.Ifthisbitis
simultaneouslyusedforsomeanalogfunction,itmustbedisabledbyclearingthecorrespondingbitoftheANSELregister.
WhenthisfirstandnecessarystepisaccomplishedandSTARTbitisdetected,dataistransferredtotheshiftregisterRSRthroughtheRX
pin.WhentheSTOPbithasbeenreceived,thefollowingoccurs:
DataisautomaticallytransferredtotheRCREGregister(ifempty)
TheflagbitRCIFissetandaninterrupt,ifenabledbytheRCIEbitofthePIE1register,occurs.Similartotransmitter,
theflagbitisclearedbysoftwareonly,i.e.byreadingtheRCREGregister.Bearinmindthatthisisatwocharacter
FIFOmemory(firstin,firstout)whichallowsreceptionoftwocharacterssimultaneously
IftheRCREGregisterisoccupied(containstwobytes)andtheshiftregisterdetectsnewSTOPbit,theoverflowbit
OERRwillbeset.Inthiscase,anewcomingdataislost,andtheOEERbitmustbeclearedbysoftware.Itisdoneby
clearingandresettingtheCRENbit.
Note:itisnotpossibletoreceivenewdataasfarastheOERRbitisset
IftheSTOPbitiszero(0),theFERRbitoftheRCSTAregisterdetectingreceiveerrorwillbesetand
Toreceive9bitdataitisnecessarytosettheRX9bitoftheRCSTAregister.
ReceiveErrorDetection
Therearetwotypesoferrorswhichthemicrocontrollercanautomaticallydetect.ThefirstoneiscalledFramingerrorandoccurswhenthe
receiverdoesnotdetecttheSTOPbitattheexpectedtime.SucherrorisindicatedviatheFERRbitoftheRCSTAregister.Ifthisbitisset,it
meansthatthelastreceiveddatamaybeincorrect.Itisimportanttoknowseveralthings:
AFramingerrordoesnotgenerateaninterruptbyitself
Ifthisbitisset,thelastreceiveddatahasanerror
Aframingerror(bitset)doesnotpreventreceptionofnewdata
TheFERRbitisclearedbyreadingreceiveddata,whichmeansthatcheckmustbedonebeforedatareadingand
TheFERRbitcannotbeclearedbysoftware.Ifneeded,itcanbeclearedbyclearingtheSPENbitoftheRCSTA
register.ItwillsimultaneouslycauseresetofthewholeEUSARTsystem.
AnothertypeoferroriscalledOverrunError.ThereceiveFIFOcanholdtwocharacters.Anoverrunerrorwillbegeneratedifthethird
characterisreceived.Simply,thereisnospaceforanotheronebyteandanerrorisunavoidable!WhenthishappenstheOERRbitofthe
RCSTAregisterisset.Theconsequencesarethefollowing:
DataalreadystoredintheFIFOregisters(twobytes)canbenormallyread
NoadditionaldatawillbereceiveduntiltheOERRbitisclearedand
Thisbitisnotdirectlyaccessed.Toclearit,itisnecessarytocleartheCRENbitoftheRCSTAregisterortoresetthe
wholeEUSARTsystembyclearingtheSPENbitoftheRCSTAregister.
Receiving9bitData
Inadditiontoreceivingstandard8bitdata,theEUSARTsystemsupports9bitdatareception.Onthetransmitside,theninthbitis"attached"
totheoriginalbytejustbeforetheSTOPbit.Onthereceiveside,whentheRX9bitoftheRCSTAregisterisset,theninthdatabitwillbe
automaticallywrittentotheRX9Dbitofthesameregister.Whenthisbyteisreceived,oneshouldtakecareofhowtoreaditsbitstheRX9D
databitmustbereadbeforereadingthe8leastsignificantbitsoftheRCREGregister.Otherwise,theninthdatabitwillbeautomatically
cleared.
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 4/20
Fig.65Receiving9bitData
AddressDetection
WhentheADDENbitoftheRCSTAregisterisset,theEUSARTmoduleisabletoreceiveonly9bitdata,whereasall8bitdatawillbe
ignored.Althoughitseemslikearestriction,suchmodesenableserialcommunicationbetweenseveralmicrocontrollers.Theprincipleof
operationissimple.Themasterdevicesends9bitdatawhichrepresentstheaddressofonemicrocontroller.Allslavemicrocontrollerssharing
thesametransmissionline,receivethisdata.Ofcourse,eachofthemmusthavetheADDENbitsetbecauseitenablesaddressdetection.
Uponreceivingthisdataeachslavechecksifthataddressmatchesitsown.Software,inwhichaddressmatchoccurs,mustdisableaddress
detectionbyclearingitsADDENbit.Themasterdevicekeepsonsending8bitdata.Alldatapassingthroughthetransmissionlinewillbe
receivedby"recognized"EUSARTmoduleonly.Uponreceivingthelastbyte,theslavedeviceshouldsettheADDENbitinordertoenable
newaddressdetection.
Fig.67SendingData
TXSTARegister
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 5/20
Fig.68TXSTARegister
CSRCClockSourceSelectbitdeterminesclocksource.Itisusedonlyinsynchronousmode.
1Mastermode.ClockisgeneratedinternallyfromBaudRateGeneratorand
0Slavemode.Clockisgeneratedfromexternalsource.
TX99bitTransmitEnablebit
19bitdatatransmissionviaEUSARTsystemand
08bitdatatransmissionviaEUSARTsystem.
TXENTransmitEnablebit
1Transmissionenabledand
0Transmissiondisabled.
SYNCEUSARTModeSelectbit
1EUSARToperatesinsynchronousmodeand
0EUSARToperatesinasynchronousmode.
SENDBSendBreakCharacterbitisonlyusedinasynchronousmodeandonlyincaseitisrequiredtoobserveLINbusstandard.
1SendingBreakcharacterisenabledand
0Breakcharactertransmissioniscompleted.
BRGHHighBaudRateSelectbitdeterminesbaudrateinasynchronousmode.ItdoesnotaffectEUSARTinsynchronousmode.
1EUSARToperatesathighspeedand
0EUSARToperatesatlowspeed.
TRMTTransmitShiftRegisterStatusbit
1TSRregisterisemptyand
0TSRregisterisfull.
TX9DNinthbitofTransmitDatacanbeusedasaddressorparitybit.
RCSTARegister
Fig.69RCSTARegister
SPENSerialPortEnablebit
1Serialportenabled.RX/DTandTX/CKpinsareautomaticallyconfiguredasinputandoutputrespectivelyand
0Serialportdisabled.
RX99bitReceiveEnablebit
1Receiving9bitdataviaEUSARTsystemand
0Receiving8bitdataviaEUSARTsystem.
SRENSingleReceiveEnablebitisusedonlyinsynchronousmodewhenthemicrocontrolleroperatesasmaster.
1Singlereceiveenabledand
0Singlereceivedisable.
CRENContinuousReceiveEnablebitactsdifferentlydependingonEUSARTmode.
Asynchronousmode:
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 6/20
1Receiverenabledand
0Receiverdisabled.
Synchronousmode:
1EnablescontinuousreceiveuntiltheCRENbitisclearedand
0Disablescontinuousreceive.
ADDENAddressDetectEnablebitisonlyusedinaddressdetectmode.
1Enablesaddressdetectionon9bitdatareceiveand
0Disablesaddressdetection.Theninthbitcanbeusedasparitybit.
FERRFramingErrorbit
1Onreceive,FramingErrorisdetectedand
0Noframingerror.
OERROverrunErrorbit.
1Onreceive,OverrunErrorisdetectedand
0Nooverrunerror.
RX9DNinthbitofReceivedDatacanbeusedasaddressorparitybit.
EUSARTBaudRateGenerator(BRG)
IfyoucarefullylookattheasynchronousEUSARTreceiverortransmitterdiagram,youwillsee,inbothcases,thatclocksignalfromthelocal
timerBRGisusedforsynchronization.Thesameclocksourceisalsousedinsynchronousmode.
Thistimerconsistsoftwo8bitregisterscomprisingone16bitregister.
Fig.610EUSARTBaudRateGenerator(BRG)
Anumberwrittentothesetworegistersdeterminesthebaudrate.Besides,boththeBRGHbitoftheTXSTAregisterandtheBRGH16bitof
theBAUDCTLregisteraffectclockfrequency.
TheformulausedtodetermineBaudRateisgiveninthetablebelow.
BI TS
BRG / EUSART MODE BAUD RATE FORMULA
SYNC BRG1G BRGH
0 0 0 8-bit / asynchronous Fosc / [64 (n + 1)]
0 0 1 8-bit / asynchronous Fosc / [16 (n + 1)]
0 1 0 16-bit / asynchronous Fosc / [16 (n + 1)]
0 1 1 16-bit / asynchronous Fosc / [4 (n + 1)]
1 0 X 8-bit / asynchronous Fosc / [4 (n + 1)]
1 1 X 16-bit / asynchronous Fosc / [4 (n + 1)]
Table61BaudRate
Thefollowingtablescontainvaluesthatshouldbewrittentothe16bitregisterSPBRGandassignedtotheSYNC,BRGHandBRGH16bitsin
ordertoobtainsomeofthestandardbaudrates.
TheformulasusedtodeterminetheBaudRateare:
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 7/20
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 8/20
Table62DeterminingBaudRate
BAUDCTLRegister
Fig.611BAUDCTLRegister
ABDOVFAutoBaudDetectOverflowbitisonlyusedinasynchronousmodeduringbaudratedetection.
1Autobaudtimeroverflowedand
0Autobaudtimerdidnotoverflow.
RCIDLReceiveIdleFlagbitisonlyusedinasynchronousmode.
1Receiverisidleand
0STARTbithasbeenreceivedandreceivingisinprogress.
SCKPSynchronousClockPolaritySelectbitactsdifferentlydependingonEUSARTmode.
Asynchronousmode:
1TransmitinverteddatatotheRC6/TX/CKpinand
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 9/20
0Transmitnoninverteddatatothesamepin.
Synchronousmode:
1Synchronizationonrisingedgeoftheclockand
0Synchronizationonfallingedgeoftheclock.
WUEWakeupEnablebit
1ReceiverwaitsforafallingedgeontheRC7/RX/DTpintostartwakingupthemicrocontrollerfromsleepmode
and
0Receiveroperatesnormally.
ABDENAutoBaudDetectEnablebitisusedinasynchronousmodeonly.
1Autobauddetectmodeisenabled.Bitisautomaticallyclearedonbaudratedetectand
0Autobauddetectmodeisdisabled.
InShort:
SendingdataviaasynchronousEUSARTcommunication:
ReceivingdataviaasynchronousEUSARTcommunication:
SettingAddressDetectionMode:
MasterSynchronousSerialPortModule
MSSPmodule(MasterSynchronousSerialPort)isaveryuseful,butatthesametimeoneofthemostcomplexcircuitwithinthe
microcontroller.Itenableshighspeedcommunicationbetweenamicrocontrollerandotherperipheralsormicrocontrollerdevicesbyusingfew
input/outputlines(maximumtwoorthree).Therefore,itiscommonlyusedtoconnectthemicrocontrollertoLCDdisplays,A/Dconverters,
serialEEPROMs,shiftregistersetc.Themainfeatureofthistypeofcommunicationisthatitissynchronousandsuitableforuseinsystems
1. ThedesiredbaudrateshouldbesetbyusingbitsBRGH(TXSTAregister)andBRG16(BAUDCTLregister)and
registersSPBRGHandSPBRG
2. TheSYNCbit(TXSTAregister)shouldbeclearedandtheSPENbitshouldbeset(RCSTAregister)inorderto
enableserialport
3. On9bitdatatransmission,theTX9bitoftheTXSTAregistershouldbeset
4. DatatransmissionisenabledbysettingbitTXENoftheTXSTAregister.BitTXIFofthePIR1registeris
automaticallyset
5. IfneededthebitTXENcausesaninterrupt,theGIEandPEIEbitsoftheINTCONregistershouldbeset
6. On9bitdatatransmission,valueoftheninthbitshouldbewrittentotheTX9DbitoftheTXSTAregisterand
7. Transmissionstartsbywriting8bitdatatotheTXREGregister.
1. BaudRateshouldbesetbyusingbitsBRGH(TXSTAregister)andBRG16(BAUDCTLregister)andregisters
SPBRGHandSPBRG
2. TheSYNCbit(TXSTAregister)shouldbeclearedandtheSPENbitshouldbeset(RCSTAregister)inorderto
enableserialport
3. Ifitisnecessarythedatareceivecausesaninterrupt,boththeRCIEbitofthePIE1registerandbitsGIEand
PEIEoftheINTCONregistershouldbeset
4. On9bitdatareceive,theRX9bitoftheRCSTAregistershouldbeset
5. DatareceiveshouldbeenabledbysettingtheCRENbitoftheRCSTAregister
6. TheRCSTAregistershouldbereadtogetinformationonpossibleerrorswhichhaveoccurredduring
transmission.On9bitdatareceive,theninthbitwillbestoredinthisregisterand
7. Received8bitdatastoredintheRCREGregistershouldberead.
1. BaudRateshouldbesetbyusingbitsBRGH(TXSTAregister)andBRG16(BAUDCTLregister)andregisters
SPBRGHandSPBRG
2. TheSYNCbit(TXSTAregister)shouldbeclearedandtheSPENbitshouldbeset(RCSTAregister)inorderto
enableserialport
3. Ifitisnecessarythedatareceivecausesaninterrupt,theRCIEbitofthePIE1bitaswellasbitsGIEandPEIEof
theINTCONregistershouldbeset
4. TheRX9bitoftheRCSTAregistershouldbeset
5. TheADDENoftheRCSTAregistershouldbeset,whichenablesadatatobeinterpretedasaddress
6. DatareceiveisenabledbysettingtheCRENbitoftheRCSTAregister
7. Immediatelyupon9bitdataisreceived,theRCIFbitofthePIR1registerwillbeautomaticallyset.Ifenabled,an
interruptoccurs
8. TheRCSTAregistershouldbereadinordertogetinformationonpossibleerrorswhichhaveoccurredduring
transmission.TheninthbitRX9Disalwayssetand
9. Received8bitsstoredintheRCREGregistershouldberead.Itshouldbecheckedwhetherthecombinationof
thesebitsmatchesthepredefinedaddress.Ifthematchoccurs,itisnecessarytocleartheADDENbitofthe
RCSTAregister,whichenablesfurther8bitdatareceive.
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 10/20
withasinglemasterandoneormoreslaves.Amasterdevicecontainsthenecessarycircuitryforbaudrategenerationandsuppliestheclock
foralldevicesinthesystem.Slavedevicesmayinthatwayeliminatetheinternalclockgenerationcircuitry.TheMSSPmodulecanoperatein
oneoftwomodes:
SPImode(SerialPeripheralInterface)
ICmode(InterIntegratedCircuit)
Asseeninfigure612below,oneMSSPmodulerepresentsonlyahalfofthehardwareneededtoestablishserialcommunication,while
anotherhalfisstoredinthedevicethedataisexchangedwith.Eventhoughthemodulesonbothendsofthelinearethesame,theirmodes
areessentiallydifferentdependingonwhethertheyoperateasaMasteroraSlave:
Ifthemicrocontrollertobeprogrammedcontrolsanotherdeviceorcircuit(peripherals),itshouldoperateasamasterdevice.Amodule
definedassuchwillgenerateclockwhenneeded,i.e.onlywhendatareceiveandtransmitisrequiredbythesoftware.Itdependsonthe
masterwhethertheconnectionwillbeestablishedornot.Otherwise,ifthemicrocontrollertobeprogrammedisapartofsomeperipheral
whichbelongstosomemorecomplexdevice(forexamplePC),thenitshouldoperateasaslavedevice.Assuch,italwayshastowaitfor
requestfordatatransferfrommasterdevice.
Fig.612MSSPModule
SPIMode
TheSPImodeallows8bitsofdatatobetransmittedandreceivedsimultaneouslyusing3input/outputlines:
SDOSerialDataOuttransmitline
SDISerialDataInreceivelineand
SCKSerialClocksynchronizationline.
Inadditiontothesethreelines,ifthemicrocontrollerexchangesdatawithseveralperipheraldevices,theforthline(SS)maybealsoused.
Refertofigure613below.
SSSlaveSelectisadditionalpinusedforspecificdeviceselection.Itisactiveonlyincasethemicrocontrollerisinslavemode,i.e.when
theexternalmasterdevicerequiresdataexchange.
WhenoperatinginSPImode,MSSPmoduleusesintotalof4registers:
SSPSTATstatusregister
SSPCONcontrolregister
SSPBUFbufferregisterand
SSPSRshiftregister(notdirectlyavailable)
Thefirstthreeregistersarewritable/readableandcanbechangedatanymoment,whiletheforthregister,sincenotavailable,isusedfor
convertingdatainto"serial"format.
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 11/20
Fig.615Step1
Fig.616Step2
Fig.613SPIMode
Asseeninfigure614,thecentralpartoftheSPImoduleconsistsoftworegistersconnectedtopinsforreceive,transmitandsynchronization.
Shiftregister(SSPRS)isdirectlyconnectedtothemicrocontrollerpinsandusedfordatatransmissioninserialformat.TheSSPRSregister
hasitsinputandoutputandshiftsthedatainandoutofdevice.Inotherwords,eachbitappearingoninput(receiveline)simultaneouslyshifts
anotherbittowardoutput(transmitline).
TheSSPBUFregister(Buffer)isapartofmemoryusedtotemporarilyholdthedatawrittentotheSSPRSuntilthereceiveddataisready.
Uponreceivingall8bitsofdata,thatbyteismovedtotheSSPBUFregister.Thisdoublebufferingofthereceiveddata(SSPBUF)allowsthe
nextbytetostartreceptionbeforereadingthedatathatwasjustreceived.AnywritetotheSSPBUFregisterduringtransmission/receptionof
datawillbeignored.Sincehavingbeenthemostaccessed,thisregisterisconsideredthemostimportantfromtheprogrammerspointof
view.
Namely,ifmodesettingsareneglected,datatransferviaSPIactuallymeanstowriteandreaddatafromthisregister,whileanother
"acrobatics"suchasmovingregistersareautomaticallyperformedbyhardware.
Fig.614SPIMode
Inshort:
PriortoinitializingtheSPI,itisnecessarytospecifyseveraloptions:
Mastermode(SCKpinistheclockoutput)
Slavemode(SCKpinistheclockinput)
Datainputphasemiddleorendofdataoutputtime(SMPbit)
Clockedge(CKEbit)
BaudRate(onlyinMastermode)and
Slaveselectmode(Slavemodeonly).
Step1.
DatatotransmitshouldbewrittentothebufferregisterSSPBUF.Immediatelyafterthat,iftheSPImoduleoperates
inmastermode,themicrocontrollerwillautomaticallyperformthefollowingsteps2,3and4.IftheSPImodule
operatesasSlave,themicrocontrollerwillnotperformthesestepsuntiltheSCKpindetectsclocksignal.
Step2.
ThisdataisnowmovedtotheSSPSRregisterandtheSSPBUFregisterisnotcleared.
Step3.
Synchronizedwithclocksignal,thisdataisshiftedtotheoutputpin(MSBbitfirst)whiletheregisterissimultaneouslybeingfilledwithbits
throughinputpin.InMastermode,themicrocontrolleritselfgeneratesclock,whiletheSlavemodeusesexternalclock(pinSCK).
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 12/20
Fig.617Step3
Fig.618Step4
Fig.619Step5
Step4.
TheSSPSRregisterisfulloncethe8bitsofdatahavebeenreceived.Itisindicatedbysetting
theBFandSSPIFbits.Thereceiveddata(thatbyte)isautomaticallymovedfromtheSSPSR
registertotheSSPBUFregister.Sincedatatransferviaserialcommunicationisperformed
automatically,therestoftheprogramisnormallyexecutedwhiledatatransferisinprogress.In
thatcase,thefunctionoftheSSPIFbitistogenerateinterruptwhenonebytetransmissionis
completed.
Step5.
Atlast,thedatastoredintheSSPBUFregisterisreadyforuseandmovedtoanyregisteravailable.
ICmode
ICmode(InterICBus)isespeciallysuitablewhenthemicrocontrollerandintegratedcircuit,whichthemicrocontrollershouldexchangedata
with,arewithinthesamedevice.Itiscommonlyaboutanothermicrocontrollersorspecialized,cheapintegratedcircuitsbelongingtothenew
generationofsocalled"smartperipheralcomponents"(memories,temperaturesensors,realtimeclocksetc.)
SimilartoserialcommunicationinSPImode,datatransferinICmodeissynchronousandbidirectional.Thistimeonlytwopinsareusedfor
datatransfer.ThesearetheSDA(SerialData)andSCL(SerialClock)pins.Theusermustconfigurethesepinsasinputsoroutputsthrough
theTRISCbits.
Perhapsitisnotdirectlyvisible.Byobservingparticularrules(protocols),thismodeenablesupto122differentcomponentstobe
simultaneouslyconnectedinasimplewaybyusingonlytwovaluableI/Opins.Briefly,everythingworksasfollows:Clocknecessaryto
synchronizetheoperationofbothdevicesisalwaysgeneratedbythemasterdevice(microcontroller)anditsfrequencydirectlyaffectsbaud
rate.Thereareprotocolsallowingmaximum3,4MHzclockfrequency(socalledhighspeedICbus),buttheclockfrequencyofthemost
frequentlyusedprotocolislimitedto100KHz.Thereisnolimitincaseofminimalfrequency.
Whenmasterandslavecomponentsaresynchronizedbytheclock,everydataexchangeisalwaysinitializedbymaster.OncetheMSSP
modulehasbeenenabled,itwaitsforaStartconditiontooccur.FirstthemasterdevicesendstheSTARTbit(logiczero)throughtheSDApin,
thenthe7bitaddressoftheselectedslavedevice,andfinally,thebitwhichrequiresdatawrite(0)orread(1)tothatdevice.Accordingly,
followingthestartcondition,theeightbitsareshiftedintotheSSPSRregister.Allslavedevicessharethesametransmissionlineandallwill
simultaneouslyreceivethefirstbyte,butonlyoneofthemhastheaddresstomatch.
Fig.620MasterandSlaveConfiguration
Oncethefirstbytehasbeensent(only8bitdataaretransmitted),mastergoesintoreceivemodeandwaitsforacknowledgmentfromthe
receivedevicethataddressmatchhasoccurred.Iftheslavedevicesendsacknowledgedatabit(1),datatransferwillbecontinueduntilthe
masterdevice(microcontroller)sendstheStopbit.
Thisisthesimplestexplanationofhowtwocomponentscommunicate.Ifneeded,thismicrocontrollerisabletocontrolmorecomplicated
situationswhen1024differentcomponents,sharedbyseveraldifferentmasterdevices,areconnected.Suchdevicesarerarelyusedin
practiceandthereisnoneedtodiscussthematgreaterlength.
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 13/20
Fig.621DataTransfer
FigurebelowshowstheblockdiagramoftheMSSPmoduleinICmode.
Fig.622MSSPBlockDiagraminICMode
TheMSSPmoduleusessixregistersforICoperation.Someofthemareshowninfigureabove:
SSPCON
SSPCON2
SSPSTAT
SSPBUF
SSPSRand
SSPADD.
SSPSTATRegister
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 14/20
Fig.623SSPSTATRegister
SMPSamplebit
SPImastermodeThisbitdeterminesinputdataphase.
1Logicstateisreadatendofdataoutputtimeand
0Logicstateisreadinthemiddleofdataoutputtime.
SPIslavemodeThisbitmustbeclearedwhenSPIisusedinSlavemode.
ICmode(masterorslave)
1Slewratecontroldisabledforstandardspeedmode(100kHz)and
0Slewratecontrolenabledforhighspeedmode(400kHz).
CKEClockEdgeSelectbitselectssynchronizationmode.
CKP=0:
1Dataistransmittedonrisingedgeofclockpulse(01)and
0Dataistransmittedonfallingedgeofclockpulse(10).
CKP=1:
1Dataistransmittedonfallingedgeofclockpulse(10)and
0Dataistransmittedonrisingedgeofclockpulse(01).
D/AData/AddressbitisusedinICmodeonly.
1Indicatesthatthelastbytereceivedortransmittedwasdataand
0Indicatesthatthelastbytereceivedortransmittedwasaddress.
PStopbitisusedinICmodeonly.
1STOPbitwasdetectedlastand
0STOPbitwasnotdetectedlast.
SStartbitisusedinICmodeonly.
1STARTbitwasdetectedlastand
0STARTbitwasnotdetectedlast.
R/WReadWritebitisusedinICmodeonly.ThisbitholdstheR/Wbitinformationfollowingthelastaddressmatch.Thisbitisonlyvalid
fromtheaddressmatchtothenextStartbit,StopbitornotACKbit.
InICslavemode
1Datareadand
0Datawrite.
InICmastermode
1Transmitisinprogressand
0Transmitisnotinprogress.
UAUpdateAddressbitisusedin10bitICmodeonly.
1IndicatesthatitisnecessarytoupdatetheaddressintheSSPADDregisterand
0AddressintheSSPADDregisteriscorrectanddoesnotneedtobeupdated.
BFBufferFullStatusbit
Duringdatareceive(inSPIandICmodes)
1Receivecomplete.TheSSPBUFregisterisfulland
0Receivenotcomplete.TheSSPBUFregisterisempty.
Duringdatatransmit(inICmodeonly)
1Datatransmitinprogress(doesnotincludethebitsACKandSTOP)and
0Datatransmitcomplete(doesnotincludethebitsACKandSTOP).
SSPCONRegister
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 15/20
Fig.624SSPCONRegister
WCOLWriteCollisionDetectbit
1Collisiondetected.AwritetotheSSPBUFregisterwasattemptedwhiletheICconditionswerenotvalidfora
transmissiontostartand
0Nocollision.
SSPOVReceiveOverflowIndicatorbit
1AnewbyteisreceivedwhiletheSSPSRregisterstillholdsthepreviousdata.Sincethereisnospacefornewdata
receive,oneofthesetwobytesmustbecleared.Inthiscase,datainSSPSRislostand
0Serialdataiscorrectlyreceived.
SSPENSynchronousSerialPortEnablebitdeterminesthemicrocontrollerpinsfunctionandinitializesMSSPmodule:
InSPImode
1EnablesMSSPmoduleandconfigurespinsSCK,SDO,SDIandSSasthesourceoftheserialportpinsand
0DisablesMSSPmoduleandconfiguresthesepinsasI/Oportpins.
InICmode
1EnablesMSSPmoduleandconfigurespinsSDAandSCLasthesourceoftheserialportpinsand
0DisablesMSSPmoduleandconfiguresthesepinsasI/Oportpins.
CKPClockPolaritySelectbitisnotusedinICmastermode.
InSPImode
1Idlestateforclockisahighleveland
0Idlestateforclockisalowlevel.
InICslavemode
1Enablesclockand
0Holdsclocklow.Usedtoprovidemoretimefordatastabilization.
SSPM3SSPM0SynchronousSerialPortModeSelectbits.SSPmodeisdeterminedbycombiningthesebits:
SSPM3 SSPM2 SSPM1 SSPM0 MODE
0 0 0 0 SPI master mode, clock = Fosc/4
0 0 0 1 SPI master mode, clock = Fosc/16
0 0 1 0 SPI master mode, clock = Fosc/64
0 0 1 1 SPI master mode, clock = (output TMR)/2
0 1 0 0 SPI slave mode, SS pin control enabled
0 1 0 1 SPI slave mode, SS pin control disabled, SS can be used as I/O pin
0 1 1 0 IC slave mode, 7-bit address used
0 1 1 1 IC slave mode, 10-bit address used
1 0 0 0 IC master mode, clock = Fosc / [4(SSPAD+1)]
1 0 0 1 Mask used in IC slave mode
1 0 1 0 Not used
1 0 1 1 IC controlled master mode
1 1 0 0 Not used
1 1 0 1 Not used
1 1 1 0 IC slave mode, 7-bit address used,START and STOP bits enable interrupt
1 1 1 1 IC slave mode, 10-bit address used,START and STOP bits enable interrupt
Table63SynchronousSerialPortModeSelectBits
SSPCON2Register
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 16/20
Fig.625SSPCON2Register
GCENGeneralCallEnablebit
InICslavemodeonly
1Enablesinterruptwhenageneralcalladdress(0000h)isreceivedintheSSPSRand
0Generalcalladdressdisabled.
ACKSTATAcknowledgeStatusbit
InICMasterTransmitmodeonly
1Acknowledgewasnotreceivedfromslaveand
0Acknowledgewasreceivedfromslave.
ACKDTAcknowledgedatabit
InICMasterReceivemodeonly
1NotAcknowledgeand
0Acknowledge.
ACKENAcknowledgeconditionEnablebit
InICMasterReceivemode
1InitiateacknowledgeconditiononSDAandSCLpinsandtransmitACKDTdatabit.Itisautomaticallyclearedby
hardwareand
0Acknowledgeconditionisnotinitiated.
RCENReceiveEnablebit
InICMastermodeonly
1EnablesdatareceiveinICmodeand
0Receivedisabled.
PENSTOPconditionEnablebit
InICMastermodeonly
1InitiatesSTOPconditiononpinsSDAandSCL.Afterwards,thisbitisautomaticallyclearedbyhardwareand
0STOPconditionisnotinitiated.
RSENRepeatedSTARTConditionEnabledbit
InICmastermodeonly
1InitiatesSTARTconditiononpinsSDAandSCL.Afterwards,thisbitisautomaticallyclearedbyhardwareand
0RepeatedSTARTconditionisnotinitiated.
SENSTARTConditionEnabled/StretchEnabledbit
InICMastermodeonly
1InitiateSTARTconditiononpinsSDAandSCL.Afterwards,thisbitisautomaticallyclearedbyhardwareand
0STARTconditionisnotinitiated.
ICinMasterMode
Themostcommoncaseiswhenthemicrocontrolleroperatesasamasterandtheperipheralcomponentasaslave.Thisiswhythisbook
coversjustthismode.Itisalsoconsideredthattheaddressconsistsof7bitsanddevicecontainsonlyonemicrocontroller(onemaster
device).
InordertoenableMSSPmoduleinthismode,itisnecessarytodothefollowing:
Setbaudrate(SSPADDregister),turnoffslewratecontrol(bysettingtheSMPbitoftheSSPSTATregister)andselectmastermode
(SSPCONregister).Afterthepreparationhasbeenfinishedandmodulehasbeenenabled(SSPCONregister:SSPENbit),oneshouldwait
forinternalelectronicstosignalthateverythingisreadyfordatatransmission,i.e.theSSPIFbitofthePIR1registerisset.
Thisbitshouldbeclearedbysoftwareandafterthat,themicrocontrollerisreadytostart"communication"withperipherals.
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 17/20
Fig.628DataTransmissioninICMasterMode
Fig.629DataTransmissioninICMasterMode
Fig.627ICinMasterMode
DataTransmissioninICMasterMode
EachclockconditionontheSDApinstartswithlogiczero(0)whichappearsuponsettingtheSENbitoftheSSPCON2register.Even
enabled,themicrocontrollerhastowaitacertaintimebeforeitstartscommunication.Itisthesocalled"Startcondition"duringwhichinternal
preparationsandchecksareperformed.Ifallconditionsaremet,theSSPIFbitofthePIR1issetanddatatransferstartsassoonasthe
SSPBUFregisterisloaded.
Sincemaximum112integratedcircuitsmaysimultaneouslysharethesame
transmissionline,thefirstdatabytemustcontainaddresswhichmatchesonly
oneslavedevice.Eachcomponenthasitsownaddresslistedintheproperdata
sheet.Theeighthbitofthefirstdatabytespecifiesdirectionofdata
transmission,themicrocontrolleristosendorreceivedata.Inthiscase,itisall
aboutdatareceiveandtheeighthbitthereforeislogiczero(0).
Whenaddressmatchoccurs,themicrocontroller
hastowaitfortheacknowledgedatabit.The
slavedeviceacknowledgesaddressmatchby
clearingtheASKSTATbitoftheSSPCON2
register.Ifthematchproperlyoccurred,allbytes
representingdataaretransmittedinthesame
way.
DatatransmissionendsbysettingtheSENbitof
theSSPCON2register.ThesocalledSTOP
conditionoccurs,whichenablestheSDApinto
receivepulsecondition:StartAddress
AcknowledgeDataAcknowledge....Data
AcknowledgeStop!
DataReceptioninICMasterMode
Preparationsfordatareceptionaresimilartothosefordatatransmission,withexceptionthatthelastbitofthefirstsentbyte(containing
address)islogicone(1).Itspecifiesthatmasterexpectstoreceivedatafromaddressedslavedevice.Withregardtothemicrocontroller,the
followingeventsoccur:
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 18/20
AfterinternalpreparationsarefinishedandSTARTbitisset,slavedevicestartssendingonebyteatatime.Thesebytesarestoredinthe
serialregisterSSPSR.Eachdatais,afterreceivingthelasteighthbit,loadedtotheSSPBUFregisterfromwhereitcanberead.Byreading
thisregister,theacknowledgebitisautomaticallysent,whichmeansthatmasterdeviceisreadytoreceivenewdata.
Attheend,similartodatatransmission,datareceptionendsbysettingtheSTOPbit:
Fig.630DataReceptioninICMasterMode
StartAddressAcknowledgeDataAcknowledge....DataAcknowledgeStop!
Inthispulsecondition,theacknowledgebitissenttoslavedevice.
BaudRateGenerator
Inordertosynchronizedatatransmission,alleventstakingplaceontheSDApinmustbesynchronizedwiththeclockgeneratedinmaster
device.Thisclockisgeneratedbyasimpleoscillatorwhosefrequencydependsonthemicrocontrollersmainoscillatorfrequency,value
writtentotheSSPADDregisterandthecurrentSPImode.
TheclockfrequencyofthemodedescribedinthisbookdependsonselectedquartzcrystalandtheSPADDregister.Theformulausedto
calculateitisshowninfigurebelow.
Fig.631BaudRateGenerator
Usefulnotes...
Whenthemicrocontrollercommunicateswithperipheralcomponents,itmayhappenthatdatatransferfailsforsomereason.Inthatcase,itis
recommendedtocheckthestatusofsomebitswhichcanclarifytheproblem.Inpractice,thestateofthesebitsischeckedbyexecutinga
shortsubroutineaftereachbytetransmissionandreception(justincase).
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 19/20
previouschapter|tableofcontents|nextchapter
WCOL(SPCON,7)IfyoutrytowriteanewdatatotheSSPBUFregisterwhileanotherdatatransmit/receiveisinprogress,theWCOLbitwill
besetandthecontentsoftheSSPBUFregisterremainsunchanged.Writedoesnotoccur.Afterthis,theWCOLbitmustbeclearedin
software.
BF(SSPSTAT,0)Intransmitmode,thisbitissetwhentheCPUwritestotheSSPBUFregisterandremainssetuntilthebyteinserialformat
isshiftedfromtheSSPSRregister.Inreceivemode,thisbitissetwhendataoraddressisloadedtotheSSPBUFregister.Itisclearedwhen
theSSPBUFregisterisread.
SSPOV(SSPCON,6)Inreceivemode,thisbitissetwhenanewbyteisreceivedbytheSSPSRregisterviaserialcommunication,whereas
thepreviouslyreceiveddatahasnotbeenreadfromtheSSPBUFregisteryet.
SDAandSCLPinsWhenSPPmoduleisenabled,thesepinsturnsintoOpenDrainoutputs.Itmeansthatthesepinsmustbeconnectedto
theresistorswhich,attheotherend,areconnectedtopositivepowersupply.
Fig.632OpenDrainOutputResistors
InShort:
InordertoestablishserialcommunicationinICmode,thefollowingshouldbedone:
SettingModuleandSendingAddress:
ValuetodeterminebaudrateshouldbewrittentotheSSPADDregister
SlewRatecontrolshouldbeturnedoffbysettingtheSMPbitoftheSSPSTATregister
InordertoselectMastermode,binaryvalue1000shouldbewrittentotheSSPM3SSPM0bitsoftheSSPCON1
register
TheSENbitoftheSSPCON2registershouldbeset(STARTcondition)
TheSSPIFbitisautomaticallysetattheendofSTARTconditionwhenthemoduleisreadytooperate.Itshouldbe
cleared
SlaveaddressshouldbewrittentotheSSPBUFregisterand
Whenthebyteissent,theSSPIFbit(interrupt)isautomaticallysetwhentheacknowledgebithasbeenreceivedfrom
theSlavedevice.
DataTransmit:
DataistobesendshouldbewrittentotheSSPBUFregister
Whenthebyteissent,theSSPIFbit(interrupt)isautomaticallysetupontheacknowledgebithasbeenreceivedfrom
Slavedeviceand
InordertoinformtheSlavedevicethattransmitiscomplete,STOPconditionshouldbeinitiatedbysettingthePEN
bitoftheSSPCONregister.
DataReceive:
InordertoenablereceivetheRSENbitoftheSSPCON2registershouldbeset
TheSSPIFbitsignalsdatareceive.WhendataisreadfromtheSSPBUFregister,theACKENbitoftheSSPCON2
registershouldbesetinordertoenablesendingacknowledgebitand
InordertoinformSlavedevicethattransmitiscomplete,theSTOPconditionshouldbeinitiatedbysettingthePEN
bitoftheSSPCONregister.
MikroElektronika Embedded Solutions
Follow us on
PIC Solution
PIC Development Boards
PIC Compilers
PIC Programmers/Debuggers
PIC Kits
PIC Books
PIC32 Solution
PIC32 Development Boards
PIC32 Compilers
dsPIC Solution
dsPIC Development Boards
dsPIC Compilers
dsPIC Programmers/Debuggers
dsPIC Kits
dsPIC Books
AVR Solution
AVR Development Boards
AVR Compilers
STM32 Solution
STM32 Development Boards
STM32 Compilers
STM32 Programmers/Debuggers
STM32 Kits
Tiva C Series Solution
Tiva C Development Boards
Tiva C Compilers
Tiva C Programmers/Debuggers
8051 Solution
8051 Dev. Boards
8051 Compilers
8051 Programmers
8051 Books
8051 Kits
Additional Software
Visual TFT
Visual GLCD
Add-on boards
Click Boards
mikromedia shields
Communication
Storage
Real Time Clock
Display
Measurement
Audio & Voice
Power Supply
8/27/2014 Chapter 6: Serial Communication Modules - Book: PIC Microcontrollers
http://www.mikroe.com/chapters/view/7/chapter-6-serial-communication-modules/ 20/20
Copyright 1998 - 2014. MikroElektronika. All rights reserved. All trade and/or services marks mentioned are the property of their respective owners.
PIC32 Programmers/Debuggers
PIC32 Kits
AVR Programmers/Debuggers
AVR Kits
Tiva C Kits Package Manager
GLCD Font Creator
Timer Calculator
GPS
GSM/GPRS
Support Forum mikroBUS Lets make Press Legal Archive About Us Customization

Vous aimerez peut-être aussi