can due2.2 user manualmedia3.ev-tv.me/can due2.2 user manual.pdf · sd memory card reader was...

39
EVTV Motor Werks Version 2.20 Septemeber 2017 Copyright 2015 – EVTV LLC 1 User Manual CANDue Version 2.20 CAN Bus Shield For Arduino Due

Upload: others

Post on 27-Jul-2020

6 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 1

UserManual

CANDue Version 2.20

CAN Bus Shield For

Arduino Due

Page 2: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 2

INTRODUCTIONTheEVTVCANdueproductprovidesapackageofanArduinoDuecompatiblemicrocontrollerboard,CANbuscommunicationsshield,andassociatedUSBcableintendedtoprovideareasonablycompletesolutiontomonitoringCANbusnetworks,interactingwiththem,andprovidingameanstorecordlargevolumesofCANmessagetraffic.Theproductincludes:

1. TwoportCANDue2.2CANbusshieldwithEEPROMandmicroSDmemorycardslot.

2. GenericArduinoDuecompatiblemicrocontrollerboard.

3. USBcable.

Page 3: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 3

ARDUINODUETheArduinomicrocontrollerisanopen-sourcehardwaremicroprocessorcontrollerdesignedtoeasilyinterfacewithavarietyofsensors(toregisteruserinputs),andtodrivetheresponsesandbehaviorsofexternalcomponentssuchasLEDs,motors,andspeakers(torespondtouserinputs).In2005,theArduinoteamwasformedinIvrea,Italy,consistingofMassimoBanzi,DavidCuartielles,DaveMellis,GianlucaMarino,andNicholasZambetti.TheArduinoincorporatedaprogrammingenvironmentbasedonProcessinglanguage-aprogramminglanguageconceivedbyBenFryandCaseyReas,theabilitytoprogramtheboardviaastandardUSBconnection,andalowpricepoint(startingatabout$35USD).

TheArduinoachievedrapidsuccessevenwithinitsfirsttwoyearsofexistence,sellingmorethan50,000boards.By2009,ithadspawnedover13differentincarnations,eachspecializedfordifferentapplications—forexample,theArduinoLilypad(forwearabletechnologiesprojects),theArduinoMini(miniaturizedforuseinsmallinteractiveobjects),andtheArduinoBT(withbuilt-inBluetoothcapabilities).

ArduinostartedasaprojectforstudentsattheInteractionDesignInstituteIvreainIvrea,Italy.AtthattimeprogramstudentsusedtheParallaxBASICSTAMPcontrolleratacostof$100,consideredexpensiveforstudents.MassimoBanzi,oneofthefounders,taughtatIvrea.Thename"Arduino"comesfromabarinIvrea,wheresomeofthefoundersoftheproject usedtomeet. ThebaritselfwasnamedafterArduino,MargraveofIvreaandKingofItalyfrom1002to1014.

Page 4: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 4

Thefirstprototypeboard,madein2005,wasasimpledesign,anditwasn’tcalledArduino.MassimoBanziwouldcointhenamelater. Banziandhiscollaboratorswerestrongbelieversinopen-sourcesoftware.Sincethepurposewastocreateaquickandeasilyaccessibleplatform,theyfeltthey’dbebetteroffopeninguptheprojecttoasmanypeopleaspossibleratherthankeepingitclosed.Thiswaskindofaremarkableinnovation–opensourcehardware.Theproducttheteamcreatedconsistedofcheappartsthatcouldeasilybefoundifuserswantedtobuildtheirownboards,suchastheATmega328microcontroller.Butakeydecisionwastoensurethatitwouldbe,essentially,plug-and-play:something someonecouldtakeoutofabox,plugintoacomputer,anduseimmediately.BoardssuchastheBASICStamprequiredthatDIYersshelloutforhalfadozenotheritemsthataddedtothetotalcost.Butfortheirs,ausercouldjustpulloutaUSBcablefromtheboardandconnectittoacomputer—MacorPC—toprogramthedevice.

WordofArduinoquicklyspreadonline,withnomarketingoradvertising.Earlyon,itattractedtheattentionofTomIgoe,professorofphysicalcomputingattheInteractiveTelecommunicationsProgramatNewYorkUniversity.IgoetoohadbeenteachingcoursestonontechnicalstudentsusingtheBASICStampbutwasimpressedbyArduino’sfeaturesandprice.TheArduinoDueisArduino’sfirstARM-basedArduinodevelopmentboard.Thisboardisbasedonapowerful32bitCortexM3ARMmicrocontrollermadeprogrammablethroughthefamiliarArduinoIDE.ItincreasesthecomputingpoweravailabletoArduinousersbyanorderofmagnitude.TheArduinoDuehas54digitalinput/outputpins(ofwhich12canbeusedasPWMoutputs),12analoginputs,4UARTs(hardwareserialports),an84MHzclock,aUSB-OTGcapableconnection,2DAC(digitaltoanalog),2TWI,apowerjack,anSPIheader,aJTAGheader,aresetbuttonandanerasebutton.TocompilecodefortheARMprocessor,you’llneedthelatestversionoftheArduinoIDE:v1.5Note:UnlikeotherArduinoboards,theArduinoDueboardrunsat3.3V.ThemaximumvoltagethattheI/Opinscantolerateis3.3V.EarlierArduinoboardswerebasedona5vpowersupply.Asaresult,shieldsandotherhardwareforArduinoaregenerallyNOTcompatiblewiththeArduinoDue.Providinghighervoltages,like5VtoanI/Opincoulddamagetheboard.

Page 5: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 5

Features:

• Microcontroller: AT91SAM3X8E • Operating Voltage: 3.3V • Recommended Power Input Voltage: 7-12V • Min-Max Input Voltage: 6-20V • Digital I/O Pins: 54 (of which 12 provide PWM output) • Analog Input Pins: 12 • Analog Outputs Pins: 2 • Total DC Output Current on all I/O lines: 130 mA • DC Current for 3.3V Pin: 800 mA • DC Current for 5V Pin: 800 mA • Flash Memory: 512 KB all available for the user applications • SRAM: 96 KB (two banks: 64KB and 32KB) Clock Speed: 84 MHz

TheArduinoDueprovidesaveryfast,powerfulmicrocontrollerthatiseasilyprogrammedinaC++syntaxvietheArduinoIntegratedDesignEnvironment(IDE).YoucanconnectittoaPCorMacviaaUSBcabletobothpowertheboardanduploadcompiledsoftware.

CANBUSCANbus(controllerareanetwork)isavehiclebusstandarddesignedtoallowmicrocontrollersanddevicestocommunicatewitheachotherwithinavehiclewithoutahostcomputer.CANbusisamessage-basedprotocol,designedspecificallyforautomotiveapplicationsbutnowalsousedinotherareassuchasaerospace,maritime,industrialautomationandmedicalequipment.DevelopmentoftheCANbusstartedoriginallyin1983atRobertBoschGmbH.[1]Theprotocolwasofficiallyreleasedin1986attheSocietyofAutomotiveEngineers(SAE)congressinDetroit,Michigan.ThefirstCANcontrollerchips,producedbyIntelandPhilips,cameonthemarketin1987.BoschpublishedseveralversionsoftheCANspecificationandthelatestisCAN2.0publishedin1991.Thisspecificationhastwoparts;partAisforthestandardformatwithan11-bitidentifier,andpartBisfortheextendedformatwitha29-bitidentifier.ACANdevicethatuses11-bitidentifiersiscommonlycalledCAN2.0AandaCANdevicethatuses29-bitidentifiersiscommonlycalledCAN2.0B.ThesestandardsarefreelyavailablefromBoschalongwithotherspecificationsandwhitepapers.

Page 6: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 6

In1993theInternationalOrganizationforStandardizationreleasedtheCANstandardISO11898whichwaslaterrestructuredintotwoparts;ISO11898-1whichcoversthedatalinklayer,andISO11898-2whichcoverstheCANphysicallayerforhigh-speedCAN.ISO11898-3wasreleasedlaterandcoverstheCANphysicallayerforlow-speed,fault-tolerantCAN.ThephysicallayerstandardsISO11898-2andISO11898-3arenotpartoftheBoschCAN2.0specification.CANbusisoneoffiveprotocolsusedintheon-boarddiagnostics(OBD)-IIvehiclediagnosticsstandard.TheOBD-IIstandardhasbeenmandatoryforallcarsandlighttruckssoldintheUnitedStatessince1996,andtheEOBDstandardhasbeenmandatoryforallpetrolvehiclessoldintheEuropeanUnionsince2001andalldieselvehiclessince2004.Butinrecentyears,OBDIIhasevolvedmoretowardCANandtheotherprotocolsmoreorlesscompriselegacyprotocolsfoundonoldervehicles.CANwon.

ARDUINODUEANDCANTheheartoftheArduinoDueisamicroprocessorcontrollerchipdesignatedAT91SAM3X8E.Thisquitepowerful84MHz32-bitchipactuallyprovidesinternal“controllers”fortwoCANchannels.Unfortunately,thisisjustthecontrollogicforthechannels.TouseCAN,youalsoneedthe“power”componentsthatactuallytransmitaCANmessageoverthewires.These“transceivers”werenotincludedintheArduinoDuedesignandnospecificCANcommandswereincludedintheArduinoIDE.Andso,toactuallyprovideCANcommunicationsfortheArduinoDue,weneedacoupleofthings:1.HardwaretransceiversandaphysicalconnectortowirethesystemtoaCANbus.2.A“library”objectmoduletoextendtheArduinolanguagetoincludeCANcommands.

Page 7: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 7

EVTVCANDUECANBUSSHIELDTheEVTVCANDueVersion2.2“Teodora”CANbusshieldwithEEPROMandMicroSDmemorycardreaderwasoriginallydesignedbyPauloAlmeidaandCelsoMenaiaofLisbonPortugalandproducedbyEVTVMotorWerks.ThisboardfeaturestwoCAN2.0compliantcommunicationschannelscapableofdataratesupto1Mbpsanda256KBElectricallyErasableProgrammableMemorychip(EEPROM).TheoriginalArduinofeatureda4KBEEPROMinthecontrollerchipitself.Thiscanbeveryhandytostoreconfigurationvariablesthatyouwanttobeabletochange,butwouldliketobepersistentfromonepowercycletothenext.TheAT91SAM3X8EmicrocontrollerusedontheDueversionofArduinodoesnotprovidethisEEPROM.Itdoesfeatureapersistent“flash”memoryofanimpressive512KB,butthismemorycontainsthecompiledsoftwareyouuploadtotheArduino.Anytimeyouuploadanewversionofthissoftware,youwouldloseallyourconfigurationdata.Andsoweincludedaquitelarge256KBEEPROMtostorevariablesorlogdata.TheCANbustransceiversusedareaTexasInstruments3.3vtransceiverdesignatedSN65HVD234.EachoftwochipsmanagesasingleCANchanneldesignatedCAN0andCAN1.Thecommunicationsinterfaceofthesechipsisprovidedbyscrewterminalsattheedgeoftheboard.CANTERMINATION.TheCANbusspecificationrequiresthatthetwoendsofthetwowire,twistedwirebusbeterminatedwitharesistiveimpedanceof120ohms.IfyouareusingtheCANbusshieldtocommunicateonanexistingvehicleCANbus,itisprettymuchagiventhatthebusalreadyhastwodevicesonitthatserveas“ends”andthattheyprovideproperimpedancetermination.Butinsomeapplications,forexamplecommunicatingwithasinglechargerorbatterymanagementcomponent,theArduinoandthisshieldAREoneoftheendsofthebus.Toprovideforthis,eachCANchannelfeaturestwo60ohmresistors,oneforeachofthetwoCANwires,andacapacitor.Thecapacitorfiltersnoisetoground.Thetwo

Page 8: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 8

60ohmresistorscombinefortherequisite120ohmswhileprovidingapointforthecapfiltertoconnectsothatthereactanceisequalizedacrossthetwowires.Inanupgradefromtheswitchedterminationonversion2.0.the2.2iterationsimplyincludesacoupleof0ohmresistors.Inourexperience,invirtuallyEVERYcaseyourboardmustbeterminatedtohaveanysuccessontheCANbus.Intheextremeandunlikelyeventthatyoumightneedanunterminatedconnection,youwillhavetoremovetheresistorsbydesolderingthemfromtheboard.We’vebasicallyneverhadthisrequirement..

TheCAN0andCAN1portsareprovidedonascrewterminalstriponthesideoftheshield.ThisallowsyoutoeasilyconnectCAN1HIandCAN1LOtoanykindofcablepigtailorconnectordesired.Twoofthescrewterminalsarealsoconnectedto12VINandGND.CANDueVersion2.2alsosupportssinglewireCAN-a33.33kbpsvariantusedontheEbenspacherHeaterandtheTESLAChargerforexample.Dataistransferredataslowerspeedonasinglewireusingframegroundasthedifferential.SWCAN,

Page 9: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 9

GND,andtwoscrewterminalsareprovidedforaloadresistorgenerallyusedonSWCANapplications.Finally,twoscrewterminalsareprovidedfora10kNTC(NegativeTemperatureCoefficient)Thermistor.Avoltagedividercircuitconnectsthe3.3vreferencevoltageacrosstheNTCandthisvoltagedividertoprovideareadableinputtoAnaloginput0ontheDue.ThisinputisalsoguardedbyaZenerdiodetopreventminorovervoltages.Inthisway,youcanusetheDuetocalculatetemperatureusingmostGeneralMotorstemperaturesensors.

DUE_CAN

due_canisanArduinoDuespecificlibrarywrittenbyCollinKidderofSpartaMichigan.ItprovidesfunctionsandmethodstoeasilydealwiththeverypowerfulCANbustransceiverfunctionsavailableintheCANDueshield.TheArduinoIDE(IntegratedDesignEnvironment)providesabasicC++programminglanguagesyntaxwithsomecurious“extensions”todealwithhardwareeasilyanddirectly.Theseextensionsareessentiallyhardwarespecificanddealwiththingslikedigitalinputandoutputpins,analogtodigitalconversionpins,andpulsewidthmodulatedoutputpins.Andso,boththeArduinohardwareandtheArduinoIDE“language”arecuriouslyadaptedtodealingwithhardwareandsensorsandtheoutsideworld–lights,switches,potentiometers,temperaturesensors,etc.ThehardwareoftheArduinoisendlesslyextensiblebytheadditionof“shields”.Shieldsareprintedcircuitboardswithadditionalhardwarethatcanbasically“plugin”totheheadersonthemainArduinoDueboardandsoconnecttoit.Intheory,themanipulationofpinsanddataonthemwillofcourseoperateanyhardwareprovidedonshields.AsYogiBerrasays,intheory,theoryandpracticearethesame,butinpractice,theyaren’t.Muchhardwarehasveryinvolveddataschemestoeithersenddatatoitorretrievedatafromit.AndsowefindthelanguageofArduinoisALSOextensible.Wedothiswith“libraries”thatbasicallyprovidenewC++CLASSstructuresandmethodsthatacttoextendthelanguage.Andthesehidemostofthedetailofdealingwiththehardwaredevice,reducingittoanOBJECTyoucaneasilycommandwithmuchsimplerinstructions.

Page 10: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 10

Toaddalibrary,youusuallysimplyaddittoyourusers/Arduino/Librariesdirectory.Butineachprogramwhereyouusethatlibrary,youmustalsoaddan“include”statement.Thiscausesthelibrarytobeincludedwhentheprogramiscompiled,andcallstofunctionsandmethodsinthatlibraryarethenlinkedintotheresultingprogram.

#include<due_can>; //This is an include statement AndsoyoumayhaveMANYlibrariesinyourusers/Arduino/librariesdirectory,butonlythosespecifiedwithincludestatementswillbeusedinanyparticularprogram.

CANPORTSTheCANDueshieldprovidestwohardwareportsCAN0andCAN1..

INITIALIZATIONSANDBEGINNINGSSoourfirstrequirementisanincludestatement.

#include<due_can>; //This is an include statement OursecondistoINITIALIZEtheCANportwewanttousewithabeginstatement.Wecandoeitherorboth.

Page 11: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 11

pinMode(50,OUTPUT);

if (Can0.begin(25000,50)) {

Serial.println("Using Can0 - initialization completed.\n");

}

else Serial.println("Can0 initialization (sync) ERROR\n");

pinMode(48,OUTPUT);

if (Can1.begin(25000,48)) {

Serial.println("Using Can1 - initialization completed.\n");

}

else Serial.println("Can1 initialization (sync) ERROR\n");

Thebasicinitializationishandledby

Can0.begin(25000,50) Notethat250000isthedatarate250kbpsand50 istheENABLEpin.ThisisahardwarefunctionofthisparticularCANDueshield.Weusedigitalpin50toenabletheCan0hardwaretransceiver.Weusedigitalpin48toenabletheCan1transceiver.Due_caniscapableofsupportingvirtuallyanyCANshield–butyouneedtoknowtheENABLEpinsusedbytheparticularshieldyouareusingtoproperlyinitializethis.IfyourCANboarddoesnotuseanENABLEpin,setthesevaluesto255.Ifnopinisspecified,thedefaultvaluesthatwillthenbeusedarepin62forCan0andpin65forCan1.IfCan0initializationissuccessful,theCan0.beginroutinewillreturnavalueof1whichisBooleanTRUE.Asyoucanseeabove,weusedthisfeaturetodeterminewhetherCANinitializationwassuccessfulandsendamessageouttheSerialporttodisplayonscreen.Finally,weneedtoestablishsomeveryspecificvariablestohandleCANframedatathatwewanttosendandCANframedatathatwewillbereceiving.ThesevariablesareoftypeCAN_FRAME.

Page 12: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 12

CAN_FRAME outFrame, inFrame;

CAN_FRAMEDATATYPESTRUCTUREInthisexample,wehavesettwovariables,outFrameandinFrameoftheCAN_FRAMEtype.CAN_FRAMEisactuallyaSTRUCTURE–avariableformthatcontainsanumberofothervariableswithinitsstructuralenvelope.TosendCANdata,wehavetopopulateoneoftheseframeswithourdatawewanttosend(outFrame).AndtoreceiveCANdata,wehavetohavethisvariablestructureavailabletostorethereceiveddata(inFrame).TheCANprotocolhasanumberofoptionsbutisbasicallyprettysimple.SomehousekeepingdataupfrontincludingthemessageID,howlongthedatapayloadis,andsomeotherincidentals,andthenadatapayloadof1to8bytes.TheeasiestwaytodealwiththatissetupastructurewithALLoftheelementspossibleinaCANmessageframe.Youfillintheonesyouneedandonceyouhaveeverythingyouwantaccountedfor-thensendtheframewithonecall.It’skindoflikefillingoutamessageformbeforehandingittothetelegraphertosend.AndsowefindthatoutFrameactuallyhasanumberofstructuralelements.

outFrame.id //uint32_t – a 32bit (4 byte) variable

// containing the CAN message ID.

outFrame.fid //uint32_t – a 32 bit (4 byte) variable for

// family ID. Not commonly used.

outFrame.rtr //uint8_t – a one byte variable for

//Remote Transmission Request. Rarely used.

outFrame.priority //uint8_t a one byte for Priority,

//occasionally used for TX frames.

Page 13: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 13

outFrame.extended //uint8_t a one byte for Extended

//Addressing (29-bit) flag 0= 11-bit

outFrame.length //uint8_t a one byte for number of data

//bytes to follow

outFrame.data.bytes[0] //uint8_t first data byte

outFrame.data.bytes[1] //uint8_t data byte

outFrame.data.bytes[2] //uint8_t data byte

outFrame.data.bytes[3] //uint8_t data byte

outFrame.data.bytes[4] //uint8_t data byte

outFrame.data.bytes[5] //uint8_t data byte

outFrame.data.bytes[6] //uint8_t data byte

outFrame.data.bytes[7] //uint8_t data byte inFramehasexactlythesamestructure,butofcourseinadifferentlocationinmemory.ForconveniencetherearetwoOTHERwaystoaddressthedataintheeightdatabytepayloadoftheCANframebytes[0]throughbytes[7].

outFrame.s0 //uint16_t bytes[0] and bytes[1] as a two

//byte unsigned integer.

outFrame.s1 //uint16_t bytes[2] and bytes[3] as a two

//byte unsigned integer.

outFrame.s2 //uint16_t bytes[4] and bytes[5] as a two

//byte unsigned integer.

outFrame.s3 //uint16_t bytes[6] and bytes[7] as a two

//byte unsigned integer.

Page 14: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 14

outFrame.s0throughoutFrame.s3isactuallyquiteconvenient.CANdataisoftenmoreeasilydealtwithasaseriesoffourtwo-byteintegersforpresentingdatathatcanoftenbelargerthan255.Thefinalwaytoaddressdataintheeightdatabytepayloadisaslowandhigh–two32-bitunsignedintegers.

outFrame.low //uint32_t bytes[0] - bytes[3] as a four

//byte unsigned integer.

outFrame.high //uint32_t bytes[4] - bytes[7] as a four

//byte unsigned integer. Thisallowsustosendandreceive32-bitdataviaCAN.WhenwedefineavariableastypeCAN_FRAME,itsimplyreservesbytesinmemoryunderthatname(inFrame)toholdtheframeandallowsaccessbyuseoftheframesubunits(inFrame.id, inFrame.data.bytes[5]).YoucandefineasmanyCAN_FRAMEvariablesasyoulike.

SENDINGCANFRAMESSendingCANframesisactuallyverysimple.Asdescribed,weloadtheCANframewewanttosend,andthensenditwithasinglecall.

CAN_FRAME myFrame;

myFrame.id = 0x25A;

myFrame.length = 1

myFrame.data.bytes[0] = 128;

Can0.sendFrame(myFrame);

HerewedefinemyFrameastype CAN_FRAME.

Page 15: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 15

Wethensettheidto0x25A.Byconvention,andyou’llrarelyseethisotherwise,CANmessageIDsarealmostalwaysreferredtointhehexadecimalnumberingsystem.Wenotethisbyprepending0xtothenumber.WealsosetmyFrame.lengthto1indicatingthatwewillonlybetransmittingasingledatabyte.Wedefinethatdatabyteascontainingthedecimalvalue128.Andfinally,wesendtheframewiththestatementCan0.sendFrame(myFrame);We’rebasicallytellingtheCAN0hardwareporttomakeupaCANmessagefromthedatainthemyFramestructure,andsenditoutonthebus.NotethatthereareanumberofelementsdefinedinthestructuremyFramethatwedidn’tsetatall.Thedefaults,usuallyzero,willbefine.Inthemajorityofcases,allyouneedisanID,adatalengthandyourdata.Infact,inthiscase,tosendanotherframewithnewdata,Iknowthattheidandlengtharealreadyset.

myFrame.data.bytes[0] = 129;

Can0.sendFrame(myFrame);

Andsoweseethatwehavesentanentirenewframewithjustthedatabytechanging.sendFrameisthemostcommonmethodtosenddataoverCAN.ButthereisasimplifiedalternativecommandyoucanusetosendCANframesthatdoesnotinvolveusingaCAN_FRAMEdatastructurethatyoumayfinduseful.

Can0.setWriteID(0x620);

Can0.write(SomeValue); YoufirstusethesetWriteIDfunctiontoestablishthemessageIDyouwanttouse.Thismethodtakesasingleargumentandwilluse11-bitor29-bitextendedaddressingautomaticallybasedontheIDnumberyouprovide.Thewritefunctionsimplystuffswhateverdatayouprovideintothe8databytesavailableinsequence.Thiscanbeusefulincertainspecializedinstances.Forexample,ArduinoDuefeatures32-bitLONGintegersthatareactuallyfourbytes.

Page 16: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 16

Long myLongInteger=2914145897000;

Can0.setWriteID(0x620);

Can0.write(myLongInteger); ThesethreelineswouldwritethefourdatabytescontainingthevalueinmyLongInteger undermessageID0x620.Thelastfourbytesoftheblockwouldbepaddedwithzeros.NotethatArduinoDueusesa“littleendian”dataformatwheretheleastsignificantofthefourbytesisstoredinthefirstpositionwhilethemostsignificantbyteofthelongintegerissentinthefourthbyteposition.Attimes,youmightwishtoreversethis.

Can0.setBigEndian(true); ThisstatementsetsCan0.write()methodtosendtheintegerinthereverseorder–mostsignificantbyteinthefirstdatabytepositionandtheleastsignificantbyteinthefourthdatabyteposition.

RECEIVINGBUFFEREDCANFRAMESWecanreceiveCANframesintwoways.CANDueactuallybuffersincomingframeswhichwecancheckfororpollusingtheavailablecommand.Wecanalsosetupaninterruptsuchthatanytimeaframeisreceived,itisroutedtoamethodinourprogramthatisdesignedtohandletheincomingframe.Thiswillbedescribedlater.

CAN_FRAME inFrame; if (Can0.available()) { Can0.read(inFrame);

} WewouldplacethiscallsomewhereinourLOOPportionoftheArduinoprogram.Periodically,itwouldpollforCan0.available()whichwouldreturn1iftrueand0otherwise.

Page 17: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 17

Ifthereisaframeavailable,theCan0.readcommandretrievesitandloadsallthedataintoouralreadydefinedinFramestructure.AndsoCan0.readactuallypassestheaddressoftheinFramestructuretotheobjectwhichthenusesthataddresstocopydataoutofthebufferandintotheinFramestructuredvariable.Oncewehavereceivedthedata,wecanthengoexamineitintheinFramestructure.

CANFRAMEFILTERSCANcansupportanumberofdevicesintheory.Inpractice,aboveabout30devicesandthebusbecomesquitebusy.ButthecentraltennetofCANisthattherereallyisnointelligenceintheprotocol.Themessagesaren’tevenaddressedtoanyspecificdevice.Eachdevicesimplybroadcaststheirmessagestoeveryoneonthebus.Nocheckingtoseeifitwasreceived.Nohandshakes.Nothing.Theintelligenceissupposedtobeinthedevicesthemselves.TheDMOC645controllerforexample,knowsthatatorquecommandwillbereceivedundermessageID0x232andthatthefirsttwobyteswillcontainthecommandasa16-bitunsignedintegerthatisoffsetby30000.Soitreceivesthevalue,subtracts30000,andtakestheresultasatorquecommand.TheVehicleControlUnitbroadcaststhistorquecommandandsetsthemessageIDto0x232.Itdoesn’tknowifthereareanyDMOC645’sonthebus,doesn’tknowhowmany,anddoesn’tknoworcarewhatitdoeswithit.Itsimplytranslatesthrottleinputstoatorquecommand,adds30000toit,andputsitinthefirsttwobytesofthepayload.SowhatdoestheDMOC645devicedowhenitreceivesaCANmessagewithID0x332?Nothing.Ithasnoknowledgeof0x332messagessoitsimplydiscardsthem.Actually,itisworsethanthat.Sinceithasnoknowledgeof0x332messages,itactuallysetsafilterintheCANtransceiverchiptonoteveninterruptitfor0x332messages.Asaresult,itneverreceivesthematall.TheinternalCANtransceiverreceivesit,andsimplyignoresit–dramaticallyreducingthecomputationaloverheadfortheDMOC645multicontroller.SopicturetheDMOC645asactuallyLOOKINGfor0x232messages,andtotallyignoring,infactfilteringout,all0x332messages.Inthisway,eachdeviceonthebushasalistofmessagesitsends,andthedataitwantstosendinthem.Anditalsohasalistofmessagesitwillreceive,andhowtodealwithdatainthose.Andtypicallyanyspecificdevicemighthave3-5messagesit

Page 18: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 18

sends,andanother3or4itrespondsto.ALLOTHERTRAFFICISTOTALLYIGNORED.Somedevicesbroadcastasinglemessageidwithspecificinformationinitanddon’tlistenforANYmessagesincoming.Thiswouldbelikeatemperaturesensor.Itonlydoesonething–measuretemperature.AnditreportsitontheCANbusforanywhocare.Butitdoesn’tDOanythingelse,anddoesn’tneedinformationfromanyotherdeviceatall.due_canfeaturessomepowerfulfilteringoptions.IfyouwanttomonitorallthetrafficonaCANbus,obviouslyyoudon’twanttofilteroutanything.Butformostapplications,youarelookingforarelativehandfulofmessages,anditisanenormousreductioninprocessoroverheadtosetfilterstoignoreeverythingelse.ThisisdonewiththesetRXFiltercommand.

Can0.setRXFilter(msgid, mask, extended); Thiscommandtakesthreearguments(withanoptionalfourth).ThefirstisthemessageidofthemessagesyouWANTtoreceive.ThesecondelementistheMASKandthethirdindicateswhetherthisisforstandard11-bitmessageidsorextended29-bitmessageids.

Can0.setRXFilter(0x232, 0x7FF, false); Inthisexample,themessageIDincludedis 0x232.Thethirdelementisfalseindicatingstandard11-bitaddressesareused.TheMASKinthiscaseindicatesthatwewanttoreceiveONLYmessagesthatexactlymatchthe0x232messageIDOurmask,0x7FFwouldberepresentedinbinaryas 0111 1111 1111

Notethat11of12bitsareset.OurstandardmessageIDsarelimitedto11bitsandsoallmessagesmustbenumberedintherange000to7FF.ThinkofthemaskasdefiningthespecificbitsthatMUSTMATCH.Andsothismaskindicatesthatall11bitsmustmatchforamessagetobevalid.Ifwesetamaskof0x7F0 0111 1111 0000 Andourbasemessageis 0x230 0010 0011 0000 WelogicallyANDthosetwotogettheresult 0010 0011 0000 Ifwereceiveamessageof 0x23A 0010 0011 1010 AndwelogicallyANDthatwiththemasktogettheresult 0010 0011 0000

Page 19: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 19

WeseethattheresultsoftheFIRSTANDandtheresultsoftheSECONDANDareequalandweacceptthemessage. OurmaskindicatesthatthelastfourbitsdoNOThavetomatchbutthefirst7DO.Thiswouldacceptanynumberfrom0x230to0x23F.Ifwesetthemaskto0x700 0111 0000 0000Ourmaskindicatesthatonlythefirstthreebitsneedmatch.WecanacceptanymessageIDfrom0x200 to0x2FF.Andofcourseamaskof0x000wouldacceptallmessages.Itwouldbepointlesstosetsuchafilter.

Can1.setRXFilter(0x18FF50e5, 0x1FFFFFFF, true); Inthisfilterexample,weuse29-bitextendedaddresses.ThemaskindicatesthatwemusthaveanexactmatchonallbitsformessageswithID 0x18FF50e5Notethatyoucansetupto8differentfilterscovering8differentmessagerangesandanycanbeeither11-bitor29-bit.

EASYCANFILTERSCANfilterscanbesomewhateasiertoemployusingthewatchForfunctions.

Can0.watchFor(); ThiscommandallowsALLmessagestobeaccepted.Butbetter,itactuallysetsuponemailboxforstandardframes,andasecondmailboxforextendedframes.Allmessagesofeitherstandardorextendedframearethenaccepted.

Can0.watchFor(0x740); ThiscommandwillcauseCAN0towatchforaspecificaddress,inthiscase,0x740.Whetheritisextendedorstandardaddressingissetautomaticallydependingontheaddressprovided.

Page 20: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 20

Can0.watchFor(0x620, 0x7F0); Thiscommandspecifiesamessage0x620andamask0x7F0.Itappliesthemaskjustasdescribedearliertoacceptallmessagesfrom0x620through0x62F.

Can0.watchForRange(0x620, 0x64F); ThiscommandacceptsmessagesbymessageIDintherangefromthefirstmessageIDgiventothesecond.

CANINTERRUPTSAnearlierdescriptionprovidedthedetailsofbufferedCANframesandhowtoretrievethem.ThereisasecondwaytoreceiveCANframesthatmanyfindmoreefficient.ThisisthroughCANinterrupts.CANinterruptsaresimplyamethodofcallingaprocessingmethodinyourprogram,whenandonlywhenaCANframeisreceived.Inthisway,yourprogramcanattendtootherdutieswithouttheoverheadofcheckingtoseeifaCANframehascomein.WhenavalidmessageDOESarriveandqualifiesthroughthefiltersset,theCANobjectcallsthedefinedmethodinyourprogramandpassesittheCANframe.ItcanthenprocesstheCANframeandreturn.ThisisanINTERRUPTanditdoesinterruptyournormalprogramoperation.Itstopsit,savesitsstate,processestheCANframe,andthenreturnstotheexactpointintheprogramwheretheinterruptoccurred.AsthenormalArduinoDueprogramloopcancyclehundredsofthousandsoftimespersecond,thisvastlyreducestheoverheadofCANmessages,whichmightbereceived30timespersecond.Better,youcanhavedifferentCANhandlermethodsfordifferentreceivedmessageIDs.

Can1.setRXFilter(1, 0x18FF50e5, 0x1FFFFFFF, true);

Can1.attachCANInterrupt(1, convertIncoming) Inthefirstlineabove,weseeourfamiliarfilterstatement.Butwehaveanewelement,thefirst,setto1.Whenyousetafilter,thelibrarynormallyjustpicksa

Page 21: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 21

mailboxforyou.Thereare8“mailboxes”provisionedasafunctionofthechipdesignandthisiswhyyoucanhaveuptoeightfilters.Butyoucanoptionallydesignateaspecificmailboxtouse0-7.Wecanusethistosetourfilter,andthentietheoutputtoagivenroutineinourprogram.Thesecondlineintroducesanewfunction,attachCANInterrupt.Thisfunctionthenletsustieanyvalidmessagefilteredthroughmailbox1toberoutedtoourroutineinourprogramthathandlesthis.InourArduinoprogramstructure,youalwayshaveasetuproutineandalooproutine.

void setup(){

Some setup statements.…

}

void loop () {

Some statements we execute over and over without end.

} WewanttoaddamethodtoourprogramtohandlethisCANmessage,butwedoNOTwantittobepartofthemainprogramlooporthesetup.

Page 22: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 22

byte fromCharger[15];

void convertIncoming(CAN_FRAME *frame){

fromCharger[3]=(uint8_t) (frame->id>>24);

fromCharger[2]=(uint8_t) (frame->id>>16);

fromCharger[1]=(uint8_t) (frame->id>>8);

fromCharger[0]=(uint8_t) (frame->id>>0);

for(int i=4; i<12; i++){

fromCharger[i]=frame->data.bytes[i-4];

}

calculateCharger();

} ThelibrarypassestheCANmessagedatastructuretotheconvertIncomingmethodasframe.Inthismethod,weareextractinginformationfromtheframeandarrangingitina15bytearraytitledfromChargerandthencallingANOTHERmethod,calculateCharger,whichhasaccesstofromCharger aswell.Wecansetupto8interruptsandeachcanbetothesamemethod,orotherentirelydifferentmethodsinourprogram,allbasedontheirincomingaddresses.Finally,wecansetaGENERALinterrupttohandleallmailboxesthatdonototherwisehaveacallbackassociatedwiththem.

Can1.attachCANInterrupt(someOtherMethod); Notethatthisisthesamecall,butdoesnotspecifyamailbox.Itwillbeappliedtoanymailboxesthatdonothaveaninterruptattached.Thiscombinationisactuallyquitepowerful.Forexample,wecouldsetfiltersandinterruptsfortwonamedmailboxes,andthensetsixmorefiltersthatdon’tspecifyamailbox.Thenwecansetoneinterruptforthefirstmailbox,anotherinterruptforthesecondmailbox,andthenageneralinterrupttohandletheremainingsix.Inthisway,wecanroutemessagestospecificmethodsbasedontheirmessageID.ThemethodsareONLYcalledwhenaspecificmessageisreceived.Onceprocessed,controlisreturnedtotheoverallgeneralArduinoprogramloop.

Page 23: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 23

CANinterruptscanberemovedwiththecommandCan0.detachCANInterrupt(0); Thiswouldremovetheinterruptattachedtomailbox0.Ifthemailboxisomitted,Can0.detachCANInterrupt(); willremoveALLCan0interrupts.Thissectionprovidesdescriptionsofthebasicfunctionsofdue_canandthesearecertainlysufficienttowritepowerfulCANprograms.Buttherearemanymorefunctionsinthelibrary.Refertothelibrarysourcecodeandexampleprogramsformoredetailedinformation.

PUTTINGITALLTOGETHER–ACANEXAMPLELet’sputallthisnewCANknowledgetogetherinasimplebuttrickyexample.WehavetwoArduinoDue’sthatwestartupattwodifferenttimes.Themillis()methodwillgiveusthenumberofmillisecondsthathaveoccurredsincewestartedthemachine.Inthiscase,wewanttodisplaythetimeinhoursminutesandsecondsonBOTHArduinoDue’sBasicallywewanttosynchronizeourwatchesviaCAN.OnthefirstArduinoDue:

#include<due_can>; //includes due_can library

uint8_t correction; //8bit integer holding a correction

void setup(){ //Our setup function

Serial.begin(115000);

pinMode(50,OUTPUT);

If (Can0.begin(500000,50);){

Serial.println(“Can0 initialized…”);

}

else Serial.println(“Can0 failed…”);

Page 24: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 24

Can0.setWriteID(0x05B); //Let’s use message ID 0x500

correction=5; //5 milliseconds for propogation

}

void loop(){

Can0.write(millis()+correction);

int seconds = (int)(millis()/1000)%60;

int minutes = (int)((millis()/(1000*60))%60);

int hours = (int)((millis()/(1000*60*60))%24);

char buffer[9];

sprintf(buffer,"%02d:%02d:%02d.%03d",hours,minutes,

seconds,milliseconds);

Serial.println(buffer);

} ThisprogramsetsupCAN0asouroutputportatadatarateof500KBPS.Inthemainloop,itprintsthecurrenttimesincestartupinhours,minutesandsecondssincestartupouttheserialportandtransmitsafourbytevaluerepresentingcurrentmillisecondsplusacorrectionvalueof5millisecondstoaccountforthepropagationdelayinsendingourtimeoverthebus.AnditdoesthisinthestandardArduinoDuelittleendianformat–storingthisvalueinthefirstfourbytesusingmessageaddress0x05B.

Page 25: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 25

OnthesecondArduinoDuedevice:

#include<due_can>; //includes due_can library

void setup(){ //Our setup function

Serial.begin(115000);

pinMode(48,OUTPUT);

If (Can1.begin(500000,48);){

Serial.println(“Can1 initialized…”);

}

else Serial.println(“Can1 failed…”);

Can1.setRXFilter(1, 0x05B, 0x7FF, false);

Can1.attachCANInterrupt(1, getOurTime)

}

void loop(){

}

void getOurTime (CAN_FRAME *timeFrame){

long remillis=timeFrame.low;

int milliseconds = (int(remillis/1)%1000 ;

int seconds = (int)(remillis/1000)%60;

int minutes = (int)((remillis/(1000*60))%60);

int hours = (int)((remillis/(1000*60*60))%24);

char buffer[9];

sprintf(buffer,"%02d:%02d:%02d.%03d",hours,minutes,

seconds,milliseconds);

Serial.println(buffer);

}

Page 26: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 26

Thisprogramisalittlebitdifferent.First,wearegoingtosetafilteronmailbox1thatONLYrespondsto05BmessageIDs.TheCANbushaslittleintelligence,butitDOESworkoutbuscontentionondifferentdevices.Weareonlygoingtotransmitthistimemarkoncepersecond,andwearegoingtocorrectitwithacalibrationfactoraccountingforpropagationdelay.ButweDOwantthatmessagetogetthroughontime.AndsobysettingaLOWmessageaddressIDnumber,wegiveitahigherpriorityonthebus.Inthisway,asweadddevicesonthebuswithhigheraddresses,ourdelayshouldnotchangemucheventhoughthetrafficonthebusgrowsenormously.Second,wesetaninterruptforCan1thatpassesreceivedframestothefunctiongetOurTime.ThisfunctionreceivestheframefromthelibraryandnotethatwedonotreallyexplicitlydeclarethetimeFramevariableelsewhere.getOurTime setsalocalremillisvariabletotimeFrame.low.Recallthat.lowisanalternatedatastructurerepresentingthefirstfourbytesinadatastructureofupto8bytes.Sincemillis()returnsalongintegeroffourbytes,inlittleendianformat,thisisperfect.Wecansimplycopythisvaluetotheremillisvariableonthesecondmachine.Finally,ourinterruptfunctionprintsthenewformattedhours,minutesandsecondsouttheserialport.IfwesetupthesetwoArduinosconnectedtotwolaptopsdisplayingtheUSBoutputonrespectiveterminalprograms,theobjectiveisfortheprintedtimestomatch.Iftheydonot,wecancorrectbygoingbacktothefirstprogramandchangingthecorrectvariablevaluefrom5tosomethingelseandinthiswaysynchronizingthetwosystems.Notethatinthiscase,thestandardArduinoloopfunctioncontainsnocode.Infact,youcanplace12000linesofcodeinthisloopandhavetheprogramdowhateveryoulike.Itwillhavenoeffectonourtimefunctionatall.Thisisbecausethatloopprogramiterationwillbeinterruptedonreceiptofa0x05Btimemessageandthetimeprintedagain.Oncethatverybriefoperationhasconcluded,theprogramcodeinloopwillcontinuefromexactlywhereitleftoffwheninterrupted.

EEPROMUSETheElectricallyErasableProgrammableMemoryprovidedontheDualChannelCANShieldisa2megabitmemorychipaccessedseriallythroughI2ContheSCAandSCLpinsontheArduinoDueboard.The2megabitsofstorageworksoutto256kilobytesofstorage–262,1448-bitbytelocations.

Page 27: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 27

ThesignificanceofEEPROMstorageisthatanythingyouwritetothismemoryisretainedevenwhenpowerisremoved.Becauseofthis,itcanbeusedtostoredatawhichyoudesiretobe“persistent”andretainitsvaluethroughanynumberofpowercycles.WhileArduinoFlashmemorycouldbepurposedforthesamethingwithabitofcodemagic,ifyouuploadaNEWversionofyourprogram,youloseanypersistentdataheldinflashmemorythisway.NotsowithEEPROMstoreddata.Itisalwaysretained.Examplesofdatawhereyouwouldwantthisnormallyincludesconfigurationvariableswhereyoudesiretosetavariablecontrollingprogramoperation,butyoudon’treallywanttogothroughthisconfigurationeverytimeyoupowerup.BywritingtheseitemstoEEPROM,youcanplacecodeinyourprogramSETUPtoretrievethisdatawhenyoufirstpowerupandsowesaytheseitemsareheldin“persistent”storage.Theyarethereeverytimeyoupowerup.Storingdata8-bitsatatimeisabitofaproblem.BYTE,CHAR,BOOL,andINT_8TandUINT_8Tdatatypescanofcoursebestoreddirectly.ButtheC++usedintheArduinoDuefeaturesarichsetofdatatypes,often32bitsinlength.Storingandretrievingthesevariablesrequiresabitofworknormally.Fortunatelywehaveeliminatedmostofit,againthroughtheuseoflibraries.ThelibrariesrequiredforoptimumuseofthisEEPROMstorageincludes:#include <due_wire >ThislibraryletsusmaketheserialcommunicationschanneltotheEEPROMchipthroughArduinoSCAandSCLpinsLOOKlikeasimpleserialchannel.Wecaninitializethisas:#include <Wire_EEPROM.h>CollinKidderaccesstheEEPROMchip–revisedforArduinoDueandthelarger256KBEEPROMsize#include <eepromAny.h>Thislibrarygreatlysimplifiesthestorageofmultibytevariables.

We also have to initialize our EEPROM. We use Arduino Due Serial3 to communicate with the EEPROM.

EEPROM.setWPPin(19);

Serial3.begin(2400);

Page 28: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 28

STORINGVARIABLESTOEEPROMAgain,EEPROMisreallyaseriesof8-bitbytes.ButthevariousdatatypesinC++canbemuchlonger.eepromAnymakesthismucheasiertodealwith.

EEPROM_write(address, variable); Theaddresscanbeanyunsignedintegeraddressfrom0to266,143.Andthevariablecanbeanynamedvariableofanyofthebasictypes.Forexample:

float amperehours=121.32;

uint_8t AHaddress = 1200;

EEPROM_write(AHaddress, amperehours); Thevariableamperehoursisactuallyafour-bytefloatingpointvariablecontainingthevalue121.32.Wearestoringitatlocation1200.YouAREtaskedwithkeepingawareofthelengthofyourvariableswhenassigninglocations.Thelibrarieswillquiteallowyoutodothefollowing:

EEPROM_write(AHaddress, amperehours);

EEPROM_write(1202, 1034589); Sinceamperehoursrequires4bytes,youhavejustwrittenthevalue1,034,589toEEPROM,butyou’veoverwrittentheamperehoursvariablestoredtherebecauseyouwroteittolocation1202,whichwasalreadybeingusedbytheamperehoursvalueyouwroteinthepreviousline.Soyousee,someawarenessofmemorygeometryisrequired.

RETRIEVINGVARIABLESFROMEEPROMRetrievingvariablesfromEEPROMisactuallyeveneasier.

EEPROM_read(address, variable);

Page 29: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 29

Thesyntaxisessentiallythesame.Thedatastoredataddresswillbecopiedintothevariableinyourprogrambythatname.

EEPROM_read(AHaddress, amperehours); Itwouldbeveryunusualtoneed266,144bytesofstorageforwhatisusuallyahandfulofconfigurationvariables.ButinrecentyearsEEPROMchipshavebecomeveryinexpensive–lessthan$4forthemostpart.Andthedifferenceinpricebetweena4KBanda256KBchipisbasicallynil.Weprovide256KBasyoumaywanttohavearoutinethat“logs”acertainamountofdatatothechipandperhapsanotherthatprintsthatlogouttheserialporttoyourcomputer.Youcouldthencapturethatasatextfile,andimporttoMicrosoftExcel.

PAGEMODEWritingtoEEPROMviaserialSCL/SCAinvolvesabitoftime.AnditisveryimportanttonottrytowritetoitWHILEitiswritingtoit.Therearewaysusinginterruptstodojustthat.Additionally,EEPROMsarelifelimitedtothenumberofwritesyoucanperformonthechipitself.Thisparticularchiphasaratherlongwritelifeof4,000,000operations.ButifyoudothisinyourLOOPsection,itdoesn’ttakelongtoevenbreachthatlimitat84MHz.TheEEPROMisactuallyarrangedin1024individual“pages”of256byteseach.Itcanbeanadvantagetowriteanentirepageatatime.ThisactuallyREDUCESthetimeyouspendwritingtoEEPROM,whichisabitcounterintuitive.Fortunately,Mr.KidderhasprovidedusapagemodeoperationinhisWire_EEPROMlibrary.ThefirstthingwewanttodoisdefineaCLASScontainingnothingbutpublicvariables.Thesevariablescanincludeanykindofexistingvariablesorevenstructureswithintheclass.ThisclassisdefinedimmediatelyafterourincludestatementsandsotheclassanditsvariablesbehaveessentiallyasGLOBALvariablesaccessiblefromanywhereintheprogram.

Page 30: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 30

#include <Arduino.h>

#include <due_can.h>

#include <due_wire.h>

#include "variant.h"

#include <Wire_EEPROM.h>

class EEPROMvariables {

public:

uint8_t CANdo

uint16_t voltage;

uint16_t current;

uint16_t terminate;

float AH;

float kilowatthours;

};

EEPROMvariables myVars;

Immediatelyaftertheclass,weinstantiateanobjectofthatclass.HerewearecallingtheclassEEPROMvariablesandwehaveinstantiatedanobjectmyVarsinthisclass.Fromthatpoint,anywhereinourprogamwecanreadandwritetoanyofthosevariablesveryquicklysimplybyusingthemintheformofmyVars.voltage, myVars.current, myVars.AH, myVars.kilowatthours,etc.Inoursetup,wewanttoinitializeourconnectiontoEEPROMandloadourlastsavedpageofthesevariables.

void setup(){

Wire.begin();

EEPROM.setWPPin(19);

EEPROM.read(200, myVars);

}

Page 31: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 31

TheEEPROM.readcommandnamesthenumericpage(somevaluebetween0and1023andtheobject.Itthenloadsthatspecificpageofmemoryintotheobjectusingthestructureofthevariablesintheclass.Thememoryrequirementsoftheclasscanofcoursebesmallerthanthe256bytepage,buttheyCANNOTbelongerthan256bytes.IfyouneedmoreEEPROMvariables,youwillhavetodefinemoreinstancesofyourobjectandkeepthemonDIFFERENTpages.ThefirsttimewedoSETUPofcoursethepagewillbeemptyandasaresultsowillallourvariables.ButifsomewhereinourprogramwedoaEEPROM.write(200, myVars);thenthosevariables,inwhateverstatewehadtheminandcontainingwhateverdatawestoredthere,wouldbewrittentothatpageinEEPROM.Thenexttimewepowercyclethedevice,thestoreddatawouldbeloadedcorrectlyintoourmyVars object.Inthisway,wecanusethesevariablesquicklyandcontinuouslyinourprogram.ButweonlyactuallysavethemtoEEPROMoccasionally.Howoccasionally,itdependsonthetimenatureofyourdata.Intheexampleabove,weareaccumulatingamperehoursinthevariablemyVars.AHandweareupdatingthisevery20millisecondsorso.Ifwefailedtosavethisforaperiodofsay,5seconds,wewouldpotentiallylosethelast5secondsofaccumulationworstcase.Icanlivewithit.Itisn’tthatmuch.ButhowoftenyouactuallywritetoEEPROMisafunctionofhowtimesensitiveyourdatais.Oftenyouaresimplystoringconfigurationoptionsforyourprogramandtheysimplyarenottimesensitiveatall.

void loop(){

if(millis()-lastime >5000)

{

lastime=millis();

EEPROM.write(200, myVars);

}

} Inourloopabove,weusethebuilt-inArduinosfunctionmillis()todeterminethepassageoftime.Milliswillreturnthenumberofmillisecondssincethelastpowercycle.Ifitisgreaterthan5000msor5seconds,wearegoingtoexecutetheselines.

Page 32: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 32

Thefirstthingwedoisresetourtimerbysettinglastimetomillis().ThenwewritemyVars topage200ofourEEPROM.OnthenextLOOPpass,andforseveralhundredsofthousandsofothers,whenwecomparemillis()tolastime,itisgoingtobelessthan5000foralongtime.Inthisway,wecanhavereadyandimmediateaccesstoanumberofvariablesofentirelydifferenttypes,butstillstorethemtoEEPROMsotheywillbeavailablethenexttimewepowercycle.This,whileminimizingthewritestoourlifelimitedEEPROM.

MICROSDCARDSLOTUSETheCANDueboardfeaturesamicroSDcardslotcapableofholdingverysmallSDcards.Inrecentyears,thedatastoragecapacityofthesetinycardshasgrownenormously–256GBormore.Filescanbecreated,removed,writtento,andreadfromusingthefamiliarDOSFAT16or32fileformatusingfilenamesinthefamiliar8.3format(uptoeightnamecharactersplusthreecharacterextension).FAT16isgoodupto2GB.Forfilesabove2GByoumustuseFAT32astheformat.Thisfeatureprovidesenormousdataloggingcapacityinaremovablemedium.TheArduinoDueaccessesthedatacardslotthroughadedicatedSerialPeripheralInterface(SPI)asixpinconnectorinthecenteroftheboard.SerialPeripheralInterface(SPI)isasynchronousserialdataprotocolusedbymicrocontrollersforcommunicatingwithoneormoreperipheraldevicesquicklyovershortdistances.Itcanalsobeusedforcommunicationbetweentwomicrocontrollers.WithanSPIconnectionthereisalwaysonemasterdevice(usuallyamicrocontroller)whichcontrolstheperipheraldevices.Typicallytherearethreelinescommontoallthedevices:MISO(MasterInSlaveOut)-TheSlavelineforsendingdatatothemaster,MOSI (MasterOutSlaveIn)-TheMasterlineforsendingdatatotheperipherals,

Page 33: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 33

SCK(SerialClock)-Theclockpulseswhichsynchronizedatatransmissiongeneratedbythemasterandonelinespecificforeverydevice:SS(SlaveSelect)-thepinoneachdevicethatthemastercanusetoenableanddisablespecificdevices. Whenadevice'sSSpinislow,itcommunicateswiththemaster.Whenit'shigh,itignoresthemaster.ThisallowsyoutohavemultipleSPIdevicessharingthesameMISO,MOSI,andCLKlines.ThemicroSDcardreaderusesdigital output pin 10astheSS. BywayoftriviayouprobablydoNOTneedtoprogramthiscard,ontheArduinoDueversiononly:MISOusesdigitalpin75MOSIusesdigitalpin74SCKusesdigitalpin76VerylittleofthisisnecessarytosuccessfullyusethemicroSDcardslot.WhatyouDOneed:

1. PreformatedmicroSDcard.ThisshouldbeformattedusingyourPCorMACideallyforDOSFAT16butcanbeFAT32.

2. SPI.hlibrary3. SD.hlibrary

ItisimportantthattheSDcardbeproperlyformatted.Generally,youwillgetmuchbetterperformancebyNOTusingtheutilitiesonyourMacintoshorMicrosoftWindozePC.TheSDCardAssociationhasawebsiteathttps://www.sdcard.org/downloads/formatter_4/.TheyactuallyhavesomeverygoodsoftwareforformattingthesecardsthatgreatlyimprovesaccessspeedfortheArduino.ThetwolibrarieshaveactuallymadeitintotheArduinoIDEsoyoudonotactuallyhavetogetthemandaddthem.

#include<SPI.h>

#include<SD.h> Youalsoneedtoestablishpin10asyourSlaveSelectpin

Page 34: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 34

pinMode(10, OUTPUT); NotethatthelibraryalreadyestablishestheSSconstantaspin10.

// see if the card is present and can be initialized:

if (!SD.begin(SS))

{

Serial.println("Card failed, or not present");

return;

}

else Serial.println("card initialized."); TouseanSDcard,wearefortunatetohavetheSDlibrarywrittenbyWilliamGreiman. TheSD.hlibrarygivesustwonew“classes”youcanuseinyourprograms.Aclassprovidesadditionalcommandsspecifictothedevicethatarenotnormallypartofthebasicprogramminglanguage.They“extend”thelanguagetoaccessthefunctionsofthenewhardware.ThetwonewclassesaretheSDclassandtheFILEclass.

SDCLASSTheSDclassprovidesfunctionsforaccessing theSDcardandmanipulatingitsfilesanddirectories.

• begin() SD.begin(10) //opens communications to SDcard

• exists()

SD.exists(logger.txt); //Returns TRUE if file logger.txt exists. 8.3 filenames.

• mkdir()

SD.mkdir(root/jack/stuff) //Creates directory

Page 35: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 35

• open() File dataFile=SD.open(example.txt); //Opens example.txt file for READ beginning at byte one. Note definition of dataFile as type File. This is your file handle.

File dataFile=SD.open(/JACK/example.txt, FILE_WRITE) //Opens file for both reading AND writing starting at END of file

• remove()

SD.remove(/JACK/example.txt) //Removes file rmdir() SD.rmdir(/JACK/STUFF) //Removes directory

FILECLASSTheFileclassallowsforreadingfromandwritingtoindividualfilesontheSDcard. • available()

dataFile.available(); //This would return the number of bytes in the dataFile instance of the File class (returned by SD.open())

• close()

dataFile.close(); //Closes the file designated by the dataFile file handle. Writes any data written to the file to the SD card.

Page 36: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 36

• flush() dataFile.flush(); // Ensures that any bytes written to the file are physically saved to the SD card. This is done automatically when the file is closed.

• peek()

dataFile.peek(); //Returns the value at the current file position but does not increment file pointer.

• position()

dataFile.position();//Returns the position of the current file pointer (long integer)

• print()

dataFile.print(data, BASE);// Print data to the file, which must have been opened for writing. Prints numbers as a sequence of digits, each an ASCII character (e.g. the number 123 is sent as the three characters '1', '2', '3'). Optional BASE of BIN, DEC, OCT or HEX

• println()

dataFile.println (data, BASE);// Same as print() but it terminates string with carriagereturn and newline characters.

• seek()

dataFile.seek(pos); //Set file pointer to pos in file • size() dataFile.size(); // Return size of file in bytes

Page 37: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 37

• read() dataFile.read(); //Returns next byte in file or -1 if end

• write() dataFile.write(data); // the byte, char, or string (char *) to write

dataFile.write(buf, len); // buf: an array of characters or bytes len: the number of elements in buf

• isDirectory()

dataFile.isDirectory();//Returns true if directory

• openNextFile() dataFile.openNextFile(); //If dataFile is dir, returns next file in directory

• rewindDirectory() dataFile.rewindDirectory(); //Resets to first file in directory

#include<SD.h>

const int SS = 10; //Set SS as pin 10

File datafile;

if (!SD.begin(SS))

{

Serial.println("Card failed, or not present");

return;

}

else Serial.println("card initialized.");

Page 38: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 38

dataFile = SD.open("datalog.txt", FILE_WRITE); // if the file is available, write to it: if (dataFile)

{ dataFile.println(“Hello World…”); dataFile.close();

if (SD.exists("datalog.txt")) {

Serial.println(datalog.txt exists."); SD.remove("example.txt"); }

FILE myFile = SD.open("datalog.txt"); if (myFile)

{ while (myFile.available())

{ Serial.write(myFile.read()); } myFile.close();

uint32_t volumesize; Sd2Card card; SdVolume volume; SdFile root Serial.print("\nVolume type is FAT"); Serial.println(volume.fatType(), DEC); Serial.println(); volumesize = volume.blocksPerCluster(); // clusters are collections of blocks volumesize *= volume.clusterCount(); // we'll have a lot of clusters

Page 39: CAN Due2.2 User Manualmedia3.ev-tv.me/CAN Due2.2 User Manual.pdf · SD memory card reader was originally designed by Paulo Almeida and Celso Menaia of Lisbon Portugal and produced

EVTVMotorWerks Version2.20 Septemeber2017

Copyright 2015 – EVTV LLC 39

volumesize *= 512; // SD card blocks are always 512 bytes Serial.print("Volume size (bytes): "); Serial.println(volumesize); Serial.print("Volume size (Kbytes): "); Serial.println("\nFiles found on the card (name, date and size in bytes): "); root.openRoot(volume);