MATLAB Answers

0

int16 to uint8 array conversion for Serial Transmit

phil 님이 질문을 제출함. 26 May 2017
최근 활동 phil 님이 답변함. 26 May 2017
Hello there, I would like to take a int16 and split it into a uint8 array to transmit via serial connection (arduino).
Then i would like to reassemble the the two bytes to give me back my original int16. Any help would be appreciated :)

  댓글 수: 0

로그인 to comment.

답변 수: 3

Guillaume 님의 답변 26 May 2017
Guillaume 님이 편집함. 26 May 2017

exampleint16 = int16(12345);
sameasuint8 = typecast(exampleint16, 'uint8')
restoredint16 = typecast(sameasuint8, 'int16')
However, if all you want to do is transmit that int16. You could just fwrite it as is, and read it as an uint8:
%on the sender
fwrite(serialobj, yourint16, 'int16')
%on the reader
fread(serialobj, 2, 'uint8')

  댓글 수: 1

If you fwrite() the int16 then be sure to check the serial ByteOrder property.
If you split into uint8 using typecast() then you need to take care of the endian problems yourself. For this purpose you need to know that if you typecast a 16 bit quantity into uint8 then on all current implementations of MATLAB, the first byte of the result is the least significant byte.

로그인 to comment.


phil 님의 답변 26 May 2017
phil 님이 편집함. 26 May 2017

Your answer works fine in Matlab however in simulink i get port dimension errors. This is probably due to the fact that i could be varying size? any ideas how to cope?\

  댓글 수: 0

로그인 to comment.


phil 님의 답변 26 May 2017

Ok a little bit more resarch has turned out specifying data size in the model explorer works: :)

  댓글 수: 0

로그인 to comment.



Translated by