Escolar Documentos
Profissional Documentos
Cultura Documentos
HowtouseanR/CControllerwithArduinoandSimulink|MakerZone
LEARN
GETINSPIRED
16COMMENTS
SHAREYOURPROJECT
COMPETE
BLOG
SUBSCRIBE
5TAGS
11MAR2014
R/CControllerforArduino+Simulink
BySergioBiagioni
ThisarticleshowshowtoprogramanArduinoMega2560usingSimulinktoreceivethesignalsfromaanR/CReceiver.Thearticlebeginswitha
sequenceofthreevideosthatexplainhowtosetup,deployandchangetheparametersoftheRCReceivedriverblock.Thisblockisplacedinthe
SimulinkmodeltoallowtheusertogeneratecodewhichreceivessignalsfromanR/Creceiver.Afterthevideos,thearticleexplainswhatthedriver
blockdoes,howtosetupthehardware,andgoesoverthematerialpresentinthevideosinmoredetail.
TosetuptheRCReceivedriverblock,seethefollowingvideo
http://makerzone.mathworks.com/resources/howtouseanrccontrollerwitharduinoandsimulink/
1/11
25/9/2016
HowtouseanR/CControllerwithArduinoandSimulink|MakerZone
TodeploytheRCReceivedriverblockontotheArduinoMega2560,seethefollowingvideo
TochangetheparametersoftheRCReceivedriverblock,i.e.SampleTimeandPinNumbers,seethefollowingvideo
Contents
Introduction
http://makerzone.mathworks.com/resources/howtouseanrccontrollerwitharduinoandsimulink/
2/11
25/9/2016
HowtouseanR/CControllerwithArduinoandSimulink|MakerZone
Prerequisites
RequiredHardware
Task1:SetuptheHardware
Task2:DownloadtheCode
Task3:SetuptheEnvironment
Task4:SetuptheDriverBlock
Task5:RunthemodelontheArduinoMega2560Board
Howdoesthecodework?
FutureWork
Introduction
OnecommonquestionwhenworkingwithdifferentrobotsishowtouseanR/Ccontrollertocontrolit.StandardroboticshastheR/Creceiversenda
servostylepwmsignaldirectlytotheservomotorsorthemotorcontrollerasindicatedbythediagrambelowwithMethod1.Manyroboticistslookto
changethisrelationshipbyplacingamicrocontrollerinbetweentheR/CreceiverandthemotorsasshownwithMethod2.Thisallowstheuserto
createfly/drivebywireprogramsonthemicrocontrollerwhereyoucanforexample,designtractioncontrolalgorithms.Youcouldeventakeitone
stepfartherbyusingoneofthechannelsontheR/CControllertoswitchthecodebetweendifferentoperatingmodesi.e.R/Ccontrolvs.Automated.
ThisexamplewillshowhowtoprogramanArduinoMega2560usingSimulinktoreceiveR/Csignals.Asecondarticlewillbemadetodemonstratea
drivebywireprogramwithafourwheelvehicle,andwillshowhowtouseoneofthechannelstoswitchbetweenremoteandautonomousmodes.
Figure1.MethodsofR/Ccontrol.
TheoutputoftheR/Creceiverconsistsof4servostylesignals.Servosignalsarepulseswithawidthofabout12msandaperiodofabout20ms.
Thelengthof1msistheminimumpulse,2msisthemaximumpulseand1.5msistheneutralpulse.Therearetwotypesofservomotors,
continuousservosandpositionservos.Foracontinuousservo,thelengthofthepulsecorrespondstothespeedofrotation.Forapositionservo,
thelengthofthepulsecorrespondstotheangularpositionoftheservo.WhencontrollingaircraftwithanR/Cremote,thereceiverisconnectedto
positionservos.
http://makerzone.mathworks.com/resources/howtouseanrccontrollerwitharduinoandsimulink/
3/11
25/9/2016
HowtouseanR/CControllerwithArduinoandSimulink|MakerZone
Figure2.Servosignals[imagesource].
Whenaneutralpulseissenttoacontinuousservotheservostops.Whenamaximumpulseissenttothecontinuousservo,theservomovesfull
speedinonedirectioni.e.clockwiseat180/s.Whentheminimumpulseissentthecontinuousservomovesfullspeedintheoppositedirectioni.e.
counterclockwiseat180/s.Anyvalueinbetweentheserangescorrespondstoaparticularspeed.
Similarly,whenaneutralpulseissenttoapositionservo,theservomovestoaneutralposition.Whenamaximumpulseissenttoapositionservo,
theservomovestosomeangleinonedirectioni.e.clockwiseto+90.Whentheminimumpulseissentthepositionservomovestosomeanglein
theoppositedirectioni.e.counterclockwiseto90.Anyvalueinbetweentheserangescorrespondstoaparticularangle.
Prerequisites
WerecommendcompletingGettingStartedwithArduinoMega2560Hardware.
RequiredHardware
Torunthisexampleyouwillneedthefollowinghardware:
Controllerboard:
ArduinoMega2560board
USBcable
RadioControl:
GenericR/Ccontrollerandreceiver
DebugCircuit:
4xLEDs
4x100OhmResistor
Task1:SetuptheHardware
1.Connectpins2,3,18,and19tothe4channelsontheR/Creceiver.
2.SupplypowertotheR/Creceiver.Isupplied5VfromtheArduino5VpintoanESCwhichthenpluggedintothereceiver.
Figure3.Circuitdiagram.
http://makerzone.mathworks.com/resources/howtouseanrccontrollerwitharduinoandsimulink/
4/11
25/9/2016
HowtouseanR/CControllerwithArduinoandSimulink|MakerZone
Figure4.Physicalcircuit.
Task2:DownloadtheCode
DownloadtheRCReceiveblockfromtheMathWorksFileExchange.
DownloadProjectFiles
Task3:SetuptheEnvironment
SettinguptheenvironmentneedstobeperformedonlyonceperversionofMATLABthatyouhaveinstalled.Ifyouhaveperformedthesesteps
before,pleaseignorethissection.
1.Makesurethatacompilerisinstalled.Youcansetupthecompilerbytyping(>>mexsetup)attheMATLABcommandwindow.Ifno
compilersshowupwhenyoutypethiscommanddeterminewhichcompileryoushoulduseanddownloadfromhere:
http://www.mathworks.com/support/compilers/current_release/
FormyWindows7machinerunningMATLAB64bit,IamusingtheWindowsSDK7.1compiler,whichisfree.
2.Type(>>targetinstaller)tosetuptheArduino
Task4:SetuptheDriverBlock
Settingupthedriverblockneedstobeperformedonlyonce.Ifyouchangetheunderlyingcodeintheblock,youwillneedtosetupthedriver
blockagain.
Tousethecustomdriverblock,3filesneedtobegenerated
sfcn_rcreceive_wrapper.cpp
sfcn_rcreceive.tlc
sfcn_rcinterupt.[mex],where[mex]canbemexw32,mexw64,mexmaci64dependingonyourOSandversionofMATLAB.Formy
Windows7machineusingMATLAB64bit,theextensionis.mexw64.
1.Openthercreceive.slxmodel.
2.OpentheRCReceiveSfunctionBuilderblock.
3.ClickBuild
4.Type(>>modify(sfcn_rcreceive)attheMATLABCommandWindow
Task5:RunthemodelontheArduinoMega2560Board
1.VerifythatyourworkingdirectoryorCurrentFolderisthefolderwherethefollowingfilesarelocated(i.e.C:\rcdriverblock):
rcreceive.slx.
sfcn_rcreceive.[mex]
sfcn_rcreceive.tlc.
sfcn_rcreceive_wrapper.cpp.
2.Openthemodelrcreceiveifnotopenedalready.
3.ClicktheRunbuttontoenterexternalmode.
http://makerzone.mathworks.com/resources/howtouseanrccontrollerwitharduinoandsimulink/
5/11
25/9/2016
HowtouseanR/CControllerwithArduinoandSimulink|MakerZone
4.Ifyoumovethejoystickscorrespondingtochannels1,2,3and4onpins2,3,18,and19,thecorrespondingvaluesintheDisplayblockand
Scopewillchange.Ifthevaluesgoover1750,thecorrespondingLEDswillturnon.
Figure5.Liveviewofjoysticksignals.
Howdoesthecodework?
Thisdriverblockattachesexternallytriggeredinterruptstothepinsthatarespecifiedintheblock.Theseinterruptsarebidirectionallytriggered(i.e.
whentheinputgoesfromhightoloworlowtohigh).Thecodeinthisblockusesthetwotriggerstomeasurethelengthoftheinputpulse.Asthe
joystickmovesintheuporrightdirection,thepulsegetslarger,andthecodereturnsalargervalue.
Formoreinformationonthis,feelfreetocheckoutthefollowingblog,whichdescribesthecimplementationofthealgorithmintheArduinoIDE:
HowtoreadmultipleR/Cchannels
FutureWork
ShowhowtousetheR/Cremotewithamobileplatform,i.e.drivebywire.
PublishedwithMATLABR2014a
Author:
Sergio Biagioni
http://makerzone.mathworks.com/resources/howtouseanrccontrollerwitharduinoandsimulink/
6/11
25/9/2016
HowtouseanR/CControllerwithArduinoandSimulink|MakerZone
TAGS
arduino
control
r/c
radio
radiocontrol
16Comments
ESModelDesigner
July18,2014at5:34am
AccordingtothisusefuldemoprojectIhaveafewquestionwhichIhopetogetdetailsanswersorreferences
whichaddresstheseissues.
1Whatisthemechanismbehindcompilingcodeofthecontrolalgorithmswiththecapabilitytorunitonthe
targethardwarewithoutneedingSimulinkCoderandEmbeddedCoder?andhowdoesitwork?
2DoesforexampleArduinoDUEorMEGAsupportcodegenerationformStateflow?
Bestregards!
Reply
SergioBiagioni
July22,2014at3:22am
Hello,
1.CertaintargetsareconsideredSimulinkTargetsandthereforedonotneedanyoftheCoderProducts
(i.e.SimulinkCoder,EmbeddedCoder).TogeneratecodeoutofSimulinkfortheArduino,startbytyping
>>supportPackageInstallerattheMATLABCommandWindow,selectingArduinofromthelistoftargets,
andfollowingtheinstructionsintheinstaller.Whentheinstallationiscomplete,itwillshowyouuseful
documentation.Forexample,thedocumentationpagecalledGettingStartedwithArduinoMega2560
HardwarewillshowyouhowtoeasilybuildcodefortheArduino.
TofindoutwhichhardwareisconsideredaSimulinkTarget,youcansearchforRunonTarget
HardwareintheMathWorksHardwareSupportpageorusethefollowinglink
2.ModelswithStateflowchartsaresupportedforcodegenerationtoanytargets,includingtheArduino
Mega2560andDue.
Best,
Sergio
Reply
ESModelDesigner
July22,2014at11:14pm
ThanksforAnswers.IthinkmyfirstquestiondidnotaddresshowtoinstallandruntheSIMULINKmodeltothe
target,youhighlightthatperfectlyinthistutorial,butImeantinthefirstquestionwhatisthemechanismbehind
generatingcodefortargetwithoutneedingSUMULINKcoderandEmbeddedCoder?Iguessthatbothtools
codersmadeavailableforspecifictargetswithlimitedfeatures,doesit?
ArethegeneratedCcodeandfilesavailable/visibleforfurthercodeanalysisandtraceability?
Reply
SergioBiagioni
July23,2014at3:45am
ThemechanismwhichallowsSimulinktogeneratecodefortheSimulinkTargetsandthe
Simulink/EmbeddedCoderTargetsistheSystemTargetFile.TheSimulinkTargetusestherealtime.tlc
SystemTargetFiletobuildthecode,whiletheEmbeddedCodertargetsusetheert.tlcSystemTargetFile.
BothallowtheusertogeneratecodeoutofSimulinkmodelsandplacethecodeontothetargets.
http://makerzone.mathworks.com/resources/howtouseanrccontrollerwitharduinoandsimulink/
7/11
25/9/2016
HowtouseanR/CControllerwithArduinoandSimulink|MakerZone
Thedifferenceisthattherealtime.tlctargetfilehaslimitedfunctionalitywhenitcomestofeatureslike
codeanalysisandtraceability.
TheCcodeisnotvisibleifyoudonothavetheCoderproducts.IfyoudohavetheCoderproducts,the
generatedcodeisplacedintothecurrentdirectory.
Reply
MichaelC.
July30,2014at6:58am
HiSergio,
IamhavingabitoftroublesettingthisdriverblockuponaDue.IwentthroughtheentiretutorialbutIcouldnt
getittowork.Isetupthehardwarewiththe4LEDs.IwentthroughtheBuildsetup(firstwithyourtsandpins,
thenwithadifferentset).Iranthemodifymfileaftereachbuild.Ithentriedrunninginexternalmodeandby
deployingittothehardware.Itdoesntworkformeatallineithermode.TheoutputIgetisallovertheplace
(from0to6000).
IsetthesystemupwithjustonechannelfromtheRCreceiverpluggedintotheDuebutallIgotwasacrazy
output(theremighthavebeenapatterntoit).IwoulduploadapictureofthescopegraphbutIdontknowhow
todothathere.
Duringoneofthetests,IdecidedtosplitthesignalfromtheRCreceiverandcheckwithanoscilloscopetosee
ifthereceiverwastheproblem.ThesignalwasexactlywhatisexpectedfromaRCreceiver,soIthinkthe
problemhassomethingtodowiththesoftware.IcheckedtheAttachInterrupt()functionontheArduinowebsite
andthisiswhatitsaysregardingtheDue:TheArduinoDueboardhaspowerfulinterruptcapabilitiesthat
allowsyoutoattachaninterruptfunctiononallavailablepins.Youcandirectlyspecifythepinnumberin
attachInterrupt().SoitshouldbeabletoworkontheDuebutIdontknowwhyitdoesnt.
IhaveaMega2560cominginsoonsoIcantryitwiththatbutIwashopingtobeabletousetheblockwiththe
Due.Anyhelpyoucangivewouldbeverymuchappreciated.
Thanks,
Michael
Reply
SergioBiagioni
August5,2014at2:30pm
HiMichael,
Theissueisthattheblockconvertedspecifiedpinnumberstointerruptnumberssincethatiswhat
attachInterruptfortheArduinoUnoandMega2560requires.TheArduinoDuerequirespinnumbersas
theinputtotheattachInterruptinstead.IhavemodifiedthecodeontheFileExchangeentryaccordingly
sothatitdoesnotperformtheconversionwhenbuildingcodefortheArduinoDue,butitmighttakeupto
aweektoupdate.Ifyouwanttomakethechangesyourselfsothatyoucanusethisblockwiththe
ArduinoDueonly,youcanperformthefollowingforeachlinewherethereisanattachInterruptcallinthe
DiscreteUpdatetaboftheSFunctionBuilder:
Change"attachInterrupt(getIntNum(pins[i]),calc0,CHANGE);"to
"attachInterrupt(pins[i],calc0,CHANGE);"
AssoonastheFileExchangeentryisupdatedwiththenewcodeIwillletyouknow.
Best,
Sergio
Reply
SergioBiagioni
September16,2014at2:55am
ThiscodeshouldnowworkwiththeArduinoMega2560,DueandUno.SeethecorrespondingFile
ExchangewebpagetodownloadorclicktheDownloadProjectFileslocatedabove.
http://makerzone.mathworks.com/resources/howtouseanrccontrollerwitharduinoandsimulink/
8/11
25/9/2016
HowtouseanR/CControllerwithArduinoandSimulink|MakerZone
Reply
ESModelDesigner
August5,2014at5:21am
HelloSergio,
AftercarryingoutthisexampleIcameuptoaquestionaboutthepossibilityofcompilinganddeployingonly
oneSimulinkStateFlowsubsystemwhilesimulatingtheotherSimulinksubsystemsonthehostmachine.More
precisely,letsaywehaveaSimulinkmodelconsistsofthreesubsystemsthatareconnectedtoeachotherat
thesamelevel(allsubsystems(SS)areparent).ThefirstSSgeneratesdifferentpulseswhichtriggersome
actionsinthesecondStateflowSS.TheoutputsofthesecondSStriggerinturnsthethirdStateflowSS.One
inputofthethirdSSareconnectedtotheArduinoinputblockwhilethecorrespondingoutputsareconnected
toArduinooutputblocksanddifferentscops.Now,canIdeploysuchasystemtothetargethardware?ifyes,
Howdoesitactuallywork?IguessonlytheSSwhichareconnectedtotheArduinoblocksarecompiledtothe
targetwhiletheotherSSsaresimulatedohthehostmachine.PleasecorrectmeifIamwrong!
Reply
SergioBiagioni
August8,2014at5:43am
Hello,
IthinkyouarelookingtoimplementaProcessorIntheLoop(PIL)Simulation.SimulinkTargetdoesnot
supportPIL.Todoso,checkouttheEmbeddedCoderTargetforArduinoontheMathWorksFile
Exchange.Youshouldbeabletoimplementyourdesiredworkflowwiththattarget.
AnythingthatisinamodelforaSimulinkTargetisdeployedtotheArduinowhentheDeploybuttonis
pressedandthemodelisconfiguredfortheArduino,regardlessofwhetherornotitisconnectedtoan
Arduinoblock.
Best,
Sergio
Reply
fahadtariq
November13,2014at12:35am
hello
canyoupleaseelaboratewhichtypeofRCTransandreciversaresuitableforthis??
sometransandreciversareprogramableandsomearenot.!whichoneistobeused..??
likethisisnotprogramable
https://www.hobbyking.com/hobbyking/store/__8337__Hobby_King_2_4Ghz_4Ch_Tx_Rx_V2_Mode_1_.html
andthisonerequirescomputerprogramming
https://www.hobbyking.com/hobbyking/store/__9041__Hobby_King_2_4Ghz_6Ch_Tx_Rx_V2_Mode_1_.html
iwillbegreatfullifuspecifythetypeoftransandreciverwhicharetobeusedfromHOBBYKINGorsomeother
website
thanksinadvance
Reply
November14,2014at3:27am
http://makerzone.mathworks.com/resources/howtouseanrccontrollerwitharduinoandsimulink/
9/11
25/9/2016
HowtouseanR/CControllerwithArduinoandSimulink|MakerZone
SergioBiagioni
HiFahad,
Thankyouforyourquestion.ThisblockwillworkwithallRCTransmitters/Receivers.AllRCReceivers
outputaservosignalfromthereceivertocontrolservomotors,regardlessofwhetherornotitis
programmable.Ifyoulookatthepicturesofthetworeceiversyoumentioned,theybothhave3pinsfor
thereceiveroutputs(PowerGroundServoSignal).Oneofthesepinsoutputsaservosignal.Theservo
signalisapulsewhichchangesinwidth(12ms)basedononthecorrespondingtransmitterscontrol
sticklocation.ThisblocksimplymeasuresthisservopulseandoutputstheresulttotheSimulinkmodel.
Best,
Sergio
Reply
fahad
November14,2014at3:50am
greatthanksalot
Reply
Bart
December7,2014at2:29am
hello,
Whentryingthisonthearduinouno,IgetthefollowingerrorwhenItrytorunontargethardware:CRL:None
cannotbefoundintheregistry.
Also,whenselectingexternal,therunbuttonbecomesinactive.Clickingconnecttotargetgivesthe
sameerror.Doesanyoneknowwhatcouldbetheproblem?
thx
Reply
SergioBiagioni
December9,2014at10:43am
Hi,
ThishappensingeneralwhenamodelfromaolderversionofMATLABisopenedinanewerversionof
MATLAB.TheStandardMathLibrarysettinggetsclearedforsomereason.TrysettingtheCode
Generation>Parameters>StandardMathLibrarytoC89/90(ANSI).
Ifthisdoesntfixtheissue,letmeknowwhatversionofMATLAByouareusingnowandbeforeifyou
wereusingapreviousversionatsomepoint.
Best,
Sergio
Reply
Seb
April22,2015at3:47am
Hisergio,
Sorryformypoorenglish,butimfrenchimveryinterestingaboutyourcode,ijustliketousethereceiver
signaltoswitchon/offtheplanepositionflight/imaketheflightcodeandimnotunderstandhowcanidofor
thisswitchhaveyougotaidea..
http://makerzone.mathworks.com/resources/howtouseanrccontrollerwitharduinoandsimulink/
10/11
25/9/2016
HowtouseanR/CControllerwithArduinoandSimulink|MakerZone
thanksinadvance
best
sb
Reply
SergioBiagioni
April22,2015at1:37pm
HiSeb,
Iwoulduseoneofthechannelstodetermineastate(i.e.autonomousvs.RCcontrolmode).Forexample,
ifthefourthchannelsvalueisabove1500puttheplaneinautonomousmode.Ifthefourthchannels
valueisbelow1500,puttheplaneinmanualRCcontrolmode.
YoucanuseaComparetoConstanttoperformthiscomparisonandsendtheresulttoaStateflowChart
oran(IfandIfElseActionSubsystemblock)whichcanbeusedtorunmodespecificcode.
PleaseseethedocumentationforStateflowortheIfblocktoseehowthisisdone.
Best,
Sergio
Reply
LeaveaReply
Comment
Name(required)
Mail(willnotbepublished)(required)
Website
POSTCOMMENT
Copyright2016|TheMathWorks,Inc.
http://makerzone.mathworks.com/resources/howtouseanrccontrollerwitharduinoandsimulink/
11/11