(1) Conversion between data type and byte array
The data transmitted directly in the string is a byte array bytearray, which is an array of type uint8.
The data of a float type can be represented by 4 bytes, the data of type Double is 8 bytes, and so on, each type of data has a corresponding byte array representation.
What we want to achieve is to convert the float type data to the corresponding uint8 array, and transmit the uint8 array through the serial port. Converts the received byte array to the corresponding float type data.
(2) method in. m file: Using the Typecast method in MATLAB
1. Converting a byte array to float type data
Mybytearray = [1 2 3 4];
Mybytearray = Uint8 (Mybytearray);
Mysingle = Typecast (Mybytearray, ' single ');
2. Convert the float data to the corresponding Uint8 array, which is the byte array.
Mysingle=single (3.24);
Mybytearray=typecast (Mysingle, ' uint8 ');
(3) Methods in Simulink: Using the Simulink->matlab function module, call typecast functions in the MATLAB function module, the following example converts four types of float data into byte arrays, Plus the beginning of the data, through the serial communication sent to the COM3.
Data processing function:
function ByteArray = dataprocessing (head,velocity,x,y,angular_velocity)
head=uint8 (Head);
Velocity=single (Velocity);
X=single (X);
Y=single (Y);
Angular_velocity=single (angular_velocity);
Mybytearray1=typecast (Velocity, ' uint8 ');
Mybytearray2=typecast (X, ' uint8 ');
Mybytearray3=typecast (Y, ' uint8 ');
Mybytearray4=typecast (angular_velocity, ' uint8 ');
ByteArray = [Head MyByteArray1 MyByteArray2 MyByteArray3 MyByteArray4];
Problem: There are a lot of problems with this program running directly:
The problem is that the output type does not match and you need to set the output size to the desired fixed value in the MATLAB function module.
Method: Right click on function module, select Explore, set Input Size property (default is-1, for this function ByteArray size should be [1 18],head size should be set to [1 2])
In this way, the program runs successfully.