Simulink Com serial communication how to send a hexadecimal command?
7 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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
0 Kommentare
Akzeptierte Antwort
Suman
am 19 Jun. 2024
Bearbeitet: Suman
am 19 Jun. 2024
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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Simulink Environment Customization finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!