Matlab Simulink 串口通讯之float数据到字节数组(uint8)的相互转化

来源:互联网 发布:被网络诈骗报警有用吗 编辑:程序博客网 时间:2024/06/07 18:31

(1)数据类型与字节数组之间的相互转化

串口中直接传输的数据是字节数组ByteArray,也就是uint8型的数组。

一个float型的数据可由4个字节表示,double型的数据8个字节表示,等等每种类型的数据都有对应的字节数组表示。 

我们要实现的是将要传输的float型数据转化为对应的uint8数组,通过串口传输uint8数组。 将接收到的字节数组转化为对应的float型数据。

(2).m文件中的方法:使用MATLAB中的typecast方法

1.将字节数组转化为float型数据

MyByteArray = [1 2 3 4];MyByteArray = uint8(MyByteArray);MySingle = typecast(MyByteArray,'single');

2.将float型数据转化为对应的uint8数组,也就是字节数组。

MySingle=single(3.24);MyByteArray=typecast(MySingle,'uint8');

(3)Simulink中的方法:使用Simulink->MATLAB Function模块,在Matlab Function 模块中调用typecast函数,下面的例子将四个float型的数据转化为字节数组,加上数据的开始位,通过串口通讯发送到COM3。


Data Processing 函数:

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];
出现的问题:这个程序直接运行会出现很多问题:

问题原因是Output类型不匹配,需要在MATLAB Function模块中设置Output的Size为所需要的固定值。

方法:右键点击Function模块,选择Explore,设置输入的Size属性(默认为-1,对于这个函数ByteArray的Size应该为[1 18],Head的Size应该设置为[1 2])





这样,程序就运行成功了。