university college of southeast norwayhome.hit.no/~hansha/documents/matlab/training/data acquisition...

32
University College of Southeast Norway http://home.hit.no/~hansha Data Acquisition in MATLAB Hans-Petter Halvorsen, 2016.11.01

Upload: votuong

Post on 06-Feb-2018

216 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

UniversityCollegeofSoutheastNorway

http://home.hit.no/~hansha

DataAcquisitioninMATLABHans-PetterHalvorsen,2016.11.01

Page 2: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

2

TableofContents1 Introduction......................................................................................................................4

1.1 MATLAB......................................................................................................................4

1.2 Simulink......................................................................................................................5

1.2.1 DataAcquisitionToolbox.....................................................................................6

1.3 USB-6008DAQDevice................................................................................................6

1.4 NIDAQmxdriver.........................................................................................................7

2 DataAcquisition................................................................................................................8

2.1 Introduction................................................................................................................8

2.1.1 Physicalinput/outputsignals..............................................................................9

2.1.2 DAQdevice/hardware.........................................................................................9

2.1.3 Driversoftware..................................................................................................10

2.1.4 Yoursoftwareapplication.................................................................................11

2.2 MAX–MeasurementandAutomationExplorer......................................................11

2.3 DAQinMATLAB........................................................................................................12

2.3.1 NI-DAQmx..........................................................................................................12

3 DataAcquisitionToolbox................................................................................................14

3.1 GettingHelp..............................................................................................................15

4 MyFirstDAQApp............................................................................................................16

4.1 Introduction..............................................................................................................16

4.2 LegacyInterface........................................................................................................16

4.2.1 SimpleDAQApplication....................................................................................17

Page 3: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

3 TableofContents

Tutorial:DataAcquisitioninMATLAB

4.2.2 SourceCode.......................................................................................................18

4.3 Session-basedInterface............................................................................................19

4.3.1 Summingup.......................................................................................................20

5 DAQinSimulink...............................................................................................................22

5.1 AnalogIn...................................................................................................................22

5.2 AnalogOut................................................................................................................24

6 ControlApplication.........................................................................................................27

6.1 Introduction..............................................................................................................27

6.2 Low-passFilter..........................................................................................................28

6.3 PIController..............................................................................................................28

6.4 ProcessModel..........................................................................................................30

Page 4: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

4

1 IntroductionInthisTutorialwewilllearnhowtocreateDAQ(DataAcquisition)applicationsinMATLABandSimulink.WewilluseaUSB-6008DAQdevicefromNationalInstrumentsasanexample.InordertouseDAQdevicesfromNationalInstrumentsinMATLAB/SimulinkweneedtoinstalltheNI-DAQmxdriverprovidedbyNationalInstruments.InadditionweneedtheDataAcquisitionToolboxforMATLAB/Simulink.

1.1 MATLABMATLABisatoolfortechnicalcomputing,computationandvisualizationinanintegratedenvironment,e.g.,

• Mathandcomputation• Algorithmdevelopment• Dataacquisition• Modeling,simulation,andprototyping• Dataanalysis,exploration,andvisualization• Scientificandengineeringgraphics• Applicationdevelopment,includinggraphicaluserinterfacebuilding

MATLABisdevelopedbyTheMathWorks.MATLABisashort-termforMATrixLABoratory.MATLABisinuseworld-widebyresearchersanduniversities.

Formoreinformation,seewww.mathworks.com

BelowweseetheMATLABEnvironment:

Page 5: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

5 Introduction

Tutorial:DataAcquisitioninMATLAB

MATLABhasthefollowingwindows:

• CommandWindow• CommandHistory• Workspace• CurrentDirectory

TheCommandwindowisthemainwindow.UsetheCommandWindowtoentervariablesandtorunfunctionsandM-filesscripts(moreaboutm-fileslater).

Watchthefollowing“GettingStartedwithMATLAB”video:

http://www.mathworks.com/demos/matlab/getting-started-with-matlab-video-tutorial.html

1.2 SimulinkSimulink,developedbyTheMathWorks,isacommercialtoolformodeling,simulatingandanalyzingdynamicsystems.Itsprimaryinterfaceisagraphicalblockdiagrammingtoolandacustomizablesetofblocklibraries.ItofferstightintegrationwiththerestoftheMATLABenvironmentandcaneitherdriveMATLABorbescriptedfromit.Simulinkiswidelyusedincontroltheoryanddigitalsignalprocessingforsimulationanddesign.

BasicinformationaboutSimulinkcanbefoundhere:

Page 6: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

6 Introduction

Tutorial:DataAcquisitioninMATLAB

WatchthevideoGettingStartedwithSimulinkbyTheMathWorks.

Readthe“IntroductiontoSimulink”document.YouwillneedtoknowthesetopicswhendoingtherestofthetasksinthisLabWork.

TheTutorialisavailablefrom:http://home.hit.no/~hansha/.

1.2.1 DataAcquisitionToolbox

DataAcquisitionToolboxsoftwareprovidesacompletesetoftoolsforanaloginput,analogoutput,anddigitalI/OfromavarietyofPC-compatibledataacquisitionhardware.Thetoolboxletsyouconfigureyourexternalhardwaredevices,readdataintoMATLABandSimulinkenvironmentsforimmediateanalysis,andsendoutdata.

DataAcquisitionToolboxalsosupportsSimulinkwithblocksthatenableyoutoincorporatelivedataorhardwareconfigurationdirectlyintoSimulinkmodels.Youcanthenverifyandvalidateyourmodelagainstlive,measureddataaspartofthesystemdevelopmentprocess.

WewillusetheDataAcquisitionToolboxinordertowriteandreaddatatoandfromaUSB-6008DAQdevicefromNationalInstruments.

1.3 USB-6008DAQDeviceNIUSB-6008isasimpleandlow-costmultifunctionI/OdevicefromNationalInstruments.

Thedevicehasthefollowingspecifications:

• 8analoginputs(12-bit,10kS/s)• 2analogoutputs(12-bit,150S/s)• 12digitalI/O• USBconnection,Noextrapower-supplyneeded

Page 7: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

7 Introduction

Tutorial:DataAcquisitioninMATLAB

• CompatiblewithLabVIEW,LabWindows/CVI,andMeasurementStudioforVisualStudio.NET

• NI-DAQmxdriversoftware

TheNIUSB-6008iswellsuitedforeducationpurposesduetoitssmallsizeandeasyUSBconnection.

Note!The64-bitversionofDataAcquisitionToolboxsupportsNationalInstrumentsdevicesthatcanbeusedwiththe“session-basedinterface”(moreaboutthislater).ForothersupportedNIdataacquisitiondevices,youmustusethe32-bitversionofDataAcquisitionToolboxandMATLAB.The32-bitversionsofDataAcquisitionToolboxandMATLABcanbeinstalledona64-bitWindowsOS.

1.4 NIDAQmxdriverYouneedtoinstalltheDAQmxdriverinordertouseitinMATLAB.

Page 8: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

8

2 DataAcquisition2.1 IntroductionThepurposeofdataacquisitionistomeasureanelectricalorphysicalphenomenonsuchasvoltage,current,temperature,pressure,orsound.PC-baseddataacquisitionusesacombinationofmodularhardware,applicationsoftware,andacomputertotakemeasurements.Whileeachdataacquisitionsystemisdefinedbyitsapplicationrequirements,everysystemsharesacommongoalofacquiring,analyzing,andpresentinginformation.Dataacquisitionsystemsincorporatesignals,sensors,actuators,signalconditioning,dataacquisitiondevices,andapplicationsoftware.

Sosummingup,DataAcquisitionistheprocessof:

• Acquiringsignalsfromreal-worldphenomena• Digitizingthesignals• Analyzing,presentingandsavingthedata

TheDAQsystemhasthefollowingpartsinvolved,seeFigure:

[Figure:www.ni.com]

Thepartsare:

• Physicalinput/outputsignals• DAQdevice/hardware• Driversoftware• Yoursoftwareapplication(Applicationsoftware)

Page 9: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

9 DataAcquisition

Tutorial:DataAcquisitioninMATLAB

2.1.1 Physicalinput/outputsignals

Aphysicalinput/outputsignalistypicallyavoltageorcurrentsignal.

2.1.2 DAQdevice/hardware

DAQhardwareactsastheinterfacebetweenthecomputerandtheoutsideworld.Itprimarilyfunctionsasadevicethatdigitizesincominganalogsignalssothatthecomputercaninterpretthem

ADAQdevice(DataAcquisitionHardware)usuallyhasthesefunctions:

• Analoginput• Analogoutput• DigitalI/O• Counter/timers

WehavedifferentDAQdevices,suchas:

• “DesktopDAQdevices”whereyouneedtoplugaPCIDAQboardintoyourcomputer.Thesoftwareisrunningonacomputer.

• “PortableDAQdevices”forconnectiontotheUSBport,Wi-Ficonnections,etc.Thesoftwareisrunningonacomputer

• “DistributedDAQdevices”wherethesoftwareisdevelopedonyourcomputerandthenlaterdownloadedtothedistributedDAQdevice.

Page 10: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

10 DataAcquisition

Tutorial:DataAcquisitioninMATLAB

[Figure:www.ni.com]

[Figure:www.ni.com]

2.1.3 Driversoftware

Driversoftwareisthelayerofsoftwareforeasilycommunicatingwiththehardware.Itformsthemiddlelayerbetweentheapplicationsoftwareandthehardware.Driversoftwarealsopreventsaprogrammerfromhavingtodoregister-levelprogrammingorcomplicatedcommandsinordertoaccessthehardwarefunctions.

Page 11: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

11 DataAcquisition

Tutorial:DataAcquisitioninMATLAB

DriversoftwarefromNationalInstruments:NI-DAQmx

2.1.4 Yoursoftwareapplication

Applicationsoftwareaddsanalysisandpresentationcapabilitiestothedriversoftware.Yoursoftwareapplicationnormallydoessuchtasksas:

• Real-timemonitoring• Dataanalysis• Datalogging• Controlalgorithms• Humanmachineinterface(HMI)

InordertocreateyourDAQapplicationyouneedaprogrammingdevelopmenttool,suchasVisualStudio/C#,LabVIEW,etc..

2.2 MAX–MeasurementandAutomationExplorer

Measurement&AutomationExplorer(MAX)providesaccesstoyourNationalInstrumentsdevicesandsystems.

WithMAX,youcan:

• ConfigureyourNationalInstrumentshardwareandsoftware • Createandeditchannels,tasks,interfaces,scales,andvirtualinstruments • Executesystemdiagnostics • Viewdevicesandinstrumentsconnectedtoyoursystem • UpdateyourNationalInstrumentssoftware

Inadditiontothestandardtools,MAXcanexposeitem-specifictoolsyoucanusetoconfigure,diagnose,ortestyoursystem,dependingonwhichNIproductsyouinstall.AsyounavigatethroughMAX,thecontentsoftheapplicationmenuandtoolbarchangetoreflectthesenewtools.

Page 12: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

12 DataAcquisition

Tutorial:DataAcquisitioninMATLAB

2.3 DAQinMATLABWecancreateDAQapplicationswithorwithoutMeasurementStudio.InbothsituationsyouneedtheNI-DAQmxdriverlibrary.

2.3.1 NI-DAQmx

NationalInstrumentsprovidesanative.NETAPIforNI-DAQmx.ThisisavailableasapartoftheNI-DAQmxdriveranddoesnotrequireMeasurementStudio.

Ingeneral,dataacquisitionprogrammingwithDAQmxinvolvesthefollowingsteps:

Page 13: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

13 DataAcquisition

Tutorial:DataAcquisitioninMATLAB

• CreateaTaskandVirtualChannels• StarttheTask• PerformaReadoperationfromtheDAQ• PerformaWriteoperationtotheDAQ• StopandCleartheTask.

Dataacquisitionintextbased-programmingenvironmentisverysimilartotheLabVIEWNI-DAQmxprogrammingasthefunctionscallsisthesameastheNI-DAQmxVI’s.

Page 14: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

14

3 DataAcquisitionToolboxDataAcquisitionToolboxsoftwareprovidesacompletesetoftoolsforanaloginput,analogoutput,anddigitalI/OfromavarietyofPC-compatibledataacquisitionhardware.Thetoolboxletsyouconfigureyourexternalhardwaredevices,readdataintoMATLABandSimulinkenvironmentsforimmediateanalysis,andsendoutdata.

DataAcquisitionToolboxalsosupportsSimulinkwithblocksthatenableyoutoincorporatelivedataorhardwareconfigurationdirectlyintoSimulinkmodels.Youcanthenverifyandvalidateyourmodelagainstlive,measureddataaspartofthesystemdevelopmentprocess.

WewillusetheDataAcquisitionToolboxinordertowriteandreaddatatoandfromaUSB-6008DAQdevicefromNationalInstruments.

Note!InadditionyouneedtoinstalltheNIDAQmxdriverfromNationalInstruments.

BelowweseethedataflowfromthesensorstotheMATLAB:

[Figure:www.mathworks.com]

Page 15: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

15 DataAcquisitionToolbox

Tutorial:DataAcquisitioninMATLAB

3.1 GettingHelpTodetermineifDataAcquisitionToolboxsoftwareisinstalledonyoursystem,type

ver

ThiswilllistallyourToolkitsthatyouhaveinstalledandtheversionnumbers.

InordertogetanoverviewoftheDataAcquisitionToolboxyoucantypethefollowingintheMATLABCommandwindow:

help daq

ThenyouwillgetanoverviewofallthefunctionsavailableintheDataAcquisitionToolbox.

ThisToolboxhasDAQfunctionalitybothforMATLABandSimulink.

Youcanviewthecodeforanyfunctionbytyping:

type function_name

Youcanviewthehelpforanyfunctionbytyping:

help function_name

Page 16: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

16

4 MyFirstDAQAppIntheseexampleswewilluseanUSB-6008devicefromNationalInstruments.InadditionyouneedtoinstalltheNIDAQmxdriverfromNationalInstruments.

4.1 IntroductionNote!The64-bitversionofDataAcquisitionToolboxsupportsNationalInstrumentsdevicesthatcanbeusedwiththesession-basedinterface.ForothersupportedNIdataacquisitiondevices,youmustusethe32-bitversionofDataAcquisitionToolboxandMATLAB.The32-bitversionsofDataAcquisitionToolboxandMATLABcanbeinstalledona64-bitWindowsOS.

Session-basedInterface LegacyInterface

32-bitMATLAB X X

64-bitMATLAB X

NIUSB-6008supportbothinterfaces,boththeprogrammingisdifferentinMATLAB.

Session-basedInterface:

Youmayusethedaq.getVendors()inordertogetalistofsupportedadinstalleddevices.

UsingSession-basedInterfaceyoucreateadataacquisitionsessionobjectwithdaq.createSession.Youcanthenaddchannelstothesessionandoperateallchannelswithinthesessiontogether.

Legacyinterface:

TheinterfaceavailablewithDataAcquisitionToolboxworkswithallsupporteddataacquisitionhardware,exceptCompactDAQdevicesanddevicesusingthecounter/timersubsystem.Usingthisinterfaceyoucreatedataacquisitionobjectswiththesecommands:

analoginput() analogoutput()

4.2 LegacyInterface

Page 17: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

17 MyFirstDAQApp

Tutorial:DataAcquisitioninMATLAB

Note!Ifyouhave64-bitMATLAByoucannotusethismethod.

WewillusetheDataAcquisitionToolboxinMATLABtocreateasimpleDataAcquisitionapplication.

WestartbycheckingiftheDAQmxdriverhasbeenproperlyinstalled.Usethefollowingcode:

out = daqhwinfo out.InstalledAdapters

Dependingonwhatyouhaveinstalled,youmay,e.g.,getthefollowinganswer:

ans = 'mcc' 'nidaq' 'parallel' 'winsound'

Note!Ifyoudon’tfindyourDAQcardinthelist,makesureyourunMATLABasanadministrator.Right-clickontheMATLABiconandselect“RunasAdministrator”.

4.2.1 SimpleDAQApplication

ASimpleDAQapplicationshouldfollowthesesteps:

1. Initialization2. Read/Write3. CleanUp

Wewillexplainthedifferentstepsbelow:

1-Initialization:

CreatingaDeviceObject:

InInitializationyouneedtospecifywhatkindofdeviceyouareusing.Wecanusetheanaloginput()andanalogoutput()functionsintheDataAcquisitionToolbox.

Example:

ai = analoginput('nidaq', 'Dev1');

and:

ao = analogoutput('nidaq', 'Dev1');

TheDataAcquisitionToolboxsupportsDAQdevicesfromdifferentvendors.InordertouseadevicefromNationalInstruments,weneedtoset“nidaq”astheadaptername.“DevX”isthedefaultnamecreatedbythesystem,seMAX(MeasurementandAutomationExplorer)fordetailsaboutyourdevice.

Page 18: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

18 MyFirstDAQApp

Tutorial:DataAcquisitioninMATLAB

AddingChannels:

Nextweneedtospecifywhichchannel(s)wewanttouse.Wecanusetheaddchannel()function.

Example:

ai0 = addchannel(ai, 0);

2-Read/Write:

IfwewanttowriteasinglevaluetotheDAQdevice,wecanusetheputsample()function.

Example:

ao_value = 3.5; putsample(ao, ao_value)

IfwewanttoreadasinglevaluefromtheDAQdevice,wecanusethegetsample()function.

Example:

ai_value = getsample(ai)

3-CleanUp:

WhenwearefinishedwiththeDataAcquisitionweneedtocloseordeletetheconnection.Wecanusethedelete()function.

Example:

delete(ai)

4.2.2 SourceCode

Inthissimpleexamplewewillcreateam-filethatwriteonesinglevaluetotheDAQdeviceandthenreadonesinglevaluefromtheDAQdevice.

WestartbyconnectingtheAnalogInandAnalogOutwirestogetherontheDAQdevice(asocalledLoopbackconnection).

Ifwewrite,e.g.,3.5VtotheDAQdeviceonaAOchannel,wewillthenreadthesamevalueontheAIchannel.

SourceCodeforaSimpleDAQExampleinMATLAB:

% Write and Read to a NI USB-6008 DAQ device

Page 19: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

19 MyFirstDAQApp

Tutorial:DataAcquisitioninMATLAB

clear clc % Initialization----------------------- % Analog Input: ai = analoginput('nidaq', 'Dev1'); % Analog Output: ao = analogoutput('nidaq', 'Dev1'); % Adding Channels----------------------- % Analog Input - Channel 0 ai0 = addchannel(ai, 0); % Analog Output - Channel 0 ao0 = addchannel(ao, 0); % Write Data--------------------------- ao_value = 3.5; putsample(ao, ao_value) % Read Data---------------------------- ai_value = getsample(ai) % Cleaning Up-------------------------- delete(ai) delete(ao)

4.3 Session-basedInterfaceNote!Ifyouhave64-bitMATLAByouneedtousethismethod.

Youmayusethedaq.getVendors()inordertogetalistofsupportedadinstalleddevices.

>> daq.getVendors() ans = Data acquisition vendor 'National Instruments': ID: 'ni' FullName: 'National Instruments' AdaptorVersion: '3.0 (R2011b)' DriverVersion: '9.3.5 NI-DAQmx' IsOperational: true

UsingSession-basedInterfaceyoucreateadataacquisitionsessionobjectwithdaq.createSession.Youcanthenaddchannelstothesessionandoperateallchannelswithinthesessiontogether.

Syntax:

myDaq = daq.createSession(VENDORID)

Example:

>> myDaq = daq.createSession('ni') myDaq = Data acquisition session using National Instruments hardware: Will run for 1 second (1000 scans) at 1000 scans/second. No channels have been added.

Page 20: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

20 MyFirstDAQApp

Tutorial:DataAcquisitioninMATLAB

ThenyouhavedifferentMethods,PropertiesandEventsavailableyoucanuse.

ThemostusedmethodswillbeaddAnalogInputChannel()andaddAnalogOutChannel().

Syntax:

addAnalogInputChannel(DEVICEID,CHANNELID,MEASUREMENTTYPE)

and:

addAnalogOutputChannel(DEVICEID,CHANNELID,MEASUREMENTTYPE)

ThedevicecanbefoundusingMAX(MeasurementandAutomationExplorer).

Example:

>> mydaq.addAnalogInputChannel('dev1', 'ai0', 'Voltage') ans = Data acquisition session using National Instruments hardware: Will run for 1 second (1000 scans) at 1000 scans/second. Number of channels: 1 index Type Device Channel MeasurementType Range Name ----- ---- ------ ------- --------------- ---------------- ---- 1 ai Dev1 ai0 Voltage (Diff) -20 to +20 Volts

Thenwecan,e.g.,useinputSingleScaninordertoreaddatafromtheAnalogInputChannel(s).

Example:

>> myvalue = mydaq.inputSingleScan myvalue = 0.8244

4.3.1 Summingup

Westarttomakesurethedriver(NIDAQmx)isinstalledproperly:

daq.getVendors

Thisgivesthefollowingansweronmycomputer:

ans = Data acquisition vendor 'National Instruments': ID: 'ni' FullName: 'National Instruments' AdaptorVersion: '3.0 (R2011b)' DriverVersion: '9.6.0 NI-DAQmx' IsOperational: true

Page 21: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

21 MyFirstDAQApp

Tutorial:DataAcquisitioninMATLAB

Next,wecheckiftheDAQdevice(InthistutorialistheNIUSB-6008used)pluggedinandworking:

daq.getDevices

Thisgivesthefollowingansweronmycomputer:

ni Dev1: National Instruments USB-6008 Analog input subsystem supports: 8 ranges supported Rates from 0.1 to 10000.0 scans/sec 8 channels 'Voltage' measurement type Analog output subsystem supports: 0 to +5.0 Volts range Rates from 0.0 to 0.0 scans/sec 2 channels 'Voltage' measurement type Counter input subsystem supports: Rates from 0.0 to 0.0 scans/sec 1 channel 'EdgeCount' measurement type

Nextwecancreatesimplescriptthatwriteasinglevaluetoananalogoutchannelandthenreadthesamevaluefromtheanaloginputchannel.

Weuseasocalled“Loopback”connection,i.e.westartbyconnectingtheAnalogInandAnalogOutwirestogetherontheDAQdevice.Ifwewrite,e.g., 3.5𝑉 totheDAQdeviceonanAOchannel,wewillthenreadthesamevalueontheAIchannel.

Thecodeisasfollows:

% Initialization mydaq = daq.createSession('ni') mydaq.addAnalogOutputChannel('dev1', 'ao0', 'Voltage') mydaq.addAnalogInputChannel('dev1', 'ai0', 'Voltage') % Analog Output ao_value = 3.5; mydaq.outputSingleScan(ao_value) % Analog Input ai_value = mydaq.inputSingleScan

Theresultsfromthescriptis:

ai_value =

3.5059

Knowingthesebasicfunctionswecannowimplementmoreadvancedapplications,usingfor/whileloops,etc.

Page 22: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

22

5 DAQinSimulinkSimulinkhasbuilt-inblocksforDataAcquisition,butdependingontheversionofMATLAB/SimulinkyouareusingtheymightnotworkproperlywiththeUSB-6008DAQdevice.InthatcaseyoucancallMATLABfunctionsfromSimulink.

WewillcreateasimpleSimulinkapplicationwhereyouwriteandreadvaluesfromtheUSB-6008DAQdevice.

InthischapterMATLAB/SimulinkR2007aisused.TheDataAcquisitionToolboxhasbeenupdatedsincethisrelease.

Belowweseethebuilt-inblocksinSimulink/DataAcquisitionToolbox(R2007a):

5.1 AnalogInWecreateasimpleapplicationinSimulinkinordertodemonstratehowtoreadfromtheDAQdevice:

Page 23: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

23 DAQinSimulink

Tutorial:DataAcquisitioninMATLAB

PropertiesforAnalogInputBlock:

InthePropertieswindowwecandefinechannels,samplerate,etc.

Page 24: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

24 DAQinSimulink

Tutorial:DataAcquisitioninMATLAB

5.2 AnalogOutWecreateasimpleapplicationinSimulinkinordertodemonstratehowtowritetotheDAQdevice:

PropertiesforAnalogOutputBlock:

Inthiscasewegetthefollowingerror:

Page 25: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

25 DAQinSimulink

Tutorial:DataAcquisitioninMATLAB

→ThisisduetothattheSimulinkblocksonlysupporthardwarethathasinternalclocking,whichtheNIUSB-6008doesnotonanalogoutput.You’llneedtocallintoaMATLABfunctiontodoPUTSAMPLE.

Tosolvethisproblem,wecanusethe“EmbeddedMATLABfunction”blockinSimulinkwhereweimplementMATLABcodeforthewriteoperation:

TheEmbeddedMATLABcodeisasfollows:

Page 26: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

26 DAQinSimulink

Tutorial:DataAcquisitioninMATLAB

Page 27: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

27

6 ControlApplication6.1 IntroductionInthisexamplewewilluseMeasurementStudiotocreateasimplecontrolapplication.Wewillcontrolthelevelinawatertankusingmanualcontrol.Theprocessisasfollows:

Wewanttocontrolthelevelinthewatertankusingapumpontheinflow.WewillreadthelevelusingourUSB-6008DAQdevice(AnalogIn)andwritethecontrolsignal(AnalogOut)totheDAQdevice.

TheAnalogOut(controlsignal)willbeasignalbetween 0 − 5𝑉 andtheAnalogIn(Level)willbea 0 − 5𝑉 signalthatweneedtoscaleto 0 − 20𝑐𝑚.

ThenextimprovementstoourapplicationwouldbetoimplementaLow-passFilterinordertoremovethenoisefromthesignalwhenreadingthelevel.AnotherimprovementwouldbetoreplacethemanualcontrolwithaPIcontrollerthatdothejobforus.Finallyitwouldbenicetohaveamathematicalmodelofourwatertanksowecansimulateandtestthebehavioroftherealsystemwithoutconnecttoit.

Page 28: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

28 ControlApplication

Tutorial:DataAcquisitioninMATLAB

Soweneedtocreatediscreteversionsofthelow-passfilter,thePIcontrollerandtheprocessmodel.Wecan,e.g.,usetheEulerForwarddiscretizationmethod:

𝑥 ≈𝑥,-. − 𝑥,

𝑇0

ortheEulerBackwarddiscretizationmethod:

𝑥 ≈𝑥, − 𝑥,1.

𝑇0

𝑇0 istheSamplingTime.

6.2 Low-passFilterThetransferfunctionforafirst-orderlow-passfiltermaybewritten:

𝐻 𝑠 =𝑦6(𝑠)𝑦(𝑠) =

1𝑇6𝑠 + 1

Where 𝑇6 isthetime-constantofthefilter, 𝑦(𝑠) isthefilterinputand 𝑦6 𝑠 isthefilteroutput.

Discreteversion:

Itcanbeshownthatadiscreteversioncanbestatedas:

𝒚𝒇,𝒌 = 𝟏 − 𝒂 𝒚𝒇,𝒌1𝟏 + 𝒂𝒚𝒌

Where

𝒂 =𝑻𝒔

𝑻𝒇 + 𝑻𝒔

Where 𝑇0 istheSamplingTime.

6.3 PIControllerAPIcontrollermaybewritten:

𝑢 𝑡 = 𝑢E + 𝐾G𝑒 𝑡 +𝐾G𝑇I

𝑒𝑑𝜏L

E

Where 𝑢 isthecontrolleroutputand 𝑒isthecontrolerror:

Page 29: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

29 ControlApplication

Tutorial:DataAcquisitioninMATLAB

𝑒 𝑡 = 𝑟 𝑡 − 𝑦(𝑡)

PIControllerasaTransferfunction:

Laplace:

𝑢 𝑠 = 𝐾G𝑒 𝑠 +𝐾G𝑇I𝑠

𝑒 𝑠

Thisgivesthefollowingtransferfunction:

𝐻OP 𝑠 =𝑢(𝑠)𝑒(𝑠) = 𝐾O +

𝐾G𝑇I𝑠

=𝐾O(𝑇I𝑠 + 1)

𝑇I𝑠

i.e,

𝑯𝑷𝑰 𝒔 =𝑲𝑷(𝑻𝒊𝒔 + 𝟏)

𝑻𝒊𝒔

PIControllerasaState-spacemodel:

Weset 𝑧 = .0𝑒 ⇒ 𝑠𝑧 = 𝑒 ⇒ 𝑧 = 𝑒

Thisgives:

𝑧 = 𝑒

𝑢 = 𝐾G𝑒 +𝐾G𝑇I𝑧

Where

𝑒 = 𝑟 − 𝑦

Discreteversion:

UsingEuler:

𝑧 ≈𝑧,-. − 𝑧,

𝑇0

Where 𝑇0 istheSamplingTime.

Thisgives:

𝑧,-. − 𝑧,𝑇0

= 𝑒,

Page 30: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

30 ControlApplication

Tutorial:DataAcquisitioninMATLAB

𝑢, = 𝐾G𝑒, +𝐾G𝑇I𝑧,

Finally:

𝒆𝒌 = 𝒓𝒌 − 𝒚𝒌

𝒖𝒌 = 𝑲𝒑𝒆𝒌 +𝑲𝒑

𝑻𝒊𝒛𝒌

𝒛𝒌-𝟏 = 𝒛𝒌 + 𝑻𝒔𝒆𝒌

ThisalgorithmcaneasilybeimplementedinC#.

6.4 ProcessModelAverysimple(linear)modelofthewatertankisasfollows:

𝐴Lℎ = 𝐾G𝑢−𝐹 aL

or

ℎ =1𝐴L

𝐾G𝑢−𝐹 aL

Where:

• ℎ [cm]isthelevelinthewatertank• 𝑢 [V]isthepumpcontrolsignaltothepump• 𝐴L [cm2]isthecross-sectionalareainthetank• 𝐾G [(cm3/s)/V]isthepumpgain• 𝐹 aL [cm3/s]istheoutflowthroughthevalve(thisoutflowcanbemodeledmore

accuratelytakingintoaccountthevalvecharacteristicexpressingtherelationbetweenpressuredropacrossthevalveandtheflowthroughthevalve).

WecanusetheEulerForwarddiscretizationmethodinordertocreateadiscretemodel:

𝑥 ≈𝑥,-. − 𝑥,

𝑇0

Thenweget:

ℎ,-. − ℎ,𝑇0

=1𝐴L

𝐾G𝑢,−𝐹 aL

Page 31: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

31 ControlApplication

Tutorial:DataAcquisitioninMATLAB

Finally:

𝒉𝒌-𝟏 = 𝒉𝒌 +𝑻𝒔𝑨𝒕

𝑲𝒑𝒖𝒌−𝑭𝒐𝒖𝒕

Page 32: University College of Southeast Norwayhome.hit.no/~hansha/documents/matlab/training/Data Acquisition in... · 6 Control Application ... MATLAB is in use world-wide by researchers

Hans-PetterHalvorsen,M.Sc.

E-mail:[email protected]

Blog:http://home.hit.no/~hansha/

UniversityCollegeofSoutheastNorway

www.usn.no