How do I save the entire input buffer for a UDP communication without taking each item one by one?

8 vues (au cours des 30 derniers jours)
I am using UPD communication to read from a high frequency sensor. The sensor writes a reading to the buffer while the code performs a real time analysis. However, because the sensor fills the buffer much faster than my code can read data from the buffer, I end up filling the buffer and losing future data points. If I record data asynchronously, I miss data points in the middle. For reference, here is what I have been trying:
t=udp('192.168.0.101', 2390);
t.InputBufferSize=500000;
fopen(t);
fopen(t);
fwrite(t,'1'); %handshake that activates the communication. Not integral.
data=fscanf(t, '%c' , t.BytesAvailable);
fscanf in this case only returns to me the most recent entry in the buffer regardless of how many more entries are in the buffer.
I would like wait until the buffer is partially full, and then copy all the data into a matrix for analysis while the sensor refills the buffer again.
Any ideas?

Réponses (1)

Astarag Chattopadhyay
Astarag Chattopadhyay le 16 Mai 2017
Hi,
I would suggest you to use the callback function ' BytesAvailableFcn ' which can be called to read the data from the buffer when a pre-specified amount of data is available. You can define the callback function considering 't' as your UDP object as the following:
t.BytesAvailableFcn = @callback_function;
Inside the callback function, you can read the data from the buffer using 'fread' in a while loop until there is data available in the buffer. You can accomplish this using the following code snippet:
function callback_function(t, event)
availableBytes = get(t, 'BytesAvailable');
while availableBytes
data = fread(t, bytesAvailable, 'char');
availableBytes= get(t, 'BytesAvailable');
end
end
Also, in your use-case, sensor data from the input buffer has to be read when it is partially full. Thus, the requirement will also involve specifying the amount of data required to be read for every read cycle from the buffer along with the mode of reading by:
t.BytesAvailableFcnCount = 10;
t.BytesAvailableFcnMode = 'byte';
Do note that the above two lines of the code will be included in the main file.
However, a drawback of this procedure is that it will continue calling the callback function even when the buffer is empty.

Community Treasure Hunt

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

Start Hunting!

Translated by