Useful Matlab Code Snippets
E11 Lab 3
2008

## Loop for 10 seconds:

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```

## Initialize DAQ

```%1) Create a data acquistion object
% (and specify single-ended inputs)
daqInfo=daqhwinfo('nidaq');
ai.InputType='SingleEnded';

%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```

## Close DAQ

```delete(dio);
clear dio;
delete(ai);
clear ai;```

Note: this code assumes aio and dio exist.

## Set P0.0 low (or high)

```putvalue(dio,0);
% or putvalue(dio,1);```

Note: this code assumes dio exists and consists of P0.0

## Read from Channel 0 (or 1)

```start(ai);
wait(ai,1);
data=getdata(ai);
val=mean(data(:,chan+1));  %where chan=0 or chan=1...```

## Plot blue circle, but keep axes consistent

```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.