Elmo Gold Maestro G-MAS User manual

G‐MAS–GoldMaestro
SoftwareUser’sManual
March2011(Ver.1.0)
www.elmomc.com

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
1‐2
ImportantNotice
Thisdocumentisdeliveredsubjecttothefollowingconditionsandrestrictions:
•ThisdocumentiscopyrightedandallrightsarereservedbyElmoMotionControlLtd.This
productmaynot,inwholeorinpart,becopied,photocopied,reproduced,translated,orreduced
toanyelectronicmediumormachine‐readableformwithoutpriorconsent,inwriting,byElmo
MotionControlLtd.
•ThisdocumentcontainsproprietaryinformationbelongingtoElmoMotionControlLtd.Such
informationissuppliedsolelyforassistingusersofGoldMaestroNetworkMotionController.
•Thetextandgraphicsincludedinthisdocumentareforthepurposeofillustrationandreference
only.Thespecificationsonwhichtheyarebasedaresubjecttochangewithoutnotice.
•ElmoMotionControlandtheElmoMotionControllogoaretrademarksofElmoMotionControl
Ltd.
Documentno.XXXXXXXXXXXXXXXXX
Copyright©2011
ElmoMotionControlLtd.
Allrightsreserved.

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
1‐1
Tableofcontents
Chapter1: AbouttheG‐MASandthismanual..............................................................1‐3
1.1. WhatistheG‐MAS ........................................................................................1‐3
1.2. G‐MASFeatures ............................................................................................1‐4
1.3. WhattheDocumentCoversandHowtoUseIt ................................................1‐5
Chapter2: JustBeforeStartingUp ..............................................................................2‐6
2.1. PreparingYourComputer ..............................................................................2‐6
2.2. UsingtheManual’sExamples .........................................................................2‐6
Chapter3: ProgrammingPracticesandGuidelines .......................................................3‐9
3.1. Projectsandfiles...........................................................................................3‐9
3.1.1. ProjectLocationandNaming........................................................ 3‐10
3.1.2. Project’sFiles .............................................................................. 3‐11
3.1.3. Project’sDescriptionFiles ............................................................ 3‐11
3.2. Functions,VariablesandConstants...............................................................3‐12
3.3. CandHeaderFiles.......................................................................................3‐12
3.4. Wrapperfunctions ......................................................................................3‐13
3.4.1. HidingComplexand/orNotImportantCodeSegments................... 3‐13
3.4.2. HidingRepeatedSegmentsofCode............................................... 3‐14
3.4.3. ProvidingEasierInterfaces ........................................................... 3‐14
3.5. Implementingmachinesequences................................................................ 3‐15
3.5.1. Themain()programstructure....................................................... 3‐17
3.5.2. TheMachineSequences()Function................................................ 3‐18
3.5.3. TheMachineSequencesTimer()function........................................ 3‐20
3.6. Handlingerrors ...........................................................................................3‐28
3.7. Samplecode ...............................................................................................3‐30
Chapter4: G‐MASsoftwarestructureandinterfaces..................................................4‐46
4.1. TheHost.....................................................................................................4‐47
4.2. TheG‐MAS .................................................................................................4‐49
4.2.1. FunctionBlocksInterfaces............................................................ 4‐50
4.2.2. Multi‐AxisMotionControlCoreStructure...................................... 4‐50

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
1‐2
4.3. Thedevicenetwork.....................................................................................4‐53
4.4. Additionaltools...........................................................................................4‐54
4.4.1. KPAStudio .................................................................................. 4‐54
4.4.2. IPConfigurationoverUSB ............................................................ 4‐54
Chapter5: TheXYZrobotexample ............................................................................5‐55
Chapter6: FurtherProgrammingExamples................................................................6‐56
Chapter7: PCSoftwareInstallationandhowtouse ...................................................7‐57

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
1‐3
Chapter 1:
About the G-MAS and this manual
ThischapterdescribestheG‐MASproductandtheorganizationofthismanual.Personsbeginningto
understandtheG‐MASandprogramit,shouldreadthismanualcarefully.However,experienced
G‐MASusersmayomitthischapter.
1.1. What is the G-MAS
TheGoldMaestro–G‐MASisanadvancedmulti‐axismachinecontroller.
Itisaprogrammablecontrolunit,withbuilt‐in,ready‐to‐use,standardized
functionalitiesforcommunications,motions,emergencies,timing,eventsandall
thatisrequired(anddesired)toimplementacompletemulti‐axismotioncontrol
system.
Thefigurebelowpresentsthestructureofamotioncontrol
systembasedontheG‐MASandElmo’sdigitaldrives.This
systemisbasedonthefollowingthreelayers:
•Hostcomputer(orPLCorHMIPanel)
•G‐MAS
•Devices(DigitalDrives,I/Ocontrollers,networkencoders…)
Themachine’shostcomputer(orPLC,HMIpanel)typicallyexecutestheinterfacestothemachine
operatorandperformshigh‐levelmanagementandmachinealgorithms,asnecessary.

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
1‐4
Digitalservodrivescontrolanddrivemotors,witheachdrivegenerallyresponsibleforasingleaxis
(control,motions,safety,limits,etc.),aswellassomeI/Osthatmaybeconnectedtothedigitalservo
drive.WithElmointelligentdigitalservodrives,eachdrivecanbeprogrammedtoperformsimple
andadvancedprocesses,whichisonlylimitedtoaxislevelprocess(incontrasttomachine,ormulti‐
axeslevel).
I/Ocontrollersandotherdevicescanbeaddedtothedevicenetwork.
Thehostcomputer(orPLC,HMIpanel)isresponsibleforuserinterfacesandhigh‐levelmachine
processes,whereasthedigitalservodrives(andI/Oscontrollers)executeaxisorI/Olevelprocesses.
Therefore,anintermediarylayerisnecessarytoperformthemachine’ssequencesandmulti‐axis
synchronizedmotions.ThisisexactlywheretheG‐MAScomesin.
TheG‐MASislocatedintheintermediarylayer.Itreceiveshigh‐levelcommandsfromthehost
computer,performstherequiredmachinesequences,calculatesmulti‐axismotionsand,
opportunely,communicatesviathedevicenetworktosynchronouslysendcommandstoeachaxis.
Obviously,theG‐MASalsocollectsstatusesfromthenetworkdevicesandinturnsendsitsown
statusestothehostcomputer.
Fromthenetworkdevicesview,theG‐MASisimportant,sinceeachnetworkdeviceviewsonlyavery
narrow(axis,I/O)portionoftheoverallsystemandthereforecannotcreateorcontroloverallsystem
sequencesormulti‐axissynchronizedmotions.ThenetworkdevicesrequireadeviceliketheG‐MAS
totakethisresponsibility.
Fromthehostcomputer(orPLC,HMIPanel)view,theG‐MASisnotasimportant,asintheory,one
canimplementallthefunctionsoftheG‐MASintothehostcomputer.However,thisentailsavariety
ofsignificantdrawbackse.g.hugedevelopmenttime,significantrisks,non‐modularimplementation,
“inventingthewheel”etc.thatareeasilyandelegantlysolvedusingtheG‐MAS.
Withitsturnkey,in‐builtfunctionality(standardimplementationof:PLCopenmotions,Ethernet
communications,CANopen,CANopenoverEtherCAT,etc.)andsupportforCuserprograms,toeasily
implementamulti‐axismotioncontrolsystem,youonlyneedtowriteyourfirstCprogramfortheG‐
MAS.Thisisprobablywhyyouarenowreadingthismanual…
1.2. G-MAS Features
ThefollowingpresentssomeoftheG‐MASfeatures.YoumayrefertoElmo’swebsiteat
www.elmomc.comforadditionaldetailedinformationandbrochures.
•Highperformance,distributedmulti‐axisnetworkcontroller,withreal‐timeextensionofthe
Linuxoperatingsystem.
•Controlsupto100axesoverdevicenetworkwithahighlevelofsynchronizationandaccuracy.
•Hostcommunicationchannelsandprotocols:
Ethernet,TCP/IP,UDP(fastbinaryprotocols,MODbus,Ethernet/IP,Telnet,FTP,HTTP)
USB2.0
•Devicenetworks(fieldbuses)andprotocols:
EtherCATreal‐timedevicenetworking(CoE,Distributedclock),or:

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
1‐5
CANopen:DS‐301,DS‐305,DS‐401(I/Odeviceprofile),DS‐402(driveandmotioncontrol
deviceprofile)
•Built‐infunctionalblocklibraries:
Communicationwithhost
CANopenoverCANandEtherCAT
PLCopenmotion
Events
Datarecording
•Programming:
Nativeapplication'C'programmingonthetarget
IEC61131‐3,PLCopen(futurefeature)
•Packageandpowersupply:
Verycompact,spacesavingpackage.TheGoldLionforembeddedmilitaryapplications.
DCpowered:14Vto196V.
ItisimportanttonotethatoneofthemaincriteriathatguidedtheG‐MASdevelopment(together
withallElmo’sGoldfamilyproducts)wastousemarket‐leadingstandardswhereverpossible.
Furthermore,eachstandardwasaccuratelyimplemented,ensuringmandatorycomplete
implementationofthestandard.WithElmo’sGoldproductfamily,thiscanbefound,forexample,in
thehostcommunication(MODbus,Ethernet/IP),DeviceNetwork(CANopen,CANopenover
EtherCAT),safety,PLCmotionlibrary,I/Osinterfacecircuits,etc.
1.3. What the Document Covers and How to Use It
ThismanualisorganizedtocreateaprogressivepathfortheuserstartingfromtheG‐MASbasicsto
graduallyachievethepotentialforadvancedandcomplexsystemsprogramming.
ThemanualbeginsexplainingtheG‐MASstructureandprogrammingguidelinesandcontinueswitha
detailedexplanationofanApplicationprogramwrittenforanXYZrobot.
Theexplanationstartswiththetop‐levelcodestructureandlater,systematically,immersesintothe
codedetails.Therefore,forbeginners,itisrecommendedtoreadthismanualchapter‐by‐chapter.
Themanualanditscodeexamplesareorganizedtoallowthereadertolearn,chapterbychapter,
firstlyabouttheG‐MASfunctionsandeaseofuse,andthenprogressively,aboutthedetailsof
implementation,withincreasingdetailsrevealedinlaterchaptersorexplanation.

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
2‐6
Chapter 2:
Just Before Starting Up
ThischapterpresentstherequiredpreparationsbeforeyoucanstartusingtheG‐MASanditsPC
softwareenvironment.
Inaddition,itexplainshowtheincorporatedexamplesrelatetoElmo’sdemosuitcase,andhowthey
canbeadaptedtomatchyourspecificsystem.
Thischaptermustberead,andthepreparationsdescribedwithin,implemented,tobe
properlyproficientinoperatingtheG‐MASanddevelopinguserprogramsforit.
2.1. Preparing Your Computer
ThePCsoftwareenvironmentfortheG‐MASincludestheEAS(ElmoApplicationStudio)andtheC
programmingdevelopmentenvironment.Theseapplicationmodulesmustbeinstalledtobeableto
operatewiththeG‐MAS.
TheEASisElmo’ssetupandmaintenanceapplicationfortheGoldlineproducts,includingtheG‐MAS
andGoldDrives.AsaG‐MASuser,youwillneedthisapplicationtoconfigureyoursystem(network,
devices,etc.),communicatewiththeG‐MAS,andtoperformavarietyoffeaturesincorporated
withinEAS,e.g.tocreate,recordanddisplaymulti‐axismotions.
TheCprogrammingdevelopmentenvironmentisnecessarytodevelop(write,download,debug)C
programsfortheG‐MAS.
PleaserefertoChapter7:PCSoftwareInstallationandhowtousefordetailsregardingthe
installationoftherequiredG‐MASsoftwareprocess,andhowtousethesesoftwaremodules.
Pleasecontinueusingthismanualonlyafterproperlyinstallingtheapplicationsandunderstanding
howtousethem.Theremainderofthismanualassumesthattheuserisfamiliarwiththeapplication
environments.
2.2. Using the Manual’s Examples
TheentireCprogramsexamples(unlessspecificallymentionedotherwise)includedwithinthis
manualweredevelopedfor,andtestedwithElmo’sdemosuitcase.ThissuitcaseconsistsofaG‐MAS
andtwoElmodigitalservodrives(andmotors)connectedtoitoveradevicenetwork.

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
2‐7
TheGoldLinedemosuitcaseincludestwoGoldlinedigitalservodrivesconnectedtotheG‐MASover
EtherCATwhiletheSimplIQLinedemosuitcaseincludestwoSimplIQdrivesconnectedtotheG‐MAS
overtheCANbus.
Therefore,theexamplesprovidedwithinthismanualareadjustedtoeitherconfiguration,whether
GoldorSimplIQdemosystem,andismentionedwithineachexample.However,notallexamples
mayworkforadifferentsystemconfiguration.
Itisthereforerecommendedtoconsiderpurchasingofademosuitcase(GoldorSimplIQ,depending
onyourneeds)forconvenientlypracticingthismanual’sexamples.PleaseaddressyourlocalElmo’s
saleschanneltoorderademosuitcase.
Ifyouprefertouseyourownsystemforpracticingthismanual’sexamples,youwillneedtoslightly
modifythemaccordingtothestructureofyourownsystem.Usetheguidelinesdescribedwithinthe
followingthetabletoproperlymodifythismanual’examples.
YourSystemStructureNecessarymodificationsfor
exampleswrittenforCAN
Necessarymodificationsforexamples
writtenforEtherCAT
G‐MASwith2xSimplIQ
drivesoverCANbusNone
Resourcefilethatrepresentsthe
system.
ShouldcalltheGetCommStatistics()
APIinordertocheckthatthenetwork
setupisOK.Thisisinsteadof
NetworkInfo()whichisforCAN.
ChangeoperationmodetoCyclic
PositionmodeandnotInterpolated
Position.
G‐MASwith1xSimplIQdrive
overCANbus
Newresourcefile.Orchangethe
secondaxistovirtualmode.
Asaboveplusthechangestotheleft
forthesingleaxis.
G‐MASwithNxSimplIQ
drivesovertheCANbus
(N>2)
AsaboveAsabove
G‐MASwith2xGolddrives
overtheCANbus
Currently,weuseinterpolation
mode,asdefinedinDS402ver.
II.Thenewstandardusescyclic
positioninstead.
Currently,weuseinterpolationmode,
asdefinedinDS402ver.II.Thenew
standardusescyclicpositioninstead.

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
2‐8
YourSystemStructureNecessarymodificationsfor
exampleswrittenforCAN
Necessarymodificationsforexamples
writtenforEtherCAT
G‐MASwith1xGolddrive
overtheCANbusAsaboveAsabove
G‐MASwithNxGolddrives
overtheCANbus(N>2)AsaboveAsabove

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
3‐9
Chapter 3:
Programming Practices and Guidelines
ThischapterdescribesthepracticesandguidelinesusedbyElmo’steamtodevelopedexamplesand
applicationprogramsfortheG‐MAS.TheseguidelinesarebasedonworldwidecommonC
programmingpracticeswithsomeexpansionsrequiredtocreateacompletesetofguidelinesand
conceptsfortheG‐MASCprogramming
Mostoftheguidelinesdonotreallyaffecttheexecutionofthecode(donotdirectlyimprovecode
size,orspeed,orperformanceingeneral),so,whyisitsoimportanttousethem?Forthefollowing
reasons:
1.Mostoftheguidelinesrelatetocodereadability,portability,easeofdevelopment,and
debugging.Thismeansthatyourdevelopmentprocessisassumedfasterandeasierwith
theseguidelines.
2.Someoftheguidelines,especiallythosethatrelatetoprogrammingconcepts,aremore
thanjust“howtomakemycodeclearer”.Theyreallyaffecttheeaseofimplementation,
executionperformance,andthetime‐to‐marketofyourproject.Oneoftheseguidelinesis
theconceptofStatesMachineprogramming,asyouwillseelateronthismanual.Itisone
offewpossiblemethodstoimplementmachinesequences,andpractically,itproveditself
thesimplestandthemostsuccessfulmethodtouse.
3.YoucanbetterusetheexamplesandCaseStudiesprovidedbyElmo,astheyareallwritten
accordingtotheseguidelinesandprogrammingconcepts.
4.Andmostimportant,toenablethebestsupportyoucangetfromElmo.Application
programsmaybecomelargeandquitecomplexforsignificantprojects.Usingyourown
programmingconcepts,asgoodastheysurelyare,willmakeitmuchmoredifficultfor
Elmo’ssupportengineerstoperformin‐depthanalysis.Youmayneedtosendusyourcode,
orpartsofit,atsomepointinthefuture,anditmaybecomeimpossibleforustoanalyze
andtrackitsdetailsunlessitiswrittenaccordingtotheguidelinesandconceptsdescribed
inthischapter.
Itisthereforestronglyrecommendedtousetheseguidelines,practicesand
programmingconceptswhendevelopingyourownCprogramsfortheG‐MAS.
3.1. Projects and files
Thissectiondescribessomeguidelinesregardingorganizationandnamingofprojectsandfiles.

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
3‐10
3.1.1. Project Location and Naming
Allprojects(applications)shallbelocatedundertheC:\GMAS\MyGMASProjectsdirectory,whichis
createdduringthesoftwareenvironmentinstallationprocess.TherootdirectoryC:\canbereplaced
withtheactualnameofyourdisk.
Eachprojectshouldbelocatedwithinaspecificdirectoryundertheabovelocation,withonlyone
projectwithinagivendirectory.
Thenameofaproject’sdirectoryshouldreflectthenameoftheproject(application).Forexample,
fromElmo’ssetofCprogramsexamples:“C_ReadDigitalInput”(seescreensnapshotbelow).Note
thatthenameoftheproject’sdirectoryrespectsthefollowingguidelines:
•Itreflectstheproject/applicationcontents.
•Ithasnospaces.
•Ifitconsistsoffewwords,eachwordstartswithaCapitalletterforeasyreading.
•Finally,forconvenienceonly,Elmoaddsaprefixtotheproject’sname(inthiscase:“C_”)toforce
thelistoftheprojectstoappearinagivenorderwithinWindowsexplorer.Thisisdoneinorder
toorganizeourbuilt‐inexamplesinadesiredorderforthereadersofthismanual.Youarenot
requiredtoaddthisprefix(seecustomer’sprojectWalkingRobotPrototypewithinthescreen
snapshotbelow).
Theabovethreeguidelinesfornamingproject’sdirectory,arealsoapplicablefornamingallofthe
project’sCandHfiles.Thenamemustreflectthecontentofthefile,includenospacesandeach
wordinthenameshouldstartwithacapitalletter,e.g.:ReadDigitalInput.c

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
3‐11
3.1.2. Project’s Files
EachprojectwillbebasedonamainCfile,respectingthefollowingguidelines:
•Itsnamewillbeidenticaltotheproject’sdirectoryname(withouttheprefix,ifused).For
example:ReadDigitalInput.c
•Itwillincludethemain()function,whichwillbethefirstfunctionwithinthefile.
Eachprojectwillalsoincludeamainheader(*.h)file,whichwillbealsonamedwiththenameofthe
project(e.g.ReadDigitalInput.h)andwillincludealldefinitionswhicharespecificfortheproject
(suchasconstants,functionsprototypes,etc.).
Inaddition,thedevelopercancreateadditionalcodeandheaderfiles,asmaybeneededtoproperly
organizethevariousCfunctions.Allfilesshouldbenamedusingtheabovefilenamingguidelines.
3.1.3. Project’s Description Files
Elmohighlyrecommendsthatanapplicationprogrammershouldaddsomefilestoaproject’s
directorythatexplaintheprojectgoals,tasks,methodsofimplementation,etc.Itcanbeasimple
readmefileorfilesthataremorecomplex(machinespecification,motionsequences,machine’sATP,
designreviewsfortheimplementation,etc.).Thisinformation,ifsuppliedwiththeoverallproject
codefiles(foranewmemberinthedevelopmentteam,and/orforElmo’sstaffforsupport,etc.)can
significantlyimproveprocessese.g.learning,supportfortheproject,etc.
Pleaserefertotheproject’sdescriptionfilesincludedwitheachofElmo’sexamples(locatedat
C:\GMAS\MyGMASCProjectsaspartoftheDevelopmentSoftwareinstallationprocess)forexamples
ofsuchfiles.
Projectsdirectory
ReadDigitalInputproject
WalkingRobotproject

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
3‐12
3.2. Functions, Variables and Constants
Thenamingandusageoffunctions,variablesandconstantsshouldabidebythefollowingguidelines:
•Functionsshouldbenamedsimilarlytofiles.Forexample:MainTimer().
•Variablesshouldalsobenamedsimilarly,butshouldbeprecededwiththevariabletypeinlower
case,accordingtothetablebelow.Forexample:iSpeedcanbethenameofanintegervariable
holdingavalueofspeed.
TypePrefixExample
IntegeriiMotorSpeed
UnsignedintegeruiuiUpperLimit
LongllPosition
UnsignedlongululLimitPosition
ShortssAnalogInput
UnsignedshortususDigitalInputs
CharccErrorString
UnsignedcharucucASCIICode
EnumeeTargetPositions
StructststHalt
•Constantsshallbenamedusingthefollowingformat:MY_CONSTANT(allcapitals,“_”between
eachword).
•Globalvariablesareallowedandrecommendedforvariablesaccessedbymorethanone
function.TheyshouldbedefinedatthetopofaCfile(inmostcases,theproject’smainCfile).
TheGlobalvariable’snameshouldhaveanadditional“G”atitsprefix,e.g.glPosition,
gcErrorString.ThiswillindicatetotheprogrammerthatthevariableisGlobal.
3.3. C and Header Files
ThecodewithintheCfilesshouldrespectthefollowingguidelines:
•Themainproject’sCfileshouldstartwithsomecommentslinesdescribingtheapplication.
•Eachfunctionshouldbeprecededwithsomecommentslines,providingasmuchdetailsas
possibleaboutthefunction(whatitdoes,inputandoutputparameters,whowroteit,version,
etc.).
•Themain()functionshouldbethefirstfunctionwithintheproject’smainCfile.Itshouldbe
typicallydefinedas:Voidmain()
meaning,noargumentsareexpectedwhenexecutingtheprojectandnoreturnedvaluetothe
operatingsystemuponexitingtheapplication.
Incaseargumentsshouldbepassedtotheapplicationcodefromtheoperatingsystem,orifthe

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
3‐13
applicationshouldreturnavaluetooperatingsystemuponexiting,pleaserefertotherelevant
exampleincludedwithintheexamplesdirectory(c:\GMAS\MyGMASCProjects).
•ACfileshould“include”onlytheheaderfilesnecessary.
•Thecodeshouldnotincludenumbers.Constantsshouldbedefinedwithintherelevantheader
fileandthevalueoftheconstantshouldbedefinedonlywithintheheaderfile.Forexample:
HOMING_SPEED.
•Thisincludesvalueslike“0”and“1”.DefineOKandNOT_OK(and/orsimilarly,likeTRUE,FALSE).
•Codeshouldbeverticallyalignedandproperlynested.
•UseTABS,notspacestoalignthecodevertically.
•Openingandclosingbrackets(“{“and“}”)shouldbeeachwritteninaseparateline.
•Comments(filesandfunctionstitles,in‐linecomments,endoflinecomments,etc.)shoulduse
theformat(orstyle)asshownwiththesamplecodeattheendofthischapter.
3.4. Wrapper functions
Wrapperfunctionsfilesarefilesthatholdasetoflogicallyrelatedfunctions(actually,alibraryof
functions).Eachfunctioniswrittento“hide”arelativelycomplexprocess/codewithasimple
interfacefortheprogrammer.AnexamplecanbeaWrapperFunctionsfilethatwillincludeasetof
functionsformotion.Itmaycontain,forexample,afunctionlikeMyMoveAbsolute(dSpeed,
dPosition).Thisfunctionhasaverysimpleinterface(canbeeasilyusedtocreateamotion,asallyou
needtoenterarevaluesforSpeedandPosition),butinternally,itwillusethelesssimplePLCopen
Motionfunction,includingparametersinitializations,validitychecks,etc.
WrapperFunctionshelptokeepthemaincodecleanerandmoreelegant.Whilereading(and
debugging/modifying)themaincode,onewouldliketoeasilyseetheimplementedmachine
sequence(programflow)andthiscanbedoneonlyifthedetailsofthecodearehiddenwithin
functioncalls.
Acalltoafunctionnamed“MMC_InitSystem(…)”willbemuchclearerthanplacingthedetailedcode
ofthesysteminitialization(axes,communicationetc.)onlinewithinthemaincode.Therefore,if
necessary,thedevelopercanperformin‐depthanalysisonthedetailedcodeinthewrapperfunction.
WrapperFunctionscanbeusedforvariousproposes:
•HidingComplexand/orNotImportantCodeSegments
•Hidingrepeatedsegmentsofcode
•Providingeasierinterfaces(“shortcuts”)forrepeatedcallstofunctions
3.4.1. Hiding Complex and/or Not Important Code Segments
Whenprogrammingacomplexsynchronizeddistributedsystem,theoverallcodewilltypically
includerelativelycomplex,longand“non‐interesting”segmentsofcode.Thesesegmentsgenerally
dealwiththedetailedimplementationofthesysteminitialization,management,errorhandling,
terminationetc.Thiscodeisnotnecessarilyrelatedtothemaingoaloftheproject–toperformthe
machinesequence.

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
3‐14
Ifthesesegmentsofcoderemainwithinthemaincode,themaincodewillbecometoocomplex,
blockingreasonablereadingandtrackingofwhatismostimportant;theimplementationofthe
machinesequencesandlogic.
WrapperFunctionscanbeusedtohidethesesegmentsofcode.SuchWrapperFunctionsare
suppliedbyElmosothatourexamplescanbereadandunderstoodmucheasier.
3.4.2. Hiding Repeated Segments of Code
Repeatedsegmentsofcode,evenifnotcomplex,andevenifimportanttounderstandtheprogram
flow(themachinesequences),canbehiddeninsideaWrapperFunctiontominimizethemaincode
length.
3.4.3. Providing Easier Interfaces
Someofthebuilt‐inG‐MASFunctionBlockfunctionshavecomplexinterfaces,i.e.afunctionwith
manyarguments,withsomeoftheseargumentsalsocomplexstructures.Thiscomplexityis
necessarytomaintaincompatibilitywithstandardslikePLCopenMotionandtoenablefulloperation
ofthefunction.
However,inmostsituations,andyourcasemaybeoneofthem,theapplicationdoesnotneedfull
operationoftheFunctionBlock,butonlyneedsasmallsubsetoftheFunctionBlockinterfaces.
Underthesecircumstances,theprogrammer(orElmowithinitsexamples)maydefineanew
functionthatwillhaveasimpleinterfacewiththeprogramandwillinternallyassumesomedefaults
fortheremainingfunctionsarguments.
Anexamplecanbeasimplemotionfunction(tobetypicallylocatedwithinaWrapperFunctionsfile
thatwillincludemanyfunctionsforsimplemotions),e.g.MoveAbs(iPosition).
Thisfunctionacceptsonlyoneargument,thedesiredposition,andcreatesamotiontothistarget
position,usingthefullmechanismofthePLCopenMotionFunctionBlocks.Itwillassumedefault
valuesfortheadditionallyneededarguments,likespeedandacceleration,orwillkeepthevalues
usedrecently–dependingontheactualcodingoftheMoveAbs()function(thisofcoursemustbe
clearlydocumentedfortheusersofthewrapperfunction).
Assumingthattheuserunderstandswhatarethedefaultactionstakenbythewrapperfunction,itis
mucheasiertocalltheMoveAbs()thanthestandardPLCopenMoveAbsolutefunction.
Anotherexamplemaybe:
intiEndMotionReason=MoveAbsWaitEndMotion(iPosition)
Thisisclearlyafunctiontocreatemotionandtowaittoitsend(whateveristhereason;reachingthe
target,limit,error,…).Thefunctionreturnsonlywhenthemotionends,returningthereasonforthe
endofmotion.
Ingeneral,WrapperFunctionsarelibrariesoffunctionsthatareaimedtosimplifythe
writingandthereadingofthemaincode–themachinesequences.

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
3‐15
ElmosuppliesasetofWrapperFunctionsfilesaspartofitssetofexamples.Youcandefineand
createyourownsetofWrapperFunctionsfiles(startingfromscratchorbasedononeofElmo’s
examples),assuitableforyourprojectsandstyleofwriting.
WrapperFunctionsfilesshouldfollowthefollowingguidelines:
•Elmo’ssuppliedWrapperFunctionsfilesshouldnotbemodified.Instead,ifmodificationsare
necessary,copythefiletoanewfileandmodifyit.
•EachWrapperFunctionsfileshouldincludeasetoffunctionsthatarelogicallyrelated.Each
functionshouldhaveasimpleuserinterface.
•EachWrapperFunctionsfileshouldbenamedtoreflectitscontents.Forexample:
SimplifiedSynchronizedMotions.c.
•EachWrapperFunctionsCfileshouldhaveaheaderfile(*.h),withthesamename.Theheader
filewillincludedefinitionsrelevanttotheWrapperFunctionsfile,aswellasprototypesforthe
wrapperfunctionsincludedwithinit.
•Thegeneral(notexamplespecific)WrapperFunctionsfilesthataresuppliedbyElmo,arelocated
undertheG:\GMAS\GMASCWrapperFunctionsFiles.
•AdditionalWrapperFunctionsfilesthataremorespecifictoagivenproject/applicationshouldbe
locatedwithintheprojectdirectory.
•IfaWrapperFunctionacquiresanumberofassumptions(defaultvalues,keepingprevious
values,etc.),theseassumptionsmustbeclearlydocumentedfortheuser.
•ItisstronglyrecommendedthataWrapperFunction(unlessitwaswrittentoaveryspecificand
fixedproject)willnotincludedefaultvaluesforparameters.Aneasymistakecanbe,for
example,toassumeavalueof100000(forexample)forasimplifiedmotionfunction.Thismay
workperfectlyforagivenexample,butwillnotbesuitableforafutureexample,whennoone
willrememberthisdefaultdecision.Othersolutionsarerecommended(forexample,toincludea
WrapperFunctionwithinthefilethatwillbeusedtoinitializeallthisdefaultvaluesfromthe
maincode).Somethinglike:
InitMotionsWrapper(iSpeed,iAcceleration,iDecelaration,iMode,iSmoothing,…)
ThentheprogrammercanfreelyuseMoveAbs(iPosition)etc.
3.5. Implementing machine sequences
Aprogramthathandlesmachinesequencesshouldanswerthefollowingrequirements:
•Capabletohandleanumberofsequencesinparallel.
Forexample,assumingthattheG‐MASshouldhandleamachinewiththreeaxes(e.g.X,YandZ)
togetherwithanAutomaticLoaderthatshouldloadandunloadtheobjectto/fromthemachine,
itselfconsistingof4axes.
Eachofthesesub‐assembliesshouldbecontrolledinparallel,havingsequencesthatare
independentwhilenecessarilysynchronized.
AUserApplicationattheG‐MASshouldbeabletoexecutebothsequences(themachineandthe
Loader)inparallel,andtosynchronizethem,whensynchronizationisrequired.

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
3‐16
•Capabletohandlebackgroundsystemprocessessuchasvalidationread,andhandlestatuses,
emergencies,etc.
Manytasksshouldbecontinuouslyormoreaccurately,periodically,handledbytheapplication.
Thesetasksshouldbeexecutedindependentlyofthemachinestatusand/ormodeofoperation.
•Capabletoalwaysbereadytoreceiveincomingcommunication(typically,fromtheHost)with
reasonableresponsetimeandmoreimportant,withpre‐definedlimitedresponsetime.
Theapplicationprogramshouldnotbetoobusy(intermsoftime)withanygiventask,and
shouldalwaysbeabletoobtainandproperlyrespondtoincomingcommunication.
•Determinism.
Theapplicationprogramshouldexecutethesamesequences,respondtoincomingmessages,
andcreatecommunicationstothedevicenetwork,inadeterminedway,withlittledelaysor
jittersandwithinapredefinedlimit.
•Maintainability.
Finally,butnotlessimportantistherequirementforeasydevelopmentandmaintenanceofthe
program.Theprogrammustbeorganizedinawaythatcomplexsequencescanbeeasilywritten,
controlled,andmaintained.
Therearenumerousmethodstowriteaprogramthatwillanswertheaboverequirements.For
example:multi‐taskingandinterrupts.
Elmohasanextensiveexperienceinthedevelopmentofuserapplications.Wehaveacquiredthis
experienceduringmanyyearsofcustomerssupportandduringin‐housedevelopmentofuser
applications.
Basedonthisexperience,wehaveconcludedthattheoptimalmethodtowriteprogramsfor
machinesequencesisastructurethatisbasedonStatesMachines.Thisprogrammingstructure
optimallyanswerstheaboverequirements.
WithaStatesMachinestructure,aprogramdoesnotneedMulti‐Tasking(acomplexstructurefor
mostprogrammers,andobviouslymostMotionControlengineers)andinmostcaseseveninterrupts
arenotrequired.AllthatisneededisanunderstandingofthebasicsofStatesMachine
programming.Thecodethenbecomesverysimpletodevelopandtomaintain.
AllprogramsexamplesprovidedbyElmoareimplementedusingStatesMachinestructure.Itis
stronglyrecommendedtousethisprogrammingstructure.ItwillenableeasieruseofElmo’s
examples,allowElmo’ssupportteamtoprovidebetterandfastersupport.Inaddition,itwillshorten
yourtime‐to‐marketandreduceyourdevelopmentriskssignificantly.
ThisisagoodpointtostartexplainingthedetailsofStatesMachineprogrammingstructure.The
explanationisnotsimple,andispresentedinasystematicprocedure.

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
3‐17
3.5.1. The main() program structure
Elmo’srecommendedstructureforthemain()functionofaG‐MASUserApplicationprogramis
presentedinFigure1:
Figure1:Main()programstructure
Themain()startswithacalltoMainInit(),afunctionthatperformsallprogramandsystem
initializations(moreonthislaterwithinthemanual’sexamples).Afterallinitializationsare
completed,theMachineSequences()functioniscalled.Thisfunctionintentionallystartsthe
executionofthemachinesequencesandmotions.Duringthemachineoperation,the
MachineSequences()functiondoesnotreturntothemain(),untiltheprogramrequeststoterminate
(dueto,e.g.errors,userrequesttoclose,etc.).Whenthemachineoperationiscomplete,the
MachineSequences()functionreturnstothemain(),whichcallstheMainClose()functiontoclose
everythingthatrequiresclosing,beforetheprogramterminates.
Thisisthemain()functionoftheprogram.Simpleandcleanaspossible.Nowweprogressintothe
MachineSequences()functiontofindtheimplementationofthemachinesequences,usingtheStates
Machinestructure.

G‐MAS–GoldMaestroSoftwareUser’sManual SoftwareUserManual
XXXXXXXXXXXX(0.01)
3‐18
3.5.2. The MachineSequences() Function
Figure2presentsElmo’srecommendedstructurefortheMachineSequences()function.
Pleasenotethatablockcoloredred,isasegmentofcodethatrequirestoexecuteasfastaspossible
andshouldnotincludeanyprocesswitharelativelylongexecutiontimeordelay.Thiswillbecome
especiallyrelevantasweinvestigatedeeperwithintheprogramstructure.Obviously,itshouldnot
includeanyendlesslooporanywaitingforasystemprocesstoend.Aredcoloredblockshould
includeasegmentofcodethatunconditionallyexecutesalimitedsizecode,withnodelaysorwaits.
MachineSequences()startswithacalltoMachineSequencesInit().Thisfunctioninitializesallvariables
asmayberequiredtoactivatetheMachineSequencesTimer()andtomanagetheStatesMachine
(refertoFigure2).
Immediatelyafter,MachineSequences()callstheEnableMainTimer(TIMER_CYCLE(Remember,the
format(CAPITAL_LETTERS)referstoaconstantdefinedbytheprogrammerintheheaderfile))to
starttheexecutionoftheMachineSequencesTimer()functionandtodefinethatitwillbe
automaticallyexecutedbytheOperatingSystem(OS)eachTIMER_CYCLEms.Asatypicalvaluefor
thesedescriptions,let’sassumeaTIMER_CYCLE=20ms.
Fromthispointon,theOSactivatestheMachineSequencesTimer()every20ms.Thistimerfunction
actuallyhandlesandmanagestheStatesMachine,asexplainedbelow.
TheMachineSequences()functionnowentersanendlesswhileloop,waitingforaglobalvariable
(giTerminate)toindicatethattheMachineSequencesTimer()isaskingtoterminatetheprogram.The
giTerminatevariablewillinitializetoFALSEwhentheMachineSequencesInit()functionstarts,andwill
optionallybesettoTRUE,whenandifneeded(possibleforaprogramtoneverterminate)bythe
MachineSequencesTimer()function.
Generallyspeaking,thisendlesswhileloopneedstodonothingexceptwaitforatermination
request.InordernottoloadtheCPUjustforrunning‐in‐loops‐doing‐nothing,aSleep(SLEEP_TIME)is
insertedintheloop.AtypicalvaluefortheSLEEP_TIMEis100ms,meaning(inourexample)thatthis
backgroundloopisactivatedapproximatelyeach5cyclesofthetimerfunction(whichisactivated
every20ms).
Notethatthetimermethodisanaccuratemethodtocreatecallstothetimerfunctioneachgiven
period.TheSleep()methodisnotaccuratebuttimingaccuracyisnotanissueforthisidleloop.
Finally,sincewehavehereabackgroundloopcodethatisactivatedperiodicallyinarelativelylow
rate,wecanuseittoperformsomelesstime‐criticalprocessesasmayberequiredbythe
application.Processes,thatyoumaynotwanttoincludeinthemainStatesMachinewhichis
Table of contents
Other Elmo Controllers manuals