Serial communications in Matlab is very slow. Is there any way to speed it up?

I wrote a program for some serial communication (RS232) in Matlab, which should interact with a microprocessor. It works fine, receiving data from it, but when sending data, it takes from 0.2 to 0.5 seconds for two bytes of data. Is there a way to speed up serial communication in Matlab or will I have to live with it?

Here is the code I use for writing:

% confa serieporten com_port = '/dev/tty.FireFly-16CB-SPP'; ser = serial(com_port, 'BaudRate', 115200); ser.BytesAvailableFcnCount = 1; ser.BytesAvailableFcnMode = 'byte'; ser.Timeout = 5; i = 1; while i <=length(buffer) fwrite(ser, buffer(i)); i = i + 1; end 
+4
source share
2 answers

I am sure that the SERIAL object uses the Java API (at least it was used, the implementation may have changed since I worked with it). The overhead of using the MATLAB object system, unlike talking to Java objects โ€œdirectlyโ€ in MATLAB, is trivial. Therefore, I would not try to skip the SERIAL object and switch to "directly in Java".

My question to you is: "Do you have an attempt to send every byte at once ?" The message should be much more efficient if you use a larger value for BytesAvailableFcnCount .

If your equipment does not have special restrictions, I recommend choosing the size of a larger buffer. (This may require you to force a reset at the end of the data stream, since you cannot expect the byte to be written automatically. But presumably you are already closing and deleting the object at the appropriate time, so it should not be difficult to clear the buffer at the same time).

If you do not specify a value, MATLAB uses the default value of 48 bytes. I donโ€™t remember how the exact value was chosen, but writing several values โ€‹โ€‹at once will be much more efficient than writing to buffers and washing them with a byte at the same time.

EDIT: Another thought; I don't have MATLAB to test this right now, but what happens if you don't write data in a for loop - instead, leave BytesAvailableFcnCount to 1, and fwrite the entire buffer in one shot?

The way I read the documentation , BytesAvailableFcnCount only indicates a โ€œtriggerโ€ for how big the buffer can get before it is flushed, and not how big the buffer can be. Therefore, having BytesAvailableFcnCount of 1 and writing 128 (say) 128 to a buffer in one shot, it can be flushed to the device only once, and not 128 times, which your existing code does.

+2
source

First of all, before you do any kind of optimization, you must perform profiling.

Menu โ†’ Desktop โ†’ Profiler

Open the Matlab profiler, launch your program and find out where the bottleneck is.

+2
source

Source: https://habr.com/ru/post/1347356/


All Articles