+ All Categories
Home > Documents > CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified...

CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified...

Date post: 30-Apr-2021
Category:
Upload: others
View: 3 times
Download: 0 times
Share this document with a friend
42
CONTROLLER AREA NETWORK PROTOTYPING WITH ARDUINO COPPERHILL TECHNOLOGIES https://copperhilltech.com
Transcript
Page 1: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

CONTROLLERAREANETWORK

PROTOTYPINGWITHARDUINO

COPPERHILLTECHNOLOGIES

https://copperhilltech.com

Page 2: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s
Page 3: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

CONTROLLERAREANETWORKPROTOTYPINGWITHARDUINObyWilfriedVossPublishedbyCopperhillTechnologiesCorporation158LogPlainRoadGreenfield,MA01301USACopyright©2014byCopperhillTechnologiesCorporationCoverDesignbyCopperhillTechnologiesCorporationNopartofthispublicationmaybereproduced,storedinaretrievalsystemortransmittedinanyformorbyanymeans,electronic,mechanical,photocopying,recording,scanningorotherwise, except as permitted under Sections 107 or 108 of the 1976 United StatesCopyrightAct,withoutthepriorwrittenpermissionofthePublisher.All trademarks or copyrights mentioned herein are the possession of their respectiveownersandCopperhillMediamakesnoclaimofownershipbythementionofproductsthatcontainthesemarks.“Arduino”isatrademarkoftheArduinoteam.ISBN-10:1938581164ISBN-13:978-1-938581-16-8Disclaimer:Whilethepublisherandauthorhaveusedtheirbestefforts inpreparingthisbook, they make no representations or warranties with respect to the accuracy orcompletenessofthecontentsofthisbookandspecificallydisclaimanyimpliedwarrantiesor merchantability or fitness for a particular purpose. No warranty may be created orextended by sales representatives or written sales materials. The advice and strategiescontained herein may not be suitable for your situation. You should consult with aprofessionalwhereappropriate.Neitherthepublishernorauthorshallbeliableforanylossorprofitoranyothercommercialdamages,includingbutnotlimitedtospecial,incidental,consequential,orotherdamages.

https://copperhilltech.com

Page 4: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

4

Page 5: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

I

FromtheAuthorItseemslikeamillionyearssinceIhadasolderingironinmyhandandthatIhavebeenengaging inmymost favoriteprogrammingactivity,namelyprogrammingofembeddedsystems. In thepast, Idid shyaway from theexpenses that camewithembedded programming, but with the emergence of inexpensive prototypingsystemssuchastheArduinoorRaspberryPithisconcerndoesn’texistanymore.Addtothisavirtuallynon-existinglearningcurve.WithmyArduinoUnoIorderedabook explaining Arduino Sketches, and I read it for about 30 minutes to scanthroughthemostimportantinformation.Thenittookmaybeanother30minutestogetmyfirstapplicationrunning.Iknow,IamjoiningtheenormousclubofArduinouserswhomadeandexpressedthesameexperience,butthatdoesn’tchangethefactthattheArduinoistheperfectenvironmentforprototypingofembeddedcomputersystems.Naturally,withmyknowledgeofallkindsofControllerAreaNetworktopics,Iwaseager to convert that knowledge into the real thing, namely a working CANapplication.ThatCANapplicationwillbethebasicsofanUSB-to-CANGatewaywithCAN networkmonitoring and diagnostic features as explained in the chapters tofollow.Fromhereon,withtheknowledgegainedthroughthisproject,Iencourageyou to letyourmind flowandextend theapplication.Thepossibilitiesareplenty.Enjoy!However, beforewe get there letme explain the approachofwriting this book: IcouldhaveengagedintowritingmanypagesaboutArduinobasics,whatitis,whereitcomesfrom,howtouseit,etc.,forthemerepurposeofaddingmorepagesand,asaresult,beingabletochargemoremoneyformybook.However,therearemyriadsofbooksonArduino,ArduinoSketches,andArduinoShieldsavailableinthemarket,andIwon’twasteyourmoneyortime.However,referencestoArduinobasicsmayappearbutonlyinpassing.Thatbeingsaid, thisbookassumessomeknowledgeoftheArduinohardwareanditsprogramming.ItalsoassumessomebasicknowledgeofControllerAreaNetwork(CAN).IwillreferbrieflytosomeaspectsofCAN,butthesearethemerebasicsoftheactualprotocol,justenoughtounderstandtheconcept.Inalltruth,thereisnoneedtounderstandalldetailsoftheprotocol,since100%oftheprotocolisimplementedonachip,theCANcontroller.Allweneedtodo in thisbook is toreceive, transmit,andprocessdata.Therestisuptoyourfantasy.

Page 6: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

II

Nevertheless, the CAN protocol utilizes some ingenious features, and if you areinterested in learning more, please refer to AComprehensibleGuide toControllerAreaNetworkasmentionedintheliteratureappendixofthisbook.Last, but not least, let me lose some words on my programming style that isdefinitelydifferentthanwhatyouusuallysee.Iputgreatemphasisnotonlyonreadabilityofcode;IalsohavedebugginginmindwhenIwritecode.IamusingaslightlymodifiedversionoftheHungarianNotation,meaninglookingatavariable’sorfunction’snameprovidesyousomeinformationabout its nature. For instance, the prefix n indicates an integer variable (e.g.nVariable). Inaddition,beingfamiliarwithanumberofprogramminglanguages, Iattempttokeepthebestofallworlds.Forinstance,Iaddcommentsbehindalmosteverybracket to indicate informationsuchasendiforendwhile,etc.,whichhelpsidentifyprogramblocks.ThismaybehelpfulforVisualBasicprogrammerswhoarenewtoC/C++programming.Like under Visual Basic, my functions/routines start with either Sub (the returncodeisvoid)orxFct(wherex indicatesthetypeofthereturncode,forinstance,nforinteger).AbouttheAuthorI am the author of the “Comprehensible Guide” series of technical literaturecoveringtopicslikeControllerAreaNetwork(CAN),SAEJ1939,IndustrialEthernet,andServoMotorSizing.IhaveworkedintheCANindustrysince1997andbeforethatwasamotioncontrolengineer inthepapermanufacturing industry. Ihaveamaster’s degree in electrical engineering from the University of Wuppertal inGermany.Duringthepastyears, Ihaveconductednumerousseminarsonindustrial fieldbussystems such as CAN, CANopen, SAE J1939, Industrial Ethernet, andmore duringvarious Real Time Embedded And Computing Conferences (RTECC), ISA(Instrumentation,Systems,andAutomationSociety)conferencesandvariousothereventsallovertheUnitedStatesandCanada.Ihadtheopportunityoftravelingtheworldextensively,butsettledinNewEnglandin1989.IpresentlyliveinanoldfarmhouseinGreenfield,Massachusettswithmyred-haired,green-eyedIrish-AmericanwifeandoursonPatrick.

Page 7: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

III

For more information on my works and to contact me, see my website athttps://copperhilltech.com.ContacttheAuthorDespiteallefforts inpreparingthisbook,thereisalwaysthepossibilitythatsomeaspectsor factswillnot findeverybody’sapproval,whichpromptsus,authorandpublisher,toaskforyourfeedback.Ifyouwouldliketoproposeanyamendmentsorcorrections, please send us your comment. We look forward to any support insupplementingthisbook,andwewelcomealldiscussionsthatcontributetomakingthetopicofthisbookasthoroughandobjectiveaspossible.To submit amendments and corrections please log on to the author’s website athttps://copperhilltech.com/contact-us/andleaveanote.CodeAndProjectsDownloadAny additional information created after the publishing date of this book plusproject & source code (Arduino andWindows) are available as a free downloadthrough the author’s website at https://copperhilltech.com/controller-area-network-can-prototyping-with-arduino/

Page 8: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

TableofContent1.IntroductiontoControllerAreaNetwork..................................................................................12.PrototypingHardwareanditsVariants......................................................................................32.1Arduino..............................................................................................................................................32.2IntelGalileo......................................................................................................................................42.3LeafLabsMapleMicrocontrollerBoard...............................................................................4

3.ArduinoCANShields...........................................................................................................................53.1MicrochipMCP2515CANController....................................................................................53.2ArduinoCAN-BusShieldbySKPangelectronics............................................................73.3CAN-BUSShieldbySeeedStudio............................................................................................9

4.ArduinoCANSketches.....................................................................................................................104.1TheMCP2515Library..............................................................................................................114.1.1FunctionCalls......................................................................................................................114.1.2Implementation..................................................................................................................12

4.2CANProgramming.....................................................................................................................134.2.1SimpleCANShieldTest...................................................................................................134.2.2ExtendedCANShieldTest.............................................................................................154.2.3ASimpleCANNetworkMonitoringandDiagnosticsProgram......................17

4.3CANNetworkMonitoringunderWindows.....................................................................255Conclusion.........................................................................................................................................31

Appendix–RecommendedLiterature..........................................................................................33

Page 9: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

1

1.IntroductiontoControllerAreaNetwork

ControllerAreaNetwork (CAN) isa serialnetwork technology thatwasoriginallydesigned for the automotive industry, especially for European cars, but has alsobecomeapopular bus in industrial automation aswell as other applications. TheCAN bus is primarily used in embedded systems, and as its name implies, is anetwork technology thatprovides fast communicationamongmicrocontrollersuptoreal-timerequirements,eliminating theneed for themuchmoreexpensiveandcomplextechnologyofaDual-PortedRAM.CAN isa two-wire,halfduplex,high-speednetworksystem, that is farsuperior toconventional serial technologies such as RS232 in regard to functionality andreliabilityandyetCANimplementationsaremorecosteffective.

While,forinstance,TCP/IPisdesignedforthetransportoflargedataamounts,CANisdesignedforreal-timerequirementsandwithits1MBit/secbaudratecaneasilybeat a 100 MBit/sec TCP/IP connection when it comes to short reaction times,timelyerrordetection,quickerrorrecoveryanderrorrepair.CAN networks can be used as an embedded communication system formicrocontrollersaswellasanopencommunicationsystemfor intelligentdevices.Someusers,forexampleinthefieldofmedicalengineering,optedforCANbecausetheyhavetomeetparticularlystringentsafetyrequirements.Similar requirements had to be considered bymanufacturers of other equipmentwithveryhighsafetyorreliabilityrequirements(e.g.robots,liftsandtransportationsystems).Thegreatest advantageofControllerAreaNetwork lies in the reducedamountofwiring combinedwith an ingenious prevention ofmessage collision (meaning nodatawillbelostduringmessagetransmission).

Page 10: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

2

WithoutCAN WithCANThefollowingshowsaneed-to-knowoverviewofCAN’stechnicalcharacteristics.ControllerAreaNetwork

• Isaserialnetworkingtechnologyforembeddedsolutions.

• NeedsonlytwowiresnamedCAN_HandCAN_L.

• Operatesatdataratesofupto1Megabitpersecond.

• Supportsamaximumof8bytespermessageframe.

• Doesnot supportnode IDs,onlymessage IDs.Oneapplicationcan support

multiplemessageIDs.

• Supports message priority, i.e. the lower the message ID the higher its

priority.

• SupportstwomessageIDlengths,11-bit(standard)and29-bit(extended).

• Doesnotexperiencemessagecollisions(astheycanoccurunderotherserial

technologies).

• Is not demanding in terms of cable requirements. Twisted-pair wiring is

sufficient.

Note:FormoredetailedinformationonCAN,pleasereferto“AComprehensibleGuidetoControllerAreaNetwork”asmentionedintheliteratureappendixofthisbook.

Page 11: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

3

2.PrototypingHardwareanditsVariants

As I hadmentioned earlier in this book, it is assumed that you have some basicknowledge of the Arduino, Arduino Sketches, and Arduino Shields. I willneverthelesstaketheopportunityofmentioningtheprototypinghardwareanditsvariants.ItisimportanttoknowthattheArduino,eventhoughperfectforprototypingduetoits low price and ease of programming, is not, in its bare form, an industrial-strengthsolution,notonlyintermsofenvironmentalspecs(e.g.temperaturerange,etc.)butalsointermsofexecutionspeedandmemoryresources.Specifically,whenitcomestoCANapplicationsat1Mbit/secandhighdatatraffic,the Arduino may reach its limits quickly. There are, however, advanced and yetcompatiblealternativestotheArduinoasexplainedinthefollowingchapters.2.1Arduino

In order to develop and test the sampleprograms(sketches)asshowninthisbook,Iused the Arduino Uno. The hardwareconsists of an open-source hardware board,usuallydesignedaroundan8-bitAtmelAVRmicrocontroller with 2 KB RAM (workingmemory), 32 KB Flash Memory (sketches)and1KBEEPROM(non-volatile).Thesetechnicalspecificationsaremorethansufficient for basic prototyping of CAN

applications and the proof of concept. However, to re-iterate the point, withgrowingdemandsforexecutionspeedandextendedfunctionality,theArduinomayquicklyreachitslimits.Note: All Arduino programs (sketches) as shown in this book were developed andtestedwiththeArduinoUno.Thereisnoguaranteethattheseprogramswillwork“asis”onanyothercompatiblesystem.

Page 12: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

4

2.2IntelGalileo

TheIntelGalileoisamicrocontrollerboardbased on the Intel® Quark SoC X1000Application Processor, a 32-bit IntelPentium-class system on a chip. It isdesignedtobehardwareandsoftwarepin-compatible with Arduino shields designedfortheUnoR3.The Galileo board is also softwarecompatible with the Arduino softwaredevelopment environment, which should

makeusabilityandintroductionasnap.InadditiontoArduinohardwareandsoftwarecompatibility,theGalileoboardhasseveral PC industry standard I/O ports and features to expand native usage andcapabilitiesbeyondtheArduinoshieldecosystem.Afullsizedmini-PCIExpressslot,100MbEthernetport,Micro-SDslot,RS-232serialport,USBHostport,USBClientport,and8MByteNORflashcomestandardontheboard.The CPU is a 400MHz 32-bit Intel®Pentium instruction set architecture (ISA)-compatibleprocessor,andthereisupto8MByteofFlashavailable.(Source:GalileoDatasheetbyIntel) For more information see: http://www.intel.com/content/www/us/en/do-it-yourself/galileo-maker-quark-board.html.2.3LeafLabsMapleMicrocontrollerBoard

As similar as it may be to the Arduino, thedifferencesarewhatreallymaketheMaplestandout. It harnesses the power of a 32-bit ARMCortex-M3clockedat72MHztopush39GPIOs,16analog pins, 12-bit ADC resolution and 15 PWMpins at 16-bit resolution. In order to make sureyouhaveplentyofprogrammingroomtoflexthathardware,theMaplealsoprovides128kFlashand20KBSRAM.AllofthisperformanceisdeliveredinthesameformfactorastheArduinoPro.

Page 13: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

5

IfyourcurrentArduino-basedprojectispushingagainsttheperformancelimitsoftheATmega,portingitovertoMaplemaybethefastestandeasiestwaytocontinuedevelopingyourprojectwithoutstartingfromscratch.Byswappingthepopular"avr-gcc"compilerwithCodeSourcery's"arm-none-eabi-gcc," LeafLabsmanages to provide a nearly identical programming experience toArduino despite targeting a completely different architecture. Also, while someArduino shields are incompatible due to certain capabilities being allocated todifferentpins,severalofthemarecurrentlysupportedandtherearemoretocome.ThereisalsoaguideavailableontheproductpageforportingArduinolibrariesandsourcecodeovertoMaple.(Source:LeafLabsopenelectronics)Formoreinformationsee:http://leaflabs.com/docs/hardware/maple.html3.ArduinoCANShields

Since Controller Area Network (CAN) is predominantly targeted at industrialsolutions(versusthevastlymorepopularUSBfornon-industrialusesuchashomeandlab),therearen’ttoomanychoicesavailableinthemarket.Throughsomeresearch(i.e.browsing)Ifoundtwoverysimilarsolutions,andtheyboth work with the same CAN library (as explained in a later chapter). Bothsolutions use the Microchip MCP2515 CAN controller. Also, both solutions aredistributedthroughworldwideonlineresources.3.1MicrochipMCP2515CANController

MicrochipTechnology’sMCP2515isastand-aloneControllerAreaNetwork(CAN)controller that implements the CAN specification, version 2.0B. It is capable oftransmitting and receiving both standard and extended data and remote frames.TheMCP2515hastwoacceptancemasksandsixacceptancefiltersthatareusedtofilter out unwanted messages, thereby reducing the host MCUs overhead. TheMCP2515 interfaceswithmicrocontrollers (MCUs)viaan industrystandardSerialPeripheralInterface(SPI).Thefeaturesincludetworeceivebufferswithprioritizedmessagestorage,six29-bitfilters, two29-bitmasks, and three transmitbufferswithprioritizationandabortfeatures.(Source:MicrochipDatasheet)Note: CAN specification 2.0B refers to the capability of using standard CAN frameswith11-bitmessageidentifierplustheextendedformatwitha29-bitmessageID.

Page 14: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

6

TodownloadthefullMCP2515datasheetlogonto:http://ww1.microchip.com/downloads/en/DeviceDoc/21801G.pdfBoth CAN shields as described in the following chapters utilize the MicrochipMCP2551CANtransceiver,whichconvertstheinternalTTLsignalstoadifferentialvoltageasdemandedbytheCANstandard.TodownloadthefullMCP2551datasheetlogonto:http://ww1.microchip.com/downloads/en/DeviceDoc/21667f.pdf

Page 15: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

7

3.2ArduinoCAN-BusShieldbySKPangelectronics

This shield by SK Pang electronicsprovidestheArduinoCAN-Buscapability.As explained previously, it uses theMicrochipMCP2515CANcontrollerwithMCP2551 CAN transceiver. The CANconnection is realized via a standard 9-way sub-D, however the pin assignmentfor CAN_H, CAN_L is not according tostandard.

Note:Inalltruth,thereisnomandatorystandardforpinassignment,buttheindustryusespins2(CAN_L)and7(CAN_H)asavirtualstandard.Irecommendusingtheon-boardCAN_LandCAN_HcontactstosoldertheCANcabledirectlytotheboard.The shield also comes with a uSD card holder, a serial LCD connector, and aconnector for anEM406GPSmodule,making this shield suitable for data loggingapplication.Features

• CANv2.0Bupto1Mb/s• HighspeedSPIInterface(10MHz)• Standardandextendeddataandremoteframes• CANconnectionviastandard9-pinsub-Dconnector• Asanoption,powercanbesuppliedtotheArduinobysub-Dviaresettable

fuseandreversepolarityprotection.• SocketforEM406GPSmodule• MicroSDcardholder• ConnectorforserialLCD• Resetbutton• Joystickcontrolmenunavigationcontrol• TwoLEDindicator

Page 16: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

8

Notes

• Nocablesincluded• Headerpinsarenotincluded;theymustbeorderedseparately• PinassignmentforCAN_H,CAN_Lnotaccordingtostandard

AlltechnicalinformationregardingtheuseoftheCANcontroller,uSDcardholder,joystick,LEDs,etc.canbefoundonthecompany’swikiwebsiteat:https://code.google.com/p/skpang/OrderingInformationToordertheSKPangele3ctronicsCANshield,youcanusethefollowingresources(orbrowsefor“ArduinoCAN-BUSShield”forfurtheroptions):Sparkfun-https://www.sparkfun.com/products/10039SK Pang electronics - http://skpang.co.uk/catalog/arduino-canbus-shield-with-usd-card-holder-p-706.html

Page 17: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

9

3.3CAN-BUSShieldbySeeedStudio

In terms of CAN capabilities, theshield by Seeek Studio provides thesame functionality as the one by SKPang electronics, however, it comeswithamuchlowerpricetag,becauseit does not have any additionalcomponents besides the CANinterface.Overall, the device makes a solidimpression,especiallysincetheCANconnection is according to standardand in addition provides CANconnectivity through easily

accessibleterminals.Features

• ImplementsCANV2.0Batupto1Mb/s• SPIInterfaceupto10MHz• Standard(11bit)andextended(29bit)dataandremoteframes• Tworeceivebufferswithprioritizedmessagestorage• Industrialstandard9pinsub-Dconnector• TwoLEDindicators

Notes

• NocablesincludedAll technical informationregarding theuseof theCANcontrollercanbe foundonthecompany’swikiwebsiteat:http://www.seeedstudio.com/wiki/CAN-BUS_ShieldOrderingInformationTo order the Seeed Studio CAN shield, you can use the following resources (orbrowsefor“ArduinoCAN-BUSShield”forfurtheroptions):SeeedStudio-http://www.seeedstudio.com/depot/CANBUS-shield-p-2256.html

Page 18: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

10

Importanttoknow:TheSeeedStudioCANbusshieldhasbeenundergoingsomehardware changes tobecome compatiblewith systems such as theArduinoMega2560.Theversion1.0willworkwiththeArduinoUno,whileallhigherversionsalsoworkwith theMega 2560. Thiswill also affect the code of the Arduino projects,specificallytheline“MCP_CANCAN0(10);”inthemainmoduleselectingtheCSpin.Thatlinemustchangeto“MCP_CANCAN0(9);”forallCANbusshieldversionsabove1.0.Ihaveaddedacommentinthecorrespondingsectionofthecode.4.ArduinoCANSketches

The implementation of either one of the introduced CAN-BUS Shields and thecorrespondingCANsketcheswentsurprisinglysmoothwhenpairedwiththerightlibrarysoftware.IfoundseveralsourcecodesforaccessingtheMCP2515CANcontroller,butmostofthemdidn’tevenpasstheinitialqualitycontrolphase(IreadthecodefirstbeforeIuse it). One of the quality criteria was the support for 29-bit CAN messageidentifiers (CAN 2.0B Compatibility), which is mandatory when it comes toimplementing,forinstance,theSAEJ1939vehiclenetworkprotocol.SomesoftwaresamplesIfoundwerejustliterally“samples”andtheyleftampleroomforguessinggames.IwasmostpleasedbytheMCP2515LibrarybyCoryFowler,whichcanbefoundathttps://github.com/coryjfowler/MCP2515_libThislibraryiscompatiblewithanyshieldorCANinterfacethatusestheMCP2515CANprotocolcontroller.

Page 19: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

11

InordertotestandverifythepropertransmissionandreceptionofCANmessages,IusedtheADFwebCAN-to-USBgatewaywithitsWindowsinterface.Note: InordertotestaCANapplication,youneedatleasttwoCANnodestoestablishanetworkcommunication.ThesecondnodecanbeanotherArduinowithCANshieldor(ifthebudgetallows)anotherCANdevicewithCANdatamonitoringcapabilities.4.1TheMCP2515Library

Aswithanyserialnetworkingcontroller,theessentialfunctionsare:

1.Initialization2.ReadData3.WriteData4.CheckStatus

IncaseoftheMCP2515library,thesefunctionsarerepresentedby:

1.Initialization:CAN0.begin2.ReadData:CAN0.readMsgBufincl.CAN0.checkReceive,CAN0.getCanId3.WriteData:CAN0.sendMsgBuf4.CheckStatus:CAN0.checkError

4.1.1FunctionCalls

Function: CAN0.beginPurpose: InitializestheCANcontrollerandsetsthespeed(baudrate)Parameter: CAN_5KPS…CAN_1000KPS(Seemcp_can_dfs.h)ReturnCode: CAN_OK=Initializationokay CAN_FAILINIT=InitializationfailedFunction: CAN0.checkReceivePurpose: CheckifmessagewasreceivedParameter: None

Page 20: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

12

ReturnCode: CAN_MSGAVAIL=Messageavailable CAN_NOMSG=NomessageFunction: CAN0.readMsgBufPurpose: ReadthemessagebufferParameter: nMsgLenreturnsthemessagelength(numberofdatabytes) nMsgBufferreturnstheactualmessageReturnCode: NoneFunction: CAN0.getCANIdPurpose: RetrievestheIDofthereceivedmessageParameter: NoneReturnCode: m_nID=MessageIDFunction: CAN0.sendMsgBufPurpose: SendamessagebufferParameter: id=MessageID ext=CAN_STDID(11-bitID)orCAN_EXTID(29-bitID) len=Numberofdatabytes(0…8) buf=MessagebufferReturnCode: NoneFunction: CAN0.checkErrorPurpose: ChecksCANcontrollerforerrorsParameter: NoneReturnCode: CAN_OK=Statusokay CAN_CTRLERROR=ErrorTherearefurtherfunctions,amongothers,formessagefilteringandsettingsmasks,andtheyareworthbeingcheckedoutformoresophisticatedfunctions,buttheyarenotnecessaryforsimpleCANcommunicationtasks.4.1.2Implementation

The implementationof theMPC2515 library is fairlyeasy:OpenArduino,createanewfile,thenusethemenuitemsSketch->AddFile…toincludethefollowingfilestotheproject:

• mcp_can.cpp• mcp_can.h• mcp_can_dfs.h

Page 21: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

13

IntheArduinoprojectfileaddthefollowingontop:#include"mcp_can.h"#include<SPI.h>MCP_CANCAN0(10);Letmerepeathere:TheSeeedStudioCANbusshieldhasbeenundergoingsomehardware changes tobecome compatiblewith systems such as theArduinoMega2560.Theversion1.0willworkwiththeArduinoUno,whileallhigherversionsalsoworkwith theMega 2560. Thiswill also affect the code of the Arduino projects,specificallytheline“MCP_CANCAN0(10);”inthemainmoduleselectingtheCSpin.Thatlinemustchangeto“MCP_CANCAN0(9);”forallCANbusshieldversionsabove1.0.Youarenowreadytogo.Thefollowingchapterswilldescribehowtoimplementthefunctioncalls.4.2CANProgramming

ThemostexcitingpartaboutthisprojectiswhenitcomestothepointwheretwoCAN nodes communicate with each other. I started off with writing a simpleprogramthatsentmessagesthatwerereceivedbymyUSB-to-CANgatewayanditsWindows monitoring software. From there on, I extended the program to alsoreceiveCANmessagesanddisplaythemontheArduinoserialmonitor.In a later chapter, I will also show a Windows programming example thatestablishesacommunicationwiththeArduino.4.2.1SimpleCANShieldTest

The following represents a very simple CAN test program that periodically (i.e.every1second)sendsoutaCANmessagewitha29-bitidentifieratabaudrateof250kbit/sec.// Simple CAN Shield Test #include "mcp_can.h" #include <SPI.h> MCP_CAN CAN0(10); // Set CS to pin 10 unsigned char stmp[8] = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37}; // SYSTEM: Setup routine runs on power-up or reset void setup() { // Set the serial interface baud rate

Page 22: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

14

Serial.begin(9600); // Initialize the CAN controller // Baud rates are defined in mcp_can_dfs.h if (CAN0.begin(CAN_250KBPS) == CAN_OK) Serial.print("CAN Init OK.\n\r\n\r"); else Serial.print("CAN Init Failed.\n\r"); }// end setup // Main Loop - Arduino Entry Point void loop() { // Send data: id = 0x1FF, extended frame, data len = 8, stmp: data buf // ID mode (11/29 bit) defined in mcp_can_dfs.h CAN0.sendMsgBuf(0x1FF, CAN_EXTID, 8, stmp); // Run in 1 sec interval delay(1000); }// end loop

While the code is short and sufficiently self-explanatory, letme explain the stepstakenintheprogram.In thesetup() routine, theprograminitializes theserial interface(USB) toabaudrateof9600bps (Pleasemakesure thatyourArduinoserialmonitor is set to thesamerate).It then initializes the CAN controller to a data transmission rate of 250 kbits/secanddisplayspossibleerrormessagesontheArduinoserialmonitor.Inthemainloop()routine,theprogramsendsan8-byteCANmessageusinganIDof 0x1FF in extendedmessaging format (29-bitmessage ID). The actualmessage(unsignedcharstmp[8]inthisexample)containsastringfromASCII0to7,whichcanbeeasilyspottedwhenusingadatamonitoringsoftware.Using my test conditions, the message was received through the USB-to-CANgatewayanddisplayedunderWindows:

Page 23: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

15

While this program may not be very useful without a CAN monitoring software(meaning you can’t see the result), in the least it demonstrates how simple CANprogrammingcanbe.4.2.2ExtendedCANShieldTest

Inthisnext,extendedexample,weusethesameprogramasshowninthepreviouschapterbutaddaCANreceivingroutinetoit.Theresult,i.e.thereceivedmessages,willbedisplayedthroughtheArduinoserialmonitor.// Simple CAN Shield Test #include <stdlib.h> #include "mcp_can.h" #include <SPI.h> MCP_CAN CAN0(10); // Set CS to pin 10 // Test message unsigned char stmp[8] = {0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37}; // SYSTEM: Setup routine runs on power-up or reset void setup() { // Set the serial interface baud rate Serial.begin(9600); // Initialize the CAN controller // Baud rates defined in mcp_can_dfs.h if (CAN0.begin(CAN_250KBPS) == CAN_OK) Serial.print("CAN Init OK.\n\r\n\r"); else

Page 24: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

16

Serial.print("CAN Init Failed.\n\r"); }// end setup // Main Loop - Arduino Entry Point void loop() { // Declarations byte nMsgLen = 0; byte nMsgBuffer[8]; char sString[4]; // Send out a test message // Send data: id = 0x1FF, extended frame, data len = 8, stmp: data buf // ID mode (11/29 bit) defined in mcp_can_dfs.h CAN0.sendMsgBuf(0x1FF, CAN_EXTID, 8, stmp); // Check for a message if(CAN0.checkReceive() == CAN_MSGAVAIL) { // Read the message buffer CAN0.readMsgBuf(&nMsgLen, &nMsgBuffer[0]); INT32U nMsgID = CAN0.getCanId(); // Print message ID to serial monitor Serial.print("Message ID: 0x"); if(nMsgID < 16) Serial.print("0"); Serial.print(itoa(nMsgID, sString, 16)); Serial.print("\n\r"); // Print data to serial monitor Serial.print("Data: "); for(int nIndex = 0; nIndex < nMsgLen; nIndex++) { Serial.print("0x"); if(nMsgBuffer[nIndex] < 16) Serial.print("0"); Serial.print(itoa(nMsgBuffer[nIndex], sString, 16)); Serial.print(" "); }// end for Serial.print("\n\r\n\r"); }// end if // Run in 1 sec interval delay(1000); }// end loop

Obviously, theprogramhasgrowncomparedto thepreviousone,butmostof theaddedcodeisusedforthedatadisplayontheArduinoserialmonitor.First,noteontoptheline#include<stdlib.h>.Thestdlib.hfileallowsustoconvertintegerdataintoASCII,whichisnecessaryforthedatadisplay.Thesetup()routineremainsthesameasitwasinthepreviousexample.

Page 25: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

17

Intheloop()routine,wefirstdeclaresomevariablesforthemessagereceptionandcode conversion. We still send out the same message as before by calling theCAN0.sendMsgBuf()function.Next,wecheckforthereceptionofaCANmessage,andifthatisthecase,wereadthemessage into the assigned buffer and retrieve themessage ID. The followingcodeisallaboutconvertingthereceiveddataintoahuman-readableformat(ASCII)anddisplayitontheArduinoserialmonitor.Last,butnotleast,wehaltthesystemforonesecond(1000milliseconds).Naturally,underreal-lifeconditions,thisdelayisnotreasonable,sincetherecanoccurliterallythousands ofmessages per one second.However, this code ismeantmerely as ademosamplethatprovesthattheactualCANcommunicationcanbeaccomplishedwithverylittlecode.IfyouloadthisprogramontotwoseparateArduinoswithCANshield,youhavenotonlyaccomplishedafullCANnetwork,youcanalsoseetheCANmessagesastheyareexchangedbetweenthetwonodes.Note: Itmaysoundobvious,butpleasemakesure,incaseyouusemorethanoneCANnode,thatallnodesareinitializedwiththesamebaudrate.Usingdifferentbaudratesisthemostcommoncausewhendatacommunicationfails.4.2.3ASimpleCANNetworkMonitoringandDiagnosticsProgram

TheArduinoboardincombinationwiththeCANshieldprovidesthehardwareforafull-fledgedCANnetworkmonitoringtool,andthisnextArduinoprogramisafirststepinthatdirection.However, before we get into more detail, let me issue some warnings regardingpossiblerestrictionsofthesystem:

• The MCP2515 has only two receive buffers, which limits the system’scapabilitiestorespondinatimelyfashionwhilereceivingandprocessingthedatatraffic.Forhigh-speed,high-busloadapplications,itisrecommendedtousethemessagefilterfunctionstoreducetheprocessingloadontheCPU.

• Besides the limited processing speed of the 8-bit CPU, the Arduino comes

withonly32kByteprogrammemory,whichissufficientforagreatnumberof small applications. However, when it comes to more demanding taskssuch as a CAN monitoring tool, the memory resources may be exhausted

Page 26: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

18

quicker thanexpected. For instance, the followingapplicationalreadyusesroughly20percent of the totalmemory space, and it provides only a veryrudimentaryversionofamonitoringtool.

In all consequence, if you are serious about creating a more-or-less professionalapplication,youmightwanttoconsideralternativehardwaresolutionsasdiscussedinapreviouschapter.InordertocreateaCANmonitoringsystem,weneedto:

1. ReceiveCANmessagesanddisplaythem2. BeabletoenterCANmessagesandtransmitthem

With the previous two programming samples in mind, we have alreadyaccomplishedstep#1,butthenextstep(enteringCANmessages)needsabitmorework.TheideaistoentertheCANmessageintoArduino’sserialmonitorandtransmittheresultbyclickingtheSendbutton.Inordertoaccomplishthat,weneedtofollowadataentryformatasshowninthefollowing.Command: SendCANMessage(11bit)Description: NodereceivesamessageandtransmitsitintotheCANbusFormat: #SMidndddd…. id=MessageID(2bytes,hex) n=Numberofbytes(1byte,0to8) d=databytes(hex,uptoeightbytes) Example: #SM01FF83031323334353637Inthispreviousexample,wedesignaCANmessagewithanIDof01FFandadatalength of 8 bytes. These 8 bytes are represented by the number 30 (hex) to 37,whichistheequivalentofASCII-0toASCII-7.

Page 27: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

19

While thebasic functionalityof sending and receivingCANmessages remains thesame, the program size and complexity has, naturally, grown. Most of the code,however, is being used for conversion between hex and ASCII formats (forreadability)andsomerudimentarysyntaxcheck.Note: The data entry in this following programming sample is not fool-proof,meaning,whiletheprogramdoessomesyntaxchecks,itisstillpossiblethatincorrectdataentrieswillstillbeinterpretedasvalidCANmessageformats.Also, this example still uses 9600baud for the communicationwithArduino’s serialmonitor. A faster transmission speed is recommended for CAN networks with highdatatraffic.// Simple CAN Shield Test #include <stdlib.h> #include "mcp_can.h" #include <SPI.h> MCP_CAN CAN0(10); // Set CS to pin 10 // Constants #define MAX_CMD_LENGTH 60 #define CR "\n\r" #define CRCR "\n\r\n\r" // SYSTEM: Setup routine runs on power-up or reset void setup() { // Set the serial interface baud rate Serial.begin(9600); // Initialize the CAN controller // Baud rates defined in mcp_can_dfs.h if (CAN0.begin(CAN_250KBPS) == CAN_OK) Serial.print("CAN Init OK.\n\r\n\r"); else Serial.print("CAN Init Failed.\n\r"); }// end setup // Main Loop - Arduino Entry Point void loop() { // Check for a received CAN message and print it to the Serial Monitor SubCheckCANMessage(); // Check for a command from the Serial Monitor and send message as entered SubSerialMonitorCommand(); }// end loop // ------------------------------------------------------------------------

Page 28: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

20

// Check for CAN message and print it to the Serial Monitor // ------------------------------------------------------------------------ void SubCheckCANMessage(void) { // Declarations byte nMsgLen = 0; byte nMsgBuffer[8]; char sString[4]; if(CAN0.checkReceive() == CAN_MSGAVAIL) { // Read the message buffer CAN0.readMsgBuf(&nMsgLen, &nMsgBuffer[0]); INT32U nMsgID = CAN0.getCanId(); // Print message ID to serial monitor Serial.print("Message ID: 0x"); if(nMsgID < 16) Serial.print("0"); Serial.print(itoa(nMsgID, sString, 16)); Serial.print("\n\r"); // Print data to serial monitor Serial.print("Data: "); for(int nIndex = 0; nIndex < nMsgLen; nIndex++) { Serial.print("0x"); if(nMsgBuffer[nIndex] < 16) Serial.print("0"); Serial.print(itoa(nMsgBuffer[nIndex], sString, 16)); Serial.print(" "); }// end for Serial.print(CRCR); }// end if }// end subCheckCANMessage // ------------------------------------------------------------------------ // Check for command from Serial Monitor // ------------------------------------------------------------------------ void SubSerialMonitorCommand() { // Declarations char sString[MAX_CMD_LENGTH+1]; bool bError = true; unsigned long nMsgID = 0xFFFF; byte nMsgLen = 0; byte nMsgBuffer[8]; // Check for command from Serial Monitor int nLen = nFctReadSerialMonitorString(sString); if(nLen > 0) { // A string was received from serial monitor if(strncmp(sString, "#SM ", 4) == 0) { // The first 4 characters are acceptable

Page 29: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

21

// We need at least 10 characters to read the ID and data number if(strlen(sString) >= 10) { // Determine message ID and number of data bytes nMsgID = lFctCStringLong(&sString[4], 4); nMsgLen = (byte)nFctCStringInt(&sString[9], 1); if(nMsgLen >=0 && nMsgLen <=8) { // Check if there are enough data entries int nStrLen = 10 + nMsgLen * 3; // Expected msg length if(strlen(sString) >= nStrLen) // Larger length is acceptable { int nPointer; for(int nIndex = 0; nIndex < nMsgLen; nIndex++) { nPointer = nIndex * 3; // Blank character plus two numbers nMsgBuffer[nIndex] =

(byte)nFctCStringInt(&sString[nPointer + 11], 2); }// end for // Reset the error flag bError = false; // Everything okay; send the message CAN0.sendMsgBuf(nMsgID, CAN_STDID, nMsgLen, nMsgBuffer); // Repeat the entry on the serial monitor Serial.print(sString); Serial.print(CRCR); }// end if }// end if }// end if }// end if // Check for entry error if(bError == true) { Serial.print("???: "); Serial.print(sString); Serial.print(CR); } }// end if }// end SubSerialMonitorCommand // ------------------------------------------------------------------------ // Read message from Serial Monitor // ------------------------------------------------------------------------ // Returns string length // byte nFctReadSerialMonitorString(char* sString) {

Page 30: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

22

// Declarations byte nCount; nCount = 0; if(Serial.available() > 0) { Serial.setTimeout(100); nCount = Serial.readBytes(sString, MAX_CMD_LENGTH); }// end if // Terminate the string sString[nCount] = 0; return nCount; }// end nFctReadSerialMonitorString // ------------------------------------------------------------------------ // Convert string into int // ------------------------------------------------------------------------ // Note: nLen MUST be between 1 and 4 // // Returns integer value (-1 indicates an error in the string) // int nFctCStringInt(char *sString, int nLen) { // Declarations int nNum; int nRetCode = 0; // Check the string length if(strlen(sString) < nLen) nRetCode = -1; else { // String length okay; convert number int nShift = 0; for(int nIndex = nLen - 1; nIndex >=0; nIndex--) { if(sString[nIndex] >= '0' && sString[nIndex] <= '9') nNum = int(sString[nIndex] - '0'); else if(sString[nIndex] >= 'A' && sString[nIndex] <= 'F') nNum = int(sString[nIndex] - 'A') + 10; else goto nFctCStringInt_Ret; nNum = nNum << (nShift++ * 4); nRetCode = nRetCode + nNum; }// end for }// end else // Return the result nFctCStringInt_Ret: return nRetCode;

Page 31: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

23

}// end nFctCStringInt // ------------------------------------------------------------------------ // Convert string into unsigned long // ------------------------------------------------------------------------ // Note: nLen MUST be between 1 and 4 // // Returns integer value (-1 indicates an error in the string) // unsigned long lFctCStringLong(char *sString, int nLen) { // Declarations unsigned long nNum; unsigned long nRetCode = 0; // Check the string length if(strlen(sString) < nLen) nRetCode = -1; else { // String length okay; convert number unsigned long nShift = 0; for(int nIndex = nLen - 1; nIndex >=0; nIndex--) { if(sString[nIndex] >= '0' && sString[nIndex] <= '9') nNum = int(sString[nIndex] - '0'); else if(sString[nIndex] >= 'A' && sString[nIndex] <= 'F') nNum = int(sString[nIndex] - 'A') + 10; else goto lFctCStringLong_Ret; nNum = nNum << (nShift++ * 4); nRetCode = nRetCode + nNum; }// end for }// end else // Return the result lFctCStringLong_Ret: return nRetCode; }// end lFctCStringLong

Note:Thisprogrammingexample,unlikethefirsttwosamplesinthisbook, isbasedon the use of an 11-bit message identifier, paying tribute to the majority of CANapplications.Withoutgoingintothelastdetail,hereisabriefdescriptionofthecode:Thesetup()functionremainsthesameasinthefirsttwoprogrammingexamplesinthis book, i.e. it handles the initialization of the serial connection and the CANcontroller.

Page 32: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

24

Theloop()routine,however,looksextremelysimple,butthatonlymeansthatthemajorpartofthefunctionalityhasbeendistributedtoanumberofnewfunctions.Insideloop()areonlytwofunctioncalls:

1. SubCheckCANMessage()checksforareceivedCANmessageanddisplaysitontheArduinoserialmonitor.

2. SubSerialMonitorCommand() receives a string from Arduino’s serial

monitor, achieves some rudimentary syntax check, and sends out the CANmessage.

Theremainingfunctioncallsare:

• nFctReadSerialMonitorString() readsthedata formatstringasenteredbytheuserandreturnsthestringlength.

• nFctCStringInt()convertsastringintointegerandreturnstheintegerdata.

• lFctCStringLong()convertsastringintolongandreturnsthelongdata.

Note:UnlikeC#,theCandC++programminglanguagesprovideonlylimitedsupportfordata conversion, and sometimeswriting yourown conversion functions fits yourapplicationneedsbetterthantheprovidedlibraryfunctions.The following shows screen shots taken trough a sessionwith this programmingexample:

Page 33: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

25

First,wereceivedtwoCANmessages(IDs0x80and0x100),thenwesenttwoCANmessages(IDs01FFand00EF).Forthisoperation,Iusedmystandardtestconfiguration(i.e.USB-to-CANgatewaywithWindowsmonitoring tool as the second CAN node), but from here on, it ispossibletousetwoArduinoswithCANshieldrunningthesameapplication.In order to extend the functionality of this programming example, the followingcommandswould be helpful to provide a full-fledgedmonitoring and diagnosticstool:

• CANStart/Stop–StartsorstopsdisplayingmessagesontheArduinoserialmonitor.

• CANBaudRate–ModifytheCANbaudrate.• RequestCANSettings–Reportsthecurrentsettingssuchasbaudrateand

messageIDmode.• SendCANMessagein29-bitformat.• AddCANMessageFilter• DeleteCANMessageFilter• DeleteAllCANMessageFilters

Andyes,therearemultiplepossibilitiesofextendingthisprogramtowardareallyprofessionalversion.However,whattheArduinocannotprovideisaprofessionallylookinggraphicaluserinterface,andthisiswheretheexistingUSBconnectiontoaPCopensthedoortomorepossibilities.4.3CANNetworkMonitoringunderWindows

WhileprogrammingtheArduinocanbeexciting(especiallysinceeverythingworkssosmoothly),therealfuncomeswhenyoucanextendtheArduino’sreachtoaPCrunningWindows.Note:MyapologiestoallMacandLINUXusersforbringingaWindowsprogrammingexample,butthereisnobetterprogrammingthanusingC#underMicrosoft’sVisualStudio. I have enjoyed programming under OS-X and LINUX, but when it comes toproducing quick and effective programming examples, I prefer to stay with VisualStudio. However, the experienced programmer should be able to replicate thefunctionalityoftheserialmonitor.

Page 34: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

26

To learnmore about serial port programming (RS-232 and USB) under LINUX seehttp://www.teuniz.net/RS-232/. I consider this by far the most professionalapplication for serial ports under LINUX. It also suits Windows applications but isprimarily meant for compilers inferior to Visual Studio and/or for programmingembeddedsystems.In the followingweassumethatyouhave theArduinoUSBdriver installedunderyour Windows machine. The driver is automatically installed with the Arduinodevelopmentenvironment.As Ihavementioned inmynote, I amusingMicrosoft’sVisual Studio2012, and Ihave designed the following GUI that may look very familiar to the Arduinodeveloper. Basically, this very simple program is a replica of the Arduino serialmonitor.

The screen elements are a textbox for data entry, a commandbutton to send theentrytotheArduino,andanother largertextboxtodisplaythedatacomingfromthe Arduino. Last, but not least, there is a combobox displaying all available USBCOM ports (It is your task to determine the proper USB port; there is no autodetection).

Page 35: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

27

Whattheprogramdoesnotprovideisthebaudratesettings,whichhasbeenhard-codedas9600baudintotheprogrambutcanbemodifiedeasily.Ofcourse,thisisnottheprofessionalwayofdoingit,but,afterall,thisprogrammingsampleservesasanexampleonreading/sendingmessagesfrom/totheArduino.InregardstotheenvisionedextendedCANnetworkmonitoringanddiagnostics tool, youwillneedmore anddifferent screen elements, and the baud rate settings should be part ofthatproject.Allscreenelementsinthisprojectstickwiththeirdefaultsettings,howeverwithafewexceptionsasshowninthefollowing:Element Name ModifiedProperty EventsForm Form1 Text=“SerialMonitor” -Text txtSend - -Text txtReceived Multiline=True Scrollbars=VerticalButton btnSend Text=”Send” ClickComboBox cboCOMPort - SelectedIndexChangedThefollowingshowstheC#programlisting(theentireprogramiswithintheform):using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.IO.Ports; using System.Threading; namespace USBAccess { public partial class Form1 : Form { // Constants public const int REC_BUFFER_SIZE = 500; public const int READ_TIMEOUT = 500; public const int WRITE_TIMEOUT = 500; public const int REC_BUFFER_FILLTIME = 80; public static SerialPort _serialport; public Form1() { InitializeComponent();

Page 36: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

28

string[] sPorts = new string[20]; sPorts = SerialPort.GetPortNames(); for (int nIndex = 0; nIndex < sPorts.Length; nIndex++) cboCOMPort.Items.Add(sPorts[nIndex]); }// end Form1 // SetTextDeleg // ------------- private delegate void SetTextDeleg(string text); // sp_DataReceived // ---------------- void sp_DataReceived(object sender, SerialDataReceivedEventArgs e) { // Set the receive buffer size char[] sRecData = new char[REC_BUFFER_SIZE + 1]; // Give the hardware some time to receive the whole message Thread.Sleep(REC_BUFFER_FILLTIME); try { int nBytes = _serialport.BytesToRead; // Read the string int nIndex; for (nIndex = 0; nIndex < nBytes; nIndex++) { int nRec = _serialport.ReadByte(); sRecData[nIndex] = (char)nRec; }// end for sRecData[nIndex] = (char)0; // Terminate the string string sStr = new string(sRecData); // In case of RS232, this line causes a timeout,

// meaning no data is being received this.BeginInvoke(new SetTextDeleg(si_DataReceived),

new object[] { sStr }); } catch (TimeoutException) { } }// end _serialport_DataReceived // si_DataReceived // ---------------- private void si_DataReceived(string data) { if(txtReceived.TextLength == 0) txtReceived.Text = data; else txtReceived.Text += "\n\r" + data;

Page 37: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

29

// Set cursor to end of screen txtReceived.SelectionStart = txtReceived.TextLength;

txtReceived.ScrollToCaret(); txtReceived.Refresh(); }// end si_DataReceived // btnSend_Click // -------------- private void btnSend_Click(object sender, EventArgs e) { // Make sure the serial port is open before trying to write try { if (!(_serialport.IsOpen)) _serialport.Open(); if (txtSend.Text.Length > 0) _serialport.Write(txtSend.Text); else

MessageBox.Show("Please enter a message to be sent.", "Attention!");

} catch (Exception ex) { MessageBox.Show("Error opening/writing to serial port." + ex.Message, "Error!"); } }// end btnSend_Click

// Event : cboCOMPort_SelectedIndexChanged //------------------------------------------ private void cboCOMPort_SelectedIndexChanged(object sender,

EventArgs e) { // Define the serial port for the USB device _serialport = new SerialPort(cboCOMPort.SelectedItem.ToString(), 9600, Parity.None, 8, StopBits.One); _serialport.Handshake = Handshake.None; // Set the read/write timeouts _serialport.ReadTimeout = READ_TIMEOUT; _serialport.WriteTimeout = WRITE_TIMEOUT; _serialport.ReadBufferSize = REC_BUFFER_SIZE; _serialport.Open(); _serialport.DataReceived +=

new SerialDataReceivedEventHandler(sp_DataReceived); }// end cboCOMPort_SelectedIndexChanged }// end class }// end namespace

Page 38: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

30

Reference:ThehandlingoftheUSBportisbasedonanarticlebyRyanAlford(withaddedcontentbyArjunWalmiki,GregoryKrzywoszyjaandMaheshChand)at:http://www.c-sharpcorner.com/uploadfile/eclipsed4utoo/communicating-with-serial-port-in-C-Sharp/Atprogramstart,theuserfirstneedstoselecttheapplicableUSBCOMport,whichinitializestheport(SelectedIndexChangedevent).Beyondthat,theprogramfunctionsasasimpleUSBterminal:MessagesaretypedinthetoptextboxandsentbyclickingontheSendcommandbutton.Thelargertextboxdisplaysthereceiveddata.The following shows screen shots taken througha sessionwithourArduinoCANNetworkMonitoringandDiagnosticsprogram:

Inthiscase,wesenttwoCANMessageswiththesameID(0100)butdifferentdata.Next,wereceivedtomessagesthroughmystandardtestconfiguration(i.e.USB-to-CANgatewaywithWindowsmonitoringtoolasthesecondCANnode).

Page 39: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

31

Theprevioustwoscreenshotsserveasevidencethatthemessagessentto/fromtheserialmonitorviatheArduinoCANShieldwerereceived/transmittedasexpected.5Conclusion

Atthispoint,afterhavingaccomplishedallthenecessarysteps,itiseasilypossibleto develop a professional, full-fledged CANNetworkMonitoring, Diagnostics, andSimulationSoftware.The groundwork has been laid for all necessary hardware and softwarecomponents:

1. AUSB-to-CANGatewaytoprovideCANconnectivitytothehostsystem2. AcommunicationprotocolbetweentheUSB-to-CANandthehostsystem3. Agraphicaluserinterface(GUI)forthepresentationoftheCANnetwork

Formore technical informationandarticlesand to contactme, seemywebsiteathttp://copperhilltech.com.

Page 40: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s
Page 41: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

33

Appendix–RecommendedLiterature

There is more than plenty and valuable literature available on the Arduino, but,beinganexperiencedprogrammer,theoneandonlyworkIreadwas:ProgrammingArduinoGettingStartedwithSketchesBySimonMonkISBN978-0-07-178422-1Alsorecommendedforprovidingmorebackgroundinformation:AComprehensibleGuidetoControllerAreaNetworkByWilfriedVossISBN978-0976511601AComprehensibleGuidetoJ1939ByWilfriedVossISBN978-0976511632All works are available through Amazon.com and all their international onlinestores,Barnes&Noble,Abebooks.comandalltheirinternationalonlinestores,andanyothergoodbookstore.

Page 42: CONTROLLER AREA NETWORK - Copperhill Tech Prototyping with Arduino.pdfI am using a slightly modified version of the Hungarian Notation, meaning looking at a variable’s or function’s

34


Recommended