Borrar filtros
Borrar filtros

Read a split integer in matlab sent over TCP?

1 visualización (últimos 30 días)
Ronan
Ronan el 19 de Mayo de 2015
Comentada: Ronan el 19 de Mayo de 2015
So i m sending an integer over tcp using arduinos Serial.write() function. This function can only write 1 byte at a time meaning you have to split an integer into 2 bytes . I had been doing this successfully before using I2C with the code
first_part = (byte) (testInt & 0xFF);
second_part = (byte) ((testInt >> 8) & 0xFF);
where testInt is the integer. However when i send the two bytes over wifi to matlab, when i try read them, it fails and i get this weird symbol ‡. So when the two bytes become available in matlab i tried reading as a byte eg fscanf(t, '%x',1). I also tried reading as a character but this didnt work?

Respuesta aceptada

Guillaume
Guillaume el 19 de Mayo de 2015
Editada: Guillaume el 19 de Mayo de 2015
Whereas before you were sending the integer encoded as a string, you're now sending the integer bytes. It's a different function to send, and thus a different function to read. You want to use fread:
t.ByteOrder = littleEndian; %see comment below
value = fread(t, 1, 'uint16') %assuming your integer is unsigned. Otherwise use 'int16'.
Make sure that the ByteOrder property of your connection is set correctly for the order you send the bytes in. If you send first_part first, then you're using littleEndian. Otherwise, you're using bigEndian.
My example assumes an unsigned 16-bit (2-bytes) integer, that is it's in the range 0-65535. If your integer is actually signed (in the range [-32678, +32767]), then use 'int16'.
  1 comentario
Ronan
Ronan el 19 de Mayo de 2015
Ha, so you recognise its me again. The previous way, sending characters was working fine but the reason i m switching to this way is because its more efficient and faster to have less bytes transmitted rather than having all those extra bytes for characters. Its also a good learning exercise to know multiple ways of doing things. This worked great. Thank you very much for your help.

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Más información sobre MATLAB Support Package for Arduino Hardware en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by