How to write integers to port using PySerial

TheDarkTurtle picture TheDarkTurtle · Jul 25, 2014 · Viewed 20.5k times · Source

I am trying to write data to the first serial port, COM1, using PySerial.

import serial
ser = serial.Serial(0)
print (ser.name)
ser.baudrate = 56700
ser.write("abcdefg")
ser.close()

ought to work. However, I need to send 28 bytes of integers constantly; in the form

255 255 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000

on loop, with each integer using one byte of data.

Trying:

import serial
ser = serial.Serial(0)
print (ser.name)
ser.baudrate = 56700
while True:
    ser.write(255 255 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000 000)
ser.close()

raises a Syntax Error.

How can you write integers to a serial port if write only sends strings? How can I ensure that each number is sent as 8-bits?

There is very little in the documentation for the class serial, so any help will be appreciated.

Answer

LtWorf picture LtWorf · Jul 25, 2014

First of all, writing 123 12 123 123 123 is not a valid Python syntax.

Create a list or a tuple with your integers: values = (1,2,3,4,5)

Now, we need to convert that data into a binary string that represents our values.

So here how we do it

import struct

values = (1,2,3,4,5)

string = b''

for i in values:
    string += struct.pack('!B',i)

# Now send the string to the serial port

Depending on how many bytes you want to use per number, you need to pack them differently. See the documentation here: https://docs.python.org/3/library/struct.html