Tutorial: Data Acquisition in LabVIEW
Transcription
Tutorial: Data Acquisition in LabVIEW
UniversityCollegeofSoutheastNorway DataAcquisitioninLabVIEW Hans-PetterHalvorsen,2016.10.28 http://home.hit.no/~hansha Preface ThistutorialexplainsthebasicconceptsofaDataAcquisitioninLabVIEW. Youfindthisdocumentandadditionalresourcesonlineat: http://home.hit.no/~hansha/?tutorial=daq YoushouldhavesomebasicknowledgeaboutLabVIEW,e.g.,the“IntroductiontoLabVIEW” tutorial.Thisdocumentisavailablefordownloadathttp://home.hit.no/~hansha/. FormoreinformationaboutLabVIEW,visit:http://home.hit.no/~hansha/?page=labview. InadditiontoLabVIEW,youwillneedtoinstallthedriverNI-DAQmx. [Figureontitlepage:www.ni.com] 2 TableofContents Preface......................................................................................................................................2 TableofContents.....................................................................................................................iii 1 IntroductiontoLabVIEW.....................................................................................................1 1.1 Dataflowprogramming................................................................................................1 1.2 Graphicalprogramming................................................................................................1 1.3 Benefits.........................................................................................................................2 2 IntroductiontoDataAcquisition.........................................................................................3 2.1 IntroductiontoDAQ-DataAcquisition........................................................................3 2.1.1 Physicalinput/outputsignals.................................................................................4 2.1.2 DAQdevice/hardware...........................................................................................4 2.1.3 Driversoftware......................................................................................................5 2.1.4 Yoursoftwareapplication(Applicationsoftware).................................................6 2.2 MAX–MeasurementandAutomationExplorer..........................................................6 2.3 NI-DAQmx.....................................................................................................................7 2.3.1 DAQAssistant........................................................................................................8 2.4 NIUSB-6008..................................................................................................................8 3 Physicalinput/outputsignals............................................................................................10 3.1 Transducers................................................................................................................10 3.2 Signals.........................................................................................................................11 3.2.1 AnalogSignals......................................................................................................11 3.3 DigitalSignals..............................................................................................................13 4 MAX...................................................................................................................................15 iii iv TableofContents 5 NI-DAQmx.........................................................................................................................17 5.1.1 DAQAssistant......................................................................................................18 5.2 SimulatingaDAQDevice............................................................................................18 6 DAQDevices......................................................................................................................20 6.1 PerformingAnalog-to-DigitalConversion...................................................................21 6.2 PerformingDigital-to-AnalogConversion...................................................................21 6.3 UsingCounters...........................................................................................................21 6.4 UsingDigitalI/O..........................................................................................................22 7 NIUSB-6008......................................................................................................................23 7.1 ConnectNIUSB-6008tothePC..................................................................................23 7.1.1 TestingtheUSB-6008inMAX..............................................................................24 7.2 UsingNIUSB-6008inLabVIEW...................................................................................30 7.3 DAQAssistant.............................................................................................................31 7.3.1 AnalogInput........................................................................................................31 7.3.2 AnalogOutput......................................................................................................38 8 LoggingtoFile...................................................................................................................43 8.1 WritingtoMeasurementFile.....................................................................................43 8.2 ReadfromMeasurementFile.....................................................................................46 Tutorial: Data Acquisition in LabVIEW 1 IntroductiontoLabVIEW LabVIEW(shortforLaboratoryVirtualInstrumentationEngineeringWorkbench)isa platformanddevelopmentenvironmentforavisualprogramminglanguagefromNational Instruments.Thegraphicallanguageisnamed"G".OriginallyreleasedfortheApple Macintoshin1986,LabVIEWiscommonlyusedfordataacquisition,instrumentcontrol,and industrialautomationonavarietyofplatformsincludingMicrosoftWindows,variousflavors ofUNIX,Linux,andMacOSX.VisitNationalInstrumentsatwww.ni.com. Thecodefileshavetheextension“.vi”,whichisanabbreviationfor“VirtualInstrument”. LabVIEWofferslotsofadditionalAdd-OnsandToolkits. 1.1 Dataflowprogramming TheprogramminglanguageusedinLabVIEW,alsoreferredtoasG,isadataflow programminglanguage.Executionisdeterminedbythestructureofagraphicalblock diagram(theLV-sourcecode)onwhichtheprogrammerconnectsdifferentfunction-nodes bydrawingwires.Thesewirespropagatevariablesandanynodecanexecuteassoonasall itsinputdatabecomeavailable.Sincethismightbethecaseformultiplenodes simultaneously,Gisinherentlycapableofparallelexecution.Multi-processingandmultithreadinghardwareisautomaticallyexploitedbythebuilt-inscheduler,whichmultiplexes multipleOSthreadsoverthenodesreadyforexecution. 1.2 Graphicalprogramming LabVIEWtiesthecreationofuserinterfaces(calledfrontpanels)intothedevelopmentcycle. LabVIEWprograms/subroutinesarecalledvirtualinstruments(VIs).EachVIhasthree components:ablockdiagram,afrontpanel,andaconnectorpanel.Thelastisusedto representtheVIintheblockdiagramsofother,callingVIs.Controlsandindicatorsonthe frontpanelallowanoperatortoinputdataintoorextractdatafromarunningvirtual instrument.However,thefrontpanelcanalsoserveasaprogrammaticinterface.Thusa virtualinstrumentcaneitherberunasaprogram,withthefrontpanelservingasauser interface,or,whendroppedasanodeontotheblockdiagram,thefrontpaneldefinesthe inputsandoutputsforthegivennodethroughtheconnectorpane.ThisimplieseachVIcan beeasilytestedbeforebeingembeddedasasubroutineintoalargerprogram. 1 2 IntroductiontoLabVIEW Thegraphicalapproachalsoallowsnon-programmerstobuildprogramssimplybydragging anddroppingvirtualrepresentationsoflabequipmentwithwhichtheyarealreadyfamiliar. TheLabVIEWprogrammingenvironment,withtheincludedexamplesandthe documentation,makesitsimpletocreatesmallapplications.Thisisabenefitononeside, butthereisalsoacertaindangerofunderestimatingtheexpertiseneededforgoodquality "G"programming.Forcomplexalgorithmsorlarge-scalecode,itisimportantthatthe programmerpossessanextensiveknowledgeofthespecialLabVIEWsyntaxandthe topologyofitsmemorymanagement.ThemostadvancedLabVIEWdevelopmentsystems offerthepossibilityofbuildingstand-aloneapplications.Furthermore,itispossibletocreate distributedapplications,whichcommunicatebyaclient/serverscheme,andaretherefore easiertoimplementduetotheinherentlyparallelnatureofG-code. 1.3 Benefits OnebenefitofLabVIEWoverotherdevelopmentenvironmentsistheextensivesupportfor accessinginstrumentationhardware.Driversandabstractionlayersformanydifferenttypes ofinstrumentsandbusesareincludedorareavailableforinclusion.Thesepresent themselvesasgraphicalnodes.Theabstractionlayersofferstandardsoftwareinterfacesto communicatewithhardwaredevices.Theprovideddriverinterfacessaveprogram developmenttime.ThesalespitchofNationalInstrumentsis,therefore,thatevenpeople withlimitedcodingexperiencecanwriteprogramsanddeploytestsolutionsinareduced timeframewhencomparedtomoreconventionalorcompetingsystems.Anewhardware drivertopology(DAQmxBase),whichconsistsmainlyofG-codedcomponentswithonlya fewregistercallsthroughNIMeasurementHardwareDDK(DriverDevelopmentKit) functions,providesplatformindependenthardwareaccesstonumerousdataacquisition andinstrumentationdevices.TheDAQmxBasedriverisavailableforLabVIEWonWindows, MacOSXandLinuxplatforms. Tutorial: Data Acquisition in LabVIEW 2 IntroductiontoData Acquisition ThischapterexplainsthebasicconceptsofusingDAQinLabVIEW. Topics: • • • IntroductiontoDAQ-DataAcquisition MAX–MeasurementandAutomationExplorer NI-DAQmx LabVIEWisverypowerfulwhenitcomestocreatingDAQapplications.LabVIEWincludesa setofVIsthatletyouconfigure,acquiredatafrom,andsenddatatoDAQdevices.Often, onedevicecanperformavarietyoffunctions,suchasanalog-to-digital(A/D)conversion, digital-to-analog(D/A)conversion,digitalI/O,andcounter/timeroperations.Eachdevice supportsdifferentDAQandsignalgenerationspeeds.Also,eachDAQdeviceisdesignedfor specifichardware,platformsandoperatingsystems. NationalInstruments,theinventorofLabVIEW,alsomakeDAQdevices,sotheintegration withtheDAQdevicesfromNIandtheLabVIEWsoftwareisseamlessandmakesiteasytodo I/OoperationsfromtheLabVIEWenvironment. 2.1 IntroductiontoDAQ-DataAcquisition Thepurposeofdataacquisitionistomeasureanelectricalorphysicalphenomenonsuchas voltage,current,temperature,pressure,orsound.PC-baseddataacquisitionusesa combinationofmodularhardware,applicationsoftware,andacomputertotake measurements.Whileeachdataacquisitionsystemisdefinedbyitsapplication requirements,everysystemsharesacommongoalofacquiring,analyzing,andpresenting information.Dataacquisitionsystemsincorporatesignals,sensors,actuators,signal conditioning,dataacquisitiondevices,andapplicationsoftware. Sosummingup,DataAcquisitionistheprocessof: • • Acquiringsignalsfromreal-worldphenomena Digitizingthesignals 3 4 • IntroductiontoDataAcquisition Analyzing,presentingandsavingthedata TheDAQsystemhasthefollowingpartsinvolved,seeFigure: Thepartsare: • • • • Physicalinput/outputsignals DAQdevice/hardware Driversoftware Yoursoftwareapplication(Applicationsoftware) ForanIntroductiontoDataAcquisition,seethiswebcast: http://zone.ni.com/wv/app/doc/p/id/wv-169 2.1.1 Physicalinput/outputsignals Aphysicalinput/outputsignalistypicallyavoltageorcurrentsignal. Avoltagesignalcantypicallybea0-5Vsignal,whileacurrentsignalcantypicallybea420mAsignal. 2.1.2 DAQdevice/hardware DAQhardwareactsastheinterfacebetweenthecomputerandtheoutsideworld.It primarilyfunctionsasadevicethatdigitizesincominganalogsignalssothatthecomputer caninterpretthem ADAQdevice(DataAcquisitionHardware)usuallyhasthesefunctions: • • Analoginput Analogoutput Tutorial: Data Acquisition in LabVIEW 5 • • IntroductiontoDataAcquisition DigitalI/O Counter/timers WehavedifferentDAQdevices,suchas: • • • “DesktopDAQdevices”whereyouneedtoplugaPCIDAQboardintoyour computer.Thesoftwareisrunningonacomputer. “PortableDAQdevices”forconnectiontotheUSBport,Wi-Ficonnections,etc.The softwareisrunningonacomputer “DistributedDAQdevices”wherethesoftwareisdevelopedonyourcomputerand thenlaterdownloadedtothedistributedDAQdevice. [www.ni.com] 2.1.3 Driversoftware Driversoftwareisthelayerofsoftwareforeasilycommunicatingwiththehardware.Itforms themiddlelayerbetweentheapplicationsoftwareandthehardware.Driversoftwarealso preventsaprogrammerfromhavingtodoregister-levelprogrammingorcomplicated commandsinordertoaccessthehardwarefunctions. DriversoftwarefromNationalInstruments: • NI-DAQmx Tutorial: Data Acquisition in LabVIEW 6 • IntroductiontoDataAcquisition NI-DAQmxBase TheDAQAssistant,includedwithNI-DAQmx,isagraphical,interactiveguideforconfiguring, testing,andacquiringmeasurementdata.Withasingleclick,youcanevengeneratecode basedonyourconfiguration,makingiteasierandfastertodevelopcomplexoperations. BecauseDAQAssistantiscompletelymenu-driven,youwillmakefewerprogrammingerrors anddrasticallydecreasethetimefromsettingupyourDAQsystemtotakingyourfirst measurement. NI-DAQmxBaseoffersasubsetofNI-DAQmxfunctionalityonWindowsandLinux,MacOSX, WindowsMobileandWindowsCE. 2.1.4 Yoursoftwareapplication(Application software) Applicationsoftwareaddsanalysisandpresentationcapabilitiestothedriversoftware.Your softwareapplicationnormallydoessuchtasksas: • • • • • Real-timemonitoring Dataanalysis Datalogging Controlalgorithms Humanmachineinterface(HMI) InordertocreateyourDAQapplicationyouneedaprogrammingdevelopmenttool,suchas LabVIEW. 2.2 MAX–MeasurementandAutomation Explorer Measurement&AutomationExplorer(MAX)providesaccesstoyourNationalInstruments devicesandsystems. WithMAX,youcan: • • • • ConfigureyourNationalInstrumentshardwareandsoftware Createandeditchannels,tasks,interfaces,scales,andvirtualinstruments Executesystemdiagnostics Viewdevicesandinstrumentsconnectedtoyoursystem Tutorial: Data Acquisition in LabVIEW 7 • IntroductiontoDataAcquisition UpdateyourNationalInstrumentssoftware Inadditiontothestandardtools,MAXcanexposeitem-specifictoolsyoucanuseto configure,diagnose,ortestyoursystem,dependingonwhichNIproductsyouinstall.Asyou navigatethroughMAX,thecontentsoftheapplicationmenuandtoolbarchangetoreflect thesenewtools. 2.3 NI-DAQmx TheNI-DAQmxDriversoftwareisthelayerofsoftwareforeasilycommunicatingwiththe hardware.Itformsthemiddlelayerbetweentheapplicationsoftwareandthehardware. Tutorial: Data Acquisition in LabVIEW 8 IntroductiontoDataAcquisition Driversoftwarealsopreventsaprogrammerfromhavingtodoregister-levelprogramming orcomplicatedcommandsinordertoaccessthehardwarefunctions. TheDAQmxpaletteinLabVIEW: The“DAQAssistant”isaneasywaytostartusingtheDAQfeaturesinLabVIEW.Wewill learnmoreaboutthe“DAQAssistant”inalaterchapter. 2.3.1 DAQAssistant TheDAQAssistant,includedwithNI-DAQmx,isagraphical,interactiveguideforconfiguring, testing,andacquiringmeasurementdata.Withasingleclick,youcanevengeneratecode basedonyourconfiguration,makingiteasierandfastertodevelopcomplexoperations. BecauseDAQAssistantiscompletelymenu-driven,youwillmakefewerprogrammingerrors anddrasticallydecreasethetimefromsettingupyourDAQsystemtotakingyourfirst measurement. 2.4 NIUSB-6008 NIUSB-6008isasimpleandlow-costmultifunctionI/OdevicefromNationalInstruments. Tutorial: Data Acquisition in LabVIEW 9 IntroductiontoDataAcquisition Thedevicehasthefollowingspecifications: • • • • • • 8analoginputs(12-bit,10kS/s) 2analogoutputs(12-bit,150S/s) 12digitalI/O USBconnection,Noextrapower-supplyneeeded CompatiblewithLabVIEW,LabWindows/CVI,andMeasurementStudioforVisual Studio.NET NI-DAQmxdriversoftware TheNIUSB-6008iswellsuitedforeducationpurposesduetoitssmallsizeandeasyUSB connection. Tutorial: Data Acquisition in LabVIEW 3 Physicalinput/output signals Dataacquisitioninvolvesgatheringsignalsfrommeasurementsourcesanddigitizingthe signalforstorage,analysis,andpresentationonaPC.Dataacquisition(DAQ)systemscome inmanydifferentPCtechnologyformsforgreatflexibilitywhenchoosingyoursystem. ScientistsandengineerscanchoosefromPCI,PXI,PCIExpress,PXIExpress,PCMCIA,USB, WirelessandEthernetdataacquisitionfortest,measurement,andautomationapplications. TherearefivecomponentstobeconsideredwhenbuildingabasicDAQsystem • • • • • Transducersandsensors Signals Signalconditioning DAQhardware Driverandapplicationsoftware InthischapterwefocusonTransducers,sensorsandSignals. 3.1 Transducers Dataacquisitionbeginswiththephysicalphenomenontobemeasured.Thisphysical phenomenoncouldbehetemperatureofaroom,theintensityofalightsource,the pressureinsideachamber,theforceappliedtoanobject,ormanyotherthings.Aneffective DAQsystemcanmeasureallofthesedifferentphenomena. Atransducerisadevicethatconvertsaphysicalphenomenonintoameasurableelectrical signal,suchasvoltageorcurrent.TheabilityofaDAQsystemtomeasuredifferent phenomenadependsonthetransducerstoconvertthephysicalphenomenaintosignals measurablebytheDAQhardware.TransducersaresynonymouswithsensorsinDAQ systems.Therearespecifictransducersformanydifferentapplications,suchasmeasuring temperature,pressure,orfluidflow.Belowweseesomecommonphenomenaandthe transducersusedtomeasurethem. Phenomenon Transducer 10 11 Physicalinput/outputsignals Temperature Thermocouple,RTD,Thermistor Light PhotoSensor Sound Microphone ForceandPressure StrainGage,PiezoelectricTransducer Positionand Displacement Potentiometer,LVDT,OpticalEncoder Acceleration Accelerometer pH pHElectrode Differenttransducershavedifferentrequirementsforconvertingphenomenaintoa measurablesignal.Sometransducersmayrequireexcitationintheformofvoltageor current.Othertransducersmayrequireadditionalcomponentsandevenresistivenetworks toproduceasignal. Refertoni.com/sensorsformoreinformationontransducers. 3.2 Signals Theappropriatetransducersconvertphysicalphenomenaintomeasurablesignals.However, differentsignalsneedtobemeasuredindifferentways.Forthisreason,itisimportantto understandthedifferenttypesofsignalsandtheircorrespondingattributes.Signalscanbe categorizedintotwogroups: • • Analog Digital 3.2.1 AnalogSignals Analoginputistheprocessofmeasuringananalogsignalandtransferringthemeasurement toacomputerforanalysis,display,orstorage.Ananalogsignalisasignalthatvaries continuously.Analoginputismostcommonlyusedtomeasurevoltageorcurrent.Youcan usemanytypesofdevicestoperformanaloginput,suchasmultifunctionDAQ(MIO) devices,high-speeddigitizers,digitalmultimeters,andDynamicSignalAcquisition(DSA) devices. Tutorial: Data Acquisition in LabVIEW 12 Physicalinput/outputsignals [ww.ni.com] Ananalogsignalcanbeatanyvaluewithrespecttotime.Afewexamplesofanalogsignals includevoltage,temperature,pressure,sound,andload.Thethreeprimarycharacteristicsof ananalogsignalis: • • • Level Shape Frequency Level Becauseanalogsignalscantakeonanyvalue,thelevelgivesvitalinformationaboutthe measuredanalogsignal.Theintensityofalightsource,thetemperatureinaroom,andthe pressureinsideachamberareallexamplesthatdemonstratetheimportanceofthelevelof asignal.Whenmeasuringthelevelofasignal,thesignalgenerallydoesnotchangequickly Tutorial: Data Acquisition in LabVIEW 13 Physicalinput/outputsignals withrespecttotime.Theaccuracyofthemeasurement,however,isveryimportant.ADAQ systemthatyieldsmaximumaccuracyshouldbechosentoaidinanaloglevel measurements. Shape Somesignalsarenamedaftertheirspecificshape-sine,square,sawtooth,andtriangle.The shapeofananalogsignalcanbeasimportantasthelevel,becausebymeasuringtheshape ofananalogsignal,youcanfurtheranalyzethesignal,includingpeakvalues,DCvalues,and slope.Signalswhereshapeisofinterestgenerallychangerapidlywithrespecttotime,but systemaccuracyisstillimportant.Theanalysisofheartbeats,videosignals,sounds, vibrations,andcircuitresponsesaresomeapplicationsinvolvingshapemeasurements. Frequency Allanalogsignalscanbecategorizedbytheirfrequency.Unlikethelevelorshapeofthe signal,frequencycannotbedirectlymeasured.Thesignalmustbeanalyzedusingsoftware todeterminethefrequencyinformation.Thisanalysisisusuallydoneusinganalgorithm knownastheFouriertransform. Whenfrequencyisthemostimportantpieceofinformation,itisimportanttoconsider includingbothaccuracyandacquisitionspeed.Althoughtheacquisitionspeedforacquiring thefrequencyofasignalislessthanthespeedrequiredforobtainingtheshapeofasignal, thesignalmuststillbeacquiredfastenoughthatthepertinentinformationisnotlostwhile theanalogsignalisbeingacquired.Theconditionthatstipulatesthisspeedisknownasthe NyquistSamplingTheorem.Speechanalysis,telecommunication,andearthquakeanalysis aresomeexamplesofcommonapplicationswherethefrequencyofthesignalmustbe known. 3.3 DigitalSignals Adigitalsignalcannottakeonanyvaluewithrespecttotime.Instead,adigitalsignalhas twopossiblelevels:highandlow.Digitalsignalsgenerallyconformtocertainspecifications thatdefinecharacteristicsofthesignal.Digitalsignalsarecommonlyreferredtoas transistor-to-transistorlogic(TTL).TTLspecificationsindicateadigitalsignaltobelowwhen thelevelfallswithin0to0.8V,andthesignalishighbetween2to5V.Theuseful informationthatcanbemeasuredfromadigitalsignalincludesthestateandtherate. Tutorial: Data Acquisition in LabVIEW 14 Physicalinput/outputsignals State Digitalsignalscannottakeonanyvaluewithrespecttotime.Thestateofadigitalsignalis essentiallythelevelofthesignal-onoroff,highorlow.Monitoringthestateofaswitch- openorclosed-isacommonapplicationshowingtheimportanceofknowingthestateofa digitalsignal. Rate Therateofadigitalsignaldefineshowthedigitalsignalchangesstatewithrespecttotime. Anexampleofmeasuringtherateofadigitalsignalincludesdetermininghowfastamotor shaftspins.Unlikefrequency,therateofadigitalsignalmeasureshowoftenaportionofa signaloccurs.Asoftwarealgorithmisnotrequiredtodeterminetherateofasignal Tutorial: Data Acquisition in LabVIEW 4 MAX Measurement&AutomationExplorer(MAX)providesaccesstoyourNationalInstruments devicesandsystems. WithMAX,youcan: • • • • • ConfigureyourNationalInstrumentshardwareandsoftware Createandeditchannels,tasks,interfaces,scales,andvirtualinstruments Executesystemdiagnostics Viewdevicesandinstrumentsconnectedtoyoursystem UpdateyourNationalInstrumentssoftware Inadditiontothestandardtools,MAXcanexposeitem-specifictoolsyoucanuseto configure,diagnose,ortestyoursystem,dependingonwhichNIproductsyouinstall.Asyou navigatethroughMAX,thecontentsoftheapplicationmenuandtoolbarchangetoreflect thesenewtools. LabVIEWinstallsMAXtoestablishalldevicesandchannelconfigurationparameters.MAX readstheinformationtheDeviceManagerrecordsintheWindowsRegistryandassignsa logicaldevicenumbertoeachDAQdevice. 15 16 MAX YouusethedevicenumbertorefertothedeviceinLabVIEW.YoucanaccessMAXby selectingTools»Measurement&AutomationExplorerinLabVIEW.Thisdisplaystheprimary MAXwindow. Beforeusingadataacquisitionboard,youmustconfirmthatthesoftwarecancommunicate withtheboardbyconfiguringthedevices.ForWindows,theWindowsConfiguration Managerkeepstrackofallthehardwareinstalledinthecomputer,includingNational InstrumentsDAQdevices.TheWindowsConfigurationManagerautomaticallydetectsand configuresPlug&Play(PnP)devices. WindowsConfigurationManager IfyouhaveaPnPdevice,suchasanESeriesMIOdevice,theWindowsConfiguration Managerautomaticallydetectsandconfiguresthedevice.Ifyouhaveanon-PnPdevice,or legacydevice,youmustconfigurethedevicemanuallyusingtheAddNewHardwareoption intheControlPanel.YoucanverifytheWindowsConfigurationbyaccessingtheDevice Manager. Tutorial: Data Acquisition in LabVIEW 5 NI-DAQmx Driversoftwareisthelayerofsoftwareforeasilycommunicatingwiththehardware.Itforms themiddlelayerbetweentheapplicationsoftwareandthehardware.Driversoftwarealso preventsaprogrammerfromhavingtodoregister-levelprogrammingorcomplicated commandsinordertoaccessthehardwarefunctions. DriversoftwarefromNationalInstruments: • • NI-DAQmx NI-DAQmxBase TheDAQAssistant,includedwithNI-DAQmx,isagraphical,interactiveguideforconfiguring, testing,andacquiringmeasurementdata.Withasingleclick,youcanevengeneratecode basedonyourconfiguration,makingiteasierandfastertodevelopcomplexoperations. BecauseDAQAssistantiscompletelymenu-driven,youwillmakefewerprogrammingerrors anddrasticallydecreasethetimefromsettingupyourDAQsystemtotakingyourfirst measurement. NI-DAQmxBaseoffersasubsetofNI-DAQmxfunctionalityonWindowsandLinux,MacOSX, WindowsMobileandWindowsCE. NationalInstrumentsDAQboardshaveadriverenginethatcommunicatesbetweenthe boardandtheapplicationsoftware.Therearetwodriverengines,NI-DAQmxandTraditional NI-DAQ.YoucanalsousetheDAQAssistant,anExpressVIthatcommunicateswithNIDAQmx,inLabVIEWtocommunicatewiththeDAQboard.Inaddition,NationalInstruments providesMeasurement&AutomationExplorer(MAX)forconfiguringDAQboards. TheNI-DAQmxDriversoftwareisthelayerofsoftwareforeasilycommunicatingwiththe hardware.Itformsthemiddlelayerbetweentheapplicationsoftwareandthehardware. Driversoftwarealsopreventsaprogrammerfromhavingtodoregister-levelprogramming orcomplicatedcommandsinordertoaccessthehardwarefunctions. TheDAQmxpaletteinLabVIEW: 17 18 NI-DAQmx 5.1.1 DAQAssistant TheDAQAssistant,includedwithNI-DAQmx,isagraphical,interactiveguideforconfiguring, testing,andacquiringmeasurementdata.Withasingleclick,youcanevengeneratecode basedonyourconfiguration,makingiteasierandfastertodevelopcomplexoperations. BecauseDAQAssistantiscompletelymenu-driven,youwillmakefewerprogrammingerrors anddrasticallydecreasethetimefromsettingupyourDAQsystemtotakingyourfirst measurement. Scales YoucanconfigurecustomscalesforyourmeasurementsusingMAX.Thisisveryusefulwhen workingwithsensors.Itallowsyoutobringascaledvalueintoyourapplicationwithout havingtoworkdirectlywiththerawvalues.Forexample,youcanuseatemperaturesensor thatrepresentstemperaturewithavoltage.Theconversionequationforthetemperatureis, Voltagex100=Celsius.Afterascaleisset,youcanuseitinyourapplicationprogram, providingthetemperaturevalue,ratherthanthevoltage. Whenperforminganaloginput,thetaskcanbetimedto: • • • Acquire1Sample AcquirenSamples AcquireContinuously 5.2 SimulatingaDAQDevice Tutorial: Data Acquisition in LabVIEW 19 NI-DAQmx YoucancreateNI-DAQmxsimulateddevicesinNI-DAQmx7.4orlater.UsingNI-DAQmx simulateddevices: YoucantryNIproductsinyourapplicationwithoutthehardware. Later,whenyouacquirethehardware,youcanimporttheNI-DAQmxsimulateddevice configurationtothephysicaldeviceusingtheMAXPortableConfigurationWizard. Youcanworkonyourapplicationsonaportablesystemanduponreturningtotheoriginal system,youcaneasilyimportyourapplicationwork. CreatingNI-DAQmxSimulatedDevices TocreateanNI-DAQmxsimulateddevice,right-clickDevicesandInterfacesandselectCreate New.TheCreateNewdialogboxpromptsyoutoselectadevicetoadd.SelectNI-DAQmx SimulatedDeviceandclickFinish.IntheChooseDevicedialogbox,selectthefamilyof devicesforthedeviceyouwanttosimulate.SelectthedeviceandclickOK.IfyouselectaPXI device,youarepromptedtoselectachassisnumberandPXIslotnumber.Ifyouselectan SCXIchassis,theSCXIconfigurationpanelsopen. Tutorial: Data Acquisition in LabVIEW 6 DAQDevices DAQhardwareactsastheinterfacebetweenthecomputerandtheoutsideworld.It primarilyfunctionsasadevicethatdigitizesincominganalogsignalssothatthecomputer caninterpretthem ADAQdevice(DataAcquisitionHardware)usuallyhasthesefunctions: • • • • Analoginput Analogoutput DigitalI/O Counter/timers WehavedifferentDAQdevices,suchas: • • • “DesktopDAQdevices”whereyouneedtoplugaPCIDAQboardintoyour computer.Thesoftwareisrunningonacomputer. “PortableDAQdevices”forconnectiontotheUSBport,Wi-Ficonnections,etc.The softwareisrunningonacomputer “DistributedDAQdevices”wherethesoftwareisdevelopedonyourcomputerand thenlaterdownloadedtothedistributedDAQdevice. [www.ni.com] 20 21 DAQDevices MostDAQdeviceshavefourstandardelements:analoginput,analogoutput,digitalI/O,and counters.TheDAQdevicetransfersthemeasuredsignalstoacomputerthroughdifferent busstructures.Forexample,youcanplugaDAQdeviceintothePCIbusortheUSBportofa computerorthePersonalComputerMemoryCardInternationalAssociation(PCMCIA) socketofalaptop.YoualsocanusePXI/CompactPCItocreateaportable,versatile,and ruggedmeasurementsystem. 6.1 PerformingAnalog-to-DigitalConversion Analog-to-digitalconversionisaprocessofacquiringandtranslatingsignalsintodigitaldata sothatacomputercanprocessit.Analog-to-digitalconverters(ADCs)arecircuit componentsthatconvertavoltagelevelintoaseriesofonesandzeroes.ADCssamplethe analogsignaloneachrisingorfallingedgeofasampleclock.Ineachcycle,theADCtakesa snapshotoftheanalogsignal,measuresandconvertsitintoadigitalvalue.TheADCobtains andapproximatesthesignalwithfixedprecisionandconvertsitintoaseriesofdigital values. [www.ni.com] 6.2 PerformingDigital-to-AnalogConversion Digital-to-analogconversionistheoppositeofanalog-to-digitalconversion.Indigital-toanalogconversion,thecomputergeneratesthedata. 6.3 UsingCounters Acounterisadigitaltimingdevice.Youtypicallyusecountersforeventcounting,frequency measurement,periodmeasurement,positionmeasurement,andpulsegeneration. Tutorial: Data Acquisition in LabVIEW 22 DAQDevices 6.4 UsingDigitalI/O Digitalsignalsareelectricalsignalsthattransferdigitaldataoverawire.Thesesignals typicallyhaveonlytwostates:onandoff,alsoknownashighandlow,or1and0.When sendingadigitalsignalacrossawire,thesenderappliesavoltagetothewireandthe receiverusesthevoltageleveltodeterminethevaluebeingsent.Thevoltagerangesfor eachdigitalvaluedependonthevoltagelevelstandardbeingused. Digitalsignalshavemanyusers: • DigitalsignalscontrolormeasuredigitaldevicessuchasswitchesorLEDs Tutorial: Data Acquisition in LabVIEW 7 NIUSB-6008 NIUSB-6008isasimpleandlow-costmultifunctionI/OdevicefromNationalInstruments. Thedevicehasthefollowingspecifications: • • • • • • 8analoginputs(12-bit,10kS/s) 2analogoutputs(12-bit,150S/s) 12digitalI/O USBconnection,Noextrapower-supplyneeded CompatiblewithLabVIEW,LabWindows/CVI,andMeasurementStudioforVisual Studio.NET NI-DAQmxdriversoftware TheNIUSB-6008iswellsuitedforeducationpurposesduetoitssmallsizeandeasyUSB connection. 7.1 ConnectNIUSB-6008tothePC Configuringandtesting:USB-6008canbeconfiguredandtestedusingMAX(Measurement andAutomationExplorer),whichisinstalledwiththeNI-DAQmxDriverSoftware. ThefirsttimeyouconnecttheUSB-6008tothePC,theWindowsHardwareInstallerWizard willopen. 23 24 NIUSB-6008 ThewizardsearchesthePCforthenecessarydriversoftwarefortheUSB-6008.Thisdriver softwarewasinstalledalongwiththeinstallationoftheNI-DAQsoftware.Whenthewizard hasfinishedtheinstallationofthedriversoftware,theUSB-6008isreadyforuse. 7.1.1 TestingtheUSB-6008inMAX BeforeyoustarttousetheUSB-6008inanapplication,youshouldtestthedeviceinthe MeasurementandAutomationExplorer(MAX). IntheMAXwindow,expandthe“DevicesandInterfaces”nodeandthen“NIDAQmx Devices”.Right-clickontheNIUSB-6008deviceandselect“Self-Test”. Tutorial: Data Acquisition in LabVIEW 25 NIUSB-6008 Hopefullytheself-testpasseswithouterrors.Then,youshouldtesttheindividualchannels oftheUSB-6008tocheckthattheinputsignalsaredetectedcorrectlybytheUSB-6008,and thattheoutputsignalsgeneratedbytheUSB-6009havecorrectvalues.ThisI/Ocanbe testedinseveralways,dependingonwhichchannelsyouactuallywanttotest. Wewillperformasimpleloopbacktest: Here,letustestanalogoutputchannel0(AO0)andtheanaloginputchannel0(AI0)toseeif theyworkcorrectly.Wewillperformaverysimpletest,whichissufficientifwearetocheck thatbothAO0andAI0workcorrectly.Thetestprocedure,whichisdenotedloopback,isto connecttheAI0channeltotheAO0channel.ThenwegeneratesomelegalvoltageatAO0.If AI0detectsthesamevoltage,weknowthatbothAO0andAI0work.(Wemaythenrepeat thisprocedureforotherchannels.)IfforsomereasonAI0detectssomeothervoltagethan thevaluewesetforAO0,thenthereisanerrorineithertheAI0channelorinthetheAO0 channel,andfurtherinvestigationsarenecessary. Topreparefortheloopbacktest,wewiretogetherAI0andAO0.Toseetheterminalsofthe USB-6000,select“DevicePinouts”fromtheright-clickmenu. Tutorial: Data Acquisition in LabVIEW 26 NIUSB-6008 Toactuallyperformtheloopbacktest,right-clickontheNIUSB-6008deviceinMAX,and thenselect“TestPanels..”inordertoopentheTestPanels.IntheTestPanelswindow, selecttheAnalogOutputtab. Tutorial: Data Acquisition in LabVIEW 27 NIUSB-6008 IntheAnalogOutputtab,selectanyvoltagebetween0Vand5V. Next,clicktheAnalogInputtabintheTestPanelswindow. Tutorial: Data Acquisition in LabVIEW 28 NIUSB-6008 TheAnalogInputtabshouldindicatethesame(oralmostthesame)voltageasissetouton AO0.Theremaybeasmalldifferencebetweenthevaluesduetothelimitedresolutionin theDA-converter(digital-to-analog)andintheAD-converter(analog-to-digital). Tutorial: Data Acquisition in LabVIEW 29 NIUSB-6008 Youshouldalsoalwaysuseamulti-metertocheckifthevoltagelevelsontheoutputand inputchannelsarecorrectaccordingtoyoursettings. Tutorial: Data Acquisition in LabVIEW 30 NIUSB-6008 7.2 UsingNIUSB-6008inLabVIEW InordertousetheNIUSB-6008inLabVIEWyouneedtousetheDAQmxfunctions,see Figurebelow. DAQmx–DataAcquisitionpalette: Tutorial: Data Acquisition in LabVIEW 31 NIUSB-6008 7.3 DAQAssistant TheeasiestwaysistousetheDAQAssistant. 7.3.1 AnalogInput WhenyoudragtheDAQAssistanticononyourBlockDiagram,thefollowingwindow appears: Tutorial: Data Acquisition in LabVIEW 32 NIUSB-6008 Inthiswindowyouneedtoselecteither“AcquireSignals”(i.e.,InputSignals)or“Generate Signals”(i.e.,OutputSignals). SelectAcquireSignals→AnalogInput→Voltage. Tutorial: Data Acquisition in LabVIEW 33 NIUSB-6008 InthenextwindowyouselectwhichAnalogInputyouwanttouse.Selectai0(AnalogInput channel0)andclickFinish. Thefollowingwindowappears: Tutorial: Data Acquisition in LabVIEW 34 NIUSB-6008 IntheTimingSettingsSelect“1Sample(OnDemand)”. Tutorial: Data Acquisition in LabVIEW 35 NIUSB-6008 ThenextstepistoselecttheSignalInputRange.Acommonsignalis0-5V. Youmayalsorenamethenameofthechannel(right-clickonthename): Tutorial: Data Acquisition in LabVIEW 36 NIUSB-6008 Youarenowfinishedwiththeconfiguration.ClickOKintheDAQAssistantwindowTheDAQ AssistanticonappearsontheBlockDiagram: Tutorial: Data Acquisition in LabVIEW 37 NIUSB-6008 Example: Wirethedataoutputtoanumericindicatorlikethis(andhittheRunbutton): Thennumericindicatorwillshow,e.g.,thefollowingvalue: [EndofExample] Example: Ifyouwanta“continuous”acquisition,putaWhilelooparoundtheDAQAssistantlikethis: WecanalsocommunicatewiththeDAQdevicewithoutusingtheDAQAssistant: Tutorial: Data Acquisition in LabVIEW 38 NIUSB-6008 Formoreadvancedapplicationsthisapproachisrecommended. [EndofExample] 7.3.2 AnalogOutput AnalogOutputissimilar. Tutorial: Data Acquisition in LabVIEW 39 NIUSB-6008 Tutorial: Data Acquisition in LabVIEW 40 NIUSB-6008 Example: Orinsidealoopfor“continuous”writingtotheDAQdevice: Tutorial: Data Acquisition in LabVIEW 41 NIUSB-6008 HoweveryoushouldnotusetheDAQAssistantinsidealoopbecauseofthelackof performance.Thefollowingisthereforebetter: InthisexamplewehaveusedsomeoftheotherVisintheDAQmxpaletteraswell. TheFrontPanelmayloooklikethis. Tutorial: Data Acquisition in LabVIEW 42 NIUSB-6008 Inthisexampleweassumethatweconnectwiresfor“AnalogOut”and“AnalogIn”together likethis(aso-calledloopbacktest). WecanalsocommunicatewiththeDAQdevicewithoutusingtheDAQAssistant: Formoreadvancedapplicationsthisapproachisrecommended. [EndofExample] Tutorial: Data Acquisition in LabVIEW 8 LoggingtoFile InmanycasesyouwanttowriteyourdatayougetfromtheDAQdevicetoatextfilefor lateruse.InthischapterwewilllearnhowtowritetoameasurementfileinLabVIEW.We willalsolearnhowtoreadthesamefile. Youcanusethe“WritetoMeasurementFile”functionontheFileI/OpaletteinLabVIEWfor writingdatatotextfilesYoucansaveyourdatainatabseparatedtext(LVMdatafile format)orasabinary(TDMSfileformat)file. IfweusetheLVM,itiseasytoopenandviewthedatainNotepad. 8.1 WritingtoMeasurementFile Wewillusethe“WritetoMeasurementFile”functionintheFileI/OpaletteinLabVIEWfor writingdatatotextfiles.WewillalsofocusontheLVMdatafileformat,nottheTDMSfile formatwhichgivebinaryfiles. 43 44 LoggingtoFile Whenyoudraginthe“WritetoMeasurementFile”,aconfigurationdialogwindowwill automaticallypopup. Recommendedsettingsforthe“WriteToMeasurementFile”isasfollows: Example: ExampleofLabVIEWProgramthatwritedatatoaMeasurementFile: FrontPanel: Tutorial: Data Acquisition in LabVIEW 45 LoggingtoFile Inthisapplicationwelogdatafromaprocessbasedonamanualcontrolsignal.Boththe inputsignaluandtheoutputsignal(temperature)issavedtoaMeasurementFile. BlockDiagram: TheLVMfilemaylooksomethinglikethis: Tutorial: Data Acquisition in LabVIEW 46 LoggingtoFile Thefirstcolumnisthetime,thesecondcolumnistheinputsignal,andthethirdcolumnis theoutputsignal. [EndofExample] 8.2 ReadfromMeasurementFile Whenyoudraginthe“ReadfromMeasurementFile”,aconfigurationdialogwindowwill automaticallypopup. Recommendedsettingsforthe“ReadFromMeasurementFile”: Tutorial: Data Acquisition in LabVIEW 47 LoggingtoFile Example: ExampleofLabVIEWProgramthatreaddatafromaMeasurementFile: Thisapplicationreadsthedataandplotsitin2differentgraphs. Tutorial: Data Acquisition in LabVIEW 48 LoggingtoFile BlockDiagram: [EndofExample] Tutorial: Data Acquisition in LabVIEW Hans-PetterHalvorsen,M.Sc. E-mail:hans.p.halvorsen@hit.no Blog:http://home.hit.no/~hansha/ UniversityCollegeofSoutheastNorway www.usn.no