Sie sind auf Seite 1von 35

CSC560Project5Report

JunnanLu
KaiHung
1
Contents
Introduction
PyroelectricInfraredSensors
UltrasonicRangingModuleHCSR04(SonarSensor)
RTOS
RealTerm
RadioCommunicationSection
NRF24L01RadioHardWare
NRF24L01introduction
NRF24L01PowerManagement
NRF24L01andAtmega1284PWiringDiagram
ATmega1284P/NRF24L01RadioSerialPeripheralInterface
Introduction
StepsforreadingdataonSPIinterface
StepsforwritingdataonSPIinterface
TheSPIClockPolarityandPhase
TheNRF24L01RegistersandCommands
TheNRF24L01Registers
TheNRF24L01Commands
TheNRF24L01EnhancedShockBurstDataPacketFormat
NRF24L01RadioDriver
TheSSPinOnAtmega1284PController
TheSPCRRegister
TheSPDRRegister
TheSPSRRegister
TheSPIProgramming
TheSPIInterfaceConfigurationSteps
TheNRF24L01RadioConfigurationStepsinSPI
TheNRF24L01DriverFunctions
TheNRF24L01TimingDiagram
Atmega1284P/RoombaUARTCommunication
PutEverythingTogether
TheBaseStationUnitCheckout
TheRoombaExploreUnitCheckout
TheWholeSystemDiagram
Project5Ccode
TheVideoDemo
2
Introduction
Inthelastprojectreport,weoutlinetheoveralldesignoftheRoombaExplorersystem.The
systemconsistedofaRoombaandaradiobasestation.TwoPIRsensorsandasonar
sensorweremountedontheRoombafacingforwards.OncetheRoombadetecteda
movingheatemittingobject,itwouldfollowitatafixeddistance.Otherwise,itwouldspin
onthespotuntilitfindsanothertarget.ThisiswhathappenswhentherobotisinAuto
mode.
TheRoombacanbedirectlycontrolledremotelythroughradioinmanualmode.The
Roombacanturnintoautomodeormanualmodeatanytime.
Theactualimplementationisnotmuchdifferentfromtheproject4design.
Pyroelectric Infrared Sensors
ThePIRsensorthatweuseisaverysimpleonethathasthreepins.Twopinsareground
andpowerinput.Thelastoneistheoutputpin.Uponbeingactive,theoutputpingoeshigh
(5V),otherwiseitgoeslow(0V).Thisisequivalenttodigitaloutput0or1.
Figure1.InfraredSensor.
3
Figure2.PIRSensor.
ThePIRsensorwasprettystraightforwardtouse.Whenitdetectedheatmotion,theoutput
wenthigh(digital1).Theoutputwentlow(digital0)otherwise.
However,weobservedthattheoutputwouldstayhighforalongperiod,rangingfrom1to7
seconds.Thiswasnotveryidealsinceitwouldoutputhighvoltageevenwhenthemoving
objectisoutofsight.Inspiteofthedelaytime,thewholesystemseemedtoworkfine.It
wouldbeaninterestingcompareifwereplacethePIRwehavewiththeonesthathave
shorterdelaytime.
HereisthelinktothedatasheetofthePIRsensor:
(http://www.parallax.com/sites/default/files/downloads/91028027PIRSensorREVADoc
umentationv1.4.pdf)
FigureXbelowshowshowthePIRsensorsweresampled.ThestatesofthePIRs(whether
ornottheyareactive)arestoredinglobalvariablesSENSOR0_ACTIVEand
SENSOR1_ACTIVErespectivelyforlateruse.
Inourimplementation,thisfunctionwasaroundrobintask.However,asonecansee,the
samplingoperationissofast((PIND&_BV(2))==0)and((PIND&_BV(4))==0),itis
probablylogicaltotakeoutthisfunctionandsimplyincorporatethesamplingoperations
withtherestofthecode.
4
Figure3.Codesegmentofundate_sensor_state().
Ultrasonic Ranging Module HC-SR04 (Sonar Sensor)
Thesonarsensorthatweusehasfourpinsonefor5Vpowersupply,oneforground,one
fortriggerpulseinputandoneforechopulseoutput
5
Figure4.SonarDistanceMeasurement.
Thefollowingishowitworks:
1.Sendahighlevelsignalforatleast10microsecondstothetriggerpin
2.Themoduleautomaticallysendseight40kHzsoundanddetectwhetherthereisasound
bouncesback.Atthemeantime,themoduleraisetheechooutputtohigh.
3.Ifthemoduledetectsasoundpulseback,itsetstheechooutputlow.
4.Distancecanbecalculatedthroughthetimeintervalbetweensendingtriggersignaland
receivingechosignal.range=highleveltime*velocity(340M/S)/2
*Itissuggestedinthedatasheetthatthereshouldbe60mstimedifferencebetweeneach
measurements.
6
Figure5.SonarTimingDiagram.
Theproblemwithworkingwithsonarwasthatitiserrorprone.Forexample,ifthesonar
sensorwasfacingawallatanangle,thenitwasverylikelythatthepulsesthesonarsent
outwouldbounceoffandneverreturntothesonar.Inthatcase,thedistancecouldnotbe
measured.Wedealwiththesituationswheredistancewasnotmeasuredcorrectlybythe
sonarinsoftware.
Thefigurebelowshowshowthesonarwasactivated,sendinghighsignaltothetriggerpin
ofsonarfor1ms.Thisfunctionwassetasaperiodictaskwithallowedexecutiontime
200ms.Therefore,sonarwastriggeredperiodically.
Figure6.
Theoutputpinofthesonarconnectstoinputcaptureinterrupt2.Theinterruptservice
routineISR(INT2_vect)calculatethedistancebasedontheinputfromsonar.Ontherising
egdeevent(whenthesonaristriggered),variabletime_stamp_s1capturesthetime.On
thefallingedgeevent(sonarreceivesechosoundpulse),variabletime_stamp_s2
7
capturesthetime.Thetimedifferencecanbedirectlyusedtocalculatethedistance.
Pleasereadthecommentsinthecodefordetails.
Figure7.
RTOS
TheRTOSwechoosetousewasdevelopedbypreviousstudentsScottCraigandJustin
Tannerinfall2007whoweretakingtheexactsameclass.WedevelopedourownRTOSin
project3,however,wefeelmorecomfortableusingthisonesinceitseemedtoberobust
andextensivelytested.
FordetailsofthisRTOS,pleaserefertothefollowingwebsite.
http://webhome.csc.uvic.ca/~mcheng/460/summer.2013/handouts/project2/RTOS
%20report/index.html
HereA,B,C,.Grepresentthetasks.AndthePPP[]arrayholdsalloftheperiodic
tasksnameandworsttimeduration.Thedurationisspecifiedasnumberofticks.Inour
case,onetickis5ms.IfaperiodictaskreachesTask_Next(),roundrobintasksgettorun.
Onehastorenametheirmain()tober_main().BecauseinC,therecanonlybeonemain()
anditisusedbytheRTOS.Inther_main(),thetasksarecreatedinthefollowingmanner.
Figure8.
8
Real Term
WeuserealtermtosenddatatothemicrocontrollerthroughUARTandthemicrocontroller
willinturnsendsdatatoroombathroughradio.Inourcase,themicrocontrollerconnected
tothecomputerthroughCOMport6.ForparametersofUARTandhowtosetupUART
connection,pleaserefertothefollowingfigure.
Figure9.TheRealTerm,ourcommandcontrolinterface.
WearesendingasingleACIIcharactertothemicrocontroller.Thefollowingfigureshows
anexample.
9
Figure10.RealTermcontinued.
Radio Communication Section
NRF24L01 Radio HardWare
NRF24L01 introduction
TheNRF24L01isasinglechip2.4GHZtransceiverwithbasebandprotocolengine,the
EnhancedShockBurst.TheNRF24L01radioisdesignedforoperationinworldwideISM
frequencybandat2.4002.4835GHZ.
TheNordicnRF24L01integratesacomplete2.4GHzRFtransceiver,RFsynthesizer,and
basebandlogicincludingtheEnhancedShockBursthardwareprotocolaccelerator
supportingahighspeedSPIinterfacefortheapplicationcontroller.Thelowpower
shortrange(200feetorso)TransceiverisavailableonaboardwithbuiltinAntenna.
10
NRF24L01 Power Management
TheBaseStationAtmega1284PXpldcontrollerispoweredviatheUSBconnectorfroma
PCsupplying5Vpower.TheAtmega1284PXpldsupply5VpowertotheNRF24L01by
connectingtheNRF24L01VccpintoAtmega1284PVcc_5Vpin.Thepowersuppliedto
theNRF24L01isregulatedbytheLDOpowerregulator,onboardofNRF24L01.The
rangeofinputtotheNRF24L01LDOregulatorisfrom3.3Vto7V.
NRF24L01 and Atmega1284P Wiring Diagram
Figure11.TheBaseStationNRF24L01/ATmega1284PWiringDiagram
InourimplementationoftheBaseStation,theNRF24L01isdirectlyconnectedwiththe
ATmega1284Pcontroller,justasthefigureshownabove.ThediscussionoftheNRF24L01
pinsarelistedasfellow.
GNDPin
11
ThegroundPinofNRF24L01isconnectedtotheGNDPin(Pinnumberneededhere)of
theAtmega1284Pmicrocontroller.
VCC
TheVCCpinofNRF24L01isconnectedtotheVCC_5VpinoftheAtmega1284P.The
powersupplytotheNRF24L01is5V.Andasmentionbefore,theLDOpowerregulatoron
theNRF24L01boardregulatestheinputpowerto3.3VtopowertheNRF24L01radio.
IRQ
TheIRQpinisnotconnectedtoanyofthepinsfromtheAtmega1284Pmicrocontroller.Itis
connectedtotheLogicAnalyzerfortesting.TheNRF24L01hasanactivelowinterruptpin.
ThepurposeoftheconnectingIRQpinistocheckiftheradioissendingandreceiving
successfully.TheIRQisactivatedwhenanyofthetransmitting,receiving,orreaching
maximumretransmissionlimitsofthedatapacketsoccurring.Theresultwillberesultedin
thecorrespondingbitsoftheSTATUSregisteroftheNRF24L01radio.Thelogicanalyzer
timingdiagramoftheNRF24L01willbeshownlater.
MISO
ThispinisconnectedtotheMISOpinoftheAtmega1284Pmicrocontroller.The
NRF24L01istheslavedevice.Thus,theserialoutpinforNRF24L01istheMISO.When
theNRF24L01willshift8bitvalueofSTATUSregistertotheAtmega1284PXpld
microcontrollerbyusingthispin.
MOSI
TheAtmega1284PXpldcontrolleristhemasterdevice.TheAtmega1284Pplacesthe
data,inbyteformat,intheshiftregisterandshiftthedatatoNRF24L01radio.
SCK
TheSCKpinoftheNRF24L01isconnectedtotheSPIsckpin.InSPIinterface,theshift
registeris8bitslong.After8pulses,thecontentinbothoftheMOSIandMISOareshifted.
WhenATmega1284PXpld,themasterdevice,sendsdatatotheNRF24L01,
ATmega1284PXpldcontrollerplacesdataontheMOSIregisterandgenerates8clock
pulses.AndwhenAtmega1284Pcontrollerwantstoreceivedata,theNRF24L01willplace
12
thedataontheMISOregister.After8clockpulsesgeneratedbytheATmega1284PXpld,
thedatawillbereceivedbythemicrocontroller.
CSN
TheCSNpinoftheNRF24L01isconnectedtothePB2pinonAtmega1284P.Afterthe
hightolowtransitionofthispin,Atmega1284Pcanshiftthecommandordatatothe
NRF24L01radio.
CE
TheCEpinisconnectedtoPB1pinonAtmega1284P.TheNRF24L01radiowillbein
standbymodeIafterabout13.8millisecondsaftersettingthePWR_UPbitoftheCONFIG
register.TheoperationmodeoftheNRF24L01radiowillbechangedbysettingtransitions
oftheCEpin.TheNRF24L01operationstatediagramisfellow.
13
Figure12.Radiocontrolstatediagram
ATmega1284P/NRF24L01 Radio Serial Peripheral Interface
Introduction
Theserialperipheralinterface,SPI,isaformofserialcommunicationavailablebetween
14
Atmega1284PXpldmicrocontrollersandNRF24L01radio.TheSPIbusisdevelopedto
providerelativelyhighspeed,shortdistancecommunicationwithfewpins.Thewiring
diagraminFigure1showsthatthereare6pinsconnectedbetweenAtmega1284PXpld
controllerandNRF24L01radio.SPIcommunicationinvolvesamasterandaslave.Inour
designandimplementation,theAtmega1284PXpldcontrolleristhemasterandthe
NRF24L01istheslave.BoththeAtmega1284PcontrollerandtheNRF24L01sendand
receivedatasimultaneously,buttheAtmega1284Pcontrollerisresponsibleforproviding
theclocksignalforthedatatransfer.
Asmentionedintheproject4designdocument,thefigureofconnectionbetweenthe
masterAtmega1284PcontrollerandtheslaveNRF24L01radioisshownbelow.
Figure13.SPIcommunicationscheme
ThemasterAtmega1284Pshiftout8bitsofdatatotheslaveNRF24L01viatheMOSIpin.
Thedataisshiftedonebitaclockorapulse.TheslaveNRF24L01alsoshiftsthe8bits
datatothemasterAtmega1284PviatheMISOpin.AnotherimportantissueofusingSPIin
ourimplementationistheSlaveSelectPin(SS).
BecausetheAtmega1284Pcontrolleristhemasterdeviceinourimplementation,weset
theSSpinoftheAtmega1284Pcontrollerto1.
Theremainingtwopins,CEandCSN,arealsocriticalinourimplementationforcommunication
betweenthemasterAtmega1284PandtheslaveNRF24L01radio.Asshowninfigure2,by
changingtheCEfromlowtohigh,theNRF24L01willbeinreceivingmode.Andbychangingthe
CEfromhightolow,theNRF24L01willbeintransmissionmode.
15
TheCSNpinisusedtocontroltheSPIbus.Weneedtokeepthispinlowwhenwesend
commandstoorreadvaluefromtheNRF24L01radiodevice.
Steps for reading data on SPI interface
1. HightolowtransitiononCEpintochangeoperationmodetoradiooperation
mode.
2. HightolowtransitiononCSNpintostartreadingcycle.
3. WitheachpulseoftheSCK,the8bitcommanddataisshiftedat1bitatapulse.
4. Afterall8bitcommandisshiftedfromAtmega1284PcontrollertoNRF24L01radio
viaMOSIpin,thedatafromNRF24L01isshiftedat1bitataSCKpulsefrom
NRF24L01toAtmega1284PcontrollerviaMISOpin.
5. LowtoHightransitiononCSNpintoendthereadingcycle.
6. LowtoHightransitiononCEpintochangebacktostandbymode.
Figure14.TheSPIreadoperation.
Steps for writing data on SPI interface
1. HightolowtransitiononCEpintochangeoperationmodetoradiooperation
mode.
2. HightolowtransitiononCSNpintostartreadingcycle.
3. WitheachpulseoftheSCK,the8bitcommanddataisshiftedat1bitatapulse.
4. Afterall8bitcommandisshiftedfromAtmega1284PcontrollertoNRF24L01radio
viaMOSIpin,thedatafromNRF24L01isshiftedat1bitataSCKpulsefrom
NRF24L01toAtmega1284PcontrollerviaMISOpin.
16
5. LowtoHightransitiononCSNpintoendthereadingcycle.
6. LowtoHightransitiononCEpintochangebacktostandbymode.
Figure15.TheSPIwriteoperation.
The SPI Clock Polarity and Phase
TherearefourmodesofSPIphaseandpolaritywithrespecttoserialdata,whichare
determinedbycontrolbitsCPHAandCPOLoftheSPCRregisteronATmega1284P.The
fourSPImodesareshownasthefigurebelow.
Figure16.SPImodes.
Inourimplementation,theSPImodeissettedtomode0.TheCPHAandCPOLbitsare
defaultedwhenwesettheSPCRregister.TheprogrammingdetailisshowninNRF24L01
driversection.ThefigurebelowshowstheSPIdatatransferformatbetween
Atmega1284PXpldandtheNRF24L01radio.Again,themode0isourSPImode.
17
Figure17.SPIdatatransfermode0.
The NRF24L01 Registers and Commands
The NRF24L01 Registers
ThefollowingNRF24L01registersareusedtosetupandconfiguretheNRF24L01radio.
Andeachoftheregistersare5bitsthatismaskedbyW_REGISTERandR_REGISTER
instruction.Forthedetailoftheregisters,pleasechecktheNRF24L01datasheet.
1. CONFIG,theconfigurationregister.
2. EN_AA,EnableAutoAcknowledgmentFunctionDisablethisfunctionalitytobe
compatiblewithnRF2401.
3. EN_RXADDR,EnabledRXAddresses.
4. RX_PW_P0,NumberofbytesinRXpayloadindatapipe0(1to32bytes).Inthis
implementation,thenumberofbytesis32bytes.
5. SETUP_AW,SetupofAddressWidths,inourcase,itis5bytesaddresswidth.
6. RF_CH,setthefrequencychannelthatNRF24L01operateson.Inthisprojectwe
setthefrequencychannelto5.
7. RF_SETUP,setstheairdatarate.Wesetstheairdatarateto2Mbps.
8. RX_ADDR_P0,setsthe5byteslongreceivingdatapipe0address.The5bytes
18
addresswillbeassembledtotheNRF24L01datapacketwhichwillbediscussed
later.
9. TX_ADDR,Transmitaddress.UsedforaPTXdeviceonly.SetRX_ADDR_P0
equaltothisaddresstohandleautomaticacknowledgeifthisisaPTXdevicewith
EnhancedShockBurstenabled.
10. SETUP_RETR,SetupofAutomaticRetransmission,AutoRetransmitDelayand
AutoRetransmitCount.Inthisproject,wesettheautoretransmitdelayand
retransmitcountto4000Sand15ReTransmitrespectively.
11. STATUS,StatusRegisterInparalleltotheSPIcommandwordappliedontheMOSI
pin,theSTATUSregisterisshiftedseriallyoutontheMISOpin.Wereadthevalue
fromtheSTATUSregistertocheckthestatusofNRF24L01.
The NRF24L01 Commands
ThefollowingNRF24L01commandsareusedinourradiodriverimplementation.
1. R_REGISTER,masks3mostsignificantbitsandreads5bitwidthcommandsand
valueofthestatusregistersfromtheNRF24L01.
2. W_REGISTER,masks3mostsignificantbitsandwrites5bitwidthcommandsand
valueofthestatusregistersfromtheNRF24L01.
3. R_RX_PAYLOAD,readsthe32bytesdatapayload.Thepayloadisdeletedfrom
FIFOafteritisread.Thiscommandsisusedforradioinreceivingmode.The
NRF24L01onRoombaexploreunitexecutesthiscommand.
4. W_TX_PAYLOAD,writesthe32bytesdatatotransmissionpayload.
5. FLUSH_TX,flushestransmissionFIFO.
6. FLUSH_RX,flushesreceivingFIFO.
The NRF24L01 Enhanced Shock-Burst Data Packet Format
TheEnhancedShockBurstpacketcontainsapreamblefield,addressfield,packet
controlfield,payloadfieldandaCRCfield.
Figure18.TheEnhancedShockBurstpacketwithPayloadfrom0to32byte.
19
Inourimplementation,wesetthepacketpayloadto32bytes,addressto5bytesandcyclic
redundancycheck(CRC)to2bytes.Thedatapacketconfigurationwillbeshowninthe
codesection.
NRF24L01 Radio Driver
Inthissection,wewilldiscusstheRadioDriverprogramming.TheRadioDriveris
consistedof2parts.TheyareSPIprogramminginAtmega1284Pandtheshifting
NRF24L01commandsusingSPIinterface.
ThefollowingthreeSPIregistersareusedtoconfiguretheSPIinterfaceinradiodriver.
1. SPCR,SPIcontrolregister.
2. SPSR,SPIstatusregister.
3. SPDR,SPIdataregister.
The SS Pin On Atmega1284P Controller
Itisalsoimportanttomentionhere.Inourimplementation,theAtmega1284Pcontrolleris
configuredasthemasterdevice.TheSPIinterfacehasnoautomaticcontroloftheSSpin
whentheAtmega1284Pcontrollerisconfiguredasthemasterdevice.Thus,wemustset
thevaluetoSSpinbeforethecommunicationcanstart.TheSSpinonAtmega1284Pis
associatedtothe8thbitofPORTB.TheprogrammingdetailwillbediscussedintheSPI
programmingsection.
The SPCR Register
TheSPIcontrolregister,SPCR,controlstheoperationoftheSPIinterface.TheSPCR
definitionisshowninfollowingfigure.
20
Figure19.TheSPCRregister.
Firstofall,wemustenabletheSPIinterface.ThiscanbedonebysettingtheSPEbitofthe
SPCRregisterto1.Next,asmentionedbefore,weconfiguredtheAtmega1284P
controllerasthemasterdevice.Thus,wemustsettheMSTRbitto1aswell.Finally,we
mustmakesurethattheAtmega1284PandNRF24L01agreeontheSCKfrequency.We
dothisbysettingtheSPR0bitoftheSPCRto1.Theprogrammingdetailwillbediscussed
intheSPIprogrammingsection.
21
The SPDR Register
TheSPDRregisteristheread/writeregisteroftheSPIinterface.Cautionforusingthe
SPDRregister.Toavoiddatacollision,wecanonlywritetoSPDRafterthelastbyteof
transmissioniscompleted.However,wecanreadfromSPDRbeforedataiscompletely
transmitted.ThefollowingfigureshowstheSPDRdefinition.
Figure20.TheSPDRregister.
The SPSR Register
TheSPSRregisterisusedtodetectwhentheSPIdatatransferiscompleted.Thedetailof
SPSRisshownasthefigurebelow.TheprogrammingdetailwillbediscussedintheSPI
programmingsection.
22
Figure21.TheSPSRregister.
AninterruptisgeneratedifSPIEbitinSPCRissetandglobalinterruptsareenabled.Ifthe
negativeoftheSSisaninputandisdrivenlowwhentheSPIisinMastermode,thiswill
alsosettheSPIFFlag.InourcasetheSSpinissethighandtheAtmega1284Pis
configuredasthemasterdevice.Thus,theSPIFflagwillbesetted.
The SPI Programming
NowwecanprogramtheAtmega1284PSPIinterfacetoachievedatacommunication
backandforthbetweentheNRF24L01radio.Asmentionedbefore,theAtmega1284P
23
Xpldcontrollerisconfiguredasthemasterdevice.TheSPIconfigurationcodeisshown
below.
Figure22.TheAtmega1284PSPIconfiguration.
The SPI Interface Configuration Steps
TheCcodeaboveshowsthestepsofhowweconfiguretheSPIinterfacebetweenthe
ATmega1284PcontrollerandtheNRF24L01radio.
1. TheDDRBregisterissettedascodeabove.Asshowninthe
ATmega1284P/NRF24L01wiringdiagram,weconfiguredthattheoutputpinon
Atmega1284Pasfellow,MOSI,SCK,CSNandCE.TheCE,CSN,MOSIandSCK
arePORTBpin1,3,5and7respectively.AndbecausetheAtmega1284P
controllerisoperatinginmastermode,weneedtosettheSSpinhighaswell.The
SSpinisthePORTBpin4.TheMISO,PORTBpin6,isusedtoreadinputSPIdata
fromtheNRF24L01.
2. SettheSPCRregistertoenableSPIinterface,mastermodeandSCKfrequency.
TheSPE,MSTRandSPR0bitsarediscussedintheSPIregisterssection.
3. AfterconfiguredtheSPIinterface,wecansendcommandsanddatatoconfigure
theNRF24L01radio.TheNRF24L01configurationcommandsisdefinedinthe
24
RX_setup()function.Thefunctionwillbediscussedinthenextsection.
4. AfterconfiguredtheNRF24L01settings,wecansettheoperationmodeofthe
NRF24L01radio.TheRX_mode()andTX_mode()functionsareusedtoconfigure
NRF24L01radioaseitherreceivingmodeortransmissionmode.
The NRF24L01 Radio Configuration Steps in SPI
Figure22.TheNRF24L01setup.
AfterconfiguredtheSPIinterfacebetweenAtmega1284PcontrollerandtheNRF24L01
radio,nowwecansendcommandstoNRF24L01toconfigureitssettings.Thisisdoneby
followingsteps.
1. BysettinghightolowtransitionoftheCEpin,theNRF24L01isinthestandby
mode.
2. Enableautoacknowledgement.ThetransmittergetsACKbackfromthereceiver.
25
3. Enabledatapipe0astheRXaddress.
4. Setthepayloadwidthto32bytes.Inourimplementation,theNRF24L01data
packetpayloadsizeis32bytes.Thatiswesend32bytesforeveryoutbounddata
packet.
5. Setthereceiveraddresswidthto5bytes.
6. SettheRFchannelto5.
7. Setthepowermodeandairdatarate.Inourimplementationthepowermodeis
0dBm.Andtheairdatarateis2Mbps.
8. Setthereceiverdatapipe0address.Inourimplementation,thereceivingaddress
forreceiveris0x2424242424.
9. Forreceiver,thetransmissionaddressshouldbethesameasthereceiving
address,iftheautoACKisenabled.
10. Finally,wehavetosetuptheretransmissionsettings.Inourimplementation,weset
theautoretransmissiondelayto750us.Andthenumberofretryis15.Againthe
detailoftheSETUP_RETRregisterislistedintheNRF24L01datasheet.
The NRF24L01 Driver Functions
spi_command(unsignedcharv)
Bothofthespi_Wreg_commandandspi_buf_commandfunctionscallthespi_command
functiontopassthedatatothedestinationNRF24L01registers.Thespi_commandisthe
basicfunctiontosendandreceivedatatoandfromtheNRF24L01device.Ithasonlyone
parameterv.ThevariablevisusedtodefineboththeNRF24L01registerandaswellas
thevaluetothatregister.Forexample,inspi_Wreg_commandfunction,thespi_command
willbecalledtwice.Thefirsttimecallofthespi_commandistoentertheaddressofthe
NRF24L01register.Afterenteringtheregisteraddress,thespi_commandwillbecalledto
enterthevalueforthatregister.Thecodingdetailwillbeshowninthecodesection.
spi_Rreg_command(unsignedcharreg)
ThisfunctionisusedtosendNRF24L01commandstotheNRF24L01device.Userneed
toputtheNRF24L01commandsuchasTX_FLUSHorRX_FLUSHastheparameter.
spi_Wreg_command(unsignedcharreg,unsignedcharv)
ThisfunctionisusedtowriteasingledatatotheNRF24L01registersthroughtheSPI
interface.Theyaretwoparametersinthisfunction.Thefirstparameteristhenameofthe
26
registerthatwewanttowritethedatato.Thesecondparameteristhevalueofthedata
thattheregisterwillget.
spi_buf_command(unsignedcharreg,unsignedcharv[],intlength)
ThisfunctionisusedtowriteanarrayofdatatotheNRF24L01registers.Forexample,if
wewanttoenterthe5bytesaddressforthetransmitter,wecouldusethisfunctionas
spi_buf_command(TX_ADDR,Address,5).Theregparameterhereagainisthenameof
theNRF24L01registerthatwewanttowriteto.Thev[]characterarraycontainsthe5bytes
address,suchas0x2424242424.Andthelength,ofcourse,isthelengthoftheaddress
array.Inthiscase,itis5byteslong.
TX_send(void)
TheTX_sendisusedfortransmissiondevicetotransmitthedatapackettothereceiving
device.Inourdesignandimplementation,theBaseStationisthetransmitter.Andthe
RoombaExploreisthereceiver,TheBaseStationcallsTX_sendtosendRoomba
commandsdatapacketstotheRoombaExplore.
RX_Rece(void)
TheRX_Receisusedforreceivingdevicetoreceivethedatapacketfromthe
transmissiondevice.Asmentionabove,theRoombaExploreisthereceiver.Andthe
RoombaExplorecallstheRX_RecetoreceiveRoombacommandsdatapacketsfromthe
BaseStation.
TX_mode(void)
ThisfunctionisusedtodefinetheNRF24L01operationmode.Asmentionedabove,the
BaseStationisthetransmissiondevice.ThustheBaseStationcallsTX_modetosetits
NRF24L01totransmissionmode.
RX_mode(void)
SimilartotheTX_mode,theRoombaExploreisthereceiver.Thusthesystemonthe
RoombaExploremustcallRX_modetosettheNRF24L01ontheRoombaExploreto
receivingmode.
27
The NRF24L01 Timing Diagram
Figure23.EnteringcommandstoNRF24L01radio.
FigureaboveshowsthecommanddatabeingtransmittedfromtheAtmega1284P
controllertotheNRF24L01radio.TheCEpinmustbekeptlowforenteringcommandto
theNRF24L01radio.EachpulseoftheCSNpinsignalsthestartandfinishofeach
command.ThecommanddataisrepresentedbytheMOSI.Asthecommandbinarybitsis
beingshiftedateachSCKclockpulse.TheNRF24L01statusisshiftedfromthe
NRF24L01radiototheAtmega1284PcontrollerviaMISOpin.
28
Figure24.TheNRF24L01receivingdatapacketsfromtheair.
FigureAboveshowsthattheNRF24L01radioisinreceivingmode.TheCEpiniskept
highastheNRF24L01radioismonitoringtheair.ThevalueoftheCONFIGregisteris
shiftedfromtheNRF24L01registertotheATmega1284PcontrollerviaMISO.Oncethe
NRF24L01radioreceivesthedatapacketfromthetransmitterdevice.Thesecondmost
significantbitoftheCONFIGregister,MASK_RX_DR,issethigh.Andoncethe
NRF24L01radioreceivedatapacket,theCEpinwillbeheldlow.AlloftheRX_DR,
TX_DSandMAX_RTwillbereflectedontheIRQpin.Inthiscase,theIRQpinisreflected
bytheinterruptonRX_DR.
Atmega1284P/Roomba UART Communication
ThedetailofAtmega1284P/RoombaUARTCommunicationismentionedinourProject2.
Inthisproject,theNRF24L01radio,installedontheRoombaExploreunit,isthereceiver
device.AnditreceivesRoombacommandpacketfromthebasestation.Wecansend
RoombacommandssuchasF(forward),B(backward),R(rightturn),L(leftturn)and
S(stop)fromthebasestation.
radio_receiving(void)
Theradio_receiving()functionisusedontheRoombaExploreunit.Thisfunctionisusedto
receivetheRoombacommanddatapacketsfromthebasestation.OncetheRoomba
commanddatapacketsarereceivedbytheRoombaExploreunit,theradio_receiving()
functionwillextractthepayloadofthepacketandsendcommandtotheRoombarobotvia
UARTconnection.
29
Figure25.Statediagramoftheradio_receiving()function.
AsfigureXshowsabove,inordertocontroltheRoombaremotely,therearefoursteps
implementedintheradio_receiving()function.Inthisproject,wearenotreadinganydata
fromtheRoomba.ThusthedatacommunicationbetweentheAtmega1284Pcontrollerand
theRoombaisoneway.
Step1,receivingthedatapacketsfromthebasestation.
Step2,extractingthepayloadmessagefromthedatapacketandselectingthecommand
byusingswitchstatement.
Step3,creatingUARTdatapacketbaseontheswitchstatement.
Step4,sendingUARTdatapackettoRoomba.
30
Theimplementationoftheradio_receiving()functionisinthecodingsection.
Put Everything Together
The Base Station Unit Checkout
1. ConnectingtheSparkFunNRF24L01radiowithAtmega1284PboardviaSPI
interfaceconnections.ThepowersupplytoNRF24L01is5Vfromthe
Atmega1284Pmicrocontroller.OurNRF24L01radioincludesanonboardLDO
powerregulator.Theallowedpowersupplyrangeis3.3Vto7V.Thus5Vpowerisin
therange.Atthismoment,ourBaseStationmicrocontrollerisnotconnectedtoany
computerwithpowersupply.Thus,thereisnopowersupplytotheNRF24L01radio
yet.
2. TheAtmega1284PXpldcontrollerisconnectedtoarunningcomputerviaUSB
cable.ThusourBaseStationmicrocontrollerispoweredviaUSBcable.Thepower
suppliedfromthePCisregulatedto3.3VwiththeLDOpowerregulatoronthe
Atmega1284PXpldboardtosupplypowertotheentireboard.
3. TheBaseStationmicrocontrollerreadsuserinputfromtheUSARTinterface
connectedtotheonboardAT32UC3B1256chip.TheonboardAT32UC3B1256
chipisconnectedtoaPCviaUSBcable.ThedatatransmittedfromthePCis
passedtoavirtualCOMportthentotheAtmega1284PXpldcontroller.
31
The Roomba Explore Unit Checkout
1. ConnectingPIRsensorstoportD2and4onAtmega1284Pcontroller.
2. ConnectingSonardistancemeasurementtoAtmega1284Pcontroller.Thesonar
echopinisconnectedtoAtmega1284Pportc0.Thetriggerpinisconnectedto
Atmega1284Pportb2.
3. ConnectingNRF24L01radiotoAtmega1284Pcontroller.Thewiringdetailisshown
inthefigure27.
4. ConnectingAtmega1284PcontrollertoRoombaviaUARTcommunicationchannel.
Thewiringdetailisshowninthefigure27.
5. Thepowersupplyis14.4VfromtheRoombabattery.The14.4Vpoweris
regulatedto5Vbyusingthe7805powerregulator.Theregulated5Vpoweris
suppliedtoallthedevicesontheRoombaExploreunit.
32
Figure26.RoombaRobotUnitWiringDiagram.
33
The Whole System Diagram
Figure27.Oursystemdiagram.
Project 5 C code
TheBaseStationsourcecodecanbedownloadedat
http://web.uvic.ca/~byzantin/base_station.zip
TheRoombaExploreUnitsourcecodecanbedownloadedat
http://web.uvic.ca/~byzantin/Project2_RTOS.zip
34
The Video Demo
Ourprojectvideodemocanbefoundhere:
http://www.youtube.com/watch?v=VeZTy8s4KSU
35

Das könnte Ihnen auch gefallen