0

I have 12 bytes being sent over a web socket used to represent 3 float values. The other program does this:

float m_floatArray[3]; 
...
Serial.write((byte*) m_floatArray, 12); //12 b/c 3 floats at 4 bytes each

The data I receive in my python program looks like this:

#the data is printed from: received = ser.read(12)  
received = '\xe4C\x82\xbd-\xe4-\xbe&\x00\x12\xc0'

I want to essentially do this in my python program:

x = getFirstFloat(received)
y = getSecondFloat(received)
z = getThirdFloat(received)

How can I parse my data?

8
  • This is not c it's AFAIK a specialized language for arduino, similar to c++. Commented Jan 6, 2016 at 0:02
  • That's right, updated tags. Commented Jan 6, 2016 at 0:04
  • Don't hardcode the size, use sizeof(m_floatArray) instead of 12. Commented Jan 6, 2016 at 0:06
  • @iharob the code you're commenting on is obviously only for demonstration purposes, you should be concentrating on the Python part. Commented Jan 6, 2016 at 0:18
  • P.S. the answer is struct.unpack. Commented Jan 6, 2016 at 0:19

1 Answer 1

2

A short example:

>>> a,b,c = [random.random()*10 for i in range(3)]
>>> a
0.9446191909332258
>>> b
7.578277797297625
>>> c
8.061585451293366
>>> recieved = struct.pack('fff', a, b, c)
>>> recieved
'\x90\xd2q?@\x81\xf2@A\xfc\x00A'
>>> x,y,z = struct.unpack('fff', recieved)
>>> x
0.9446191787719727
>>> a
0.9446191909332258
>>> b
7.578277797297625
>>> y
7.578277587890625
>>> c
8.061585451293366
>>> z
8.061585426330566
>>>

Note that you may want to specify the byte order in the format string

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.