- Open a serial port:
Real-time serial data conversion to ASCII data
32 次查看（过去 30 天）
We were planning to convert the data receiving from serial port to ASCII format and to save the data in .csv format.
Have tried with s-function builder, num2str(Converting only a single data)etc., unable to convert the data in run-time.
Trying to convert the serial output data as the simulink display does.
Any conversion method or an idea to proceed, would be greatly appreciated.
Thanks in advance.
Suman Sahu 2023-2-9
In MATLAB, you can perform real-time serial data conversion to ASCII data using the Serial Communication Toolbox. With this toolbox, you can read data from a serial port and convert it into ASCII characters.
Please refer below steps and code for example.
% Use the "serial" function to open a serial port. You need to specify the port name and baud rate.
s = serial("COM1", 9600);
2. Configure the serial port:
%Use the "set" function to configure the serial port properties, such as the data format and the number of data bits.
set(s, 'DataBits', 8);
set(s, 'StopBits', 1);
set(s, 'Parity', 'none');
3. Read serial data:
%Use the "fread" function to read data from the serial port. The function returns the data as a binary array, which you need to convert to ASCII.
data = fread(s, s.BytesAvailable);
ascii_data = char(data);
4. Close the serial port:
%Use the "fclose" function to close the serial port when you are done with it.
Note that you may also need to configure the data transmission settings on the device that is sending the serial data, such as the baud rate and data format. Refer the following link for more info: Configure Serial Port Communication Settings - MATLAB & Simulink