Upload
vothu
View
253
Download
2
Embed Size (px)
Citation preview
UniversityCollegeofSoutheastNorway
http://home.hit.no/~hansha
OPCandReal-TimeSystemsinLabVIEW
Hans-PetterHalvorsen,2016.10.31
ii
PrefaceOPC(OLEforprocesscontrol)isastandardinterfacebetweennumerousdatasources,–suchasprogrammablelogiccontrollers(PLCs),remoteterminalunits(RTUs),andsensorsonafactoryfloor–toHMI/SCADAapplications,applicationtools,anddatabases.WithOPC,yourdevice-sideserverandapplicationsoftwarecancommunicatewithoutyourduplicatingdevicedriverdevelopmentandprovidingsupportforhardwarefeaturechanges.TheOPCFoundationdefinesthestandardsthatallowanyclienttoaccessanyOPC-compatibledevice.
[Figure:www.ni.com]
InstallationRequirements
ThefollowingsoftwareisusedinthisTutorial(youdon’tnecessarilyneedtoinstallall;itdependsifyouareinterestedineverythingorjustpartsofthisTutorial):
• LabVIEW• LabVIEWReal-TimeModule• CompactRIO• NI-DAQmx• NIMeasurement&AutomationExplorer• LabVIEWDataloggingandSupervisoryControlModule
Inaddition,thefollowingsoftwarewillbeneededinthisTutorial:
• NIOPServers(Evaluationversionavailablefromwww.ni.com)• MatrikonOPCSimulationServer(freedownloadfromhttp://matrikon.com/)
iv
TableofContentsPreface......................................................................................................................................ii
InstallationRequirements.....................................................................................................ii
TableofContents.....................................................................................................................iv
1 IntroductiontoLabVIEW...................................................................................................1
1.1 Dataflowprogramming...............................................................................................1
1.2 Graphicalprogramming..............................................................................................2
1.3 Benefits.......................................................................................................................2
1.4 LabVIEWMathScriptRTModule................................................................................3
2 IntroductiontoOPC..........................................................................................................4
2.1 OPCServer..................................................................................................................5
2.1.1 MatrikonOPCServerforSimulation....................................................................7
2.1.2 NIOPCServers.....................................................................................................7
2.2 OPCClient...................................................................................................................7
2.3 Tags.............................................................................................................................8
2.4 WhyDoWeNeedOPCStandards?.............................................................................8
3 IntroductiontoReal-TimeSystems.................................................................................10
3.1 LabVIEWReal-TimeModule.....................................................................................10
4 IntroductiontoEmbeddedSystems................................................................................11
4.1 SomeExamplesofEmbeddedsystems.....................................................................11
4.2 EmbeddedhardwareandReal-TimesystemsfromNationalInstruments...............12
5 Real-TimeVIsinLabVIEW................................................................................................13
5.1 Synchronization........................................................................................................13
5.2 Semaphores..............................................................................................................14
v TableofContents
Tutorial:OPCandReal-TimeSystemsinLabVIEW
QueueOperations...............................................................................................................15
5.3 TimedLoop...............................................................................................................17
6 MultithreadinginLabVIEW.............................................................................................18
6.1 Multitasking..............................................................................................................18
6.2 Multithreading..........................................................................................................18
7 DataSocket......................................................................................................................21
7.1 Architecture..............................................................................................................22
7.2 DataSocketServer.....................................................................................................23
7.3 DataSocketinLabVIEW.............................................................................................23
8 OPCServersfromNationalInstruments.........................................................................25
8.1 NIOPCServers..........................................................................................................25
8.1.1 OPCQuickClient................................................................................................26
8.2 SharedVariableEngine.............................................................................................28
9 MatrikonOPCSimulationServer......................................................................................30
9.1 MatrikonOPCServer.................................................................................................30
9.2 Aliases.......................................................................................................................31
9.3 MatrikonOPCExplorer(Client)................................................................................32
10 UsingOPCfromLabVIEW................................................................................................34
10.1 OPCURL....................................................................................................................34
10.2 ReadOPCData..........................................................................................................35
10.3 WriteOPCData.........................................................................................................36
11 LabVIEWDataloggingandSupervisoryControl...............................................................38
11.1 FunctionsandVIsPalettes........................................................................................39
11.2 DSCModuleControlsPalettes..................................................................................40
11.3 CitadelDatabase.......................................................................................................40
11.4 HistoricalDataViewer..............................................................................................41
vi TableofContents
Tutorial:OPCandReal-TimeSystemsinLabVIEW
11.5 DistributedSystemManager....................................................................................41
11.6 SQLServer.................................................................................................................42
Exercises..............................................................................................................................43
11.6.1 Task1:OpenandRuntheExample...................................................................44
11.6.2 Task2:CreatingaNewProjectLibrary..............................................................44
11.6.3 Task3:CreatingaPeriodicI/OServer...............................................................45
11.6.4 Task4:DeployingthePeriodicI/OServer.........................................................50
11.6.5 Task5:CreatingSharedVariables.....................................................................52
11.6.6 Task6:ConfiguringDataLogging......................................................................54
11.6.7 Task7:ConfiguringAlarming.............................................................................55
11.6.8 Task8:EnablingLogging....................................................................................56
11.6.9 Task9:CreatetheLabVIEWapplication............................................................57
11.6.10 Task10:UsetheLabVIEWDSCFunctionsandVIs.........................................60
11.6.11 Task11:ViewingReal-TimeData...................................................................62
11.6.12 Task12:ViewingAlarmsusingtheDistributedSystemManager..................63
12 LabVIEWI/OServer.........................................................................................................65
12.1 ConnectLabVIEWtoOPCTagsbyCreatinganI/OServer........................................65
12.2 CreateSharedVariablesthatConnecttotheOPCTagsthroughtheI/OServer......66
12.3 ViewingSharedVariableswithDistributedSystemManager..................................68
12.4 UsingOPCTagDatainLabVIEW...............................................................................68
13 LabVIEWReal-TimeModule............................................................................................73
13.1 Real-TimeDevelopmentinLabVIEW........................................................................74
14 CompactFieldPoint.........................................................................................................76
14.1 Introduction..............................................................................................................76
14.2 Development............................................................................................................77
15 CompactRIO....................................................................................................................85
vii TableofContents
Tutorial:OPCandReal-TimeSystemsinLabVIEW
15.1 Introduction..............................................................................................................85
15.2 Development............................................................................................................85
1
1 IntroductiontoLabVIEWLabVIEW(shortforLaboratoryVirtualInstrumentationEngineeringWorkbench)isaplatformanddevelopmentenvironmentforavisualprogramminglanguagefromNationalInstruments.Thegraphicallanguageisnamed"G".OriginallyreleasedfortheAppleMacintoshin1986,LabVIEWiscommonlyusedfordataacquisition,instrumentcontrol,andindustrialautomationonavarietyofplatformsincludingMicrosoftWindows,variousflavorsofUNIX,Linux,andMacOSX.ThelatestversionofLabVIEWisversionLabVIEW2009,releasedinAugust2009.VisitNationalInstrumentsatwww.ni.com.
Thecodefileshavetheextension“.vi”,whichisanabbreviationfor“VirtualInstrument”.LabVIEWofferslotsofadditionalAdd-OnsandToolkits.
ThispaperispartofaserieswithLabVIEWpapers:
• IntroductiontoLabVIEW• DataAcquisitioninLabVIEW• ControlandSimulationinLabVIEW• LinearAlgebrainLabVIEW• DatabaseCommunicationinLabVIEW• DataloggingandSupervisoryControlinLabVIEW• IntermediateTopicsinLabVIEW• AdvancedTopicsinLabVIEW• Etc.
Eachpapermaybeusedindependentlyofeachother.
1.1 Dataflowprogramming
TheprogramminglanguageusedinLabVIEW,alsoreferredtoasG,isadataflowprogramminglanguage.Executionisdeterminedbythestructureofagraphicalblockdiagram(theLV-sourcecode)onwhichtheprogrammerconnectsdifferentfunction-nodesbydrawingwires.Thesewirespropagatevariablesandanynodecanexecuteassoonasallitsinputdatabecomeavailable.Sincethismightbethecaseformultiplenodessimultaneously,Gisinherentlycapableofparallelexecution.Multi-processingandmulti-threadinghardwareisautomaticallyexploitedbythebuilt-inscheduler,whichmultiplexesmultipleOSthreadsoverthenodesreadyforexecution.
2 IntroductiontoLabVIEW
Tutorial:OPCandReal-TimeSystemsinLabVIEW
1.2 Graphicalprogramming
LabVIEWtiesthecreationofuserinterfaces(calledfrontpanels)intothedevelopmentcycle.LabVIEWprograms/subroutinesarecalledvirtualinstruments(VIs).EachVIhasthreecomponents:ablockdiagram,afrontpanel,andaconnectorpanel.ThelastisusedtorepresenttheVIintheblockdiagramsofother,callingVIs.Controlsandindicatorsonthefrontpanelallowanoperatortoinputdataintoorextractdatafromarunningvirtualinstrument.However,thefrontpanelcanalsoserveasaprogrammaticinterface.Thusavirtualinstrumentcaneitherberunasaprogram,withthefrontpanelservingasauserinterface,or,whendroppedasanodeontotheblockdiagram,thefrontpaneldefinestheinputsandoutputsforthegivennodethroughtheconnectorpane.ThisimplieseachVIcanbeeasilytestedbeforebeingembeddedasasubroutineintoalargerprogram.
Thegraphicalapproachalsoallowsnon-programmerstobuildprogramssimplybydragginganddroppingvirtualrepresentationsoflabequipmentwithwhichtheyarealreadyfamiliar.TheLabVIEWprogrammingenvironment,withtheincludedexamplesandthedocumentation,makesitsimpletocreatesmallapplications.Thisisabenefitononeside,butthereisalsoacertaindangerofunderestimatingtheexpertiseneededforgoodquality"G"programming.Forcomplexalgorithmsorlarge-scalecode,itisimportantthattheprogrammerpossessanextensiveknowledgeofthespecialLabVIEWsyntaxandthetopologyofitsmemorymanagement.ThemostadvancedLabVIEWdevelopmentsystemsofferthepossibilityofbuildingstand-aloneapplications.Furthermore,itispossibletocreatedistributedapplications,whichcommunicatebyaclient/serverscheme,andarethereforeeasiertoimplementduetotheinherentlyparallelnatureofG-code.
1.3 BenefitsOnebenefitofLabVIEWoverotherdevelopmentenvironmentsistheextensivesupportforaccessinginstrumentationhardware.Driversandabstractionlayersformanydifferenttypesofinstrumentsandbusesareincludedorareavailableforinclusion.Thesepresentthemselvesasgraphicalnodes.Theabstractionlayersofferstandardsoftwareinterfacestocommunicatewithhardwaredevices.Theprovideddriverinterfacessaveprogramdevelopmenttime.ThesalespitchofNationalInstrumentsis,therefore,thatevenpeoplewithlimitedcodingexperiencecanwriteprogramsanddeploytestsolutionsinareducedtimeframewhencomparedtomoreconventionalorcompetingsystems.Anewhardwaredrivertopology(DAQmxBase),whichconsistsmainlyofG-codedcomponentswithonlyafewregistercallsthroughNIMeasurementHardwareDDK(DriverDevelopmentKit)functions,providesplatformindependenthardwareaccesstonumerousdataacquisitionandinstrumentationdevices.TheDAQmxBasedriverisavailableforLabVIEWonWindows,MacOSXandLinuxplatforms.
3 IntroductiontoLabVIEW
Tutorial:OPCandReal-TimeSystemsinLabVIEW
FormoreinformationaboutLabVIEW,visitmyBlog:http://home.hit.no/~hansha/
1.4 LabVIEWMathScriptRTModule
TheLabVIEWMathScriptRTModuleisanadd-onmoduletoLabVIEW.WithLabVIEWMathScriptRTModuleyoucan:
• Deployyourcustom.mfilestoNIreal-timehardware• ReusemanyofyourscriptscreatedwithTheMathWorks,Inc.MATLAB®softwareand
others• Developyour.mfileswithaninteractivecommand-lineinterface• EmbedyourscriptsintoyourLabVIEWapplicationsusingtheMathScriptNode
4
2 IntroductiontoOPC[Source:Wikipedia,NationalInstruments]
OLEforProcessControl(OPC),whichstandsforObjectLinkingandEmbedding(OLE)forProcessControl,istheoriginalnameforastandardspecificationdevelopedin1996.Thestandardspecifiesthecommunicationofreal-timeplantdatabetweencontroldevicesfromdifferentmanufacturers.Aftertheinitialrelease,theOPCFoundationwascreatedtomaintainthestandard.OPCFoundation:http://www.opcfoundation.org/.
In1994agroupofvendorsrepresentingabroadspectrumofdisciplinesinindustrialsegmentformedwhatisnowknownastheOPCFoundation.TheOPCFoundationputforththegoalofdevelopingasingleclient/serverspecificationthatwouldallowanyvendortodevelopsoftwareandapplicationsthatcouldsharedatainafast,robustfashion,anddoitinawaythatwouldeliminatetheproprietaryschemesthatforcedthesesamevendorstoduplicatedevelopmentefforts.TheOPCFoundationdevelopedthefirstspecificationcalledDataAccessSpecification1.0athatwasreleasedinearly1996.Usingthisspecification,vendorswereabletoquicklydevelopclientserversoftware.
AmajorgoaloftheOPCFoundationandtheDataAccessspecificationwastoeliminatetheneedofclientapplicationvendor'stodeveloptheirownproprietarysetofcommunicationsdrivers.
WhileOPCoriginallystoodfor“OLEforProcessControl”,theofficialstanceoftheOPCFoundationisthatOPCisnolongeranacronymandthetechnologyissimplyknownas“OPC”.OneofthereasonsbehindthisiswhileOPCisheavilyusedwithintheprocessindustries.
AsofJune,2006,"OPCisaseriesofstandardsspecifications".OPCconsistsofsevencurrentstandardsandtwoemergingstandards.
TheOPCSpecificationwasbasedontheOLE,COM,andDCOMtechnologiesdevelopedbyMicrosoftfortheMicrosoftWindowsoperatingsystemfamily.Thespecificationdefinedastandardsetofobjects,interfacesandmethodsforuseinprocesscontrolandmanufacturingautomationapplicationstofacilitateinteroperability.ThemostcommonOPCspecificationisOPCDataAccess,whichisusedtoreadandwritereal-timedata.WhenvendorsrefertoOPCgenerically,theytypicallymeanOPCDataAccess.
TheOPCspecifications[Wikipedia]:
• OPCDataAccess(DA)
5 IntroductiontoOPC
Tutorial:OPCandReal-TimeSystemsinLabVIEW
• OPCAlarmsandEvents• OPCBatch• OPCDataeXchange• OPCHistoricalDataAccess• OPCSecurity• OPCXML-DA• OPCUnifiedArchitecture(UA)
Note!LabVIEWsupportsonlytheOPCDataAccessspecification.
OPCserversprovideamethodformanydifferentsoftwarepackagestoaccessdatafromaprocesscontroldevice,suchasaPLC(ProgrammableLogicController)orDCS(DistributedControlSystem).Traditionally,anytimeapackageneededaccesstodatafromadevice,acustominterface,ordriver,hadtobewritten.ThepurposeofOPCistodefineacommoninterfacethatiswrittenonceandthenreusedbyanybusiness,SCADA,HMI,orcustomsoftwarepackages.
OnceanOPCserveriswrittenforaparticulardevice,itcanbereusedbyanyapplicationthatisabletoactasanOPCclient.OPCserversuseMicrosoft’sOLEtechnology(alsoknownastheComponentObjectModel,orCOM)tocommunicatewithclients.COMtechnologypermitsastandardforreal-timeinformationexchangebetweensoftwareapplicationsandprocesshardwaretobedefined.
2.1 OPCServerThebasicconceptinOPCisthatwehaveanOPCServerandoneormoreOPCClientsthatcommunicatewiththeserverinordertowriteorreaddata.AnOPCserverhasimplementedasetofservices,andtheclientsareusingtheseservices.
Atahighlevel,anOPCserveriscomprisedofseveralobjects:theserver,thegroup,andtheitem.TheOPCserverobjectmaintainsinformationabouttheserverandservesasacontainerforOPCgroupobjects.TheOPCgroupobjectmaintainsinformationaboutitselfandprovidesthemechanismforcontainingandlogicallyorganizingOPCitems.
OPCServer
OPCClient
OPCClient
…
6 IntroductiontoOPC
Tutorial:OPCandReal-TimeSystemsinLabVIEW
[Figure:www.ni.com]
TheOPCGroupsprovideawayforclientstoorganizedata.Forexample,thegroupmightrepresentitemsinaparticularoperatordisplayorreport.Datacanbereadandwritten.
TheOPCItemsrepresentconnectionstodatasourceswithintheserver.AnOPCItem,fromthecustominterfaceperspective,isnotaccessibleasanobjectbyanOPCClient.Therefore,thereisnoexternalinterfacedefinedforanOPCItem.AllaccesstoOPCItemsisviaanOPCGroupobjectthatcontainstheOPCitem,orsimplywheretheOPCItemisdefined.AssociatedwitheachitemareaValue,QualityandTimeStamp.
Note!Theitemsarenotthedatasources,theyarejustconnectionstothem.Forexample,thetagsinaDCSsystemexistregardlessofwhetheranOPCclientiscurrentlyaccessingthem.TheOPCItemshouldbethoughtofassimplyspecifyingtheaddressofthedata,notastheactualphysicalsourceofthedatathattheaddressreferences.
AlthoughOPCisprimarilydesignedforaccessingdatafromanetworkedserver,OPCinterfacescanbeusedinmanyplaceswithinanapplication.AtthelowestleveltheycangetrawdatafromthephysicaldevicesintoaSCADAorDCS,orfromtheSCADAorDCSsystemintotheapplication.ThearchitectureanddesignmakesitpossibletoconstructanOPCServerwhichallowsaclientapplicationtoaccessdatafrommanyOPCServersprovidedbymanydifferentOPCvendorsrunningondifferentnodesviaasingleobject.
[Figure:www.ni.com]
7 IntroductiontoOPC
Tutorial:OPCandReal-TimeSystemsinLabVIEW
InthisTutorialwewillusesomeOPCServerfortestpurposes:
2.1.1 MatrikonOPCServerforSimulation
MatrikonOPCSimulationisfreefornon-productionuseandcanbedistributedopenly.Itisafullyfunctioningapplicationwithoutrestriction.
MatrikonOPCSimulationServerisafreeutilityusedtohelptestandtroubleshootOPCapplications(clients)andconnections.Testingapplicationson“live”OPCserversmayresultinlossofactualproductiondata.TheMatrikonOPCSimulationServercreatesasimulatedenvironmentsothatintheeventofaproblem,norealprocessdataislost.
MatrikonOPCExplorerisanOPCClientapplicationfortestingandconfiguringOPCconnections.
http://www.matrikonopc.com/downloads/178/index.aspx
2.1.2 NIOPCServers
TheNationalInstrumentsOPCServersprovidesasingleconsistentinterfacetocommunicatewithmultipledevices,savingyoufromlearningnewcommunicationprotocolsorspendingtimeunderstandingnewapplications.ThecombinationofNIOPCServersandLabVIEWprovidesasingleplatformfordeliveringhighperformancemeasurementsandcontroltobothnewandexistingindustrialsystems.NIOPCserversconnectthroughtheOPCclientinLabVIEWDataloggingandSupervisoryControl(DSC)ModuletoenableyoudevelopafullyfledgedHMI/SCADAsystemwithPLCs,PACsandsmartsensors.
Anevaluationversionisavailablehere:http://sine.ni.com/nips/cds/view/p/lang/en/nid/4584
2.2 OPCClientAnOPCClientcanconnecttoOPCServersprovidedbyoneormorevendors.
8 IntroductiontoOPC
Tutorial:OPCandReal-TimeSystemsinLabVIEW
[Figure:www.ni.com]
2.3 TagsTagsareusedalotintheprocessindustryandarenormallyassignedtoapieceofinformation.Atagconsistsofanamedescribingasinglepointofinformationsoaprocesssystemcanconsistsofhundredsandeventhousandsoftags.TheOPCserverhasonetagforeachmeasurementpointsandcontrollerpointsintheplantanditistheresponsibilityoftheOPCservertogettheinformationfromthecontrollers.Thisisoneofthereasonsforthecomplexityoftheservers,theyneedtohavedriversforalotofcontrollersandmeasurementsystems.
2.4 WhyDoWeNeedOPCStandards?
Withhundredsofmajorhardwareandsoftwarevendors,youhavethedifficulttaskofmakingsurethatyourclientapplicationcancommunicatewithanydeviceanddriver.BeforeOPC,youhadtowriteseparateclientapplicationcodetocommunicatewitheachdevicebecauseeachdevicedriverusedadifferentAPI.OPCprovidesanindustry-standardinterface-asingleAPI-soclientapplicationscanretrieveprocessvariables,suchastemperature,pressure,flowrate,orposition,andsetcontrolvariables,suchasthecurrentordiscreteoutputonanI/Omodule.
OPCoffersthefollowingbenefits:
• SingleAPIforallOPCserverssothatyoucanreusethecodeforyourclientapplicationwitheachdevice.
• OpportunitytodevelopclientapplicationsindevelopmentenvironmentsthattakeadvantageofCOMandActiveX,suchasMicrosoftVisualBasic,VisualC++,Excel,andInternetExplorer.
9 IntroductiontoOPC
Tutorial:OPCandReal-TimeSystemsinLabVIEW
• BrowserthroughwhichyoucanselectOPCitemsavailabletoclients.AnOPCitemisachannelorvariableinareal-worlddevice(normallyanI/Opoint)thatadeviceservermonitorsorcontrols.
• DistributedandremoteaccessthroughDCOM.Youcanaccessdevicesconnectedtoothercomputersonthenetwork.
10
3 IntroductiontoReal-TimeSystemsAreal-timesystemmeansacomputerbasedsystemwhereoneormoreoftheapplicationsmustbeabletosynchronizewithaphysicalprocess.Real-timemeansthatthecomputersystemismonitoringthestatesofthephysicalprocessandmustrespondtochangesofoneormoreofthesestateswithinamaximumtime.Areal-timesystemcanthenbeusedformonitoringofdifferentparametersinthephysicalprocessforpresentation,warnings,alarmsituationsandforcontrol.
Areal-timeoperatingsystem(RTOS)isamultitaskingoperatingsystemintendedforreal-timeapplications.Suchapplicationsincludeembeddedsystems(programmablethermostats,householdappliancecontrollers),industrialrobots,spacecraft,andindustrialcontrol.
3.1 LabVIEWReal-TimeModule
TheNationalInstrumentsLabVIEWReal-TimeModuleisanadd-oncomponentfortheLabVIEWDevelopmentSystem.Wheninstalled,thissoftwarecompilesNILabVIEWgraphicalcodeandoptimizesitfortheselectedreal-timetarget.UsingtheLabVIEWReal-TimeModule,youcandevelopanddeployapplicationstoallNIreal-timehardwaretargetsincludingPXI,CompactFieldPoint,FieldPoint,CompactRIO,andstandarddesktopPCs.TheembeddedRTOSforthesetargetsisasinglededicatedkernelthatprovidesmaximumreliabilityforembeddedcode.
[Figure:www.ni.com]
11
4 IntroductiontoEmbeddedSystemsAnembeddedsystemisacomputersystemdesignedtoperformoneorafewdedicatedfunctionsoftenwithreal-timecomputingconstraints.Itisembeddedaspartofacompletedeviceoftenincludinghardwareandmechanicalparts.Bycontrast,ageneral-purposecomputer,suchasapersonalcomputer,isdesignedtobeflexibleandtomeetawiderangeofend-userneeds.Embeddedsystemscontrolmanydevicesincommonusetoday.
Embeddedsystemsarecontrolledbyoneormoremainprocessingcoresthatistypicallyeitheramicrocontrolleroradigitalsignalprocessor(DSP).Thekeycharacteristicishoweverbeingdedicatedtohandleaparticulartask,whichmayrequireverypowerfulprocessors.Forexample,airtrafficcontrolsystemsmayusefullybeviewedasembedded,eventhoughtheyinvolvemainframecomputersanddedicatedregionalandnationalnetworksbetweenairportsandradarsites.
Sincetheembeddedsystemisdedicatedtospecifictasks,designengineerscanoptimizeitreducingthesizeandcostoftheproductandincreasingthereliabilityandperformance.
4.1 SomeExamplesofEmbeddedsystems
FujiPXG5PIDController:
12 IntroductiontoEmbeddedSystems
Tutorial:OPCandReal-TimeSystemsinLabVIEW
CompactFieldPoint(fromNationalInstruments):
4.2 EmbeddedhardwareandReal-TimesystemsfromNationalInstruments
Embeddedapplicationshaveuniquerequirementssuchasdeterministicbehavior.WithLabVIEWReal-Time,realtimecontrollers,anddataacquisitionhardwarefromNIyoucancreateapplicationswithdeterministic,real-timeperformance.
YoucandevelopanddebugyourapplicationusingLabVIEWgraphicalprogramming,anddownloadtime-criticalapplicationcomponentstorunembeddedonReal-Timehardware.
13
5 Real-TimeVIsinLabVIEWAreal-timesystemmeansacomputerbasedsystemwhereoneormoreoftheapplicationsmustbeableto“synchronize”withaphysicalprocess.“Real-time”meansthatthecomputersystemismonitoringthestatesofthephysicalprocessandmustrespondtochangesofoneormoreofthesestateswithinamaximumtime.Areal-timesystemcanthenbeusedformonitoringofdifferentparametersinthephysicalprocessforpresentation,warnings,alarmsituationsandforcontrol.
Areal-timesystemwillveryoftenbeanembeddedsystem,whileanembeddedsystemdoesnotneedtobeareal-timesystem.
Importantfeaturesinsuchreal-timesystemsaresynchronization,semaphores,deadlock,multithreadingandscheduling.InthischapterwewillseehowwecanusethesefeaturesinLabVIEWwhenprogrammingourreal-timesystems.
5.1 SynchronizationTheapplicationsofthereal-timesystemmustruntogetherwiththephysicalprocess,sothereal-timesystemmustbeabletomanagesimultaneity.Thesolutionisoftentorunseveralapplicationsonthecomputersystemorondifferentcomputersinadistributedsystem.Thesesolutionsrequiresomesortofsynchronizationbetweentheapplicationsandbetweentheapplicationsandthephysicalprocess.
Whenseveralapplicationsarerunning“simultaneous”onacomputersystem,theremustalsobesomesynchronizationoftheusageoftheresourcesinthecomputersystem.Resourcescanbebothhardwareandsoftware,likeI/Oglobalvariablesinthesoftware,theCPU,memory,disketc.
LabVIEWoffersdifferentmechanismsforsynchronizationwewilluseinthistask.
BelowweseetheSynchronizationpaletteinLabVIEW:
14 Real-TimeVIsinLabVIEW
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Wecan,e.g.,usetheSynchronizationVIsandfunctionstosynchronizetasksexecutinginparallelandtopassdatabetweenparalleltasks.
5.2 Semaphores
Asemaphoreisthesimplestformofsynchronizationandhastwobasicfunctions.Thesefunctionsare:
• Request;thesystemwillmovethetasktowaitqueueifthesemaphoreisalready“occupied”byanothertask.
• Release;releasesasemaphore,thesystemwillmovethe“blocked”tasksfromthewaitqueuetothereadyqueue.
BelowweseetheSemaphorepaletteinLabVIEW:
UsetheSemaphoreVIstolimitthenumberoftasksthatcansimultaneouslyoperateonashared(protected)resource.Aprotectedresourceorcriticalsectionofcodemightincludewritingtoglobalvariablesorcommunicatingwithexternalinstruments.
YoucanusetheSemaphoreVIstosynchronizetwoormoreseparate,paralleltaskssothatonlyonetaskatatimeexecutesacriticalsectionofcodeprotectedbyacommonsemaphore.Inparticular,usetheseVIswhenyouwantcertainVIsorpartsofablockdiagramtowaituntilanotherVIorpartofablockdiagramisfinishedwiththeexecutionofacriticalsection.
15 Real-TimeVIsinLabVIEW
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Atypicalexamplecouldbewheretoresourceswanttowritetothesamefile,butonlyonecanaccesstofileatatime.WecanusetheSemaphoreVIstosynchronizethisoperation.Theapplicationcouldhave2whileloopsinparallel.Eachwhileloopcanthenwritetothesamefileifyousynchronizetheoperationsusingsemaphores.
QueueOperations
YouwillusetheQueueOperationsfunctionstocreateaqueueforcommunicatingdatabetweensectionsofablockdiagramorfromanotherVI.
TheQueueOperationspaletteinLabVIEW:
Example:
YoutypicallyusetheQueueVIsforexchangeofmessages.E.g.,aSenderactivityshallreadlettersfromthekeyboardandputthemintotheQueue.TheReceiveractivityshallreadthelettersfromtheQueueanddisplaythemonascreeninaStringindicator.TheSenderandtheReceiveractivitycouldoperateatdifferentspeed(delay).BelowweseetheLabVIEWcode:
16 Real-TimeVIsinLabVIEW
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Wetypeinnsomelettersusingthekeyboard.TheReceiverismuchslower,buttobesuretonotmissanyletters,weuseaQueuetohandlethis.BelowweseetheFrontPanel:
17 Real-TimeVIsinLabVIEW
Tutorial:OPCandReal-TimeSystemsinLabVIEW
[EndofExample]
5.3 TimedLoop
InLabVIEWwecanalsouse“TimedLoop”structureinsteadofordinaryWhileLoops.
18
6 MultithreadinginLabVIEWAmulticoresystemisasingle-processorCPUthatcontainstwoormorecores,witheachcorehousingindependentmicroprocessors.Amulticoremicroprocessorperformsmultiprocessinginasinglephysicalpackage.Multicoresystemssharecomputingresourcesthatareoftenduplicatedinmultiprocessorsystems,suchastheL2cacheandfront-sidebus.
Multicoresystemsprovideperformancethatissimilartomultiprocessorsystemsbutoftenatasignificantlylowercostbecauseamotherboardwithsupportformultipleprocessors,suchasmultipleprocessorsockets,isnotrequired.
6.1 Multitasking
Incomputing,multitaskingisamethodbywhichmultipletasks,alsoknownasprocesses,sharecommonprocessingresourcessuchasaCPU.WithamultitaskingOS,suchasWindowsXP,Vista,etc.,youcansimultaneouslyrunmultipleapplications.MultitaskingreferstotheabilityoftheOStoquicklyswitchbetweeneachcomputingtasktogivetheimpressionthedifferentapplicationsareexecutingmultipleactionssimultaneously.
6.2 Multithreading
Multithreadingextendstheideaofmultitaskingintoapplications,soyoucansubdividespecificoperationswithinasingleapplicationintoindividualthreads.Eachofthethreadscanruninparallel.TheOSdividesprocessingtimenotonlyamongdifferentapplications,butalsoamongeachthreadwithinanapplication.
InamultithreadedNationalInstrumentsLabVIEWprogram,anexampleapplicationmightbedividedintofourthreads-auserinterfacethread,adataacquisitionthread,networkcommunication,andaloggingthread.Youcanprioritizeeachofthesesothattheyoperateindependently.Thus,inmultithreadedapplications,multipletaskscanprogressinparallelwithotherapplicationsthatarerunningonthesystem.
19 MultithreadinginLabVIEW
Tutorial:OPCandReal-TimeSystemsinLabVIEW
[Figure:www.ni.com]
MultithreadinginLabVIEW:
LabVIEWautomaticallydivideseachapplicationintomultipleexecutionthreads.ThecomplextasksofthreadmanagementaretransparentlybuiltintotheLabVIEWexecutionsystem.
[Figure:www.ni.com]
Youcanalsousethe“CPUInformation”functioninLabVIEWtofindCPUinformationaboutyourPC.
MultitaskinginLabVIEW:
LabVIEWusespreemptivemultithreadingonOSsthatofferthisfeature.LabVIEWalsousescooperativemultithreading.OSsandprocessorswithpreemptivemultithreadingemploya
20 MultithreadinginLabVIEW
Tutorial:OPCandReal-TimeSystemsinLabVIEW
limitednumberofthreads,soincertaincases,thesesystemsreturntousingcooperativemultithreading.
TheexecutionsystempreemptivelymultitasksVIsusingthreads.However,alimitednumberofthreadsareavailable.Forhighlyparallelapplications,theexecutionsystemusescooperativemultitaskingwhenavailablethreadsarebusy.Also,theOShandlespreemptivemultitaskingbetweentheapplicationandothertasks.
21
7 DataSocketDataSocketisatechnologyforsharingdatabetweenapplicationsordifferentdatasources.TheDataSocketcontrolprovidesasimpleinterfacethroughwhichitcaninteractwithOPCservers,suchasNationalInstrumentsFieldPoint,fromanyActiveXcontainer,includingVisualBasicandVisualC++.YoucanconnecttoanOPCserverwithDataSocketusinganOPCURL,whichissimilartotheURLsusedinaWebbrowser.URLsprovideastandardmechanismforreferringtolocations.YoualreadyknowhowtouseURLstolocatethingsontheWeb,andyoucanlocateOPCdataitemswithDataSocketusingasimilarURLmodel:
opc://machine_name/server_name/item_name
WithDataSocket,youcansharelivedatawithoneormoreclientapplicationsonanetworkwithoutworryingaboutdataformatsandnetworkprotocols.YourLabVIEWapplicationscaneasilysharelivedatawithavarietyofclients,includingVisualBasicapplications,Webbrowsers,VisualC++,MicrosoftExcel,LabWindows/CVI,andotherLabVIEWapplications.UsingDataSockettechnology,youcanpublishandreceivedatafromanyapplicationinthesameway,givingyouthepowertoconnectdiverseapplicationseasily.
Manytypicalinstrumentationsolutionsinvolveasinglelocalapplicationforacquisition,logging,analysis,andpresentation.However,becauseoftheriseinpopularityoftheInternetandcompanyintranets,andtheneedtoremotelymonitorandcontrolyourdataacquisition,youoftenneedtoexchangelivedatawithotherapplicationsondifferentcomputersaroundtheworld.DataSocketforLabVIEWsimplifieslivedataexchangebetweendifferentapplicationsononecomputerorbetweencomputersconnectedthroughanetwork.
Althoughavarietyofdifferenttechnologiesexisttodaytosharedatabetweenapplications,includingTCP/IPanddynamicdataexchange(DDE),mostofthesetoolsarenottargetedforlivedatatransfertomultipleclients.WithTCP/IP,youhavetoconvertyourdataintoanunstructuredstreamofbytesinthebroadcastingapplicationandthenparsethestreamofbytesbackintoitsoriginalformatinsubscribingapplications.DataSocket,however,simplifieslivedatatransfer.Itimplementsaneasy-to-use,high-performanceprogramminginterfacethatisdesignedspecificallyforsharingandpublishinglivedatainmeasurementandautomationapplications.Inaddition,DataSocketfeaturesinterapplicationconnectivity,richdatatypes,andsecuritytomakesharingdataeasy.DataSocketisincludedwithLabVIEW.
IfyouarecomfortableprogrammingwithCOM,youcanwriteprogramsusingeithertheOPCCustomAPIorAutomationAPI,dependingontheprogrammingenvironmentinwhichyou
22 DataSocket
Tutorial:OPCandReal-TimeSystemsinLabVIEW
aredevelopingyourOPCclient. IfyoudonotwanttoprogramwithCOM,usetheDataSocketcontrol,anActiveXcontrolforsharingdatabetweenapplicationsanddevices.DataSocketoffersthefollowingbenefits:
• SimpleAPI,helpfultodeveloperswhodon'twanttoprogramwithCOM. • AccesstotheOPCservercustominterface,whichenablesyourapplicationstorun
fasterthanapplicationsthataccesstheautomationinterface.DataSocketisnotanextralayerbutratheradirectconnectiontoOPCservers,andDataSocketalwaysaccessesthecustominterface,regardlessoftheActiveXcontainerinwhichyouaredeveloping.
• EasyintegrationwithNationalInstrumentsproductssuchasLabVIEW.
7.1 ArchitectureDataSocketisasingle,unified,end-userapplicationprogramminginterface(API)forconnectingtodatafromanumberofsources–localfiles,filesonFTPorWebservers,anddataitemsonOPCServers.ADataSocketapplicationspecifiesthedatalocationbyusingafamiliarnetworkingstandard,theURL.JustasaWebbrowserusesaURLtoconnecttoaWebpage,aDataSocketapplicationusesaURLtoconnecttodata.Byusinganindustry-standardURL,youcanquicklyandeasilybringdataintoorsharedatafromyourDataSocketapplications.
opc://machine_name/server_name/item_name
machine_name[optional]-ComputeronwhichtheOPCserverisinstalled.DataSocketcanaccessOPCserversonothercomputersusingDCOM.Ifthemachinenameisomitted,DataSocketdirectlyconnectstotheOPCserveronthecomputeronwhichitisrunning.
server_name-OPCserver(providedwiththehardware)toconnectto.
item_name-OPCitemonthespecificOPCserver.Anitemisachannelorvariable(normallyanI/Opoint)inareal-worlddevicethatadeviceservermonitorsorcontrols.ExampleFieldPointitem:FP Res\FP-DI-330 @1\Channel 1
UpdateRate=n inmilliseconds[optional]-MaximumrateatwhichtheOPCserverwillindicatethatanitem’svaluehaschanged.Theservershoulduseanupdaterateascloseaspossibletotheraterequestedbytheclient.Ifthisparameterisomitted,thedefaultis100ms.Thefollowingexamplesetstheupdaterateto1000ms:UpdateRate=1000
DeadBand=n in%ofrange[optional]-Percentagechangerequiredbeforetheservernotifiesyourapplicationofavaluechange.Notallserverssupportthisoption.Ifomitted,
23 DataSocket
Tutorial:OPCandReal-TimeSystemsinLabVIEW
thisparameterdefaultsto0%.Thefollowingexamplesetsthedeadbandto10%:DeadBand=10
Forexample,thefollowingURLconnectstothesineitemontheNational Instruments OPCDemoserveronthelocalmachine.TheoptionsattheendoftheURLspecifyanupdaterateof1000msandadeadbandof10%.opc:/National Instruments.OPCDemo/sine?UpdateRate=1000&DeadBand=10
7.2 DataSocketServerWiththeDataSocketServer,alightweight,stand-alonecomponent,programsusingDataSocketcanbroadcastlivemeasurementdataathighratesacrosstheInternettomultipleremoteclientsconcurrently.TheseclientapplicationsuseDataSockettosubscribetothelivemeasurementdata.BecausetheDataSocketServerisastand-alonecomponent,itsimplifiesnetwork(TCP/IP)programmingbyautomaticallymanagingconnectionstoclientsandautomaticallyconvertingyourmeasurementdatatoandfromthestreamofbytessentacrossthenetwork.Youdonothavetowritetheparsingcode.AndbecausetheDataSocketServercanrunonanymachineonyournetwork,italsoimprovesperformanceandprovidessecuritybyisolatingtheWebconnectionsfromyouracquisitionapplication.
7.3 DataSocketinLabVIEW
TheDataSocketpaletteinLabVIEW:
DescriptionoftheDataSocketVIsinLabVIEW.
DataSocketSelectURLDisplaysadialogboxfortheusertoselectadatasourceandreturnstheURLtothatdata.
24 DataSocket
Tutorial:OPCandReal-TimeSystemsinLabVIEW
DataSocketOpenOpensadataconnectionyouspecifyinURL.
DataSocketReadDequeuesthenextavailabledatavaluefromtheclient-sidebufferassociatedwiththeconnectionyouspecifyinconnectioninandreturnsthedata.
DataSocketWriteWritesdatatotheconnectionyouspecifyinconnectionin.
DataSocketCloseClosesadataconnectionyouspecifyinconnectionid.
25
8 OPCServersfromNationalInstruments
NationalInstrumentsoffersdifferentOPCServers,suchas:
• NIOPCServers• FieldPointOPCServer• VariableEngine• Etc.
IfyoubrowseforOPCserversandOPCItemsonyourcomputeritprobablylookssomethinglikethis:
BelowwegothroughthebasicfunctionalityintheseOPCServers.
8.1 NIOPCServersTheNationalInstrumentsOPCServersprovidesasingleconsistentinterfacetocommunicatewithmultipledevices,savingyoufromlearningnewcommunicationprotocolsorspendingtimeunderstandingnewapplications.ThecombinationofNIOPCServersandLabVIEWprovidesasingleplatformfordeliveringhighperformancemeasurementsandcontroltobothnewandexistingindustrialsystems.NIOPCserversconnectthroughtheOPCclientinLabVIEWDataloggingandSupervisoryControl(DSC)Moduletoenableyoudevelopafull-fledgedHMI/SCADAsystemwithPLCs,PACsandsmartsensors.
26 OPCServersfromNationalInstruments
Tutorial:OPCandReal-TimeSystemsinLabVIEW
NIOPCServersarea32-bitwindowsapplicationthatprovidesameansofbringingdataandinformationfromawiderangeofindustrialdevicesandsystemsintoclientapplicationsonyourwindowsPC.OurOPCServerapplicationenablesthesharingofmanufacturingorproductiondatabetweenavarietyofapplicationsrangingfromhumanmachineinterfacesoftwareanddatahistorians,toolargeMESandERPapplications.
8.1.1 OPCQuickClient
TheOPCQuickClienthasbeendevelopedtoassistinthetestanddevelopmentoftheOPCDataAccess1.0and2.0Servers.TheOPCQuickClientdoesnotfullysupportOPCDA3.0.
TheOPCQuickClientsupportsbothlocalandremoteOPCserverconnections.Remoteconnectionsarehandledthroughtheoperatingsystem'sDCOMinterface.
27 OPCServersfromNationalInstruments
Tutorial:OPCandReal-TimeSystemsinLabVIEW
TostartusingtheOPCQuickClient,dothefollowing:
1. CreateaserverconnectionwhichwillbeusedtoconnecttoanOPCserver. 2. Next,addagrouptotheconnectionwhichcontainsvaryingproperties(suchas
updaterate,deadbandandtimebias). 3. Finally,additemstotheindividualgroups(whichcontainpropertiessuchasaninitial
activestate,datatypeandaccesspath).
AserverconnectionprovidesalinkbetweenanOPCserverandthisclient.Groupsareaddedthroughthisconnection.Tocreateanewserverconnection,clickEdit|NewServerConnection....Alternatively,clicktheNewServertoolbarbutton.
Agroupisusedtoorganizeacollectionofitemswithacommonsetofproperties.Thegroupalsospecifiesthefollowingproperties:groupname,updaterate,timebias,percentdead
28 OPCServersfromNationalInstruments
Tutorial:OPCandReal-TimeSystemsinLabVIEW
band,LanguageID,activestateandthedataconnectiontype.Tocreateanewgroup,clickEdit|NewGroup.Alternatively,clickNewGroupinthetoolbar.
ItemsrepresentdatathatmaybeaccessedviaanOPCserver.Anitemspecifiesthefollowingproperties:ItemID,accesspath,requesteddatatypeandactivestate.TodefineanitemusingtheItemEditordialog,clickEdit|NewItem.Alternatively,clickNewItemonthetoolbar.
8.2 SharedVariableEngine
29 OPCServersfromNationalInstruments
Tutorial:OPCandReal-TimeSystemsinLabVIEW
LabVIEWcontainsanOPCservercalledtheSharedVariableEngine.TheSharedVariableEnginesupportsOPCDataAccess2.xandOPCDataAccess3.0.YoucanpublishdatafromtheSharedVariableEngineusingLabVIEWsharedvariables.
ToconnecttotheSharedVariableEnginefromathird-partyOPCclient,usetheProgIDNationalInstruments.VariableEngine.IftheOPCclientallowsyoutobrowseforOPCservers,youcanlocatetheNationalInstruments.VariableEngineunderOPCversion2.xor3.0,dependingonwhichversionstheclientsupports.
30
9 MatrikonOPCSimulationServerMatrikonOPCSimulationisfreefornon-productionuseandcanbedistributedopenly.Itisafullyfunctioningapplicationwithoutrestriction.
MatrikonOPCSimulationServerisafreeutilityusedtohelptestandtroubleshootOPCapplications(clients)andconnections.Testingapplicationson“live”OPCserversmayresultinlossofactualproductiondata.TheMatrikonOPCSimulationServercreatesasimulatedenvironmentsothatintheeventofaproblem,norealprocessdataislost.
MatrikonOPCExplorerisanOPCClientapplicationfortestingandconfiguringOPCconnections.
DownloadMatrikonOPCSimulationServerandMatrikonOPCExplorerher:
http://www.matrikonopc.com/downloads/178/index.aspx
Watchthisvideo:http://www.matrikonopc.com/training/opc-multimedia-tutorial/opcda_pop.html
9.1 MatrikonOPCServer
BelowweseetheMatrikonOPCServerforSimulation:
31 MatrikonOPCSimulationServer
Tutorial:OPCandReal-TimeSystemsinLabVIEW
ViewTags:
OpentheMatrikonOPCExplorerwhereyoubrowseforavailableItems(Tags).
9.2 AliasesMatrikonOPCServers,includingthisone,providetheabilitytocreateuser-definedaliasesthatcanbeusedinplaceofregularOPCitems.Thisfeatureisparticularlyusefulwhentheitempathforagivenserverisverycomplexordifficulttoremember,forexample:Com1.Radio1.Unit1.41.4.123.Serverscanalsobeconfiguredsothatclientapplicationshaveaccesstoconfiguredaliasesonly,ratherthaneveryavailableitem.
Toinsertanewalias,performthefollowingsteps:
1. OpentheMatrikonOPCServerforSimulationConfigurationwindow.2. ClickontheAliasConfigurationnodeintheCurrentConfigurationpaneltoopenthe
AliasConfigurationpanel.
32 MatrikonOPCSimulationServer
Tutorial:OPCandReal-TimeSystemsinLabVIEW
3. Right-clickyourmouseandselecttheInsertNewAliasoption,orPresstheInsertbuttononthekeyboard,tolaunchtheInsertNewAliaswindow.
4. Fillinanameforthealias,andenteravaliditempath.Theitempathcanbefoundbybrowsingtheserver’saddressspace(usetheellipsisbuttonnexttothisfield).
5. Savethisaliaswhenfinished.ItwillnowbevisibletoOPCclientsundertheConfiguredAliasesheading.
Formoredetailedscalingoptions,pleaseconsulttheMatrikonOPCServerforSimulationUser’sManual.
9.3 MatrikonOPCExplorer(Client)
MatrikonOPCExplorerisanOPCClientapplicationfortestingandconfiguringOPCconnections.
TheMatrikonOPCExplorerlistsalltheavailableOPCServersintheupperleftcorner.
MatrikonOPCExplorerlistsOPCserversonyourcomputer(localhost)orinthenetwork.
33 MatrikonOPCSimulationServer
Tutorial:OPCandReal-TimeSystemsinLabVIEW
ClickConnectonordertoconnecttotheserver.
34
10 UsingOPCfromLabVIEWYoucanuseLabVIEWasanOPCclientbyconnectingtoanOPCserverthroughaDataSocketconnection.
TheDataSocketpaletteinLabVIEW:
DescriptionoftheDataSocketVIsinLabVIEW:
DataSocketSelectURLDisplaysadialogboxfortheusertoselectadatasourceandreturnstheURLtothatdata.
DataSocketOpenOpensadataconnectionyouspecifyinURL.
DataSocketReadDequeuesthenextavailabledatavaluefromtheclient-sidebufferassociatedwiththeconnectionyouspecifyinconnectioninandreturnsthedata.
DataSocketWriteWritesdatatotheconnectionyouspecifyinconnectionin.
DataSocketCloseClosesadataconnectionyouspecifyinconnectionid.
10.1 OPCURL
AtypicalURLforanOPCItemcouldbe:
opc://localhost/Matrikon.OPC.Simulation/Random.Int4
35 UsingOPCfromLabVIEW
Tutorial:OPCandReal-TimeSystemsinLabVIEW
oringeneral:
opc://machine_name/server_name/item_name
Youmayusethe“DataSocketSelectURL”VI inordertofindanOPCItem.
Usingthe“DataSocketSelectURL”displaysthe“SelectURL”window:
ThisVIisnicetohavewhenyoudontknowtheexactnameoftheOPCURL.
IfyouknowtheURLinadvanceyouusethe“DataSocketOpen”VI .ThisVIopensadataconnectionyouspecifyintheinputURL.Likethis:
10.2 ReadOPCData
Youuse DataSocketReadinordertogetdatafromaspecificItemintheOPCserver.
Example:
36 UsingOPCfromLabVIEW
Tutorial:OPCandReal-TimeSystemsinLabVIEW
orusingthespecificURLdirectlylikethis:
TheDataSocketReadVIhaveseveraloutputsinadditiontotheValue(data).
AllOPCItemshavethefollowingproperties:
• Value• Timestamp• Status• Quality
10.3 WriteOPCData
Youuse DataSocketWriteinordertowritedatatoaspecificItemintheOPCserver.
37 UsingOPCfromLabVIEW
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Note!InordertowritedatatoanOPCItemitmusthavetheWritepropertyset.
Example:
orusingthespecificURLdirectlylikethis:
38
11 LabVIEWDataloggingandSupervisoryControl
TheLabVIEWDataloggingandSupervisoryControl(DSC)ModuleextendstheLabVIEWgraphicaldevelopmentenvironmentwithadditionalfunctionalityfortherapiddevelopmentofdistributedmeasurement,control,andhigh-channel-countmonitoringapplications.
TheDSCModulealsoenhancestheLabVIEWsharedvariable.UsethesharedvariabletoaccessandpassdataamongseveralVIsinaLabVIEWprojectoracrossanetwork.AsharedvariablecanrepresentavalueoranI/Opoint.WiththeDSCModule,youcanlogdataautomatically;addalarming,scaling,andsecuritytothesharedvariable;andconfigurethesharedvariableprogrammatically.
TheDSCModulealsoprovidestoolsforgraphinghistoricalorreal-timetrends,enhancingthesecurityoffrontpanels,andwritingcustomI/Oservers.YoucanreadorwritetoOLEforProcessControl(OPC)connections,programmablelogiccontrollers(PLC),orcustomI/Oserversthatyouwrite.
TorunapplicationsbuiltwithLabVIEW,theDSCModuleonacomputerwithouttheDSCModuleinstalled,youmustinstallthe“DSCModuleRun-TimeSystem”onthatcomputer.TheDSCModuleRun-TimeSystemcontainscomponentsthatenabletheDSCModulefeaturesinthebuiltapplications.
TheDSCModuleincludesthefollowingcomponents:
• FunctionsandVIsPalettes• DSCModuleControlsPalettes• CitadelDatabase• HistoricalDataViewer • DistributedSystemManager
Thesecomponentsaredescribedinmoredetailbelow.
MostoftheLabVIEWDSCfunctionalityisavailablefromtheToolsmenu(“Tools→DSCModule”).
39 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
11.1 FunctionsandVIsPalettes
TheDSCModuleinstallsthefollowingpalettes:
• Alarms&Events• Historical• Tags• SharedVariables• EngineControl• Security
TheDSCModulealsoincludestheHistoricalTrendExpressVIandtheReal-TimeTrendExpressVI.
40 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
11.2 DSCModuleControlsPalettes
TheDSCModuleinstallsthefollowingcontrolspalettestohelpyoubuilduserinterfacesthatresembleaplantorsystemandtoviewreal-timedatafromtheplantorsystem:
• 2DControls• 3DControls• Vessels• AlarmControls• TrendControls
TheDSCModulealsoincludestheHistoricalTrendcontrolandtheReal-TimeTrendcontrol.
11.3 CitadelDatabase
TheDSCModulelogssharedvariabledatatotheCitadeldatabase.TheCitadeldatabasestoreshistoricaldata,alarms,andevents.YoucanaccessandviewCitadeldatausingtheHistoricalDataViewerandusingthe“HistoricalVIs”.
41 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
11.4 HistoricalDataViewer
UsetheHistoricalDataViewertoviewdatastoredintheCitadeldatabase.Select“Tools→DSCModule→ViewHistorical”DatatolaunchtheMeasurement&AutomationExplorer(MAX).Expandthe“HistoricalData”categorytoselectadatabasethatappearsunder“Citadel5Universe”.YoualsocanusetheCallHDVVItolaunchtheHistoricalDataViewerprogrammatically.
DataLogger:
11.5 DistributedSystemManager
42 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
UsetheSharedVariableMonitortoviewthecurrentvalueofasharedvariableanditsstatusandalarmstate.Select“Tools→DistributedSystemManager”tolaunchtheDistributedSystemManager.
11.6 SQLServer
TheDSCModulerequirestheMicrosoftSQLServer2005ExpressEdition(SQLExpress).ThiscomponentisinstalledbydefaultwhenyouinstalltheDSCModule.Duringtheinstallationprocess,theDSCModuleinstallercreatesaninstanceofSQLExpressnamedCITADEL.TopreventunauthorizedaccesstoSQLExpress,theinstalleralsogeneratesapasswordforthedefaultSQLExpressadministratorsa.ThedefaultpasswordisthecomputerID.CompletethefollowingstepstofindthecomputerIDusingtheNILicenseManager.
1. LaunchtheNILicenseManagerbyselecting“Start→AllPrograms→NationalInstruments→NILicenseManager”.
2. ClicktheDisplayComputerInformationbuttononthetoolbar.
TheSQLServerdatabaseisusedforconfigurations,etc.,whiletheCitadeldatabaseisusedforDatalogging.
43 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Exercises
InthefollowingexerciseswewillbuildanapplicationinLabVIEWusingthefunctionalityfromtheLabVIEWDSCModule.
TheTasksareasfollows:
• Task1:OpenandRuntheExample• Task2:CreatingaNewProjectLibrary• Task3:CreatingaPeriodicI/OServer• Task4:DeployingthePeriodicI/OServer• Task5:CreatingSharedVariables
44 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
• Task6:ConfiguringDataLogging• Task7:ConfiguringAlarming• Task8:EnablingLogging• Task9:CreatetheLabVIEWApplication• Task10:UsetheLabVIEWDSCFunctionsandVIs• Task11:ViewingReal-TimeData• Task12:ViewingAlarmsusingtheDistributedSystemManager
11.6.1 Task1:OpenandRuntheExample
OpenDSCTankSimulator.vi.TheExampleisavailablefrom:http://home.hit.no/~hansha/
TheexampledoesnotuseanyDSCfunctionalitysofar.InthenextexerciseyouwillcreateaDSCapplicationbasedonthisexample.
11.6.2 Task2:CreatingaNewProjectLibrary
InthisexerciseyouwilllearnhowtocreateanewLabVIEWprojectandaprojectlibrary.Theprojectallowsyoutomanagesharedvariables,projectlibraries,andVIsinonewindow.LabVIEWprojectlibrariesarecollectionsofVIs,typedefinitions,sharedvariables,palettemenufiles,andotherfiles,includingotherprojectlibraries.
CompletethefollowingstepstocreateaLabVIEWprojectlibrary.
• ClicktheEmptyProjectlinkintheGettingStartedwindow.TheProjectExplorerwindowappears.
• Right-clickMyComputerintheProjectExplorerwindowandselectNew→Libraryfromtheshortcutmenu.
• SelectFile→SaveAll.TheNametheProjectdialogboxappears.• Enter“TankSystem”intheFilenametextbox.• ClicktheOKbutton.TheNametheLibrarydialogboxappears.• Enter“TankSystemIOServer”intheFilenametextbox.• ClicktheOKbutton.
45 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Younowhaveaprojectcontainingaprojectlibrary.InthefollowingexerciseyouwillusetheprojectlibraryintheprojecttocreateaperiodicI/Oserver.
11.6.3 Task3:CreatingaPeriodicI/OServer
Aserverisanapplicationthatcommunicateswithandmanagesinput/outputdevicessuchasPLCs,remoteinput/outputdevices,remoteSharedVariableEngines,anddataacquisition(DAQ)plug-indevices.Theseserversreadselectedinputitemsandwritetothemondemand.TheDSCModulecanconnecttoanyOPC-compliantserverandtomanythird-partydeviceservers.YoualsocancreatecustomI/Oservers.YouwillbuildaperiodicI/Oserverinthefollowingexercise.TheperiodicI/OserverwillrunasaserviceandpublishNIPublish-SubscribeProtocol(NI-PSP)dataitemstothenetwork.
CompletethefollowingstepstoaddtheperiodicI/Oservertotheproject.
Right-clicktheTankSystemIOServer.lvlibprojectlibraryintheProjectExplorerwindowandselectNew→I/OServerfromtheshortcutmenu.TheCreateNewI/OServerdialogboxappears.
46 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
SelectCustomVI–PeriodicfromtheI/OServerTypelistandclicktheContinuebutton.TheConfigureCustomVI–PeriodicI/OServerdialogboxappears.
ClicktheNewbuttontodisplaytheSelectVIstepoftheCustomVI-basedServer–PeriodicWizard.
SelecttheDSCTankSimulator.vi.
ClicktheNextbuttonintheCustomVI-basedServer–PeriodicWizardtoadvancetotheSelectControlsandIndicatorsToPublishstep.
47 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
HereyouwillselectControlsandIndicatorsyouwanttopublishassharedvariables.
RemovethecheckmarkfromthestopcheckboxintheControlslist.Youwillpublishtheremainingcontrolsandindicators.
ClicktheNextbuttontoadvancetotheSelectMethodToStopTheServerpage.
SelectStopthefollowingWhileLoopsandPlaceacheckmarkintheWhileLoopcheckbox.
ClicktheNextbuttontoadvancetotheConfigureServerDistributionComponentstep.
48 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
LeavethedefaultoptionsandclickNext.
TheServerDistributionComponentpageappears
TheDSCModuledisplaysasummaryofthefilesthattheCustomVI-basedServer–PeriodicWizardwillcreatefromtheServerDistributionComponentpage.ClicktheBuildbutton.ThewizarddisplaystheBuildstatusdialogboxasitcreatesaVItemplatefile,aregistrationVI,andasupportDLLandVIs.
49 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
AfterthewizardcreatestheperiodicI/Oserver,theConfigureCustomVI–PeriodicI/OServerdialogboxappearswiththenameoftheperiodicI/Oserverandthedataitemsitcontains.
ClicktheOKbutton.
LabVIEWaddstheperiodicI/OservertotheTankSystemIOServerprojectlibrary.
50 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Right-clicktheCustomVI–Periodic1itemintheProjectExplorerwindowandselectRenamefromtheshortcutmenu.RenametheperiodicI/Oserver“Tank1”.TheProjectExplorerwindowappearsasshownbelow.
11.6.4 Task4:DeployingthePeriodicI/OServer
NowyoumustdeploytheperiodicI/OserversothatthedataitemsintheI/OserverareavailableforuseinotherVIsandacrossthenetwork.InthisexerciseyouwilldeploytheperiodicI/OserverandviewtheI/OserverdataintheSharedVariableMonitor.
Note!TheperiodicI/OserverrunscontinuouslyinthebackgrounduntilyouundeploythelibraryintheProjectExplorerwindowthatcontainstheI/Oserver.
CompletethefollowingstepstodeploytheTank1periodicI/Oserverandviewthedata.
Right-clicktheTankSystemIOServer.lvlibprojectlibraryundertheMyComputeritemandselectDeployAllfromtheshortcutmenutodeploytheprojectlibrary.
51 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
ClicktheDonebuttontoclosetheDeploydialogboxwhenthedeploymentiscomplete.
SelectTools→DistributedSystemManager.
ExpandTankSystemIOServer→Tank1intheleftpane.NoticethatthecontrolsandindicatorsoftheI/OserverappearunderTank1.Becauseyouhavedeployedtheprojectlibrary,theI/OserverisrunningandeachcontrolandindicatorisanI/Odataitem.
ClicktheTank1.InputFlowRate[GPM]controlandenteravalueof10andclicktheOKbutton.NoticethatthevaluesofTank1.TankLevel[Gallons]andTank1.TankOutputFlowrate[GPM]beginincreasing.
52 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
CloseDistributedSystemManager.TheperiodicI/Oservercontinuestorun.
11.6.5 Task5:CreatingSharedVariables
Inthisexerciseyouwilladdthenetwork-publishedsharedvariablesthatrepresentthedataitemsintheperiodicI/OservertotheTankSystemSharedVariablesprojectlibrary.
CompletethefollowingstepstoaddtheTankSystemSharedVariablesprojectlibrarytotheTankSystemproject.
Right-clickMyComputerintheProjectExplorerwindowandselectNew→Libraryfromtheshortcutmenu.
Right-clickthenewprojectlibraryyoucreatedandselectCreateBoundVariablesfromtheshortcutmenutodisplaytheCreateBoundVariablesdialogbox.
53 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
SelectNetworkItems.
ExpandTankSystemIOServer→Tank1intheNetworktree.ThesharedvariablesappearunderTank1.
SelecteachsharedvariablewiththedatatypeDBLandclicktheAddbuttontoaddeachvariabletotheAddedvariableslist.ClicktheOKbutton.TheCreateBoundVariablesdialogboxclosesandthesharedvariablesappearintheMultipleVariableEditorwindow.
ClicktheDonebuttontoclosetheMultipleVariableEditorwindow.
SelectFile→SaveAllintheProjectExplorer.TheNametheLibrarydialogboxappears.
Enter“TankSystemSharedVariables”intheFilenametextbox.ClicktheOKbutton.LabVIEWbindsthesharedvariablesintheTankSystemSharedVariablesprojectlibrarytothecorrespondingitemsonthenetwork.
54 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
11.6.6 Task6:ConfiguringDataLogging
Whenyouaddloggingtoasharedvariable,theDSCModulelogssharedvariabledata,includingthesharedvariablevalue,timestamp,whetherthevalueisinanalarmstate,andthequalityofthevalue.TheDSCModulelogsalldatatotheCitadeldatabase.CompletethefollowingstepstoaddloggingfortheTankLevel[Gallons]sharedvariable.
Right-clicktheTankSystemSharedVariables.lvlibprojectlibraryandselectMultipleVariableEditor.
55 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
SetthefollowingfortheTankLevel[Gallons]sharedvariableintheMultipleVariableEditor:
11.6.7 Task7:ConfiguringAlarming
Analarmisanabnormalconditiononasharedvariableorauser-definedcondition.Analarmoccursifasharedvariablevaluegoesoutofitsdefinedalarmlimitsorifasharedvariablehasbadstatus.InthisexerciseyouwilladdanalarmfortheTankLevel[Gallons]sharedvariable.
56 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
SetthefollowingfortheTankLevel[Gallons]sharedvariableintheMultipleVariableEditor:
11.6.8 Task8:EnablingLogging
CompletethefollowingstepstoenabledataloggingandalarmandeventloggingfortheTankSystemSharedVariablesprojectlibrary.
Right-clicktheTankSystemSharedVariables.lvlibprojectlibraryintheProjectExplorerwindowandselectPropertiesfromtheshortcutmenu.TheProjectLibraryPropertiesdialogboxappears.
SelectDSCSettings:DatabasefromtheCategorylist.VerifythattheoptionsintheDSCSettings:DatabasepageappearsimilartotheFigurebelow.
TheEnableDataLoggingoptionturnsondataloggingfortheprojectlibrary.localhostspecifiesthelocalcomputer.Uselocalhostinsteadofthenameofthecomputertoreduce
57 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
thechangesyoumustmakeifyoumovethisprojecttoanothercomputer.TheEnableAlarmsandEventsLoggingoptionturnsoneventloggingfortheprojectlibrary.TheUsethesamedatabaseforalarmsandeventsoptionensuresthattheDSCModulelogsalarmsandeventsforthisprojectlibrarytothesamedatabasethatitlogsdata.
YoucanchangetheDatabasenamethatappearsintheProjectLibraryPropertiesdialogboxtoamoreusefulordescriptivename.
11.6.9 Task9:CreatetheLabVIEWapplication
InthisexerciseyouwillcreateaVItodisplaydataonafrontpanel.Youdonotneedtoaddanycodetotheblockdiagram.CompletethefollowingstepstocreateafrontpaneltodisplaythedataitemsintheperiodicI/Oserver.
Right-clickMyComputerintheProjectExplorerwindowandselectNew→VIfromtheshortcutmenu.AnewVIfrontpanelandblockdiagramappear.
SelecttheTankLevel[Gallons]sharedvariablefromtheTankSystemSharedVariables.lvlibprojectlibraryintheProjectExplorerwindowanddragthesharedvariableontothefrontpanel.Thesharedvariableappearsasanumericcontrol.Noticethetrianglethatappearsnexttothecontrol.Thetriangleindicatesthatthiscontrolhasbeenconfiguredfordatabinding.
Right-clicktheTankLevel[Gallons]controlandselectChangetoIndicatorfromtheshortcutmenu.
58 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Right-clicktheTankLevel[Gallons]indicatorandselectReplace→DSCModule→Vessels→OpenTankfromtheshortcutmenu.
Right-clicktheTankLevel[Gallons]indicatorandselectPropertiesfromtheshortcutmenu.ThePropertiesdialogboxappears.SelecttheDataBindingtabinthePropertiesdialogbox.
PlaceacheckmarkintheBlinkwhileAlarmOncheckboxtoconfigurethecontroltoblinkwhenthewaterlevelreaches75,thedefaultalarmyousetintheConfiguringAlarmingsectionofthisdocument.
FortheInputFlowrate[GPM]sharedvariable:
• SelecttheInputFlowrate[GPM]sharedvariablefromtheTankSystemSharedVariables.lvlibprojectlibraryintheProjectExplorerwindowanddragthesharedvariableontothefrontpanel.
• Right-clicktheInputFlowrate[GPM]controlandselectReplace→NumCtrls→PointerSlide.
FortheTankValve[%]sharedvariable:
• SelecttheTankValve[%]sharedvariablefromtheTankSystemSharedVariables.lvlibprojectlibraryintheProjectExplorerwindowanddragthesharedvariableontothefrontpanel.
59 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
• Right-clicktheTankValve[%]controlandselectReplace→NumCtrls→PointerSlide.
SelectFile→SaveAs.TheNametheVIdialogboxappears.Enter“TankSystemHMI”intheFilenametextbox.ClicktheOKbutton.
ClicktheRunContinuouslybuttontoruntheVI.TheVIshouldfunctioninthesamewayastheexampleyouraninthefirstexercise.
BelowwesewthefinalProjectExplorer:
Belowweseethefinalapplication:
60 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
11.6.10 Task10:UsetheLabVIEWDSCFunctionsandVIs
InthistaskyouwillusetheLabVIEWDSCFunctionsandVIspalette.
ReadHistoricalData:
BlockDiagram:
FrontPanel:
61 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
ReadAlarmData:
BlockDiagram:
FrontPanel:
62 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
11.6.11 Task11:ViewingReal-TimeData
YoucanusetheDSCModuletoviewlivedata.TheReal-TimeTrendExpressVIdisplayslivedatafromasharedvariableonanXYgraph.InthefollowingexerciseyouwilladdtheabilitytoviewlivedatatotheTankSystemVI.
PlacetheReal-TimeTrendExpressVI,availableontheDSCModulepalette,ontheblockdiagram.TheConfigureReal-TimeTrenddialogboxappears.
SelecttheTankLevel[Gallons]sharedvariableandselectAdd.
Placeawaveformchartonthefrontpanel.WirethetrenddataoutputoftheReal-TimeTrendExpressVItothewaveformchartontheblockdiagram.PlaceaWhileLooparoundthewaveformchartandExpressReal-TimeTrendcontrol.RuntheVI.
63 LabVIEWDataloggingandSupervisoryControl
Tutorial:OPCandReal-TimeSystemsinLabVIEW
FrontPanel
11.6.12 Task12:ViewingAlarmsusingtheDistributedSystemManager
OpentheDistributedSystemManagerfromTools→DistributedSystemManager.
65
12 LabVIEWI/OServer
12.1 ConnectLabVIEWtoOPCTagsbyCreatinganI/OServer
Inthissection,createaLabVIEWinterfacetotheOPCtagscalledanI/OServer.TheI/OServerautomaticallyupdatesLabVIEWwiththecurrenttagvaluesatarateyouspecify.
IntheGettingStartedwindowofLabVIEW,click“File→NewProject”.ThisopensanewLabVIEWProject.
IftheContextHelpwindowisnotvisible,press“Ctrl+H”todisplaythewindow.Keepthiswindowopenforhelpfulinformationaboutitemsunderyourcursor.
IntheLabVIEWProjectwindow,right-clickMyComputerandselect“New→I/OServer”,asshownintheFigurebelow.
66 LabVIEWI/OServer
Tutorial:OPCandReal-TimeSystemsinLabVIEW
SelectOPCClientinthe“CreateNewI/OServer”windowandclickContinue.
Choose“NationalInstruments.NIOPCServers”fromtheRegisteredOPCserversfieldandsetUpdaterate(ms)to100.ThiscreatesaconnectionfromLabVIEWtotheOPCtags,whichupdatesevery100ms.
SelectOK.AlibraryisautomaticallycreatedinyourprojectexplorerwindowtomanagetheI/OServer.
Savetheprojectas“OPCDemoProject”andthelibraryas“OPCDemoLibrary”byselecting“File→SaveAll”fromtheprojectexplorerwindow.
12.2 CreateSharedVariablesthatConnecttotheOPCTagsthroughtheI/OServer
67 LabVIEWI/OServer
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Inthissection,createsharedvariables,whichareboundtotheOPCtags,givingyounativeaccessinLabVIEWtoOPCdata.Withthesharedvariable,youcansharedataacrossLabVIEWapplicationsonasinglecomputeroracrossthenetwork.
CreatenewsharedvariablesthatareboundtotheOPCtags.
IntheLabVIEWProjectwindow,right-clickMyComputerandselect“New→Library”.Thiscreatesanewlibraryforthesharedvariables,whichareusedtoconnecttothePLCs’OPCtags.
Right-clickthenewlycreatedlibraryandselect“CreateBoundVariables…”.
IntheCreateBoundVariableswindow,selecttheOPCtagstobindthesharedvariablestobybrowsingdowntothesimulatedsinedatafromtheOPCserverasshownintheFigurebelow.
SelectallthesineitemsandclickAddandOK.ThiscreatessharedvariablesthatareboundtotheOPCtagsandloadsthemintotheMultipleVariableEditor.
IntheMultipleVariableEditor,selectDone.Thisaddsthenewsharedvariablestothelibrarythatwascreatedearlier.
Note!TheLabVIEWDSCModuleenhancessharedvariablesbyaddingtheabilitytologdata,alarms,andeventsdirectlytoadatabasewithouteverwritingaLabVIEWapplication.
Savethenewlibraryas“OPCItems.lvlib”intheprojectexplorerwindowbyright-clickingthelibraryandselectingSaveAs.
68 LabVIEWI/OServer
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Deploythesharedvariablesbyright-clickingthe“OPCItems”libraryandselectingDeploy.Thispublishesthesharedvariables,makingthemavailableonthenetworktoothercomputers,OPCclients,andtheLabVIEWReal-TimePAC.
YounowhaveaccesstoOPCdatanativelyinLabVIEWthroughthesharedvariables.
12.3 ViewingSharedVariableswithDistributedSystemManager
FromtheProjectExplorerwindow,select“Tools→DistributedSystemManager”.Thisopensawindowthatyoucanusetomanageyoursharedvariablesinvariousways(view,deploy,undeploy,etc.).
IntheTreepaneoftheVariableManager,expandthe“localhost”itemunderthe“MySystems”category.Right-clickthe“OPCItems”library,andselect“WatchList”todisplaythesharedvariables,whichareboundtothePLCs’OPCtags.
Thesharedvariableswillbeupdatingwiththesimulatedsinedata.
12.4 UsingOPCTagDatainLabVIEW
Fromtheprojectexplorer,right-clickMyComputerandselect“New→VI”.ThiscreatesanewvirtualinstrumentorVI.AVIisusedtocreateauserinterfaceandexecutablegraphicalcode.
Bydefault,youseetheFrontPanel,whichistheuserinterfaceoftheVI.Select“View→ControlsPalette”orright-clickanywhereontheFrontPaneltobringuptheControlspalette.
SelectawaveformchartfromtheControlspalettebyselecting“Express→GraphIndicators→Chart”,andplaceitontheFrontPanel,asshownintheFigurebelow.
69 LabVIEWI/OServer
Tutorial:OPCandReal-TimeSystemsinLabVIEW
IntheVI,select“Window→ShowBlockDiagram”orpressCtrl+EtoshowtheBlockDiagram.TheBlockDiagramiswhereyoubuildthebehaviorofyourapplication.NoticetheiconontheBlockDiagram,whichrepresentsthechartontheFrontPanel.Bypassingdataintothisterminal,youcandisplayitinthechartontheFrontPanel.
Intheprojectexplorer,expandthe“OPCItems”libraryandselecttheSine1sharedvariable.
DraganddroptheSine1sharedvariablefromtheprojectexplorertotheBlockDiagramoftheVI.ThesharedvariableactsasasourceofdatatootherterminalsontheBlockDiagram.
70 LabVIEWI/OServer
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Select“View→ToolsPalette”orpressShift+right-clicktoshowtheToolspalette,whichcontainsvarioustoolsforbuildingtheBlockDiagram.BydefaultyouusetheAutomaticToolSelectiontool,whichselectstheappropriatetoolbasedonthelocationofthecursor.
SelecttheConnectWiretoolasshownintheFigurebelow.ThistoolisusedtowireterminalstogetherontheBlockDiagram.
UsetheConnectWiretooltowiretheSine1sharedvariabletothewaveformchartbyclickingontheSine1sharedvariableandthenonthewaveformchart,asshownintheFigurebelow.
NowdataflowsfromthesharedvariabletothewaveformchartwhentheVIisrunning.
OpentheFunctionspalettebyselecting“View→FunctionsPalette”orright-clickinganywhereontheBlockDiagram.TheFunctionspalettecontainshundredsofanalysisfunctions,controlfunctions,andstructuresforgraphicalprogramming.
SelectawhileloopfromtheFunctionspalettebynavigatingto“Express→ExecutionControl→WhileLoop”.Thisallowsyoutowrapawhilelooparoundasectionofcode.
ThewhileloopcausesthecodewithinittoexecutecontinuouslyuntilstoppedbytheuseroradditionallogicintheVI.
71 LabVIEWI/OServer
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Atimedloop,whichisanadvancedwhileloop,containsadditionalconfigurationoptionsfortimingandexecutioncontrol.Convertthewhileloopintoatimedloopbyright-clickingthewhileloopandselectingReplacewithTimedLoop.
Toconfigurethetimedloop,double-clickthetimedloopinputnode
IntheLoopTimingAttributesfield,setPeriodto100msandclickOK.Thisconfiguresthetimedlooptoexecutethecontainedcodeevery100ms.
ClicktheRunbuttononthetoolbartoexecutetheVI.
ClickCloseontheDeploy…windowoncethedeploymentcompletes.Whentheapplicationbeginsexecuting,youseetheSine1sinewavedisplayedonthewaveformchart.
72 LabVIEWI/OServer
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Congratulations!YousuccessfullyaccessedPLCdatainyourLabVIEWapplication,soyoucanincorporatepowerfulanalysisandcontrolfunctionsinyoursolution.
73
13 LabVIEWReal-TimeModuleTheNationalInstrumentsLabVIEWReal-TimeModuleextendstheLabVIEWdevelopmentenvironmenttodeliverdeterministic,real-timeperformance.Developyourapplicationonahostcomputerusinggraphicalprogrammingandthendownloadtheapplicationtorunonanindependenthardwaretargetwithareal-timeOS(RTOS).
TheNationalInstrumentsLabVIEWReal-TimeModuleisanadd-oncomponentfortheLabVIEWDevelopmentSystem.Wheninstalled,thissoftwarecompilesNILabVIEWgraphicalcodeandoptimizesitfortheselectedreal-timetarget.UsingtheLabVIEWReal-TimeModule,youcandevelopanddeployapplicationstoallNIreal-timehardwaretargetsincludingPXI,CompactFieldPoint,FieldPoint,CompactRIO,andstandarddesktopPCs.TheembeddedRTOS(Real-TimeOperatingSystem)forthesetargetsisasinglededicatedkernelthatprovidesmaximumreliabilityforembeddedcode.
[Figure:www.ni.com]
WiththeLabVIEWProfessionalDevelopmentSystemandLabVIEWReal-TimeModule,youcancreateastand-aloneexecutableanddownloadittoahardwaretargetwithonesimplestep.Youcanpermanentlyembedthecodeonthenonvolatilememoryofthereal-timesystemsoitstartsautomaticallywhenthesystembootsforautonomousfieldapplications.
EachhardwaretargetcontainsanembeddedprocessorrunninganRTOS.TheLabVIEWReal-TimeModuleembedscompiledcodeonthehardwaretargetandrunsitindependentlyofthehostcomputer.Assigntheappropriateexecutionprioritytoeachreal-timetask.TheembeddedRTOSthenusesacombinationofround-robinandpreemptiveschedulingtoensuredeterministicexecutionofyourtime-criticaltasks.
74 LabVIEWReal-TimeModule
Tutorial:OPCandReal-TimeSystemsinLabVIEW
13.1 Real-TimeDevelopmentinLabVIEW
Developingreal-timeprogramsinLabVIEWisnearlyidenticaltodevelopingstandardLabVIEWapplicationsforyourPC.Whendevelopingreal-time(RT)programsinLabVIEW,youdeveloponahostWindowscomputer,andthendownloadandrunthemonareal-timehardwaretarget.
[Figure:www.ni.com]
Whendevelopingreal-timeapplicationsinLabVIEW,youusetheLabVIEWProjectExplorertoorganizeyourprograms(VIs)andcategorizethembythehardwareplatformthattheywillrunon.Notethatyoudevelopyourcodeonageneral-purposeWindowscomputer,andthenconnecttoyourreal-timehardwareusingEthernet.
TotestyourLabVIEWReal-Timeprogramonyourhardwareplatform,simplyclickontherunarrowandyourapplicationwillautomaticallybetransferredtoyourreal-timehardwareviaEthernetandbeginrunning.YoucanusestandardNIdebuggingtoolssuchashighlight
75 LabVIEWReal-TimeModule
Tutorial:OPCandReal-TimeSystemsinLabVIEW
execution,singlestepping,andbreakpointsfromyourdevelopmentsystemeventhoughyourreal-timeprogramisactuallyrunningonaseparatesystem.
Whenyouhavefinalizedyourreal-timeprogram,youcanbuildanEXEinLabVIEWanddownloadittoyourreal-timehardwareasastartupapplication.Afterrebootingyourreal-timehardware,yourprogramwillautomaticallyruninareliable,stand-alonefashion.
YoustartanewReal-TimeProjectfromyourGettingStartedwindow.
Selecteither“Real-TimeProject”intheNewgrouporselect“Real-TimeProject”intheTargetsselectorandthen“Go”.
TheReal-TimeprojectisalsoavailablefromtheToolsmenu.
76
14 CompactFieldPoint
14.1 Introduction
CompactFieldPointisaneasy-to-use,highlyexpandableindustrialcontrolandmeasurementsystemcomposedofruggedanddependableI/Omodulesandintelligentcommunicationinterfaces.DownloadyourNILabVIEWapplicationontotheembeddedreal-timecontrollerforstand-alonedatalogging,monitoring,andadvancedcontrol.Plus,connecttovirtuallyanysensortypewiththewidevarietyofI/Omodules,suchasthermocouples,resistancetemperaturedetectors(RTDs),straingages,4-20mAsensors,andavarietyofdigitalsignalsfrom5-30VDCand0-250VAC.TheCompactFieldPointI/Omodulesfilter,calibrate,andscalerawsensorsignalstoengineeringunitsandperformself-diagnosticstolookforproblems,suchasanopenthermocouple.
WithCompactFieldPointyoucan:
• Deployreal-timeembeddedcontrollersforstand-alonedatalogging,advancedanalysis,andprocesscontrol.
• AccessI/Opointsnearbyormilesawayonthenetworkusingthesamesimplereadandwritesoftwareframework.
• Connectvirtuallyanysensordirectlytothewidevarietyofhigh-accuracyanaloganddiscreteI/Omodules.
• DownloadyourNILabVIEWapplicationtotheembeddedcontrollerforreliable,stand-aloneoperation.
77 CompactFieldPoint
Tutorial:OPCandReal-TimeSystemsinLabVIEW
CompactFieldPointisveryeasytouseandcanhelpyouquicklybeginperformingindustrialcontrolandmeasurement.Gettingstartedisasimplethree-stepprocess:
1. Installthehardware2. Configurethecontroller3. ReadorwritetheI/Ochannels
TightintegrationbetweentheLabVIEWsoftwareenvironmentandreal-timehardwaretargets,suchasCompactFieldPoint,makeyourcontroldevelopmentprocessquickandeasy.Youcantakeadvantageofpowerfulgraphicaldevelopmentusingindustry-standardLabVIEWtorapidlyimplementyourcontrolsystem.
1. First,developtheprogramonaWindowshostcomputerusinggraphicalprogrammingblocks.
2. Next,downloadtheapplicationtoanembeddedcontrollersuchtheNIcFP-2000/cFP-2220.
3. Finally,deployyourapplicationfordependablelong-termexecutionthatperformsreliablybothwithandwithoutanetworkconnection.Onceyourapplicationisdeployed,youcanaccesstheembeddedapplicationthroughanyWebbrowserbyconnectingtotheembeddedWebserverofthereal-timeCompactFieldPointcontroller.
14.2 Development
InordertoconfigureanduseyourCompactFieldPointyouneedtodothefollowingsteps.
Step1:ConnecttheCompactFieldPointtoyourPC
ConnectyourCompactFieldPointsystemtoyourPCusinganEthernetcross-overcable.IfyouuseaSwitchorHubyoumayuseastandardEthernetcable.
Step2:InstallandConfiguretheCompactFieldPoint
YouusetheMeasurement&AutomationExplorer(MAX)toconfigureyourCompactFieldPointsystem.
Goto“RemoteSystems”.Thesystemshouldnowbeautomaticallydetected.
78 CompactFieldPoint
Tutorial:OPCandReal-TimeSystemsinLabVIEW
YoumayneedtoconfiguretheIPsettings.
Step3:FindyourDevices
ClickonyourCompactFieldPointnodeandright-clickandselect“FindDevices”.
AllyourCompactFieldPointmodules(controller,I/modules)shouldnowappear.
79 CompactFieldPoint
Tutorial:OPCandReal-TimeSystemsinLabVIEW
InourcasewehaveacFP-2000controllerandacFP-AIO-610I/Omodule.
Step4:StartanEmptyProjectinLabVIEW
StartLabVIEWandselect“EmptyProject”intheGettingStartedwindow.
Right-clickontheProjectnodeandselect“TargetsandDevices…”
80 CompactFieldPoint
Tutorial:OPCandReal-TimeSystemsinLabVIEW
SelectyourCompactFieldPointdevicefromthelist(Real-TimeFieldPoint):
WhenyouclickOK,allyourmoduleswillbeautomaticallyinsertedintoyourProject.
81 CompactFieldPoint
Tutorial:OPCandReal-TimeSystemsinLabVIEW
IfyouclickonyourI/Omodule,youwillseeallyourI/Ochannelsforthatmodule:
Step5:CreateyourVI
Right-clickonyourcontrollerandselectNew→VI
82 CompactFieldPoint
Tutorial:OPCandReal-TimeSystemsinLabVIEW
GotoyourI/Omoduleintheprojecttreeandselectyourchannel,e.g.,Input0.DragthechanneltoyourBlockDiagramandthecodeforthatchannelwillbeautomaticallycreated.
Step6:FinishyourProgram
Finishyourprogram,e.g.,readInput0andplotthevaluesinaChart.
BlockDiagram:
83 CompactFieldPoint
Tutorial:OPCandReal-TimeSystemsinLabVIEW
HereareyourProjectExplorerandtheFrontDiagram:
Step6:Deployment
ClicktheRunbuttontostarttestanddeployyourprogram.LabVIEWthenautomaticallystarttocheckyourcouldanddownloadittothecontroller.
84 CompactFieldPoint
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Step6:Finish
Yoursystemshouldnowbereadytouse.
85
15 CompactRIO
15.1 Introduction
CompactRIO(cRIO)isarealtimeindustrialcontrollermadebyNationalInstruments.TheCompactRIOisacombinationofaRealTimeController,reconfigurableIOModules(RIO),FPGAModuleandanEthernetexpansionchassis.
BelowweseeaCompactRIOsystem:
YoudevelopyourCompactRIOsoftwareonyourcomputerusingLabVIEWthenyoudownloadyourcodetothesystem.TheLabVIEWReal-TimeModuleisusedforthis.
IfyouwanttousetheFPGA,youneedtoinstalltheLabVIEWFPGAModule
15.2 Development
TightintegrationbetweentheLabVIEWsoftwareenvironmentandreal-timehardwaretargets,suchasCompactRIO,makeyourcontroldevelopmentprocessquickandeasy.Youcantakeadvantageofpowerfulgraphicaldevelopmentusingindustry-standardLabVIEWtorapidlyimplementyourcontrolsystem.
1. First,developtheprogramonaWindowshostcomputerusinggraphicalprogrammingblocks.
2. Next,downloadtheapplicationtoanembeddedcontrollersuchtheNIcFP-2000/cFP-2220.
3. Finally,deployyourapplicationfordependablelong-termexecutionthatperformsreliablybothwithandwithoutanetworkconnection.Onceyourapplicationis
86 CompactRIO
Tutorial:OPCandReal-TimeSystemsinLabVIEW
deployed,youcanaccesstheembeddedapplicationthroughanyWebbrowserbyconnectingtotheembeddedWebserverofthereal-timeCompactRIOcontroller.
InordertoconfigureanduseyourCompactRIOyouneedtodothefollowingsteps.
Step1:ConnecttheCompactRIOtoyourPC
ConnectyourCompactRIOsystemtoyourPCusinganEthernetcable.
Step2:InstallandConfiguretheCompactRIO
YouusetheMeasurement&AutomationExplorer(MAX)toconfigureyourCompactRIOsystem.
Goto“RemoteSystems”.Thesystemshouldnowbeautomaticallydetected.
YoumayneedtoconfiguretheIPsettings,etc.(NetworkSettings).
87 CompactRIO
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Step3:FindyourDevices
AllyourCompactRIOmodules(controller,I/modules)shouldnowappearunderDevicesandInterfaces.
InourcasewehaveaNIcRIO-9074controller,aNI9263AnalogOutI/OmoduleandaNI9201AnalogInI/Omodule.
Step4:InstallSoftware
YouonlydothisoncewhenyouusetheCompactRIOforthefirsttimeoryouwanttoaddorupgradetheexistingsoftware.
88 CompactRIO
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Ifyouselectcustominstallation,youmightgetawarninglikethis:
Justdiscardit!
Step5:StartanewProjectinLabVIEW
StartLabVIEWandselect“Real-TimeProject”intheGettingStartedwindow.
89 CompactRIO
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Right-clickontheProjectnodeandselect“TargetsandDevices…”
90 CompactRIO
Tutorial:OPCandReal-TimeSystemsinLabVIEW
SelectyourCompactRIOdevicefromthelist(Real-TimeCompactRIO).
WhenyouclickOK,allyourmoduleswillbeautomaticallyinsertedintoyourProject.
91 CompactRIO
Tutorial:OPCandReal-TimeSystemsinLabVIEW
YouwillnowseeallyourI/OmodulesthatyouhaveandyouwillseeallyourI/Ochannelsforthesemodules.
Step6:CreateyourVI
Right-clickonyourcontrollerandselectNew→VI
GotoyourI/Omoduleintheprojecttreeandselectyourchannel,e.g.,Input0.DragthechanneltoyourBlockDiagramandthecodeforthatchannelwillbeautomaticallycreated.
BelowweseeasimpleexamplewithoneAnalogInandoneAnalogOut:
92 CompactRIO
Tutorial:OPCandReal-TimeSystemsinLabVIEW
TheFrontPanel:
Inthissimpleexamplewehaveusedasimpleloop-backtest,meaningwehaveconnectedAO0(AnalogOut,Chanel0)andAI0(AnalogIn,Chanel0)together,asshownbelow.Thismeanswhenwewrite4VtotheAO0,weshouldreceive4VonAI0.
93 CompactRIO
Tutorial:OPCandReal-TimeSystemsinLabVIEW
Step7:Deployment
ClicktheRunbuttontostarttestanddeployyourprogram.LabVIEWthenautomaticallystarttocheckyourcodeanddownloadittothecontroller.
Step8:Finish
Yoursystemshouldnowbereadytouse.
Hans-PetterHalvorsen,M.Sc.
E-mail:[email protected]
Blog:http://home.hit.no/~hansha/
UniversityCollegeofSoutheastNorway
www.usn.no