MATLAB: Unexpected behavior fscanf with serial port

fgetlfscanfMATLABserial port

I'm using matlab to read out voltages of the analog pins of an Arduino Uno. To do this, I wrote a short code for the arduino that writes the data continously to the serial port, with a BaudRate of 115200. This is functioning, as I cheched with the serial monitor build in to the online arduino editor. I wrote the data using Serial.print(string), so I was expecting a string out of the serial port. This was incorrect, but no matter, since I was sending a double as a string anyway. Now where things get weird, is that when reading the serial port, using fscanf(or fgetl, same behaviour), the data is not transmitted live. So if I increase the voltage over the pin, the read-out initially doesn't change, but after about 5-10 seconds, it 'catches up', all the while displaying a constant voltage. Even weirder, is when I change the voltage, let it sit for a few seconds and change it again, the read out changes somewhat accordingly, going to the first value and then relatively quickly going to the second value.
Any input is appreciated.
ps. I am aware of the Arduino hardware support package, but readVoltage() has a frequency of 50Hz on my machine, which is too low for my purpose.
the code:
clear all
close all
clc
%Set up the serial port
s = serial('COM3');
set(s, 'BaudRate', 115200); % set BaudRate to 115200
set(s, 'Parity', 'none'); % set Parity Bit to None
set(s, 'DataBits', 8); % set DataBits to 8
set(s, 'StopBit', 1); % set StopBit to 1
set(s,'Terminator','LF') % set terminating character to LF/new line
fopen(s); %open the port
%Determining how long I want to run the script
am = 100000;
volt1 = zeros(1,am)*am;
volt2 = zeros(1,am)*am;
val = zeros(1,am)*am;
tic %start counter for timekeeping
for i =1:am
val(:,i) = string(fgetl(s)); %retrieve value of serial port, in the form aaaa.bbbb where a and b can vary in length
if mod(i,10) == 0 %Display every 10 iterations
volt1 = floor(val)*5/1023; %Calculating actual voltage for A1, where floor(val) is first value
volt2= (volt1-floor(val))*5/0.1023; %getting only decimals for second voltage
plot(volt1) %plot the values
hold on
plot(volt2)
hold off
ylim([0 5])
xlim([i-1000 i]) %make the plot chug along
drawnow %Live
end
clc
toc
end
fclose(s); %Close off the port
delete(s);

Best Answer

The problem was with 'plot', this was way to inefficient to keep up with the datastream, after changing it to animatedline, it works like a charm!
Related Question