In this experiment, data is read from the COM2 port of the computer and saved into a text file for further analysis. Here is the MATLAB script used for this purpose:
%Name: Matlab serial port - Lab1
% Description: Read from serial port and write to txt file
s = serial('com2');
s.BytesAvailableFcnMode = 'byte'; % Set serial port settings
s.InputBufferSize = 4096;
s.OutputBufferSize = 1024;
s.BytesAvailableFcnCount = 100;
s.ReadAsyncMode = 'continuous';
s.Terminator = 'CR';
fopen(s); % Open the serial port
out = fread(s, 10, 'uint8'); % Read 10 characters at a time
fprintf('%3c', out); % Output one character with three-bit format
fid = fopen('serial_data.txt', 'w+'); % Open file in read-write mode
fprintf(fid, '%3c', out); % Write the data to the file
fclose(fid);
fclose(s);
delete(s);
2. Experiment 2: Same function, written in a more standardized way using functions. The code is as follows:% Function to open serial port
function scom = OpenSerial(sname, HReadFcn)
scom = serial(sname);
scom.BytesAvailableFcnMode = 'terminator';
scom.Terminator = '. ';
scom.BytesAvailableFcn = HReadFcn;
try
fopen(scom);
catch
fprintf('%s failed to open.\n', sname);
end
fprintf('%s successfully opened.\n', sname);
end
% Function to write to serial port
function WriteSerial(scom, str)
fprintf(scom, str, 'async'); % Asynchronous mode
end
% Callback function for reading data
function ReadFcn_Com2(obj, ~)
n = get(obj, 'BytesAvailable');
if n > 0
a = fread(obj, n, 'uchar');
c = char(a');
fprintf('%s', c);
end
end
% Function to close the serial port
function CloseSerial(scom)
try
fclose(scom);
catch
fprintf('%s shutdown failed.\n', scom.Name);
return
end
delete(scom);
end
The simulation uses a virtual serial port to connect COM2 and COM3. The serial port debugging assistant is opened by default on COM3.
In the MATLAB command window, enter the following command to open COM2:
>> scom = OpenSerial('com2', @ReadFcn_Com2);
Com2 opened successfully.
Writing to COM2:
>> WriteSerial(scom, 'Hello!');
Rf Coaxial Connector,Female Smb Coaxial Connector,Mcx Coaxial Cable Connector,Mcx Coaxial Connector
Changzhou Kingsun New Energy Technology Co., Ltd. , https://www.aioconn.com