This experiment involves reading data from the COM2 port of a computer and saving it into a text file for further analysis. Below is the MATLAB script used for this purpose:
%Name: Matlab serial port - Lab1
% Description: Reading from and writing to a serial port, saving data to a TXT file
s = serial('com2');
s.BytesAvailableFcnMode = 'byte'; % Set the byte-based function mode
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 in three-bit format
fid = fopen('serial_data.txt', 'w+'); % Open the 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 functionality, but written with a more standardized approach using functions. The code is as follows:% Function to open a 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 the serial port
function WriteSerial(scom, str)
fprintf(scom, str, 'async'); % Send data asynchronously
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 virtual serial ports 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.
Now, send data to COM2:
>> WriteSerial(scom, 'Hello!');
Automotive Connector,Jack Socket Z Female Connector,Hsd Connector Automotive,Fakra Coaxial Connector
Changzhou Kingsun New Energy Technology Co., Ltd. , https://www.aioconn.com