MATLAB Answers

Joe
1

Problems using fscanf() to read serial data

Asked by Joe
on 16 Apr 2012
Hi all,
I have a microcontroller that outputs a continuous stream of data (separated by "\n") through the USART port. It's connected to the PC via an RS232-USB cable. I'm able to read the data in Matlab using fscanf() and save it to a CSV file. However, it only lasts for a few seconds. Increasing the InputBufferSize property makes no difference. In contrast, Tera Term shows that the data flows continuously. So, it's clearly not an issue with a lack of data or an insufficient input buffer.
Using an endless while loop doesn't solve the problem either. To break the cycle in Matlab, I altered the micorcontroller program to issue a "\r" terminator character after a certain period of time followed by stopping the program. In this configuration, Matlab periodically issues a warning that "A timeout occurred before the Terminator was reached." Although the data reading continues after the warning, I suspect that some data is lost as a result. However, I don't know how to determine whether data loss has indeed happened.
Also, the loop doesn't break on its own even after the microcontroller has sent a "\r" character. Instead, I get a repeated warning that "A timeout occurred before the Terminator was reached." Only Ctrl+c would end the program.
function serial_test()
s = serial('COM3', 'BaudRate', 115200, 'DataBits', 8, 'Parity', 'none',...
'StopBits', 1, 'FlowControl', 'none', 'InputBufferSize', 65536,...
'Terminator', 'CR');
s.ReadAsyncMode = 'continuous';
fopen(s);
fid = fopen('ser_data.csv', 'w');
% ser_data = fscanf(s, '%s', 65536)
% ser_data = fscanf(s)
% fprintf(fid, '%s', ser_data);
while 1
ser_data = fscanf(s)
fprintf(fid, '%s', ser_data);
end
fclose(fid);
fclose(s);
delete(s);
clear s;
I'd be grateful for any advice and insight into this matter. Thanks.
Cheers Joe

  0 Comments

Sign in to comment.

0 Answers