1

I am trying to communicate serially with an arduino which is sending me the results of polling an ADC channel, in the form of an ASCII string with the decimal result, which is normally appended with an EOT character ('\x04'). so typical results I might expect from PySerial are:

b'0\x04'

for the integer 0, or

b'293\x04'

for the integer 293, or even

b'1023\x04'

for the highest possible value, 1023.

On the PC side i'm running python 3.2 (on Windows 7).

I want to convert the received bytes from PySerial into an integer, so I can calculate with them.

How do I convert the byte array into an integer?

I am able to stop the arduino from sending the EOT character after the numerical value, but it is probably safer to leave them in.

I'm a beginner with Python, but not so much with C.

0

1 Answer 1

3

Strip the EOT character from the right side and feed the result to int

>>> int(b'1023\x04'.rstrip(b'\x04'))
1023
Sign up to request clarification or add additional context in comments.

1 Comment

Note: If the EOT is guaranteed, you can simplify to just chopping off the last character, int(b'1023\x04'[:-1]). rstrip is usually safer though (assuming there is no risk of multiple EOT characters where the presence of more than one might have some special meaning). Other fun approaches might include replacing with whitespace (int ignores leading and trailing whitespace already, sadly, EOT doesn't count as whitespace).

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.