How to check Serial port continuously

4 views (last 30 days)
Avadhoot Telepatil
Avadhoot Telepatil on 26 Nov 2014
Answered: Samar on 18 Feb 2025 at 11:52
My task is to capture image only when char 'A' is received through COM port. So How to contineously monitor COM port to check whether data is received or no on COM port.

Answers (1)

Samar
Samar on 18 Feb 2025 at 11:52
Data can be continuously monitored using a “timer” object. The “timer” class is used to create a “timer” object which can schedule execution of MATLAB commands. It can be used to repeatedly call the function which reads and writes data through the serial port. The following code can be referred for better understanding:
serialPort = 'COM3'; % Adjust as needed
baudRate = 9600;
s = serial(serialPort, 'BaudRate', baudRate);
fopen(s);
t = timer('ExecutionMode', 'fixedRate', 'Period', 0.1, 'TimerFcn', @(~,~) readAndPlotData(s, ax));
start(t);
function readAndPlotData(serialObj, axesHandle)
if serialObj.BytesAvailable > 0
data = fread(serialObj,... serialObj.BytesAvailable, 'uint16');
plot(axesHandle, data);
drawnow;
end
end
stop(t);
delete(t);
fclose(s);
delete(s);
The first part of the sample code creates a serial object s. In this code snippet, data from the serial port is being read into the variable “data” which is being plotted. The timer object t" executes the function readAndPlotData periodically at a fixed rate of 0.1.
The last part of the code stops and deletes the timer object. This is necessary as it optimizes resource consumption.
Refer to the MathWorks documentation to know more about the functions used by typing “doc <functionName> in the command window.
Hope this helps.

Community Treasure Hunt

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

Start Hunting!