![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/520707/image.png)
Simulink: 4 bytes to float
34 ビュー (過去 30 日間)
古いコメントを表示
Hello!
I am sending with a microcontroller a float value (i.e. 145.2322308) as 4 bytes over Serial. I get the data in Simulink with " Serial Receiver" but I don't know how to combine the 4 bytes I am receiving in one variable of 32 bits and be able to scope the value 145.2322308.
With each serial package I send three values [float , float , long \CR]. I have tried different approaches but I can only scope the value of the bytes:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/520327/image.png)
Thank you in advance for your help!
0 件のコメント
回答 (2 件)
Jonas
2021 年 2 月 16 日
編集済み: Jonas
2021 年 2 月 16 日
Another way is to construct your output manually with 'Shift Arithmetic' blocks and perform bitshifts:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/520707/image.png)
The input to the left you see is a vector of 4 bytes of type uint8.
Inside the MATLAB function is the following code, since no block exists to perform a typecast:
function single_value = typecast_int32_to_single(int32_value)
single_value = typecast(int32_value,'single');
3 件のコメント
Jonas
2021 年 2 月 16 日
@Walter Roberson Yes, also works! I tested and found that the swapbytes() was necessary as you mentioned.
So the MATLAB Function becomes:
function single_value = typecast_int32_to_single(uint8_buffer)
single_value = swapbytes(typecast(uint8_buffer,'single'));
I do find the generated code of my first suggestion a bit nicer:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/521237/image.png)
compared to the integrated MATLAB Function:
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/521242/image.png)
So personally I am going to keep using my implementation with the bitshifts because I generate code from it.
Jonas
2021 年 2 月 16 日
Use the Byte Unpack block and feed those 4 bytes into it after you have muxed them. Set Output port data type to {'single'} if you want to reconstruct a 32-bit float.
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Messages についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!