Serial Communication - Learn - Sparkfun

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

18/1/2017

SerialCommunicationlearn.sparkfun.com

SerialCommunication
CONTRIBUTORS:
FAVORITE

JIMB0
37

Introduction
Embeddedelectronicsisallaboutinterlinkingcircuits(processorsorotherintegratedcircuits)tocreateasymbioticsystem.Inorderforthoseindividualcircuitstoswap
theirinformation,theymustshareacommoncommunicationprotocol.Hundredsofcommunicationprotocolshavebeendefinedtoachievethisdataexchange,and,in
general,eachcanbeseparatedintooneoftwocategories:parallelorserial.

Parallelvs.Serial
Parallelinterfacestransfermultiplebitsatthesametime.Theyusuallyrequirebusesofdatatransmittingacrosseight,sixteen,ormorewires.Dataistransferredin
huge,crashingwavesof1sand0s.

An8bitdatabus,controlledbyaclock,transmittingabyteeveryclockpulse.9wiresareused.
Serialinterfacesstreamtheirdata,onesinglebitatatime.Theseinterfacescanoperateonaslittleasonewire,usuallynevermorethanfour.

Exampleofaserialinterface,transmittingonebiteveryclockpulse.Just2wiresrequired!
Thinkofthetwointerfacesasastreamofcars:aparallelinterfacewouldbethe8+lanemegahighway,whileaserialinterfaceismorelikeatwolaneruralcountryroad.
Overasetamountoftime,themegahighwaypotentiallygetsmorepeopletotheirdestinations,butthatruraltwolanerservesitspurposeandcostsafractionofthe
fundstobuild.
Parallelcommunicationcertainlyhasitsbenefits.Itsfast,straightforward,andrelativelyeasytoimplement.Butitrequiresmanymoreinput/output(I/O)lines.Ifyouve
everhadtomoveaprojectfromabasicArduinoUnotoaMega,youknowthattheI/Olinesonamicroprocessorcanbepreciousandfew.So,weoftenoptforserial
communication,sacrificingpotentialspeedforpinrealestate.

AsynchronousSerial
Overtheyears,dozensofserialprotocolshavebeencraftedtomeetparticularneedsofembeddedsystems.USB(universalserialbus),andEthernet,areacoupleofthe
morewellknowncomputingserialinterfaces.OtherverycommonserialinterfacesincludeSPI,I2C,andtheserialstandardwereheretotalkabouttoday.Eachofthese
serialinterfacescanbesortedintooneoftwogroups:synchronousorasynchronous.
Asynchronousserialinterfacealwayspairsitsdataline(s)withaclocksignal,soalldevicesonasynchronousserialbusshareacommonclock.Thismakesforamore
straightforward,oftenfasterserialtransfer,butitalsorequiresatleastoneextrawirebetweencommunicatingdevices.ExamplesofsynchronousinterfacesincludeSPI,
andI2C.
Asynchronousmeansthatdataistransferredwithoutsupportfromanexternalclocksignal.Thistransmissionmethodisperfectforminimizingtherequiredwiresand
I/Opins,butitdoesmeanweneedtoputsomeextraeffortintoreliablytransferringandreceivingdata.Theserialprotocolwellbediscussinginthistutorialisthemost
commonformofasynchronoustransfers.Itissocommon,infact,thatwhenmostfolkssayserialtheyretalkingaboutthisprotocol(somethingyoullprobablynotice
throughoutthistutorial).
Theclocklessserialprotocolwellbediscussinginthistutorialiswidelyusedinembeddedelectronics.IfyourelookingtoaddaGPSmodule,Bluetooth,XBees,serial
LCDs,ormanyotherexternaldevicestoyourproject,youllprobablyneedtowhipoutsomeserialfu.

SuggestedReading
https://learn.sparkfun.com/tutorials/serialcommunication

1/6

18/1/2017

SerialCommunicationlearn.sparkfun.com

Thistutorialbuildsonafewlowerlevelelectronicsconcepts,including:
Howtoreadaschematic
AnalogvsDigital
LogicLevels
Binary
Hexadecimal
ASCII
Ifyourenotsuperfamiliarwithanyofthoseconcepts,considercheckingthoselinksout.
Nowthen,letsgoonaserialjourney

RulesofSerial
Theasynchronousserialprotocolhasanumberofbuiltinrulesmechanismsthathelpensurerobustanderrorfreedatatransfers.Thesemechanisms,whichwegetfor
eschewingtheexternalclocksignal,are:
Databits,
Synchronizationbits,
Paritybits,
andBaudrate.
Throughthevarietyofthesesignalingmechanisms,youllfindthattheresnoonewaytosenddataserially.Theprotocolishighlyconfigurable.Thecriticalpartismaking
surethatbothdevicesonaserialbusareconfiguredtousetheexactsameprotocols.

BaudRate
Thebaudratespecifieshowfastdataissentoveraserialline.Itsusuallyexpressedinunitsofbitspersecond(bps).Ifyouinvertthebaudrate,youcanfindoutjust
howlongittakestotransmitasinglebit.Thisvaluedetermineshowlongthetransmitterholdsaseriallinehigh/loworatwhatperiodthereceivingdevicesamplesitsline.
Baudratescanbejustaboutanyvaluewithinreason.Theonlyrequirementisthatbothdevicesoperateatthesamerate.Oneofthemorecommonbaudrates,
especiallyforsimplestuffwherespeedisntcritical,is9600bps.Otherstandardbaudare1200,2400,4800,19200,38400,57600,and115200.
Thehigherabaudrategoes,thefasterdataissent/received,buttherearelimitstohowfastdatacanbetransferred.Youusuallywontseespeedsexceeding115200
thatsfastformostmicrocontrollers.Gettoohigh,andyoullbegintoseeerrorsonthereceivingend,asclocksandsamplingperiodsjustcantkeepup.

Framingthedata
Eachblock(usuallyabyte)ofdatatransmittedisactuallysentinapacketorframeofbits.Framesarecreatedbyappendingsynchronizationandparitybitstoourdata.

Aserialframe.Somesymbolsintheframehaveconfigurablebitsizes.
Letsgetintothedetailsofeachoftheseframepieces.

Datachunk
Therealmeatofeveryserialpacketisthedataitcarries.Weambiguouslycallthisblockofdataachunk,becauseitssizeisntspecificallystated.Theamountofdatain
eachpacketcanbesettoanythingfrom5to9bits.Certainly,thestandarddatasizeisyourbasic8bitbyte,butothersizeshavetheiruses.A7bitdatachunkcanbe
moreefficientthan8,especiallyifyourejusttransferring7bitASCIIcharacters.
Afteragreeingonacharacterlength,bothserialdevicesalsohavetoagreeontheendiannessoftheirdata.Isdatasentmostsignificantbit(msb)toleast,orvice
versa?Ifitsnototherwisestated,youcanusuallyassumethatdataistransferredleastsignificantbit(lsb)first.

Synchronizationbits
Thesynchronizationbitsaretwoorthreespecialbitstransferredwitheachchunkofdata.Theyarethestartbitandthestopbit(s).Truetotheirname,thesebitsmark
thebeginningandendofapacket.Theresalwaysonlyonestartbit,butthenumberofstopbitsisconfigurabletoeitheroneortwo(thoughitscommonlyleftatone).
Thestartbitisalwaysindicatedbyanidledatalinegoingfrom1to0,whilethestopbit(s)willtransitionbacktotheidlestatebyholdingthelineat1.

Paritybits
Parityisaformofverysimple,lowlevelerrorchecking.Itcomesintwoflavors:oddoreven.Toproducetheparitybit,all59bitsofthedatabyteareaddedup,andthe
evennessofthesumdecideswhetherthebitissetornot.Forexample,assumingparityissettoevenandwasbeingaddedtoadatabytelike 0b01011101 ,whichhasan
oddnumberof 1 s(5),theparitybitwouldbesetto 1 .Conversely,iftheparitymodewassettoodd,theparitybitwouldbe 0 .
Parityisoptional,andnotverywidelyused.Itcanbehelpfulfortransmittingacrossnoisymediums,butitllalsoslowdownyourdatatransferabitandrequiresboth
senderandreceivertoimplementerrorhandling(usually,receiveddatathatfailsmustberesent).

96008N1(anexample)
96008N19600baud,8databits,noparity,and1stopbitisoneofthemorecommonlyusedserialprotocols.So,whatwouldapacketortwoof96008N1datalook
like?Letshaveanexample!
AdevicetransmittingtheASCIIcharactersOandKwouldhavetocreatetwopacketsofdata.TheASCIIvalueofO(thatsuppercase)is79,whichbreaksdownintoan
8bitbinaryvalueof 01001111 ,whileKsbinaryvalueis 01001011 .Allthatsleftisappendingsyncbits.
Itisntspecificallystated,butitsassumedthatdataistransferredleastsignificantbitfirst.Noticehoweachofthetwobytesissentasitreadsfromrighttoleft.

Sinceweretransferringat9600bps,thetimespentholdingeachofthosebitshighorlowis1/(9600bps)or104sperbit.

https://learn.sparkfun.com/tutorials/serialcommunication

2/6

18/1/2017

SerialCommunicationlearn.sparkfun.com

Foreverybyteofdatatransmitted,thereareactually10bitsbeingsent:astartbit,8databits,andastopbit.So,at9600bps,wereactuallysending9600bitspersecond
or960(9600/10)bytespersecond.

Nowthatyouknowhowtoconstructserialpackets,wecanmoveontothehardwaresection.Therewellseehowthose1sand0sandthebaudrateareimplementedat
asignallevel!

WiringandHardware
Aserialbusconsistsofjusttwowiresoneforsendingdataandanotherforreceiving.Assuch,serialdevicesshouldhavetwoserialpins:thereceiver,RX,andthe
transmitter,TX.

ItsimportanttonotethatthoseRXandTXlabelsarewithrespecttothedeviceitself.SotheRXfromonedeviceshouldgototheTXoftheother,andviceversa.Its
weirdifyoureusedtohookingupVCCtoVCC,GNDtoGND,MOSItoMOSI,etc.,butitmakessenseifyouthinkaboutit.Thetransmittershouldbetalkingtothe
receiver,nottoanothertransmitter.
Aserialinterfacewherebothdevicesmaysendandreceivedataiseitherfullduplexorhalfduplex.Fullduplexmeansbothdevicescansendandreceive
simultaneously.Halfduplexcommunicationmeansserialdevicesmusttaketurnssendingandreceiving.
Someserialbussesmightgetawaywithjustasingleconnectionbetweenasendingandreceivingdevice.Forexample,ourSerialEnabledLCDsareallearsanddont
reallyhaveanydatatorelaybacktothecontrollingdevice.Thisiswhatsknownassimplexserialcommunication.Allyouneedisasinglewirefromthemasterdevices
TXtothelistenersRXline.

HardwareImplementation
Wevecoveredasynchronousserialfromaconceptualside.Weknowwhichwiresweneed.Buthowisserialcommunicationactuallyimplementedatasignallevel?Ina
varietyways,actually.Thereareallsortsofstandardsforserialsignaling.Letslookatacoupleofthemorepopularhardwareimplementationsofserial:logiclevel(TTL)
andRS232.
WhenmicrocontrollersandotherlowlevelICscommunicateseriallytheyusuallydosoataTTL(transistortransistorlogic)level.TTLserialsignalsexistbetweena
microcontrollersvoltagesupplyrangeusually0Vto3.3Vor5V.AsignalattheVCClevel(3.3V,5V,etc.)indicateseitheranidleline,abitofvalue1,orastopbit.A0V
(GND)signalrepresentseitherastartbitoradatabitofvalue0.

RS232,whichcanbefoundonsomeofthemoreancientcomputersandperipherals,islikeTTLserialflippedonitshead.RS232signalsusuallyrangebetween13V
and13V,thoughthespecallowsforanythingfrom+/3Vto+/25V.Onthesesignalsalowvoltage(5V,13V,etc.)indicateseithertheidleline,astopbit,oradatabitof
value1.AhighRS232signalmeanseitherastartbit,ora0valuedatabit.ThatskindoftheoppositeofTTLserial.

Betweenthetwoserialsignalstandards,TTLismucheasiertoimplementintoembeddedcircuits.Howeverthelowvoltagelevelsaremoresusceptibletolossesacross
longtransmissionlines.RS232,ormorecomplexstandardslikeRS485,arebettersuitedtolongrangeserialtransmissions.
Whenyoureconnectingtwoserialdevicestogether,itsimportanttomakesuretheirsignalvoltagesmatchup.YoucantdirectlyinterfaceaTTLserialdevicewithanRS
232bus.Youllhavetoshiftthosesignals!

Continuingon,wellexplorethetoolmicrocontrollersusetoconverttheirdataonaparallelbustoandfromaserialinterface.UARTs!

UARTs
Thefinalpiecetothisserialpuzzleisfindingsomethingtobothcreatetheserialpacketsandcontrolthosephysicalhardwarelines.EntertheUART.
Auniversalasynchronousreceiver/transmitter(UART)isablockofcircuitryresponsibleforimplementingserialcommunication.Essentially,theUARTactsasan
intermediarybetweenparallelandserialinterfaces.OnoneendoftheUARTisabusofeightorsodatalines(plussomecontrolpins),ontheotheristhetwoserialwires
RXandTX.

https://learn.sparkfun.com/tutorials/serialcommunication

3/6

18/1/2017

SerialCommunicationlearn.sparkfun.com

SupersimplifiedUARTinterface.Parallelononeend,serialontheother.
UARTsdoexistasstandaloneICs,buttheyremorecommonlyfoundinsidemicrocontrollers.Youllhavetocheckyourmicrocontrollersdatasheettoseeifithasany
UARTs.Somehavenone,somehaveone,somehavemany.Forexample,theArduinoUnobasedontheoldfaithfulATmega328hasjustasingleUART,whilethe
ArduinoMegabuiltonanATmega2560hasawhoppingfourUARTs.
AstheRandTintheacronymdictate,UARTsareresponsibleforbothsendingandreceivingserialdata.Onthetransmitside,aUARTmustcreatethedatapacket
appendingsyncandparitybitsandsendthatpacketouttheTXlinewithprecisetiming(accordingtothesetbaudrate).Onthereceiveend,theUARThastosamplethe
RXlineatratesaccordingtotheexpectedbaudrate,pickoutthesyncbits,andspitoutthedata.

InternalUARTblockdiagram(courtesyoftheExarST16C550datasheet)
MoreadvancedUARTsmaythrowtheirreceiveddataintoabuffer,whereitcanstayuntilthemicrocontrollercomestogetit.UARTswillusuallyreleasetheirbuffered
dataonafirstinfirstout(FIFO)basis.Bufferscanbeassmallasafewbits,oraslargeasthousandsofbytes.

SoftwareUARTs
IfamicrocontrollerdoesnthaveaUART(ordoesnthaveenough),theserialinterfacecanbebitbangeddirectlycontrolledbytheprocessor.Thisistheapproach
ArduinolibrarieslikeSoftwareSerialtake.Bitbangingisprocessorintensive,andnotusuallyaspreciseasaUART,butitworksinapinch!

CommonPitfalls
Thatsaboutallthereistoserialcommunication.Idliketoleaveyouwithafewcommonmistakesthatareeasyforanengineerofanyexperienceleveltomake:

RXtoTX,TXtoRX
Seemssimpleenough,butitsamistakeIknowIvemademorethanafewtimes.Asmuchasyouwanttheirlabelstomatchup,alwaysmakesuretocrosstheRXand
TXlinesbetweenserialdevices.

FTDIBasicprogrammingaProMini.NoteRXandTXscrossed!
ContrarytowhattheesteemedDr.EgonSpenglerwouldwarn,crossthestreams.

BaudRateMismatch
Baudratesarelikethelanguagesofserialcommunication.Iftwodevicesarentspeakingatthesamespeed,datacanbeeithermisinterpreted,orcompletelymissed.Ifall
thereceivingdeviceseesonitsreceivelineisgarbage,checktomakesurethebaudratesmatchup.

https://learn.sparkfun.com/tutorials/serialcommunication

4/6

18/1/2017

SerialCommunicationlearn.sparkfun.com

Datatransmittedat9600bps,butreceivedat19200bps.Baudmismatch=garbage.

BusContention
Serialcommunicationisdesignedtoallowjusttwodevicestocommunicateacrossoneserialbus.Ifmorethanonedeviceistryingtotransmitonthesameseriallineyou
couldrunintobuscontention.Dundundun.
Forexample,ifyoureconnectingaGPSmoduleuptoyourArduino,youmayjustwirethatmodulesTXlineuptheArduinosRXline.ButthatArduinoRXpinisalready
wireduptotheTXpinoftheUSBtoserialconverter,whichisusedwheneveryouprogramtheArduinoorusetheSerialMonitor.Thissetsupthepotentialsituation
whereboththeGPSmoduleandFTDIchiparetryingtotransmitonthesamelineatthesametime.

Twotransmitterssendingtoasinglereceiversetsupthepossibilityforbuscontention.
Twodevicestryingtotransmitdataatthesametime,onthesameline,isbad!Atbestneitherofthedeviceswillgettosendtheirdata.Atworst,bothdevicestransmit
linesgopoof(thoughthatsrare,andusuallyprotectedagainst).
Itcanbesafetoconnectmultiplereceivingdevicestoasingletransmittingdevice.Notreallyuptospecandprobablyfrowneduponbyahardenedengineer,butitllwork.
Forexample,ifyoureconnectingaserialLCDuptoanArduino,theeasiestapproachmaybetoconnecttheLCDmodulesRXlinetotheArduinosTXline.TheArduinos
TXisalreadyconnectedtotheUSBprogrammersRXline,butthatstillleavesjustonedeviceincontrolofthetransmissionline.

DistributingaTXlinelikethiscanstillbedangerousfromafirmwareperspective,becauseyoucantpickandchoosewhichdevicehearswhattransmission.TheLCDwill
endupreceivingdatanotmeantforit,whichcouldcommandittogointoanunknownstate.
Ingeneraloneserialbus,twoserialdevices!

ResourcesandGoingFurther
Withthisshiny,newknowledgeofserialcommunication,thereareloadsofnewconcepts,projects,andtechnologiestoexplore.
Wouldyouliketolearnmoreaboutothercommunicationstandards?Maybesomethingsynchronous?
SerialPeripheralInterface
I2 C
Manytechnologiesmakeheavyuseofserialcommunication:
GPSBasics
ExploringXBeesandXCTU

https://learn.sparkfun.com/tutorials/serialcommunication

5/6

18/1/2017

SerialCommunicationlearn.sparkfun.com

Ormaybeyoudliketoseeserialinaction?
Ifyouneedtoshiftthelogiclevelsofyourserialcommunication,checkoutourLogicLevelConvertertutorial.
UsingaSerialLCD
SerialTerminalBasics
WiFlyShieldHookup

https://learn.sparkfun.com/tutorials/serialcommunication

6/6

You might also like