Page 1 of 1
int() doesn't seem to work.
Posted: Mon Sep 28, 2015 11:18 am
by cooper
Hi,
I have some code which reads in messages from the serial port and shoves it into a buffer:
Code: Select all
buffer = buffer[:-2]
br = buffer.split("=")[1]
brightness = int(br)
print(brightness)
Yet when I try to convert the string to an int, i get:
Code: Select all
ValueError: invalid syntax for integer with base 10: '0'
The thing is, when I type that code into REPL, substituting buffer with "br=057", it works fine...
I'm probably missing something very obvious here but I cant seem to figure it out, any help would be appreciated.
Thanks
Re: int() doesn't seem to work.
Posted: Mon Sep 28, 2015 12:28 pm
by pythoncoder
The serial port returns a bytes object, whereas when you type into the REPL you create a Unicode string. To replicate the behaviour of the serial port you need to do this:
Code: Select all
buffer =b"br=057" # Creates a bytes object
buffer = buffer.decode('UTF-8') # convert to string
buffer = buffer[:-2]
br = buffer.split("=")[1]
int(br)
Re: int() doesn't seem to work.
Posted: Mon Sep 28, 2015 12:56 pm
by cooper
Thank you for your reply, perhaps it would help if i pasted the entire section:
Code: Select all
while 1:
if rs485.any():
val = str(rs485.read(1).decode("ascii"))
if ord(val) == 0x02:
print(buffer)
if "br=" in buffer or "tr=" in buffer:
buffer = buffer[:-2]
br = buffer.split("=")[1]
brightness = int(br)
print(brightness)
buffer = ""
else:
buffer += val
I am decoding my bytes as ascii as opposed to unicode, I have even stuck in a print(type(buffer)) which returns
So it seems I am dealing with a string but my issue persists.
Re: int() doesn't seem to work.
Posted: Mon Sep 28, 2015 7:50 pm
by dhylands
buffer = buffer[:-2] strips the last 2 bytes off the line. Is that what you were intending?
Can you create a standalone example that doesn't need the UART to demonstrate the problem?
I tried this:
Code: Select all
>>> buffer = '05br=552'
>>> if "br=" in buffer or "tr=" in buffer:
... buffer = buffer[:-2]
... br = buffer.split("=")[1]
... brightness = int(br)
... print(brightness)
...
5
which seems to be what I would expect.
Re: int() doesn't seem to work.
Posted: Tue Sep 29, 2015 6:34 am
by cooper
Yes, the last two bytes are checksum bytes, which i dont intend to use at all.
The standalone stuff works perfectly fine, it is only when I use the data from the UART where it goes funny. Which is rather annoying as that is the only part holding back the demo!
Edit: OK, so I tried the same script on my PC with a USB to Serial converter and got this error:
Code: Select all
ValueError05br=100F6
: invalid literal for int() with base 10: '100\x03'
I had totally forgotten that there was an ETX byte in the string, which was causing me headache, as it was a non printable character it didn't show up.
Thank you for your assistance.