Read Data from Serial Device
5 次查看(过去 30 天)
显示 更早的评论
Hi,
I've got a serial device that outputs data once a second in the in following form: L,00002,00220, N,072, A,000, U,000, T,000, I,000, V,000, E,000,. I'm trying to design a GUI that will display the values in a readable format to an operator. The problem I am having is when I ask MATLAB to read in the data it often doesn't or the data is not complete.
I've included my code for the serial I/O below. Can anyone provide me with help or suggestions?
Thank you!
clear all
s = serial('COM1', 'BaudRate', 19200, 'DataBits', 8, 'Parity', 'none', 'StopBits', 1, 'FlowControl', 'none');
fopen(s);
a=fgetl(s);
fclose(s);
delete(s)
clear s
0 个评论
回答(3 个)
Vieniava
2011-1-27
If your line length is constant you could try something like that:
s.BytesAvailableFcnCount = 40;
s.BytesAvailableFcnMode = 'byte';
s.BytesAvailableFcn = @instrcallback;
0 个评论
Walter Roberson
2011-1-27
It is not recommended to use flowcontrol none with RS232 above 4800 baud. If your cables are a reasonable (short) length you may get away with it at 9600, but by 19200 you will usually be losing characters. Unless you have a good reason not to, I recommend switching to flowcontrol 'hardware'.
Siddharth Shankar
2011-1-28
Douglas,
I would recommend adding a call to FLUSHINPUT (if you are using the Instrument Control Toolbox) as soon as you FOPEN the serial port before reading data in.
I would also second the suggestion by "Vieniava" to use a BytesAvailableFcn callback to read your data as and when X number of bytes become available.
It would also be better to use FREAD instead of FGETL since with FGETL, you are assuming that the input data stream has a terminator character (which it may or may not, you would know by looking at the output data specification of the device) and that this terminator happens to match the one that your SERIAL object is expecting (look at the terminator property of your object). With FREAD, you are making no such assumptions and you are reading raw binary data. You can choose to read the number of bytes that you expect, or you have the flexibility of checking the BytesAvailable property before reading the data with FREAD.
If you are (as you mentioned) able to receive all the data when using HyperTerminal, then it is most likely that something is amiss in the way the serial object is configured, or the way the data is being read in.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Tall Arrays 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!