Reading data from a serialport connection

41 Ansichten (letzte 30 Tage)
Kevin
Kevin am 26 Jul. 2023
Beantwortet: Maddie am 15 Aug. 2023
I am attempting to receive and log data from a serial port connection. The issue that I am having is that the time out for the device is about 0.112 seconds, however with the code that I have written running the fread command takes matlab about 2~3 seconds. Is there any way to make this run faster.
Another issue that I am having is how the data is being saved. The goal is to have it output to a csv where all of the information taken over any amount of time is in the first column and there are timestamps in the second column but I cant seem to get the timer to work the way I want.
%% Connect to serial port
s = serialport('COM4',9600,"Parity","even");
s.StopBits = 1;
s.DataBits=7;
s.Timeout = 0.112;
data=[];
% %% Create timer
% t = timer;
% t.Period = 1; % Every 1 second
% t.TimerFcn = @timer_fcn;
%
% %% Start timer
% start(t)
%% Read from serial port
data =[data ; fread(s,512,'uint8')];
%%
w2 = char(w);
w3 = num2cell(w2);
%%
str = strjoin(w3);
%%
pattern = '\d \d \d \. \d \d l b';
matches = regexp(str,pattern,'match');
matches = matches';
This is what I have been able to make so far, the goal is that information can be read at a constant rate and placed into the data variable but the way I am doing it is exceptionally slow.
If any assistance can be given I appreciate it greatly.

Antworten (1)

Maddie
Maddie am 15 Aug. 2023
Hi Kevin,
Instead of fread, you can use read or readline, which are both used to read data from serial port. Additionally, you can use the configureCallback function to execute the reading from the serial port as new data comes in. You will need to use configureTerminator to set the terminator character that will trigger the callback, but the callback function can both read the serial port data and the time that the callback is activated (or "queued").
As an example, the following code should start logging to the Command Window as soon as you initialize the serialport object:
configureCallback(s,"terminator",@(obj,event) disp(event))
The contents of the "event" object contains a "DataAvailableInfo" object, that provides the AbsTime, which you can use when saving data. Here is what was printed on my end:
DataAvailableInfo with properties:
BytesAvailableFcnCount: 1
AbsTime: 15-Aug-2023 11:11:47
Or:
configureCallback(s,"terminator",@(obj,event) disp(event.AbsTime))
Would just log the date & time.
As a final note - one of the quickest ways to stop the logging (if you use the above commands to test), would be to either clear the serialport variable or delete it, "clear s" or "delete(s)".

Produkte


Version

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by