Useful Matlab Code Snippets
E11 Lab 3
2008
Note: this code is (for the most part) uncommented. If you choose to use any of it, please add comments, as appropriate, before turning it in.
Method 1
start_tm = clock();
loopTime = 10;
while etime(clock(),start_tm)<loopTime,
%... Put your code in here ...
end
Method 2 (note: this is less accurate and only works if your code takes very little time).
dt=0.1;
loopTime=10;
for i=1:(loopTime/dt),
%... Put your code in here ...
pause(dt);
end
%1) Create a data acquistion object
% (and specify single-ended inputs)
daqInfo=daqhwinfo('nidaq');
ai=analoginput('nidaq',daqInfo.InstalledBoardIds{1});
ai.InputType='SingleEnded';
%2) Add channels 0 and 1 (analog input channels);
ch=addchannel(ai,[0:1]);
%3) Change Properties to suit our needs
ai.SampleRate=10000; %10000 points per second
ai.SamplesPerTrigger=2; %Collect 2 points per channel (this is a minimum)
%4) Create a digital i/o object
dio=digitalio('nidaq',daqInfo.InstalledBoardIds{1});
addline(dio,0,0,'Out','P0.0'); %P0.0 is an output pin
delete(dio); clear dio; delete(ai); clear ai;
Note: this code assumes aio and dio exist.
putvalue(dio,0); % or putvalue(dio,1);
Note: this code assumes dio exists and consists of P0.0
start(ai); wait(ai,1); data=getdata(ai); val=mean(data(:,chan+1)); %where chan=0 or chan=1...
plot(x,y,'bo'); axis([0 5 0 5]);
email me with any comments on how to improve the information on this page (either presentation or content), or to let me know if you had any particular difficulties with this lab.