0

I'm working with a Raspberry Pi Pico using micropython and I need to send through serial port data from some sensors in and hexadecimal string.

For instance:

  • temp = 27.52
  • hum = 42
  • alt = 125.45
  • angle = 32.27

I tought of multiply the floats by 100 to eliminate the decimal point and the divided again by 100 in the server side, leaving me with:

  • temp = 2752
  • hum = 42
  • alt = 12545
  • angle = 3227

Then I'd like to serialize this between an hex code:

AA 08 26 {temp} {hum} {alt} {angle} 10 22 33

Then in the server side knowing what bytes correspond to every value I can parse the data. I need to do it in hexadecimal because this data is going to be sent through a satilital module and the manufacter asks for this format.

What's the best/pythonic/eficient way to do this?

Thanks in advance for any help you could offer.

Until now I've only been doing some tests but I don't know why I don't have the same result creating a bytearray of the "Payload" list than casting to hex every value of the list, I also don't know if there's a better way of doing this.

from machine import Pin

aceleracion = 15
angulo = 1970
temperatura = 26.57
temperatura_ant = 25.87
altura = 58.25
altura_ant = 60.27

Payload = []
hexPayload = []

Payload.append(aceleracion)
Payload.append(angulo)
Payload.append(int(temperatura*100))
Payload.append(int(temperatura_ant*100))
Payload.append(int(altura*100))
Payload.append(int(altura_ant*100))

for val in Payload:
    hexPayload.append(hex(val))

bytePayload = bytearray(Payload)

print(Payload)
print(hexPayload)
print(bytePayload)

This is what I get in the serial print.

[15, 1970, 2657, 2587, 5825, 6027]
['0xf', '0x7b2', '0xa61', '0xa1b', '0x16c1', '0x178b']
bytearray(b'\x0f\xb2a\x1b\xc1\x8b')
Fernando
  • 13
  • 3
  • The conversion to `bytearray` lost data - only the low byte of each element was kept, but all but one of your values require more than a single byte. (This appears to be a bug in micropython, regular Python would have given a "byte must be in range(0, 256)" error in this case.) – jasonharper Aug 22 '23 at 21:04

0 Answers0