Simulink Com serial communication how to send a hexadecimal command?

9 次查看(过去 30 天)
I want to send instructions (hex) to the serial port, I can use M-file code to achieve communication, but simulink is not successful. I think there is something wrong with the sending end, but I don't know how to solve it.
M code
simulink

采纳的回答

Suman
Suman 2024-6-19
编辑:Suman 2024-6-19
Hi Chi,
The error message indicates that the fread operation was not completed before the timeout.
You could go about fixing the issue in these two ways I can think of.
1) Specify the size of the data you want to read, fread(serial_obj,size). If you do not specify the size, it is going to try to read the data equal to the entire InputBufferSize, which is 512 bytes by default, and if that much data is not available it won't terminate the read and timeout is reached. You can refer to this documentation to learn how to specify the size of data to read and to set the InputBufferSize for the serial object, https://www.mathworks.com/help/matlab/ref/serial.fread.html?s_tid=doc_ta#f102-512480
2) Another approach you can take if you do not know the size of the data to be read is to read the data asynchronously. Here an example of how you can do it:
%Callback function to read data once a speficied chunck of data is
%available to read
function myCallbackFcn(obj, event)
data = fread(obj, obj.BytesAvailable, 'uint8');
end
clear all; close all;
s = serial('COM7', 'BaudRate', baudrate, 'InputBufferSize', 2000); % Set a large enough input buffer size
set(s, 'BytesAvailableFcnMode', 'byte');
set(s, 'BytesAvailableFcnCount', 1024); % Callback function will be triggered everytime this much data is available to read
set(s, 'BytesAvailableFcn', @myCallbackFcn); % Set the callback function
fopen(s);
Refer to this documentation if you would like to learn more about the serial object, https://www.mathworks.com/help/matlab/ref/serial-properties.html

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Modeling 的更多信息

产品


版本

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by