Data Acquisition in MATLAB

UniversityCollegeofSoutheastNorway
DataAcquisitioninMATLAB
Hans-PetterHalvorsen,2016.11.01
http://home.hit.no/~hansha
TableofContents
1
Introduction......................................................................................................................4
1.1
MATLAB......................................................................................................................4
1.2
Simulink......................................................................................................................5
1.2.1
2
1.3
USB-6008DAQDevice................................................................................................6
1.4
NIDAQmxdriver.........................................................................................................7
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
3
NI-DAQmx..........................................................................................................12
DataAcquisitionToolbox................................................................................................14
3.1
4
DataAcquisitionToolbox.....................................................................................6
GettingHelp..............................................................................................................15
MyFirstDAQApp............................................................................................................16
4.1
Introduction..............................................................................................................16
4.2
LegacyInterface........................................................................................................16
4.2.1
SimpleDAQApplication....................................................................................17
2
3
4.2.2
4.3
6
SourceCode.......................................................................................................18
Session-basedInterface............................................................................................19
4.3.1
5
TableofContents Summingup.......................................................................................................20
DAQinSimulink...............................................................................................................22
5.1
AnalogIn...................................................................................................................22
5.2
AnalogOut................................................................................................................24
ControlApplication.........................................................................................................27
6.1
Introduction..............................................................................................................27
6.2
Low-passFilter..........................................................................................................28
6.3
PIController..............................................................................................................28
6.4
ProcessModel..........................................................................................................30
Tutorial:DataAcquisitioninMATLAB
1 Introduction
InthisTutorialwewilllearnhowtocreateDAQ(DataAcquisition)applicationsinMATLAB
andSimulink.WewilluseaUSB-6008DAQdevicefromNationalInstrumentsasanexample.
InordertouseDAQdevicesfromNationalInstrumentsinMATLAB/Simulinkweneedto
installtheNI-DAQmxdriverprovidedbyNationalInstruments.InadditionweneedtheData
AcquisitionToolboxforMATLAB/Simulink.
1.1 MATLAB
MATLABisatoolfortechnicalcomputing,computationandvisualizationinanintegrated
environment,e.g.,
•
•
•
•
•
•
•
Mathandcomputation
Algorithmdevelopment
Dataacquisition
Modeling,simulation,andprototyping
Dataanalysis,exploration,andvisualization
Scientificandengineeringgraphics
Applicationdevelopment,includinggraphicaluserinterfacebuilding
MATLABisdevelopedbyTheMathWorks.MATLABisashort-termforMATrixLABoratory.
MATLABisinuseworld-widebyresearchersanduniversities.
Formoreinformation,seewww.mathworks.com
BelowweseetheMATLABEnvironment:
4
5
Introduction MATLABhasthefollowingwindows:
•
•
•
•
CommandWindow
CommandHistory
Workspace
CurrentDirectory
TheCommandwindowisthemainwindow.UsetheCommandWindowtoentervariables
andtorunfunctionsandM-filesscripts(moreaboutm-fileslater).
Watchthefollowing“GettingStartedwithMATLAB”video:
http://www.mathworks.com/demos/matlab/getting-started-with-matlab-videotutorial.html
1.2 Simulink
Simulink,developedbyTheMathWorks,isacommercialtoolformodeling,simulatingand
analyzingdynamicsystems.Itsprimaryinterfaceisagraphicalblockdiagrammingtoolanda
customizablesetofblocklibraries.ItofferstightintegrationwiththerestoftheMATLAB
environmentandcaneitherdriveMATLABorbescriptedfromit.Simulinkiswidelyusedin
controltheoryanddigitalsignalprocessingforsimulationanddesign.
BasicinformationaboutSimulinkcanbefoundhere:
Tutorial:DataAcquisitioninMATLAB
6
Introduction WatchthevideoGettingStartedwithSimulinkbyTheMathWorks.
Readthe“IntroductiontoSimulink”document.Youwillneedtoknowthesetopics
whendoingtherestofthetasksinthisLabWork.
TheTutorialisavailablefrom:http://home.hit.no/~hansha/.
1.2.1
DataAcquisitionToolbox
DataAcquisitionToolboxsoftwareprovidesacompletesetoftoolsforanaloginput,analog
output,anddigitalI/OfromavarietyofPC-compatibledataacquisitionhardware.The
toolboxletsyouconfigureyourexternalhardwaredevices,readdataintoMATLABand
Simulinkenvironmentsforimmediateanalysis,andsendoutdata.
DataAcquisitionToolboxalsosupportsSimulinkwithblocksthatenableyoutoincorporate
livedataorhardwareconfigurationdirectlyintoSimulinkmodels.Youcanthenverifyand
validateyourmodelagainstlive,measureddataaspartofthesystemdevelopmentprocess.
WewillusetheDataAcquisitionToolboxinordertowriteandreaddatatoandfromaUSB6008DAQdevicefromNationalInstruments.
1.3 USB-6008DAQDevice
NIUSB-6008isasimpleandlow-costmultifunctionI/OdevicefromNationalInstruments.
Thedevicehasthefollowingspecifications:
•
•
•
•
8analoginputs(12-bit,10kS/s)
2analogoutputs(12-bit,150S/s)
12digitalI/O
USBconnection,Noextrapower-supplyneeded
Tutorial:DataAcquisitioninMATLAB
7
•
•
Introduction CompatiblewithLabVIEW,LabWindows/CVI,andMeasurementStudioforVisual
Studio.NET
NI-DAQmxdriversoftware TheNIUSB-6008iswellsuitedforeducationpurposesduetoitssmallsizeandeasyUSB
connection.
Note!The64-bitversionofDataAcquisitionToolboxsupportsNationalInstrumentsdevices
thatcanbeusedwiththe“session-basedinterface”(moreaboutthislater).Forother
supportedNIdataacquisitiondevices,youmustusethe32-bitversionofDataAcquisition
ToolboxandMATLAB.The32-bitversionsofDataAcquisitionToolboxandMATLABcanbe
installedona64-bitWindowsOS.
1.4 NIDAQmxdriver
YouneedtoinstalltheDAQmxdriverinordertouseitinMATLAB.
Tutorial:DataAcquisitioninMATLAB
2 DataAcquisition
2.1 Introduction
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
Analyzing,presentingandsavingthedata
TheDAQsystemhasthefollowingpartsinvolved,seeFigure:
[Figure:www.ni.com]
Thepartsare:
•
•
•
•
Physicalinput/outputsignals
DAQdevice/hardware
Driversoftware
Yoursoftwareapplication(Applicationsoftware)
8
9
2.1.1
DataAcquisition Physicalinput/outputsignals
Aphysicalinput/outputsignalistypicallyavoltageorcurrentsignal.
2.1.2
DAQdevice/hardware
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.
Tutorial:DataAcquisitioninMATLAB
10
DataAcquisition [Figure:www.ni.com]
[Figure:www.ni.com]
2.1.3
Driversoftware
Driversoftwareisthelayerofsoftwareforeasilycommunicatingwiththehardware.Itforms
themiddlelayerbetweentheapplicationsoftwareandthehardware.Driversoftwarealso
preventsaprogrammerfromhavingtodoregister-levelprogrammingorcomplicated
commandsinordertoaccessthehardwarefunctions.
Tutorial:DataAcquisitioninMATLAB
11
DataAcquisition DriversoftwarefromNationalInstruments:NI-DAQmx
2.1.4
Yoursoftwareapplication
Applicationsoftwareaddsanalysisandpresentationcapabilitiestothedriversoftware.Your
softwareapplicationnormallydoessuchtasksas:
•
•
•
•
•
Real-timemonitoring
Dataanalysis
Datalogging
Controlalgorithms
Humanmachineinterface(HMI)
InordertocreateyourDAQapplicationyouneedaprogrammingdevelopmenttool,suchas
VisualStudio/C#,LabVIEW,etc..
2.2 MAX–MeasurementandAutomation
Explorer
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.
Tutorial:DataAcquisitioninMATLAB
12
DataAcquisition 2.3 DAQinMATLAB
WecancreateDAQapplicationswithorwithoutMeasurementStudio.Inbothsituationsyou
needtheNI-DAQmxdriverlibrary.
2.3.1
NI-DAQmx
NationalInstrumentsprovidesanative.NETAPIforNI-DAQmx.Thisisavailableasapartof
theNI-DAQmxdriveranddoesnotrequireMeasurementStudio.
Ingeneral,dataacquisitionprogrammingwithDAQmxinvolvesthefollowingsteps:
Tutorial:DataAcquisitioninMATLAB
13
•
•
•
•
•
DataAcquisition CreateaTaskandVirtualChannels
StarttheTask
PerformaReadoperationfromtheDAQ
PerformaWriteoperationtotheDAQ
StopandCleartheTask.
Dataacquisitionintextbased-programmingenvironmentisverysimilartotheLabVIEWNIDAQmxprogrammingasthefunctionscallsisthesameastheNI-DAQmxVI’s.
Tutorial:DataAcquisitioninMATLAB
3 DataAcquisitionToolbox
DataAcquisitionToolboxsoftwareprovidesacompletesetoftoolsforanaloginput,analog
output,anddigitalI/OfromavarietyofPC-compatibledataacquisitionhardware.The
toolboxletsyouconfigureyourexternalhardwaredevices,readdataintoMATLABand
Simulinkenvironmentsforimmediateanalysis,andsendoutdata.
DataAcquisitionToolboxalsosupportsSimulinkwithblocksthatenableyoutoincorporate
livedataorhardwareconfigurationdirectlyintoSimulinkmodels.Youcanthenverifyand
validateyourmodelagainstlive,measureddataaspartofthesystemdevelopmentprocess.
WewillusetheDataAcquisitionToolboxinordertowriteandreaddatatoandfromaUSB6008DAQdevicefromNationalInstruments. Note!InadditionyouneedtoinstalltheNIDAQmxdriverfromNationalInstruments.
BelowweseethedataflowfromthesensorstotheMATLAB:
[Figure:www.mathworks.com]
14
15
DataAcquisitionToolbox 3.1 GettingHelp
TodetermineifDataAcquisitionToolboxsoftwareisinstalledonyoursystem,type
ver
ThiswilllistallyourToolkitsthatyouhaveinstalledandtheversionnumbers.
InordertogetanoverviewoftheDataAcquisitionToolboxyoucantypethefollowinginthe
MATLABCommandwindow:
help daq
ThenyouwillgetanoverviewofallthefunctionsavailableintheDataAcquisitionToolbox.
ThisToolboxhasDAQfunctionalitybothforMATLABandSimulink.
Youcanviewthecodeforanyfunctionbytyping:
type function_name
Youcanviewthehelpforanyfunctionbytyping:
help function_name
Tutorial:DataAcquisitioninMATLAB
4 MyFirstDAQApp
IntheseexampleswewilluseanUSB-6008devicefromNationalInstruments.Inaddition
youneedtoinstalltheNIDAQmxdriverfromNationalInstruments.
4.1 Introduction
Note!The64-bitversionofDataAcquisitionToolboxsupportsNationalInstrumentsdevices
thatcanbeusedwiththesession-basedinterface.ForothersupportedNIdataacquisition
devices,youmustusethe32-bitversionofDataAcquisitionToolboxandMATLAB.The32bitversionsofDataAcquisitionToolboxandMATLABcanbeinstalledona64-bitWindows
OS.
Session-basedInterface LegacyInterface
32-bitMATLAB
X
X
64-bitMATLAB
X
NIUSB-6008supportbothinterfaces,boththeprogrammingisdifferentinMATLAB.
Session-basedInterface:
Youmayusethedaq.getVendors()inordertogetalistofsupportedadinstalleddevices.
UsingSession-basedInterfaceyoucreateadataacquisitionsessionobjectwith
daq.createSession.Youcanthenaddchannelstothesessionandoperateallchannelswithin
thesessiontogether.
Legacyinterface:
TheinterfaceavailablewithDataAcquisitionToolboxworkswithallsupporteddata
acquisitionhardware,exceptCompactDAQdevicesanddevicesusingthecounter/timer
subsystem.Usingthisinterfaceyoucreatedataacquisitionobjectswiththesecommands:
analoginput()
analogoutput()
4.2 LegacyInterface
16
17
MyFirstDAQApp Note!Ifyouhave64-bitMATLAByoucannotusethismethod.
WewillusetheDataAcquisitionToolboxinMATLABtocreateasimpleDataAcquisition
application.
WestartbycheckingiftheDAQmxdriverhasbeenproperlyinstalled.Usethefollowing
code:
out = daqhwinfo
out.InstalledAdapters
Dependingonwhatyouhaveinstalled,youmay,e.g.,getthefollowinganswer:
ans =
'mcc'
'nidaq'
'parallel'
'winsound'
Note!Ifyoudon’tfindyourDAQcardinthelist,makesureyourunMATLABasan
administrator.Right-clickontheMATLABiconandselect“RunasAdministrator”.
4.2.1
SimpleDAQApplication
ASimpleDAQapplicationshouldfollowthesesteps:
1. Initialization
2. Read/Write
3. CleanUp
Wewillexplainthedifferentstepsbelow:
1-Initialization:
CreatingaDeviceObject:
InInitializationyouneedtospecifywhatkindofdeviceyouareusing.Wecanusethe
analoginput()andanalogoutput()functionsintheDataAcquisitionToolbox.
Example:
ai = analoginput('nidaq', 'Dev1');
and:
ao = analogoutput('nidaq', 'Dev1');
TheDataAcquisitionToolboxsupportsDAQdevicesfromdifferentvendors.Inordertousea
devicefromNationalInstruments,weneedtoset“nidaq”astheadaptername.“DevX”is
thedefaultnamecreatedbythesystem,seMAX(MeasurementandAutomationExplorer)
fordetailsaboutyourdevice.
Tutorial:DataAcquisitioninMATLAB
18
MyFirstDAQApp 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-filethatwriteonesinglevaluetotheDAQdevice
andthenreadonesinglevaluefromtheDAQdevice.
WestartbyconnectingtheAnalogInandAnalogOutwirestogetherontheDAQdevice(aso
calledLoopbackconnection).
Ifwewrite,e.g.,3.5VtotheDAQdeviceonaAOchannel,wewillthenreadthesamevalue
ontheAIchannel.
SourceCodeforaSimpleDAQExampleinMATLAB:
% Write and Read to a NI USB-6008 DAQ device
Tutorial:DataAcquisitioninMATLAB
19
MyFirstDAQApp 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-basedInterface
Note!Ifyouhave64-bitMATLAByouneedtousethismethod.
Youmayusethedaq.getVendors()inordertogetalistofsupportedadinstalleddevices.
>> daq.getVendors()
ans =
Data acquisition vendor 'National Instruments':
ID:
FullName:
AdaptorVersion:
DriverVersion:
IsOperational:
'ni'
'National Instruments'
'3.0 (R2011b)'
'9.3.5 NI-DAQmx'
true
UsingSession-basedInterfaceyoucreateadataacquisitionsessionobjectwith
daq.createSession.Youcanthenaddchannelstothesessionandoperateallchannelswithin
thesessiontogether.
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.
Tutorial:DataAcquisitioninMATLAB
20
MyFirstDAQApp 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.,useinputSingleScaninordertoreaddatafromtheAnalogInput
Channel(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:
FullName:
AdaptorVersion:
DriverVersion:
IsOperational:
'ni'
'National Instruments'
'3.0 (R2011b)'
'9.6.0 NI-DAQmx'
true
Tutorial:DataAcquisitioninMATLAB
21
MyFirstDAQApp Next,wecheckiftheDAQdevice(InthistutorialistheNIUSB-6008used)pluggedinand
working:
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
Nextwecancreatesimplescriptthatwriteasinglevaluetoananalogoutchannelandthen
readthesamevaluefromtheanaloginputchannel.
Weuseasocalled“Loopback”connection,i.e.westartbyconnectingtheAnalogInand
AnalogOutwirestogetherontheDAQdevice.Ifwewrite,e.g., 3.5𝑉 totheDAQdeviceon
anAOchannel,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,using
for/whileloops,etc.
Tutorial:DataAcquisitioninMATLAB
5 DAQinSimulink
Simulinkhasbuilt-inblocksforDataAcquisition,butdependingontheversionof
MATLAB/SimulinkyouareusingtheymightnotworkproperlywiththeUSB-6008DAQ
device.InthatcaseyoucancallMATLABfunctionsfromSimulink.
WewillcreateasimpleSimulinkapplicationwhereyouwriteandreadvaluesfromtheUSB6008DAQdevice.
InthischapterMATLAB/SimulinkR2007aisused.TheDataAcquisitionToolboxhasbeen
updatedsincethisrelease.
Belowweseethebuilt-inblocksinSimulink/DataAcquisitionToolbox(R2007a):
5.1 AnalogIn
WecreateasimpleapplicationinSimulinkinordertodemonstratehowtoreadfromthe
DAQdevice:
22
23
DAQinSimulink PropertiesforAnalogInputBlock:
InthePropertieswindowwecandefinechannels,samplerate,etc.
Tutorial:DataAcquisitioninMATLAB
24
DAQinSimulink 5.2 AnalogOut
WecreateasimpleapplicationinSimulinkinordertodemonstratehowtowritetotheDAQ
device:
PropertiesforAnalogOutputBlock:
Inthiscasewegetthefollowingerror:
Tutorial:DataAcquisitioninMATLAB
25
DAQinSimulink →ThisisduetothattheSimulinkblocksonlysupporthardwarethathasinternalclocking,
whichtheNIUSB-6008doesnotonanalogoutput.You’llneedtocallintoaMATLAB
functiontodoPUTSAMPLE.
Tosolvethisproblem,wecanusethe“EmbeddedMATLABfunction”blockinSimulink
whereweimplementMATLABcodeforthewriteoperation:
TheEmbeddedMATLABcodeisasfollows:
Tutorial:DataAcquisitioninMATLAB
26
DAQinSimulink Tutorial:DataAcquisitioninMATLAB
6 ControlApplication
6.1 Introduction
InthisexamplewewilluseMeasurementStudiotocreateasimplecontrolapplication.We
willcontrolthelevelinawatertankusingmanualcontrol.Theprocessisasfollows:
Wewanttocontrolthelevelinthewatertankusingapumpontheinflow.Wewillreadthe
levelusingourUSB-6008DAQdevice(AnalogIn)andwritethecontrolsignal(AnalogOut)to
theDAQdevice.
TheAnalogOut(controlsignal)willbeasignalbetween 0 − 5𝑉 andtheAnalogIn(Level)
willbea 0 − 5𝑉 signalthatweneedtoscaleto 0 − 20𝑐𝑚.
ThenextimprovementstoourapplicationwouldbetoimplementaLow-passFilterinorder
toremovethenoisefromthesignalwhenreadingthelevel.Anotherimprovementwouldbe
toreplacethemanualcontrolwithaPIcontrollerthatdothejobforus.Finallyitwouldbe
nicetohaveamathematicalmodelofourwatertanksowecansimulateandtestthe
behavioroftherealsystemwithoutconnecttoit.
27
28
ControlApplication Soweneedtocreatediscreteversionsofthelow-passfilter,thePIcontrollerandthe
processmodel.Wecan,e.g.,usetheEulerForwarddiscretizationmethod:
𝑥≈
𝑥,-. − 𝑥,
𝑇0
ortheEulerBackwarddiscretizationmethod:
𝑥≈
𝑥, − 𝑥,1.
𝑇0
𝑇0 istheSamplingTime.
6.2 Low-passFilter
Thetransferfunctionforafirst-orderlow-passfiltermaybewritten:
𝐻 𝑠 =
𝑦6 (𝑠)
1
=
𝑦(𝑠) 𝑇6 𝑠 + 1
Where 𝑇6 isthetime-constantofthefilter, 𝑦(𝑠) isthefilterinputand 𝑦6 𝑠 isthefilter
output.
Discreteversion:
Itcanbeshownthatadiscreteversioncanbestatedas:
𝒚𝒇,𝒌 = 𝟏 − 𝒂 𝒚𝒇,𝒌1𝟏 + 𝒂𝒚𝒌 Where
𝒂=
𝑻𝒔
𝑻𝒇 + 𝑻𝒔
Where 𝑇0 istheSamplingTime.
6.3 PIController
APIcontrollermaybewritten:
𝐾G
𝑢 𝑡 = 𝑢E + 𝐾G 𝑒 𝑡 +
𝑇I
L
𝑒𝑑𝜏
E
Where 𝑢 isthecontrolleroutputand 𝑒isthecontrolerror:
Tutorial:DataAcquisitioninMATLAB
29
ControlApplication 𝑒 𝑡 = 𝑟 𝑡 − 𝑦(𝑡)
PIControllerasaTransferfunction:
Laplace:
𝑢 𝑠 = 𝐾G 𝑒 𝑠 +
𝐾G
𝑒 𝑠 𝑇I 𝑠
Thisgivesthefollowingtransferfunction:
𝐻OP 𝑠 =
𝐾G 𝐾O (𝑇I 𝑠 + 1)
𝑢(𝑠)
= 𝐾O +
=
𝑒(𝑠)
𝑇I 𝑠
𝑇I 𝑠
i.e,
𝑯𝑷𝑰 𝒔 =
𝑲𝑷 (𝑻𝒊 𝒔 + 𝟏)
𝑻𝒊 𝒔
PIControllerasaState-spacemodel:
.
Weset 𝑧 = 𝑒 ⇒ 𝑠𝑧 = 𝑒 ⇒ 𝑧 = 𝑒
0
Thisgives:
𝑧 = 𝑒
𝑢 = 𝐾G 𝑒 +
𝐾G
𝑧
𝑇I
Where
𝑒 = 𝑟 − 𝑦
Discreteversion:
UsingEuler:
𝑧≈
𝑧,-. − 𝑧,
𝑇0
Where 𝑇0 istheSamplingTime.
Thisgives:
𝑧,-. − 𝑧,
= 𝑒, 𝑇0
Tutorial:DataAcquisitioninMATLAB
30
𝑢, = 𝐾G 𝑒, +
ControlApplication 𝐾G
𝑧 𝑇I ,
Finally:
𝒆𝒌 = 𝒓𝒌 − 𝒚𝒌 𝒖𝒌 = 𝑲𝒑 𝒆𝒌 +
𝑲𝒑
𝒛 𝑻𝒊 𝒌
𝒛𝒌-𝟏 = 𝒛𝒌 + 𝑻𝒔 𝒆𝒌 ThisalgorithmcaneasilybeimplementedinC#.
6.4 ProcessModel
Averysimple(linear)modelofthewatertankisasfollows:
𝐴L ℎ = 𝐾G 𝑢−𝐹`aL or
ℎ=
1
𝐾 𝑢−𝐹`aL 𝐴L G
Where:
•
•
•
•
ℎ [cm]isthelevelinthewatertank
𝑢 [V]isthepumpcontrolsignaltothepump
𝐴L [cm2]isthecross-sectionalareainthetank
𝐾G [(cm3/s)/V]isthepumpgain
•
𝐹`aL [cm3/s]istheoutflowthroughthevalve(thisoutflowcanbemodeledmore
accuratelytakingintoaccountthevalvecharacteristicexpressingtherelation
betweenpressuredropacrossthevalveandtheflowthroughthevalve).
WecanusetheEulerForwarddiscretizationmethodinordertocreateadiscretemodel:
𝑥≈
𝑥,-. − 𝑥,
𝑇0
Thenweget:
ℎ,-. − ℎ,
1
=
𝐾 𝑢 −𝐹 𝑇0
𝐴L G , `aL
Tutorial:DataAcquisitioninMATLAB
31
Finally:
𝒉𝒌-𝟏 = 𝒉𝒌 +
𝑻𝒔
𝑲 𝒖 −𝑭
𝑨𝒕 𝒑 𝒌 𝒐𝒖𝒕
Tutorial:DataAcquisitioninMATLAB
ControlApplication Hans-PetterHalvorsen,M.Sc.
E-mail:[email protected]
Blog:http://home.hit.no/~hansha/
UniversityCollegeofSoutheastNorway
www.usn.no