Serial - only reads one string.

Hi
I have a microcontroller with a sensor. The uC sends out a string every tenth of a second to the COM-port. The string is filled with data XXX (Where XXX is 000-999)
Looks like this:
char output_verbose[] = {"XXX\r\n"};
The matlab-code is like this:
s1=serial('COM7','Baudrate',9600);
fopen(s1);
value=0;
str='';
sen=0;
j=1;
while(j<1000)
str=fscanf(s1);
sen=str2num(str);
accX(j)=sen;
plot(j,value);
drawnow;
j=j+1;
end;
fclose(s1);
delete(s1);
clear s1;
The probem after i have debugged a bit, is that when i want to read value number 2, the string is empty. It wont get the string from the COM-port again. And the uC sends the values 10 times a second, this is checked via PuTTY. I also have a LED that blinks everytime it sends.
Please help me

 采纳的回答

You have not configured the line terminator for the serial object.
Also your code
while(while(j<1000)
is invalid syntax.

7 个评论

That is true. I was copying part by part into the forum. So in the real code, it is not like that.
But i found out that I have to close and open the serial-port for each input. And now it samples. Here is the code, if it can help some others.
Tips for doing the code better is welcome
s1=serial('COM7','Baudrate',9600);
accX=0;
str='';
sen=0;
j=1;
x=0;
while(j<300)
fopen(s1);
str=fscanf(s1);
fclose(s1);
sen=str2num(str);
accX(j)=sen;
plot(accX);
axis([(-50+j) (5+j) 0 1000]);
drawnow;
j=j+1;
end;
fclose(s1);
delete(s1);
clear s1;
You definitely should not need to close and open the port. But you do need to set the termination character. See http://www.mathworks.com/help/instrument/terminator.html
How do I do that in MATLAB? Every string ends with \r\n from the uC, I would think I can use that as a terminator?
s1 = serial('COM7', 'Baudrate', 9600, 'Terminator', 'CR/LF');
Thank you for your help Walter. Now it runs much better. I could not use CR/LF as terminator for some reason, so I used 000.
char output_verbose[] = {"XXX 000 \r\n"};
s1 = serial('COM7', 'Baudrate', 9600, 'Terminator', 000 );
fopen(s1);
accX=0;
str='';
sen=0;
j=1;
x=0;
while(j<3000)
str=fscanf(s1);
sen=str2num(str);
accX(j)=sen/100;
plot(accX);
axis([(-50+j) (5+j) 0 10]);
drawnow;
j=j+1;
end;
fclose(s1);
delete(s1);
clear s1;
Note: in C, "XXX 000 \r\n" the 000 part is '0' '0' '0', but when you use 'Terminator', 000 in MATLAB, that is the same as 'Terminator', 0 -- a binary 0; in C that would be coded as \0, "XXX \0\r\n"
hi i also tried the same to interface uc with matlab but the terminator error persists even after i made the above changes coudl u clarify this please

请先登录,再进行评论。

更多回答(0 个)

类别

帮助中心File Exchange 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by