MATLAB: I am measuring voltage from a pot on the Arduino Uno. My time vector grows but all the index values of the voltage vector are the same as I vary the pot.

arduinoindexingvectorization

I need to store the individual voltage values as I vary the pot. I included the file, any help is appreciated.

Best Answer

I could not understand the reason for using a for loop inside the while loop. Try the following code. I have also made some other changes e.g. you were calling plot() inside while loop which can make the code slow. I have used figure handle to update the same figure.
%Use a flag so that you can "append" new data to the end of it
time=0;
t=[]; % although pre-allocation is good, but the number of samples are not known in advance.
% If your data size is small, it will not matter much.
voltage=[];
f = gcf; % instead of creating new axis inside the while loop. Create a figure, and update its handle
ax = gca;
l = line();
l.XData = [];
l.YData = []
ylim([0 5]);
xlabel('time (s)');
ylabel('voltage (v)');
title('analog data from the potentiometer');
while (flag==0)
t=[t time];
time=time+1;
voltage = [voltage readVoltage(a,pot)];
if (readDigitalPin(a,button)==1) %button is pressed
break; % nor need for flag, just break the loop
end
c=clock;
fprintf(fid,'%4.0d %2.0d %2.0d %2.0d %2.0d %6.4d %d\n',c,sin(c(6)));
pause(1);
% Plot the data
l.XData = t;
l.YData = voltage;
end
Also, you are not writing the voltage value in the file, you might want to look into that.