Converting An Integer to a Byte (for PySerial, using Python25)

2.1k Views Asked by At

This seems like it should be simple, but I haven't been able to figure it out...

I'm trying to use PySerial to communicate with a microcontroller. I want to send an index location, but when I send it, it PySerial sends the ASCII of the number (so when I send a 0, it sends 48).

I know for Python26 and up, I would just enclose the number with the built-in bytes function like so:

self.index = bytes([index])

However, Python25 doesn't have that function. I can't find any documentation suggesting an equivalent. Does anybody know what I should do?

Thanks in advance!

EDIT: Sorry, here's a simplified version of my code...

class SecondaryImage():
    def __init__(self, index):
        self.index = index
    def sendIndex(self):
        serial.write(self.index)

for i in range(64):
    img = SecondaryImage(i)
    imgs.append(img)

And then I'd call sendIndex() seperately--

imgs[2].sendIndex()
3

There are 3 best solutions below

0
On BEST ANSWER

chr is built-in which will you the character for the ordinal you send.

0
On

Serial communicates in ascii, so you want to use chr to convert numbers to their ascii character equivalents.

0
On