You are on page 1of 11

CreatingaMatlabGUIforDCMOTORS

TableofContents
1 Objective
1.1 Credits
1.2 GeneralComment(s)
2 TestingyourMotorswithMATLAB
2.2.1 SetuptheGyroforMATLAB
2.3 Step3:Uploadthesrv_gyro.pdeServer
2.3.1 HowitWorks
2.4 Step4:Addarduino.mtoMATLABPath
2.4.1 HowitWorks
2.5 Step5:InstantiatetheMATLABArduinoClass
2.5.1 FindingtheSerialPort
2.6 Step6MatlabMotorLab
3 UsingtheMATLABGUI
3.1 Help
4 LabDeliverable(s)
5 FutureWork
1
1 Objective
InthislabyouwillimplementaMATLABGUItocontrolyourDCmotorsandthestepper
motor.Specifically,youwillcreateacontrolpanelwithtwoslidersandbuttons.Asyou
increase(moveup)theslidersyouwillbeabletoseethespeedofyourDCmotors
increase.Youwillalsobeabletocontrolthesteppermotorwithpushbuttonsforleftand
rightpanning.Thesesimplecontrolsallowyoutomanuallytestthemotorsofyourrover
andhavealittlefundrivingitaround.
Forthislabyouwillneedthefollowingmaterials:
AssembledRoverfromBuild
Instructions
USBCable MATLABSoftware
Version2008orhigher
Thislabassumesthatyouhavealreadydownloadedandinstalledthe...
ArduinoIDE
AVRStudio4
1.1 Credits
ThislabwasoriginallywrittenbyJuanCadenaandElizabethSandoval(Veterans)during
theFall2011semester.Additionalcontributor'sincludeKevinNguyen(GyroneersS11)and
NicFlenghi(RangeRoverF11).Thislatestrevisionreflectsthecommentsprovidedbythe
Spring2011class.
1.2 GeneralComment(s)
Whenindoubt,closeeverythingandunplugeverythingtostartfromsquareone.
2 TestingyourMotorswithMATLAB
InstructionalVideo
http://www.mathworks.com/company/events/webinars/wbnr43537.html
2
2.1 Step1:CheckSoftwareVersion
TocompletethislabyoumusthaveMATLAB2008orhigher.
2.2 Step2:DownloadFiles
For the srv.pde sketch to compile correctly, the Adafruit Motor Shield library must first be
installed.DownloadthelibraryfromAdafruit,
Extract the files, and place them in a new folder (AFMotor) in the Arduino libraries folder
(usually: My Documents\Arduino\libraries\AFMotor), as per the instructions at LadyAda. You can
findthe
The MATLAB support package is required for serial communications with the Arduino, which is
availableatMathWorkswebsite(usetheblueDownloadAllbuttonatthetopright).
To start communicating with the Arduino, the general server file srv.pde within the srv directory
3
needstobeuploadedtotheArduinousingtheArduinoIDE.
This lab does not require support for the gyro on your rover. If you do not want to add this feature
nowyoucanskipthenextstepandworkwiththegenericsrv.pdesketch.
2.2.1 SetuptheGyroforMATLAB
For the srv_gyro.pde sketch to compile correctly, the Pololu L3G4200D library must first be
installed.DownloadthelibraryfromPololu.
NOTE:Makesuretodownloadeveryfile,notjustthe.hfiles,tothelibraryfolderfromthe
abovelinks.
DownloadandExtractthefilesintheGyro_matlab_code.zipfilesincludedinthisfolder.The
extractedfoldershouldincludethefollowingfiles.
1. srv_gyro.pde
2. install_arduino.m
3. arduino.m
4. gyro_test.m
Note:Whilesomeofthefilesnamesinthefilesdownloadedhavethesamenamesasthose
foundatMathworksNichasmodifiedthemforourclass.
2.3 Step3:Uploadthesrv_gyro.pdeServer
IfyouhaveneveruploadedanArduinosketch(i.e.,program),Iwouldhighlyrecommendyou
completetheLesson1:Lettherebeblink!ArduinoTutorialfoundhere.
Uploadsrv_gyro.pde(orsrv.pdeifyouskippedstep2.1.1)toyourArduino.TheAdafruit
motorlibraryandPololuL3G4200(srv_gyro.pdeonly)mustbeinstalledforthistocompile.
Thesrv_gyro.pdeprogramcontainsallofthecommandsnecessarytorunthemotors,
read/writetoports,andreadfromourgyro.ThisArduinoprogramactsasaservertointerface
withMATLAB.
2.3.1 HowitWorks
MATLAB(ortheserialmonitorintheArduinoIDE)sendsanalphanumericcodetoindicatewhich
4
commandwewanttorunandthenlistensfortheresultsentovertheUSBport.Thelistof
commandscanbefoundatthetopofthesrv_gyro.pdefile.
2.4 Step4:Addarduino.mtoMATLABPath
Addthemodifiedarduino.mfiletoyourMATLABpath.Youmaydothismanually,orbyrunning
install_arduino.m.YoucanfindhelponaddingafoldertotheMatlabsearchpathhere.
2.4.1 HowitWorks
Thearduino.mfiletakescareofsendingandreceivingcommandsanddatafromtheArduino
server(srv_gyro.pde).ItalsogivesusacollectionofMATLABfunctionstouseinsteadof
manuallyenteringthealphanumericcodes.Forexample,a.gyroRead(z)sendsthecode
Gzovertheserialinterfaceandlistensforthevaluesentbackfromtheboard.
Ifyouarerunningsrv_gyro.pdemakesuretousethearduino.mfiledownloadedwiththis
software.
2.5 Step5:InstantiatetheMATLABArduinoClass
Note:TheMATLABMotorServerfoldermustbeopenwhenperformingcommandssuchas
instantiatingtheArduino(Figure7).
Figure7MATLABMotorServerfolder
Oncesrv_gyro.pdeisuploadedtotheboard,thecodetoinstantiatetheArduinoobjectis:
a=arduino('COMX')
WhereCOMXistheporttheArduinoisconnectedto(thiscanbedeterminedusingtheArduino
IDEorDeviceManager).
2.5.1 FindingtheSerialPort
5
ThesimplestwaytofindoutwhichUSBport(comport)yourArduinoisconnectedtoisfromthe
ArduinoIDE.IfyouarenewtotheArduinoIDEIwouldrecommendcompletingtheLesson1:Let
therebeblink!ArduinoTutorialfoundhere.FindingtheUSBportofanArduinoUNOonWindows
7isalsofairlyeasy:StartDevicesandPrinters.
2.6 Step6MatlabMotorLab
DownloadtheDCMotorfolderandplaceitinaplacewhereyoucanaccessitthrough
Matlab(i.e.,thecurrentorworkingdirectory).
MATLABshouldshowitasfollows:

OpenMATLABandrunthearduino.mfile.
Youshouldgetthefollowingwindowoncearduino.mfileisrun
6
TypethefollowinglineinthecommandlinetomakesuretheArduinoandMATLABare
talkingtoeachother.InmycasemyArduinoisonportCOM14(makesureyouknowwhich
COMyyourarduinoisusing).MakesuretoreplaceCOM14withyyourcorresponding
COM#.
EDU>>a=arduino('COM14')
Youshouldseethefollowingoutput.
EDU>>a=arduino('COM14')
Attemptingconnection......
GeneralScriptdetected!
Arduinosuccessfullyconnected!
a=
arduinoobjectconnectedtoCOM14port
GeneralShieldServerrunningonthearduinoboard
Servo1isDETACHED
Servo2isDETACHED
Thespeedofmotornumber1issetto:0over255
Thespeedofmotornumber2issetto:0over255
Thespeedofmotornumber3issetto:0over255
Thespeedofmotornumber4issetto:0over255
Thespeedofsteppernumber1issetto:0over255
Thespeedofsteppernumber2issetto:0over255
ServoMethods:servoStatusservoAttachservoDetachservoReadservoWrite
DCMotorsandStepperMethods:motorSpeedmotorRunstepperSpeedstepperStep
7
DigitalPin02iscurrentlyUNASSIGNED
DigitalPin03iscurrentlyUNASSIGNED
DigitalPin04iscurrentlyUNASSIGNED
DigitalPin05iscurrentlyUNASSIGNED
DigitalPin06iscurrentlyUNASSIGNED
DigitalPin07iscurrentlyUNASSIGNED
DigitalPin08iscurrentlyUNASSIGNED
DigitalPin09iscurrentlyUNASSIGNED
DigitalPin10iscurrentlyUNASSIGNED
DigitalPin11iscurrentlyUNASSIGNED
DigitalPin12iscurrentlyUNASSIGNED
DigitalPin13iscurrentlyUNASSIGNED
DigitalPin14iscurrentlyUNASSIGNED
DigitalPin15iscurrentlyUNASSIGNED
DigitalPin16iscurrentlyUNASSIGNED
DigitalPin17iscurrentlyUNASSIGNED
DigitalPin18iscurrentlyUNASSIGNED
DigitalPin19iscurrentlyUNASSIGNED
PinIOMethods:pinModedigitalReaddigitalWriteanalogReadanalogWrite
ClickonmotorRunforMatlabcodingexamples.
LetstakeacloserlookattheinstanceandargumentsofmotorRun.
a.motorRun(num,dir) runsagivenDCmotor.
Thefirstargumentbeforethefunctionname,a,isthearduinoobject.Thesecondargument,
num,isthenumberofthemotor,whichcangofrom1to4(themotorportsarenumbered
onthemotorshield).Thethirdargument,dir,shouldbeastringthatcanbe'forward'(runs
themotorforward)'backward'(runsthemotorbackward)or'release',(stopsthemotor).
Notethatsinceversion3.0,a+1isinterpretedas'forward',a0isinterpretedas'release',
anda1isinterpretedas'backward'.ThemotorRunmethodreturnsrandomresultsif
motorshieldisnotconnected.
Examples:
a.motorRun(1,'forward')%runsmotor1forward
a.motorRun(3,'backward')%runsmotor3backward
a.motorRun(2,1)%runsmotor2backward
a.motorRun(1,'release')%releasesmotor1
AddthefollowinglinesofcodetomakesureyouhavecommunicationandthatMatlabis
workingproperly.
EDU>>a.motorSpeed(1,100)
8
EDU>>a.motorRun(1,'forward')
EDU>>a.motorRun(1,'release')
Line1willsetthespeedofyourmotor
Line2willsetyourmotortogoforward
Line3willsettellyourmotortostop
NowyoucanseethatyourArduinoworkswithMATLAB,butitisnotveryconvenientto
keeptypingallthelinesofcodetocontrolyourmotors.Soyouwillnowimplementa
MATLABGUItocontrolyourmotors.ByusingtheGUIyouwillbeabletocontrolboth
motorsandseeyourmotorsworkdependingonyourparameters.
3 UsingtheMATLABGUI
Doubleclickonthedc_slider.mfiletoopenthem.fileeditor.Thisiswhereyouwillmake
thefollowingchanges.
Inthedc_slider.mfilemakesuretochangetheCOMportcorrespondingtoyourArduino.
InthiscasetheArduinocomportissetto14.
Makesuretoalsochangethespeedofthemotorsatwhichyouwantthemtostartwhen
youpresstheforwardpushbutton.

Ideallyyouwanttotestyourmotorstoseeatwhatspeedtheybeginrunning.Inmycasemy
motorsbegintoturnatspeed80.
Forthesteppermotormakesurethattheseparametersmakeasmoothtransitionwhen
9
executingthesteppermovingrightorleft
%handlesstructurewithhandlesanduserdata(seeGUIDATA)
handles.a.stepperSpeed(2,50)
handles.a.stepperStep(2,'forward','interleave',10)
Whenyouexecutethedc_slider.mfileyoushouldgetthefollowinginthecommandlineif
everythingisworkingproperly.
Attemptingconnection......
GeneralScriptdetected!
Arduinosuccessfullyconnected!
EDU>>
Ifeverythinggoeswellthefollowingshouldappear
Ifyougeterrorsinthisstep,pleasecheckthefollowing:
1. MakesuretheusbcableispluggedinandtheroverstillcommunicateswiththePC
throughtheCOMXport(XistheportnumberthatthePCassignedtotheArduino
board).YoucancheckthisthroughtheDeviceManager.Unpluggingandplugging
theroverbackinwhilelookingatthelistofComswillallowyoutoseeexactlywhich
oneisconnectedtotherover.
2. CloseMatlabandtrytorunthearduino.manddc_slider.magain.Closingand
reloadingMatlabseemstobenecessaryeverytimeyouwishtoalterthecode.
10
Otherwisetheroverwontrespond.
3. Andisthebatterycharged!Ifthecodeuploadsbuttheroverdoesntmovethen
mostlikelythebatteryistoolowtomovetherover.
3.1 Help
WhenfirsttestingtheroverwithMatlabcode,itcreatesaconnectiontotheArduino.When
goingfromthearduino.mtotheGUI,anerrormayoccurwithaconnectionalreadybeing
established.ThisiseasilysolvedbyclosingandreopeningMatlab,whichactuallysolvesa
lotofproblems.IfconnectioncannotbeestablishedwiththeroverafterreopeningMatlab,
thenchecktheCOMportandtryunpluggingtheArduino.
4 LabDeliverable(s)
1. Demonstratetheoperationofyourrover
2. Findandrecordinyourlabnotebooksthestallspeedofyourrover
5 FutureWork
AsaresultoftheresearchIfoundthattheGUIisverylimitedinparametersthatyouwould
wanttoachieve,suchasmakingthetwoDCmotorsstartatthesametime.UsingtheGUI
themotorshavetobeindividuallystartedandmodifiedbecauseyouonlyhaveone
mouse/touchpadtoworkwithonacomputer/laptop.Iwouldsuggestthatforfuture
developmentoftheGUI,useRB11becauseithasupdatesfortheGUIwithbetterediting
options.
11

You might also like