Hardware and High Data Speeds on the CINEMA …...Hardware and High Data Speeds on the CINEMA...
Transcript of Hardware and High Data Speeds on the CINEMA …...Hardware and High Data Speeds on the CINEMA...
Hardware and High Data Speeds on the CINEMA
CubeSat
David McGrogan
Electrical Engineering and Computer SciencesUniversity of California at Berkeley
Technical Report No. UCB/EECS-2010-83
http://www.eecs.berkeley.edu/Pubs/TechRpts/2010/EECS-2010-83.html
May 19, 2010
Copyright © 2010, by the author(s).All rights reserved.
Permission to make digital or hard copies of all or part of this work forpersonal or classroom use is granted without fee provided that copies arenot made or distributed for profit or commercial advantage and that copiesbear this notice and the full citation on the first page. To copy otherwise, torepublish, to post on servers or to redistribute to lists, requires prior specificpermission.
Acknowledgement
Thanks to my coworkers at SSL, to my advisor Kris Pister, and to Mom andDad.
Hardware and High Data Speeds on the CINEMA CubeSat
by David Paul McGrogan
Research Project
Submitted to the Department of Electrical Engineering and Computer Sciences, University of California at Berkeley, in partial satisfaction of the requirements for the degree of Master of Science, Plan II. Approval for the Report and Comprehensive Examination:
Committee:
Professor Kris Pister Research Advisor
(Date)
* * * * * * *
Professor Robert Lin Second Reader
(Date)
- 2 -
TableofContentsTableofContents ....................................................................................................................................... 2
TableofFigures .......................................................................................................................................... 3
TableofListings ......................................................................................................................................... 3
TableofTables............................................................................................................................................ 4
1.IntroductiontotheCINEMACubeSat........................................................................................... 5
2.HardwareDesign................................................................................................................................... 6
2.1.Peripherals ...................................................................................................................................... 6
2.2.Processors ....................................................................................................................................... 7
2.3.High‐speeddatatransfermechanisms ............................................................................ 10
2.3.1.SPI................................................................................................................................................. 10
2.3.2.DMA ............................................................................................................................................. 11
2.4.Dataflow ....................................................................................................................................... 13
3.Software ................................................................................................................................................. 14
3.1.Operatingsystem....................................................................................................................... 15
3.1.1.Backgroundtaskscheduling............................................................................................. 16
3.1.2.Schedulingthecommandhandler.................................................................................. 16
3.2.Developmentplatform............................................................................................................ 19
3.3.TheSDCard.................................................................................................................................. 20
3.3.1SDcardsinspace .................................................................................................................... 20
3.3.2.SDcardbasics.......................................................................................................................... 21
3.3.3.CRCinlimitedtime ............................................................................................................... 23
3.3.4.SDfirstcontact........................................................................................................................ 29
3.3.5.SDwritebusytime ................................................................................................................ 30
3.3.6.SDreadaccesstime .............................................................................................................. 34
3.3.7.SDreadbusytime.................................................................................................................. 36
- 3 -
4.Conclusion............................................................................................................................................. 36
Appendix:ProductsUsed .................................................................................................................... 37
Sources ........................................................................................................................................................ 38
TableofFiguresFigure1:SPIcommunicationbetweentwodevices[Microchip,2009].......................... 11
Figure2:DMAsysteminthedsPIC[Microchip,2009]........................................................... 12
Figure3:CommunicationthroughasharedSPIport ............................................................. 13
Figure4:Dataflowlayout................................................................................................................... 14
Figure5:CubeSatKitDevelopmentBoard[PumpkinInc,2010] ...................................... 19
Figure6:CubeSatKitFlightMotherboard[PumpkinInc,2010] ....................................... 19
Figure7:SDCardCommandInteraction[SDGroup,2006]................................................. 22
Figure8:SDCardCommandFormat[SDGroup,2006]......................................................... 22
Figure9:CRC7EquivalentGenerator[SDGroup,2006]....................................................... 24
Figure10:CRC16EquivalentGenerator[SDGroup,2006].................................................. 27
Figure11:BusyTimesExperiencedin490WriteAttempts................................................ 32
Figure12:ContentsofSimulatedBufferFollowing490WriteAttempts ...................... 32
Figure13:RelationofBusyPeriodDurationtoWriteAddressSeparation.................. 33
TableofListingsListing1:CRC7Algorithm(dsPIC33AssemblyLanguage) .................................................. 26
Listing2:CRC16Algorithm(dsPIC33AssemblyLanguage)................................................ 29
Listing3:DMA‐DrivenReadFromSDCard(Pseudocode)................................................... 35
- 4 -
TableofTablesTable1:PropertiesofAvailableProcessors .................................................................................. 8
Table2:TableofBackgroundTasks............................................................................................... 18
Table3:TimeRequirementsofSDCardDataRetrievalandStorage .............................. 22
Table4:TheStateofaCRC7GeneratorOver4Generations............................................... 25
Table5:TheStateofaCRC16Generatorat0,4,and8Generations................................ 27
- 5 -
1.IntroductiontotheCINEMACubeSatCubeSatsaresmallsatellitesthatconformtoastandarddevelopedbyStanfordand
CaliforniaPolytechnicUniversity.Theirmasscanbeupto1kgforthestandard
10x10x10cm(1U)model,placingtheminthelargepicosatellite/smallnanosatellite
range.OtherstandardCubeSatsizesare10x10x20cm(2U)and10x10x30cm(3U),
with2kgand3kgmasslimitsrespectively.
CINEMAisa3UCubeSatcurrentlyunderdevelopmentattheUCBerkeleySpace
SciencesLaboratoryinpartnershipwiththeImperialCollegeLondon,KyungHee
University,andtheInter‐AmericanUniversityofPuertoRico.FundedbyanNSF
grant,itsmissionistomonitorspaceweatherusingnewlydevelopedminiaturized
sensors‐‐aparticledetectorandmagnetometers.ThisCubeSatisdistinguished
frommanyCubeSatsdevelopedbyothersintwomajorways.First,CINEMAwill
needtohandlelargequantitiesofdataduetothepotentialglutofinformation
generatedbytheparticledetector,whichmayapproach2megabitspersecond
duringpeaksofparticleflux.Second,CINEMAwillgatherusefulscientificdata
despitebeingbuiltlargelybystudents;manystudent‐builtCubeSatshavebeen
technologytestplatformsorsimpleradiobeacons,builtasalearningexperience
[Glaser2009,Thomsen2009].CINEMA'sprojectedlaunchdateisinlate2011.
IjoinedtheCINEMAteamneartheendofthehigh‐leveldesignphaseoftheproject.
Atthispointthesensors,formfactor,avionicsbus,partlayout,powersupply,
communicationslink,missionparameters,andsoftwarecompartmentalizationhad
beenestablished.However,theprocessorandtheoperatingsystemhadnotyet
- 6 -
beenchosen.Mytaskwastoassistinthesedecisions,definethedataconnections
betweencomponents,andbeginworkontheflightsoftware.
2.HardwareDesign
2.1.PeripheralsThemostsignificantpre‐establishedelementsofCINEMA'sdesignwerethe
peripheralswithwhichtheprocessorwouldneedtocommunicate.Definedbythe
missionspecification,theyare:
• STEINparticledetector,capableofdetectingtheenergyandchargepolarity
ofincomingparticlesbelow40keVandenergyalonebelow100keV.Using
semiconductordetectorpixels,itisanorderofmagnitudesmallerthanthe
electrostaticanalyzerinstrumentusedintheWindspacecraft.Incorporates
anFPGA,whichiscommunicatedwithusingtheSPIbus.Maximumdatarate
is16bits/particle*30,000particles/sec/pixel*4pixels=1.92Mbps.
• Magnetometers(MAGs)forestablishingsatelliteorientationandtaking
scientificdata.Threeaxespersensorunit,withoneunitinsidethesatellite's
bodyandoneunitontheendofa1mboomtoreducemagneticinterference
fromonboardelectronics.Onlyoneofthetwo3‐axismagnetometerunitsis
readatatimebythecontrollingFPGA,whichconnectsviatheSPIbus.Data
rateis19bits/sample*10samples/sec/axis*3axes=570bits/sec,plusone
byte/secforatemperaturereadingforatotalof578bits/sec.
• SDcard,providingbulkdatastorageofscientificandengineeringdatafor
laterdownlink.Sized2GB,themaximumsizeforastandardSD(asopposed
- 7 -
toSDHC)card.CancommunicateeitherinSDorSPImode;SDmodeisfaster
buthasnofreelyreleasedspecifications,soSPImodewaschosen.Datais
manipulatedinblocks,withupto512bytesinablock.Maximumdatarate
varieswiththeappliedclockrate;inSPImode,onebitisexchangedperclock
cycle.MaximumclockrateforSDcardsis25MHzineithermode.
• Radiouplink,whichreceivescommandsfromthegroundstation.Usesa
serialconnectionwithadatarateof9600bps.
• Radiodownlink,whichtransmitsresponsestocommandsincluding
engineeringdataandscientificobservations.Usesasimplebitstream
connectionwithadatarateof1Mbps,butisinterfacedviaaninternally
designedFPGAwhichperformsReed‐Solomonencodingfordatacorrection,
soanysufficientlycapabledataconnectioncouldbeused.
• Electricalpowersystem(EPS),asystemofbatteriesandelectronicsto
provideelectricityforallonboardsystems.Hasadiagnostics/commandport
thatusestheI2Cbus.AsanI2Cslavedevice,itsdatarateisdeterminedbythe
masterdevice,whichistheprocessor.Itsmaximumdatarateis400
kilobits/second.
2.2.ProcessorsTheprocessorselectionwaslimitedtothoseprovidedondaughterboards
compatiblewiththeCubeSatKitMotherboard,acommerciallyprovidedfoundation
forCubeSatsthatprovidesaserialinterface,acommunicationsbus,anSDcard
connector,areal‐timeclock,remove‐before‐launchanddeploymentswitches,and
- 8 -
otherusefulcomponents.Onlysixdaughterboardsareavailablefromthekit
vendor,whichconvenientlylimitedouroptionsfromtheentireuniverseof
microcontrollerstoareasonablysizedset.Themaindifferencesamongthe
processorsweretheirprocessingpowerandtheiravailableI/Oports.
Table1:PropertiesofAvailableProcessors
ProcessorArchi‐tecture Memory ADC
InstructionClock IntegratedPeripherals
MSP430F1612 16‐bit55KBprogrammemory,5KBon‐chipSRAM 8‐channel12‐bit 7.3728MHz 2SCIs(UART0/SPI0/I2C&UART1/SPI1)
MSP430F1611 16‐bit50KBprogrammemory,10KBon‐chipSRAM 8‐channel12‐bit 7.3728MHz 2SCIs(UART0/SPI0/I2C&UART1/SPI1)
MSP430F2618 16‐bit116KBprogrammemory,8KBon‐chipSRAM 8‐channel12‐bit 7.3728MHz
2USCI_A(UARTA0/SPIA0&UARTA1/SPIA1)2USCI_B(I2CB0/SPIB0&I2CB1/SPIB1)
C8051F120 8‐bit128KBprogrammemory,8.5KBon‐chipSRAM
8‐channel8‐bit500ksps Externalxtal 2UARTs,1SPI,1I2C
dsPIC33FJ256GP710 16‐bit256KBprogrammemory,30KBon‐chipSRAM
32‐channel10/12‐bit1.1/0.5Msps 10MHz 2UARTs,2SPIs,2I2Cs,2ECANs,DMA
PIC24FJ256GA110 16‐bit256KBprogrammemory,16KBon‐chipSRAM
16‐channel10‐bit500ksps 16MHz 4UARTs,3SPIs,3I2Cs,ParallelMasterPort
MygreatestbodyofmicrocontrollerexperiencewaswithPICs,withsomebrief
contactwiththeMSP430series.Thelatter'sclaimtofameistheirextremelylow
powerneeds;allthreeMSP430optionswouldrunon10mW,anattractiveproperty
whenallpowermustoriginatefromsolarpanels.However,aslongasthe100mW
powerbudgetfortheprocessorwasnotexceeded,anyoptionwasacceptable.(This
putlimitsonthespeedofthe8051anddsPIC33parts,ashigherfrequencies
demandmorepower.)
Theultimateprocessorselectiondependedonthecommunicationdemandsofthe
peripherals.DuetothehighdataratesanticipatedonboththeSTEIN‐to‐processor
andSDcard‐to‐processorlinks,IassumedthatatleasttwoSPIportswouldbe
needed,oneforeachconnectionduringdatatransfer.Theuplinkradiohadaserial
- 9 -
output,soclearlyaserialUARTwouldbeneeded.AnI2Cporttointerfacewiththe
EPSwouldbeuseful,butnotnecessary,asthedataratewouldbesufficientlylowto
allowsoftwareimplementationoftheprotocol.Thiseliminatedhalfoftheoptions
immediately;theMSP430F2618andthePICswerestillviableoptions.
ThePICshadtwodistinctadvantagesovertheircompetitor.First,therewere
modulesavailableinMATLABtoallowthecreationofPICbinaries,whichwas
attractivetothepeopledevelopingtheAttitudeControlSystem(ACS)softwarethat
woulddetectandreorientthesatellite'sspin.Second,andmoreimportantly,the
manufacturerofPICs,MicrochipInc,providesafreedevelopmentenvironmentthat
includesacycle‐accuratesimulator.Withthissimulator,theexecutionspeedofthe
instructionswhichcomprisetheACScodecouldbetested,demonstratingthatthe
PICswereuptothetask.Iwasalsoabletousethesimulatortodemonstratethe
capabilitiesofthePICsingeneral,suchasserialcommunicationandDMA.These
simulationsanddemos,inadditiontoitsclearlyreducedcodeanddatamemory,
removedtheMSP430F2618fromconsideration.
Finally,adecisionhadtobemadebetweenthetwoPICs.Whilethehigherclockrate
andthreeSPIportsonthePIC24wereappealing,IultimatelyendorsedthedsPIC33
duetoitsuniquecapacityforDMA.Ianticipatedthattheflexibilitygainedfrom
DMAwouldbewellworththelossinspeedandI/O.TheCINEMAteamfoundno
faultwithmyassessment,soweincorporatedthedsPIC33intotheprojectdesign.
ThedsPIC33incorporatessomeadditionalfeaturesthatareusefulinaspaceborne
design.Forexample,itcanreprogramitselfwhilerunning,whichpermits
- 10 -
reprogrammingafterlaunch.Ithasautomaticbrownout‐inducedreset,whichmight
savethemissionafterapowerfailureorallowittooperateforalittlelongerasthe
batterieswearout.Italsohasanumberofpower‐savingfeatures,fromaselection
oflow‐activityrunmodestotheabilitytoturnoffpowertounusedsubsystemson
thechip.
2.3.High‐speeddatatransfermechanisms
2.3.1.SPINotallcommunicationsbusesarecapableofsustainingmegabitspeeds.I2C,for
example,hasa400kbpslimitin"high‐speed"mode.SerialportsonthedsPIC33are
capableofreachingabove1Mbpsifpushed.Themostcapableinterfaceavailable,
however,isSPI[Microchip,2009].
SPIbehaveslikeatwo‐wordshiftregistersharedbetweentwodevices‐‐withevery
pulseontheclocklinesentfromthemasterdevicetotheslavedevice,theMSbof
eachdevice'sshiftregisterismovedtotheLSboftheotherdevice'sshiftregister.
Afterasmanyclocksastherearebitsinaword,thetwodeviceshavecompletely
exchangedthecontentsoftheirshiftregisters.
- 11 -
Figure1:SPIcommunicationbetweentwodevices[Microchip,2009]
OnthedsPIC33,theSPIbitrateislimitedtohalfoftheinstructionclockrate,andfor
CINEMAthislimitis5Mbps.Thisismorethanenoughtosupportthefull1.92Mbps
peakinputfromSTEIN,evengivensignificantoverhead.Itisalsowellwithinthe
abilitiesoftheSDcard,whichcouldreach25Mbpsiftheprocessorallowed.
2.3.2.DMADirectMemoryAccessisuniquetothedsPIC33amongtheavailableprocessors.It
comprisesasetof"DMAchannels"whichcanbeconfiguredtoautomaticallymove
datafrommemorytoaperipheral'sbuffer,orvice‐versa,asneededwithoutanyill
effectontheCPU'sactivity.Forexample,theserialportcouldbeconfiguredto
automaticallyoutputthecontentsofasectionofmemory.Aftereachbytewassent,
- 12 -
theDMAchannelassignedtothetaskwouldmovethenextbytefrommemorytothe
transmitbufferoftheserialport[Microchip,2009].
Figure2:DMAsysteminthedsPIC[Microchip,2009]
DMAisflexibleandusefulinmanyways,particularlywhenhandlingmultiple
simultaneousdatastreams,butitislimitedbytheamountofDMA‐capableRAMin
themicrocontroller;ofthedsPIC33's30KBofRAM,only2KBisDMARAM,soit
mustbeusedjudiciouslybytheprogrammer.Anotherlimitationisthatonlyone
devicemayaccessagivenwordofmemoryatatime.TheCPUhasfirstpriority,
followedbythefirstDMAchannel,thenthesecond,andsoondowntotheeighth.
DatacanconceivablybelostifaDMAchannel,configuredtowriteaperipheral's
incomingdatatoRAM,isconstantlyblockedbyotheraccessestothatlocationuntil
anotherdatumarrivesattheperipheralandoverwritesitsbuffer.However,thisis
veryunlikelytohappenwithoutintentionallybeingcaused,andshouldnotoccurat
- 13 -
allonCINEMAduetotherelativeinfrequencyofactivityonanygivenDMAchannel‐
atmaximum,onlyonecyclein16willtriggerthechannel,whichisthecaseforan
SPIport.(TheSPIportstransfer8bitsatatime,butathalftherateofthe
instructionclock,hencetherewillbe16cyclesbetweeneachDMAreadorwriteon
anSPIbuffer.)
2.4.DataflowAswiththeprocessoritself,theconnectionsbetweentheperipheralsandthe
processorweredeterminedbythepeakdataratesoftheperipherals.Theprimary
demandsondataflowweretheSTEINdetector,whichcouldemit1.92Mbpsat
peaks,andthedownlinkradio,whichdemandedaconstant1Mbpsduring
transmission.Thesetwoperipheralswouldneverbeactivesimultaneously,but
bothwouldrequiretheuseoftheSDcardwhenactive.Thissuggestedthatoneof
thetwoSPIportsbesharedbetweenSTEINandthedownlink,andtheotherSPI
portbededicatedtotheSDcard.
Theothermajorperipherals,namelythemagnetometers,EPS,anduplinkradio,
weresimpletoadd.TheMAGFPGAgeneratedonly578bitspersecond,which
couldbeeasilymultiplexedwithSTEINandthedownlinkonthesharedSPI
connection,asitsdatatoowouldneedtobewrittentotheSDcard.TheEPSwasthe
Figure3:CommunicationthroughasharedSPIport
Downlink
SDCard
STEINdsPIC
Downlink
SDCard
STEINdsPIC
STEINactive Downlinkactive
- 14 -
onlydeviceusinganI2Cconnection,soitreceiveditsownportontheprocessor.
Similarly,theuplinkradiowastheonlydevicerequiringaserialconnection.
AtthispointtheteamdecidedtouseasingleFPGAtobothcommunicatewithSTEIN
andoperatetheMAGs.Thiswasatrivialchange,asbothSTEINandMAGswould
stillusethesameSPIportontheprocessor.Thefinaldataflowlayoutplanwasas
follows;thearrowsshowtheprimarydirectionofinformationtransfer,neglecting
mostcontrolflow.
3.SoftwareTheoverarchingdesignprinciplesoftheCINEMAflightsoftwarearethatitbe
flexible,reusable,wellwritten,anddebuggable.Besidesbeinggoodgeneral
practice,flexibilityandreusabilityarerequiredbecauseatleastfourmoreCubeSats
areplannedtousethissoftwareasabase,andthefewerchangesandsurprises
involvedinthemodifications,thebetter.Thecodemustbewellwrittenforsimilar
reasons;becausetheprogrammersarestudents,mostoralloftheoriginal
Downlink
SDCard
MAGdsPIC
SPIlink
STEINFPGA
FPGA
EPS
UplinkI2Clink
Seriallink
Figure4:Dataflowlayout
- 15 -
programmerswillbegonewhenthenextsatelliteisbeingprogrammed.Easeof
comprehensibilityofthecodewillthereforebesignificantforfuture"generations"
ofprogrammers.Finally,thecodemustbedebuggabletospeeddevelopmentand
makeitmoreaccessibletonon‐advancedprogrammers.
3.1.OperatingsystemOneofthebiggestsoftwaredesignquestionswaswhethertouseareal‐time
operatingsystem(RTOS).AsimpleRTOScalledSalvowasavailablefromthe
CubeSatKitvendor,withafreedemothatIwasassignedtoscrutinize.Byusing
Microchip'sfreesimulatorIwasabletosuperficiallyverifythatitworked,butIwas
concernedabouttheeffectsanRTOSmighthaveondebuggability.Havingwritten
multithreadedapplicationsinthepast,IpresumedthataprogramusinganRTOS,
whichincludessimilarprocessor‐yieldingandsemaphoremechanisms,wouldbe
similarlymoredifficulttodebug.Analternativeschemewasproposedbyoneofthe
moreexperiencedteammembers.Thisscheme,usedinaprevioussatellite,allowed
alltaskstoexecuteonapredictable,fixedschedulewithouttheuseofanRTOS.
Thisapproachwastodividealloftheprocessor'stasksintobackgroundtasksand
foregroundtasks.Backgroundtaskswouldrunonatight,predefinedscheduleand
wouldgenerallybemaintenancetasks,suchastakingsciencedataandcheckingthe
statusofthepowersupply.Foregroundtaskswouldrunintheremainingtimewith
noparticulartimeconstraintsandwouldincludelengthycalculationsforattitude
adjustmentandcommandstransmittedfromtheground.Thetasktypeswould
haveindependentschedulers.Theforegroundschedulerwouldprioritizeuploaded
commands,butruneverythingelseround‐robin.Thebackgroundschedulerwould
- 16 -
beinterrupt‐driven‐every1/1024thofasecond,atimerinterruptwouldcallthe
scheduler,whichwouldrunthenexttaskinatableofbackgroundtasks.
3.1.1.BackgroundtaskschedulingEachbackgroundtaskmustbeexecutedfrequentlyenoughtosatisfythedemandsof
itsperipheral'sdataflow.ForatasklikeHSK,whichsamplesanalogvoltagesfrom
thedsPIC33'spins,thisistrivialbecausethetaskitselfcontrolsthecreationofdata.
However,atasklikeSTEorTXhassignificantconstraints.Atpeakflux,theSTEIN
detectoriscapableofgenerating1.92megabitspersecond,whichtheprocessor
mustabsorbandrelaytotheSDcard.Thetransmittermustbefed1megabitper
secondtoavoidwastingpreciousdownlinktime.Arethesetasksschedulable?
ThetaskswiththelargestdataratesmustinteractwiththeSDcard,andevery
transactionwiththeSDcardhassomeoverhead.Tominimizethis,weusethe
maximumSDdatablocksize,whichis512bytes.At1.92Mbps,STEINgenerates
469blockspersecond.Onlyoneblockcanbesentinatime‐sliceof1/1024thofa
second,soSTEIN'shandlertaskSTEmustoccupyatleast469of1024time‐slices.
Thisisroundedupslightly,suchthathalfofalltime‐slicesbelongtotheSTEtask.
Similarly,inordertosend1Mbpstothedownlinktransmitter,theTXtaskmust
handle245blockspersecond.TXmustthereforeoccupy245of1024time‐slices,
whichisroundeduptoone‐fourthofalltime‐slices.
3.1.2.SchedulingthecommandhandlerComparedtoSTEIN's1.92Mbps,theuplinkradio's9600bpsseemstrivial.
However,themicrocontroller'slinktoSTEINincorporatesanFPGA,whichbuffers
- 17 -
datauntilanentiredatablockisready.Theuplink'sserialconnectionhasnosuch
luxury;thereisabufferbuiltintothedsPIC33'sserialport,butitholdsonly4bytes.
A9600bpsconnectionwillfillthis300timespersecond,soitmustbeemptiedat
300Hz.However,STEalreadyhashalfofthe1024time‐slices,andTXhasone‐
quarter.Thetasktablecannotaccommodateanadditionaltaskrequiring300of
1024slices.
Thereareafewwaystofixthisproblem.Commandsmightbehandledinthe
scheduler,whichrunsat1024Hz.However,thiswouldtaketimeawayfromevery
task,includingtaskssuchasSTE,whichhaslittletimetolose.Alternatively,
becauseSTEINandthedownlinkareneverusedsimultaneously,theirtasksSTEand
TXmightbejoinedintoone.Thiswouldleavehalfofthetime‐slicesavailable,but
alsopresentanewproblem:
STE/TX STE/TX STE/TXTheSTE/TXcompositetaskrunsineveryotherslice.
CMD CMDThecommandhandlertaskrunsineverythirdslice.
STE/TX CMD STE/TX ?????Aconflictexists!
TheconflictmightberesolvedbyrunningCMDineveryothersliceinsteadofevery
third,butthentherewouldbenotimeleftforanyothertasks.Theothertasks
wouldneedtobeincorporatedintoCMD,atthecostofthepredictabletimingofthe
tasktable.
- 18 -
MysolutionwastouseDMAtoreplacetheexisting4‐bytebufferwithabufferin
memory.Specifically,aDMAchannelisconfiguredtomoveeachincomingserial
bytetoasectionofDMARAM.Thedestinationaddressautomaticallyincrements
witheachbytemoved;whentheendofthebufferregionisreached,thedestination
addressreturnstothebeginningautomatically.Inthisway,DMAemulatesthedata‐
storinghalfofaringbuffer,leavingthedata‐retrievingdutyforthecommand
handler.BecausetheDMAchanneloperatesindependentlyoftheCPU,it'sas
independentofthecurrenttaskastheoriginal4‐bytebuffer.Allthatisnecessaryis
tomaketheDMAbufferlargeenoughtostoreasmuchinformationasmightarrive
betweenexecutionsofthecommandhandler;ifthehandlerrunsat16Hz(oneslot
intheabovetable),thebuffermustbeatleast75byteslong,whichisonlyasmall
portionofthe2KBofDMARAMavailableonthedsPIC33.
Table2:TableofBackgroundTasks
BKG Module 1024 Hz Table 0 1 2 3 4 5 6 7 0 STE TX STE STE TX STE
8 HSK STE TX STE STE TX STE
16 TM STE TX STE STE TX STE
24 CMD STE TX STE STE TX STE
32 STE TX STE STE TX STE
40 PWR STE TX STE STE TX STE
48 SSR STE TX STE STE TX STE
56 MAG STE TX STE STE TX STE
This table describes .063 seconds and is repeated 16 times per second. BKG Module Function Calls Distributed in Time Phase
FN FREQ Description TX 256 Transfer data from SDCARD to Transmitter
STE 512 Transfer data from STEIN to SDCARD MAG 16 Transfer data from MAG to SDCARD HSK 16 Housekeeping A/D Sampling
- 19 -
CMD 16 Uploaded Command Handling PWR 16 Power Monitoring 16-bit timing SSR 16 Solid State Recorder Manager TM 8 Packet Multiplexing
BKG0 8 Available for future use BKG1 32 Available for future use BKG2 128 Available for future use
3.2.DevelopmentplatformForeaseofdevelopmentandinsurance
againstaccident,twosetsoftheCubeSat
KitdevelopmentboardanddsPIC33
daughterboardwerepurchased.The
developmentboardiselectrically
identicaltotheflightmotherboard,but
withadditionalcomponentsbuiltinto
simplifydevelopment,suchasindicator
LEDs,astandard9‐pinRS‐232serial
port,andadditionallateralspacefor
peripheralboards.Onesetofhardware
wasusedfordevelopmentoftheACS
software,whileIusedtheothersettobeginsystemsoftwaredevelopment.
OnefoibleofthedsPIC33isthatitpossessesthreedifferentpinpairsthatmaybe
usedforin‐circuitdebugging(ICD).Althoughitmaybeprogrammedusinganyof
thethreepairs,itwillonlyacceptICDcommandsfromonepairduringexecution.
Thisincreasesflexibility(whatifthefunctionalityyouwantedtotestusedaport
Figure4:CubeSatKitDevelopmentBoard[PumpkinInc,2010]
Figure5:CubeSatKitFlightMotherboard[PumpkinInc,2010]
- 20 -
thatsharedtheonlyprovidedICDpins?),butitcameasasurprisetome.Naturally,
thedefaultpinpairwasnotthepairconnectedtotheprogrammingheaderonthe
dsPIC33daughterboard,andthereforethe"run"commandItriedtoissuefellon
deafears.Ihadtoinvestigateseveraldatasheetsinordertodiscover,first,the
natureoftheproblem,andsecond,thelineofCcodeneededtomakethecompiler
activatethecorrectpinpair.
3.3.TheSDCardAfterthemicrocontrollerandoperatingsystemweredecidedupon,Ibecameleader
ofthestudentsdevelopingtheflightsoftware.Itookituponmyselftowritethe
interfacefortheSDcard,asitwouldmostlikelybeamongthemosttiming‐critical
piecesofcodeduetothehighdataratesinvolved.Iwasexperiencedinwriting
assemblyforPICs,soIcouldwritecodeatthelowestleveliftheSDcard'stiming
madeitnecessary.
SecureDigital(SD)flashmemorycardsareafavoriteofelectronicshobbyists
becausetheypresentasimplephysicalinterfacewithfewelectricalconnections
whileprovidinggigabytesofavailablestorage.Theyalsohaveafreelyavailable
interfaceprotocolspecificationfortheSPImode[SDGroup,2006].Forthesame
reasons,theCubeSatKitmotherboardincorporatesaslotforanSDcardandabuffer
amplifiertoisolateitfromtheprocessor[Pumpkin,2009].
3.3.1SDcardsinspaceForanelectronicitemtotravelsafelyintospace,itmustberesistanttovibration,
shock,extremetemperatures,andradiation.Isoughtahigh‐durabilitySDcardfrom
- 21 -
amainstreammanufacturer,sothatwecouldpurchaseandtestmultipleunits
withoutcostingmorethanafewhundreddollars.EventuallyIdiscoveredthe
SanDiskExtremeIIIlineofcards,whichSanDiskclaimswillkeepoperatingunder
vibration,shock,andtemperaturesfrom‐25°Cto85°C[Amazon.com,2010].Oddly,
nobodyseemstoknowhowmodernSDcardsbehavewhenbombardedwith
radiation.Nguyenetal.measuredradiation'seffectsonflashRAM,butusedcards
from1999withacapacityof128MB.Moremoderncardswithsmallerfeaturesand
higherbitdensitiesmaybemorevulnerablethanthetestedcards,whichexhibiteda
significant(0.7milliamp)increaseinstandbycurrentandfunctionalfailureafter
receivingacumulativedoseof8000rad(Si)whilepoweredon[Nguyenetal.,1999].
InalowEarthorbitwithhighinclination(20to85degrees),whichisthetypeof
orbitCINEMAisintendedtoinhabit[Curtis,2008],typicalradiationdosesare1000‐
10,000rad(Si)peryear[NASA,1996].AssumingthatmodernflashRAMistwiceas
vulnerableastheflashtestedin1999,IconjecturethatCINEMA'ssolid‐state
memoryshouldbeviableforatleast2/5ofayear(~21weeks)intheworstcase.
ThisisonthesameorderofmagnitudeasCINEMA'sexpectedmissiontimeofone
year,andshouldbemorethanenoughtimetodemonstratetheviabilityofthe
conceptandtakescientificdata,barringsomeunforeseencalamitythatmustbe
handled.
3.3.2.SDcardbasicsThefreelyavailablespecificationprovidedthedetailsofinitializing,commanding,
reading,andwritingtheSDcard.ThecardusestheSPIinterfaceinahalf‐duplex
manner;despitethefull‐duplexnatureofSPI,theprocessorandSDcardnever
- 22 -
transmitvalidinformationsimultaneously.Afteracommand,theprocessormust
repeatedlytransmitnullbyteswithallbitssetuntiltheSDcardreturnsitsresponse.
Figure6:SDCardCommandInteraction[SDGroup,2006]
Thecommandformatisfairlysimple.Itconsistsofsixbytes,thefirstofwhich
containsatwo‐bitheaderandasix‐bitcommandnumber.Themiddlefourbytes
composetheargumentofthecommand,andthelastbytecontainstheseven‐bitCRC
(cyclicredundancycheck)oftheprevious5byteswithaone‐bittrailer.
Figure7:SDCardCommandFormat[SDGroup,2006]
Myfirstconcernwastofindouthowmuchoverheadexistedinreadingandwriting,
astheoverheadmightlimithowmuchcouldbedoneinascheduledtime‐slice.As
SPIcouldtransferagivennumberofbytesinatime‐slice,Imeasuredtimeinbytes.
Table3:TimeRequirementsofSDCardDataRetrievalandStorage
Readphase Time/data Writephase Time/data
Command 6bytes Command 6bytes
- 23 -
Responsedelay 0‐8bytes Responsedelay 0‐8bytes
Response 1byte Response 1byte
Accesstime 1byte+tACCESS Pause 1bytemin.
Startblock 1byte Data 512bytes
Data 512bytes CRCofdata 2bytes
CRCofdata 2bytes Dataresponse 1byte+tBUSY
Total(max) 531bytes+tACCESS Total(max) 531bytes+tBUSY
Asingletime‐sliceis
€
5,000,000 bitssec
×byte
8 bits×
sec1024 time - slices
= 610.35 bytestime - slice
long,whichmeansthatthereisamaximumof610‐531=79bytesleftforother
activitiesinatime‐slice.Forexample,afterawriteiscompleted,itisgoodpractice
tomakesuretherewerenoerrorsbyusinganothercommandtofindouthowmany
byteswerejustwritten.However,aslongastheaccessandbusytimesweren'ttoo
large,Iwasn'tveryworriedaboutrunningoutoftimeinaslice.
3.3.3.CRCinlimitedtimeWhatdidworrymeweretheCRCfieldsinthecommandanddataoperations.A
commandwasgivenfordisablingthedata'sCRC16,butitdidn'tmentionthe
commands'CRC7.Arbitrarycommandshadtobepossibletoallowarbitrary
read/writeaddresses,whichmeantaCRC7routinehadtobemade.StandardCRC
algorithmsoperateonasinglebitatatime,XORingornotXORingagivenvalueto
theevolvingCRCvaluedependingonthestateoftheinputbit.Thiswasnot
acceptableforCINEMA,aseachbitwastransferredintwoinstructions'worthof
- 24 -
time,andthestandardalgorithmcouldnotbereducedtotwoinstructionsonthe
PICarchitecture.IlookedforfasterCRC7algorithmsonline,butfoundnothing
usefulexceptingademonstrationofCRC5foranFPGAthatusednibblesofinput
togetherwiththeentirecurrentCRCtoformaparallel‐computableexpressionfor
bitsofthenextCRC[Evgeni,2009].IfiguredthatIcouldusesimilartechniquesto
producealookuptable‐basedversionofCRC7.
Figure8:CRC7EquivalentGenerator[SDGroup,2006]
ObservingthediagramofaCRC7generatorprovidedwithintheSDcard
specifications,InoticedthattheCRCbytesmoveinaloop‐‐allthebitsmoveupby
one,andbit7isXORedwiththeinputbittocreatethenewbit1(andaffectbit4).
Thissuggestedthatbit‐shiftingby4mightplayasignificantroleinmyalgorithm.
Calculating4generationsoftheCRC7generatorresultedinthefollowing(Dx
representsthevalueonthedatainputimmediatelybeforegenerationx):
- 25 -
generation cells
0 1 2 3 4 5 6 7
1 D1^7 1 2 3^D1^7 4 5 6
2 D2^6 D1^7 1 2^D2^6 3^D1^7 4 5
3 D3^5 D2^6 D1^7 1^D3^5 2^D2^6 3^D1^7 4
4 D4^4 D3^5 D2^6 D1^7^D4^4 1^D3^5 2^D2^6 3^D1^7
Table4:TheStateofaCRC7GeneratorOver4Generations
Inoticedthatthevaluesofbits1,2,and3couldbeshiftedtotheirpositioninthe
4thgeneration,butasfortherestIinitiallyfollowedtheexampleoftheCRC5
generator,makingatableforallpotentialvaluesofbitsD1‐D4andbits7‐4.The
tableswereidentical,pointingouttheinherentpairings:D4wasalwaysXORedwith
bit4,D3withbit5,D2withbit6,andD1withbit7.Thisisespeciallyconvenient
becauseD1andbit7areboththemostsignificantbitsoftheircategories,sothetwo
highestnibblescanbeXORedinplace.ThefinalalgorithmforCRC7ingonebyteata
timeisasfollows;allvariablesareactuallyregisters,andtheinitialvalueofcrcis0.
1. temp=XOR(input,crc) //beginhighnibble
2. temp=AND(temp,0xf0) //fourbit‐pairXORvaluesready
3. temp2=RIGHTSHIFT(temp,3)
4. temp=XOR(temp,temp2) //eightbit‐pairXORvaluesready
5. crc=LEFTSHIFT(crc,4) //unpairedvaluespositioned
6. crc=XOR(crc,temp) //newCRC7complete
- 26 -
7. temp=LEFTSHIFT(input,4) //beginlownibble
8. temp=XOR(temp,crc)
9. temp=AND(temp,0xf0) //fourbit‐pairXORvaluesready
10. temp2=RIGHTSHIFT(temp,3)
11. temp=XOR(temp,temp2) //eightbit‐pairXORvaluesready
12. crc=LEFTSHIFT(crc,4) //unpairedvaluespositioned
13. crc=XOR(crc,temp) //newCRC7complete
Listing1:CRC7Algorithm(dsPIC33AssemblyLanguage)
Theleastsignificantbitintheoutputbyteisalways0,whichisperfectforSDcard
purposes.Setthatbit,andtheresultisthefinalbyteoftheSDcommandformat.
Thealgorithmis13instructionslong,leaving3instructionsforgettingthe"input"
bytefrommemory,copyingittotheSPIportforsending,andreadingthetheSPI
port'smostrecentlyreceivedbytetopreventoverflow.Itjustbarelyfits.This
algorithmismadepossiblebythedsPIC33'smultipleworkingregisters;I'mnotsure
thatitwouldbepossiblewithonlyoneworkingregister,whichwasthecaseonPICs
likethePIC16F84Icutmyteethon.
Flushwithsuccess,IdecidedtotryoptimizingCRC16aswell,sothatdata
transactionsmightalsobeverified.CRC16'sgeneratorisabitmorecomplex:
- 27 -
Figure9:CRC16EquivalentGenerator[SDGroup,2006]
generation cells 0 1 2 3 4 4 D4^13 D3^14 D2^15 D1^16 8 D8^9^D4^13 D7^10^D3^14 D6^11^D2^15 D5^12^D1^16
generation cells 0 5 6 7 4 1 2^D4^13 3^D3^14 8 D4^13 D3^14^D8^9^D4^13 D2^15^D7^10^D3^14
generation cells 0 8 9 10 11 4 4^D2^15 5^D1^16 6 7 8 D1^16^D6^11^D2^15 1^D5^12^D1^16 2^D4^13 3^D3^14
generation cells 0 12 13 14 4 8 9^D4^13 10^D3^14 8 4^D2^15 5^D1^16^D8^9^D4^13 6^D7^10^D3^14
generation cells 0 15 16 4 11^D2^15 12^D1^16 8 7^D6^11^D2^15 8^D5^12^D1^16
Table5:TheStateofaCRC16Generatorat0,4,and8Generations
AswithCRC7,CRC16'sbitsmoveinaloop,andthebitpairsappearasexpected;D1
isalwaysXORedwithbit16,D2with15,andsoon.Becausetherearemorethan8
- 28 -
bitsinCRC16,thecomputationcanmoveontothebytelevelandmakeevenmore
bitpairsthanatthenibblelevel.UsingsimilarprinciplestoCRC7,afteran8‐bitshift
alloftheunpairedbitsareintherightplace.Theremainingelementsareintwo
continuous,unbrokengroups:{D1^16...D8^9}anditssubset{D1^16...D4^13}.I
broughtthislineofthoughttofruition,resultingina13‐instructionalgorithmas
before.IthenperusedsomeCRCwebsitesIfoundbeforemakingCRC7,andnoticed
analgorithmthattookmyresultsonestepfurther[ckielstra,2005].Therewas
reallyonlyonecontinuousgroup:{D1^16...D4^13,D5^12^D1^16...D8^9^D4^13}.
Thisgroupappearedthreetimes(oncehangingoffthemost‐significantedge),and
madepossiblea10‐instructionalgorithm.Again,allvariablesareactuallyregisters.
1. SWAP(crc) //exchangebytes;workslikerotateleftby8,
whichiswhat'sneeded
2. crc=XOR.BYTE(crc,temp) //highbyteofcrcmuststaythesame;Ibuild
myXORgroupincrc'slowbyte
3. temp=RIGHTSHIFT(crc,4) //nobyte‐onlyformexists,hencethenext
instruction
4. temp=AND(temp,0x000f)
5. crc=XOR.BYTE(temp,crc) //thelowbyteisnowthemagicXORgroup,
andisintherightplaceonce
6. temp=ZEROEXTEND(crc) //thatis,temp=AND(crc,0x00ff),which
isn'tanavailableinstruction
- 29 -
7. temp=LEFTSHIFT(temp,5)
8. crc=XOR(temp,crc) //XORgroupisintherightplacetwice
9. temp=LEFTSHIFT(temp,7)
10. crc=XOR(temp,crc) //XORgroupisintherightplacethreetimes
Listing2:CRC16Algorithm(dsPIC33AssemblyLanguage)
(IlaterdiscoveredthattheSDcommandthatmakesdataCRCsoptionalalsoapplies
tocommands,sotheentireexercisecouldhavebeenskipped.I'mgladthatIdidn't
knowthat,though,becauseIprobablywouldhavedroppedtheideaifIdidn'tthink
ithadtowork.Nowthatthealgorithmexists,CINEMAcanuseittoresisterrors.)
3.3.4.SDfirstcontactUsingthespecification,Idesignedroutinestowritetheappropriatevaluestothe
SPIporttooutputthefirstcommandforSDcardinitializationandreadbackthe
response.Nothinghappened,soIhookeduptheoscilloscopetoverifythatthe
waveformsbeingemittedwereasIexpected.Nothingseemedwrong,butIknew
myinformationwaslimited,soIlookedforreferencewaveformsonline.Two
peoplehaddocumentedtheSDcardinitializationprocesswithincludedwaveforms
[ChaN,2008;ESawdust,2008],soIlearnedtochangetheidlestateofthebustoa
highstateandtoemit10bytesofhighbitstoproperlyinitializetheSDcard.
Proceedinginthecardinitializationsequence,IdiscoveredthattheSPIportonthe
dsPIC33wasveryseriousabouterrordetection‐‐ifabytearrivedbeforethe
previouslyreceivedbytehadbeenreadbytheprogram,theportsetanoverflow
- 30 -
flagandrefusedtoacceptanymorebytesuntiltheflagwasmanuallycleared.This
wasgenerallyunnecessary,astheSDcardneverreturnsvaliddatawhilethe
processorissendingacommand,butitdidmakemeabetterprogrammerby
pointingoutwhenIinsufficientlyunderstoodhowmycodewasinteractingwiththe
SPIport.
TheSDcardhastwomainstates:initializingandready.Initializationmustbedone
withalowerspeedSPIclock,asthecardoperatesinanopen‐drainmodeuntil
initializationiscomplete[SanDisk,2002].Uptothispoint,IhadbeendrivingtheSD
cardat312kHz.Oncefullspeedbecameavailable,commandsanddatawere
transferredatthedsPIC33'sfullspeedof5Mbps.Thisimmediatelycausedarashof
SPIportoverflows,astheinputbufferfilledupmorethan10timesfaster,leadingto
acorrespondingrashofimprovedcode.Also,ithadbecomepossibletoreadfrom
andwritetotheSDcard,determiningthevaluesoftheaccesstimeduringaread
andthebusytimefollowingawrite.
3.3.5.SDwritebusytimeStartingwithsingle‐blockwritestovariouslocations,Idiscoveredasurprising
trend.WhenIsetmyprogramtowritetoanewaddress,theSDcardwasbusyfor
20to30thousandbytesafterthewrite.IfIrerantheprogram,thebusytime
droppedtobetween650and900bytes.Thiswasdistressing,asnotonlydidit
implysomesortofstatesexistingwithintheSDcardbetweenoperations,italso
endangeredthe1.92Mbpsminimumdatarateweneeded.Naivelyspeaking,
ignoringtheconstraintsimposedbythebackgroundtasktable,theSDcardcouldbe
busyfor851bytes,maximum,andstillsustain1.92Mbps.
- 31 -
IdecidedthatamoreaccuratesimulationofCINEMAoperatingconditionswas
needed.WhenItriedwritingtoasequenceofadjacentaddresses,thefirstaddress
causedabusyperiodof20,000‐30,000bytesasbefore,butsubsequentwriteswere
busyforlessthan600bytes.Evenbetter,rewritingthesamesetofaddresses
reducedthestartupbusyperiodtoaround3000bytes.
Thedatashowedaninterestingpattern,visibleonlywhenmakingmultiplewrites.
Aftertheinitialtwenty‐thousand‐bytebusydelay,allwriteshadshortbusyperiods
exceptforonewriteinevery64,whichhadabusydelay2800‐4000byteslong.
PresumablythiswascausedbysomeinternalelementoftheSDcard,suchasa32
KBwritebuffer,butithadtobedealtwithbytheprocessor.Tounderstandthis
pattern'seffectonwritingItook490datapointsfromwritestotwodisparate
addresssequencesandmodeledtheireffectsifallincomingSTEINdatawerestored
inasinglebuffer.ThesimulatedsystemcheckedtheSDcard'sstatusat512Hz,and
ifthecardwerenotbusyandtherewereatleast512bytesinthebufferthesystem
wouldsendablockfromthebuffertotheSDcard.
- 32 -
Figure10:BusyTimesExperiencedin490WriteAttempts
Figure11:ContentsofSimulatedBufferFollowing490WriteAttempts
ThissimulationmodeledthebehaviorofapotentialadditiontotheactualCINEMA
system,andproducedencouragingresults.Inthebuffercontentsgraph,thebuffer
onlyexceeds2000bytesduetoanunusuallylongbusydelaycausedbyswitchingto
anewaddressregion,andrecoverssteadilyfromeventhat.Thelargesawteethare
duetotheone‐every‐64longdelays,andthesmallsawteethoccurwhenthebuffer
containslessthan512bytessothereisno512‐byteblocktosendtotheSDcard.An
18562‐>
- 33 -
8KBbufferwassufficienttodealwitha18,562bytebusyperiod;somebusyperiods
slightlyexceed30,000bytes,soa12KBbuffershouldbeabletohandleeventhose
peaks.Thisbuffermightbeinthemicrocontroller,intheFPGA,orsharedbetween
thetwo;theFPGAwillcontainatleast1KBofbufferinitspresentdesign.The
dsPIC33contains30KBofmemory;whetherornotathirdofthatcanbesparedfor
STEINbufferingisunknownbecausemuchofCINEMA'scodeisunwrittenatthis
time.Alsoinquestioniswhetheritshouldbespared,as1.92MbpsisSTEIN'speak
rate,whichweneverexpecttoseeandcouldneverrelaytothegroundifitwere
frequent.Ultimately,ifthememoryisavailable,itwillmostlikelybeused.
InthenameofscienceItriedincreasingtheaddressgapbetweenwrites.It
appearedthattherewasaroughlylogarithmicrelationbetweenbusyperiod
durationandproximitytothepreviouswrite(seefigure).However,evenmovingto
every‐other‐blockwritingpushesthemaximumbusytimeupto900bytes,so
CINEMAiseffectivelylimitedtowritingadjacentmemorylocations.
Figure12:RelationofBusyPeriodDurationtoWriteAddressSeparation
- 34 -
Finally,Itriedwritingtotwoaddresssequencesalternately,e.g.10,1000,11,1001,
12,1002,...tosimulateapairofringbuffers.Fortunately,therewasnosignificant
increaseinbusyperiodafterthesewrites;itwasindistinguishablefromwritingall
theaddressesinonesequence,thenwritingalltheaddressesintheothersequence.
Asaresult,CINEMAcansafelymaintainabufferfordiagnosticdataandrecordsthat
isindependentfromthebufferforscientificdata.Inordertoavoidthelongbusy
delaythataccompaniesthefirstwritetoamemoryregion,thefirstaddressesof
bothbuffersshouldbewrittenwithdummydatawellbeforethebuffersarelikelyto
beused.
3.3.6.SDreadaccesstimeAfterthecomplexitiesoftheSDcard'swritebehavior,Iwasbracingmyselffor
strangefluctuationsintheaccesstimesthatoccurduringreads.Becausetheyare
presentinthemiddleofreadinginsteadoftheend,longaccessdelaysmight
significantlycomplicatesendingdatatothetransmitter.Desiringtoseetheworst
possiblecase,Imaderandomizedreadsacrosstheentire2GBaddressspace.The
resultwasapleasantsurprise.Thereweretwolongaccessdelaysinthebeginning
oftheprocess,alwaysexactly484and480byteslongrespectively.(Usuallythey
occurredonthefirstandsecondrandomreads,butonceonthefirstandfifth.)All
otheraccesstimeswereinthe72‐76byterange,withtheoccasionalaccesstimein
the52‐56byterangewithnoobviousdistribution.
Becausenoaccessdelayexceeds484,anyreadoperationcanbehandledinasingle
610‐byte‐longtime‐sliceiftheinitialreadrequestismadeinthefirsthundredbytes
oftime,butitwillrequiretheuseofDMAtomaintainthetransferafterthetime‐
- 35 -
sliceends.Thishasanupsideforforegroundtasks,inthatshortaccesstimescan
usethesameDMAmechanismtoendthebackgroundtaskearly,leavinghundreds
ofbytesoftimeavailableforforegroundtaskwork.Thealgorithmisasfollows:
1. IfthedownlinkFPGAcanholdanotherblock,sendSDreadcommand.
2. SetupDMAchannel1:readfromsingleDMARAMlocation,writetoSDcard,
move514bytes./*Thesinglelocationcontains0xFF,SDcard's"null"byte.*/
3. SetupDMAchannel2:readfromSDcard,writeto514bytesofDMARAM,
move514bytes.
4. SetupDMAchannel3:readfrom514bytesofDMARAM,writetodownlink
FPGA,move512bytes./*ThedownlinkFPGAdoesn'tcareabouttheCRC.*/
5. Manuallysendone0xFFbytetotheSDcard.
6. Iftheresponseisn'tthe"blockstart"byte,goto5.
7. EnableDMAchannels1,2,and3.
8. ActivateDMAchannel1.SDcardwillbeginsendingthedatablock,which
willbemovedintoDMARAMbyDMAchannel2.
9. AfterthefirstbytearrivesviaDMAchannel2,activateDMAchannel3.
10. Returnfrominterrupt.AllDMAchannelswillauto‐disablewhenfinished.
Listing3:DMADrivenReadFromSDCard(Pseudocode)
- 36 -
3.3.7.SDreadbusytimeSomethingnotmentionedintheSDcardspecificationwasthebusyperiodthat
followedthereadoperations.Everysinglerandomreadwasfollowedbyadelayof
exactly172bytes.Theiroriginisuncertainbutirrelevant,astheyoccurafterthe
DMAmechanismfinishesmovingthedata.However,thealgorithmabovesendsno
bytestotheSDcardafterthedatablockanditsCRC16arereceived;theSDcard
mayrequireaclockinputtofinishwhateverit'sdoingduringthe172bytes.Ifthis
isthecase,asolutionistoincreasethenumberofbytestransferredbyDMAchannel
1to686(514+172).ThiswillcauseareceiveoverflowontheSPIportconnected
totheSDcard,buttheonlydatalostwillbe"busy"bytesfromtheSDcard.Itwill,
however,beimportanttocleartheoverflowflagbeforethenextcommunication
withtheSDcard,asotherwisetheincomingbyteswillbedropped.
4.ConclusionInmytimeattheSpaceSciencesLaboratoryatUCBerkeley,Ihavechosena
processor,designeddataflows,determinedtaskfrequencies,workedaround
constraintsusingDMA,andheavilyinterfacedandcharacterizedanSDcard.My
workhasbeenintegraltotheprogressoftheCINEMAproject,andIleaveitata
goodbreakpoint.Futureworkintheseareasmightincluderadiationbombardment
ofamoremodernSDcard,andwillcertainlyinvolveahigher‐levelinterfacetomy
SDcardroutines.
- 37 -
Appendix:ProductsUsed
Flightmotherboard:PumpkinP/N710‐00484Rev.D
Developmentboard:PumpkinP/N710‐00297Rev.D
Processordaughterboard:PumpkinP/N710‐00528Rev.A
EPS:Clydespace3UEPS,30Whlithiumbatteries
Uplinkradio:Helium100
Downlinkradio:EmhiserEDTC‐01DEA
SDcard:SanDisk2GBExtremeIIISDMemoryCard(SDSDX3‐002G‐A21)
- 38 -
Sources
Amazon.com."SanDisk2GBExtremeIIISDMemoryCard(SDSDX3‐002G‐A21
RetailPackage):Electronics."2010.http://www.amazon.com/SanDisk‐Extreme‐
Memory‐SDSDX3‐002G‐A21‐Package/dp/B000FKKWVM(January28,2010)
ChaN."HowtoUseMMC/SDC."2008.http://elm‐chan.org/docs/mmc/mmc_e.html
(March8,2010)
ckielstra."CRC16,veryefficient."2005.
http://www.ccsinfo.com/forum/viewtopic.php?t=24977(March9,2010)
Curtis,David,andJohnSample."CubeSat:CubeSatforIons,Neutrals,Electron,and
MagneticFields(CINEMA)."2008.
ESawdust."SD/MMCSPIInitializationWaveforms."2008.
http://www.esawdust.com/blog/serial/files/SPI_SD_MMC_ATMega128_AVR.html
(March4,2010)
Evgeni."OutputLogic.com>>ParallelCRCGenerator."2009.
http://outputlogic.com/?p=158(March1,2010)
GHSInfotronic."OnlineCRCCalculation."https://www.ghsi.de/CRC/index.php
(March15,2010)
Glaser,DavidL."MechanicalSystemDesignoftheCubeSatforIons,Electrons,
Neutrals,andMagneticFieldsMission(CINEMA)".2009.
- 39 -
Jakacki,Peter."SPI/SDinitializationsequence‐myway."2005.
http://www.embeddedrelated.com/groups/lpc2000/show/9497.php(March8,
2010)
MicrochipInc."dsPIC33FJXXXGPX06/X08/X10DataSheet."2009.
http://ww1.microchip.com/downloads/en/DeviceDoc/70286C.pdf(Sept.112009)
NASA."SpaceRadiationEffectsonElectronicComponentsinLowEarthOrbit.1996.
http://klabs.org/DEI/References/design_guidelines/design_series/1258jsc.pdf
(Oct.5,2009)
Nguyen,D.N.etal."RadiationEffectsonAdvancedFlashMemories."1999.
http://parts.jpl.nasa.gov/docs/Flash‐99.pdf(Oct.5,2009)
PumpkinInc."CubeSatKitMotherboard(MB)."2009.
http://www.cubesatkit.com/docs/datasheet/DS_CSK_MB_710‐00484‐D.pdf(Sept.
22,2009)
SanDisk."HostDesignConsiderations:NANDMMCandSD‐basedProducts."2002.
http://www.sandisk.com/media/216454/appnotemmc_sdv1.0.pdf(April26,2010)
SDGroup."SDSpecificationsPart1PhysicalLayerSimplifiedSpecification."2006.
http://www.sdcard.org/developers/tech/sdcard/pls/Simplified_Physical_Layer_Sp
ec.pdf(Sept22,2009)
Thomsen,Michael."Michael'sListofCubesatSatelliteMissions."2009.
http://mtech.dk/thomsen/space/cubesat.php(October9,2010)
- 40 -
UltimaSerial."FactorsaffectSDandMMC'sdatathroughputrate."2010.
http://www.ultimaserial.com/sandisk.html(Apr8,2010)