How to write integers to port using PySerial

99封情书 提交于 2021-02-07 12:48:31

问题


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.


回答1:


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




回答2:


I never used pySerial, but looking at the documentations it says, you can also send bytes. So please have a look at: https://docs.python.org/3.1/library/functions.html#bytes




回答3:


The idiom I often use for this purpose (making a string from list of byte values) is:

''.join(map(chr,values))

and if you literally started out with a space delimited list of numbers, you can go a little crazy and use:

''.join(map(chr,map(int,values_string.strip().split())))

You can probably guess I like map. It's even more fun with lambda functions!



来源:https://stackoverflow.com/questions/24956308/how-to-write-integers-to-port-using-pyserial

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!