使用PySeri发送ASCII命令

2024-04-29 07:49:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试发送以下ASCII命令: 关闭1

使用PySerial,下面是我的尝试:

import serial

#Using  pyserial Library to establish connection
#Global Variables
ser = 0

#Initialize Serial Port
def serial_connection():
    COMPORT = 3
    global ser
    ser = serial.Serial()
    ser.baudrate = 38400 
    ser.port = COMPORT - 1 #counter for port name starts at 0




    #check to see if port is open or closed
    if (ser.isOpen() == False):
        print ('The Port %d is Open '%COMPORT + ser.portstr)
          #timeout in seconds
        ser.timeout = 10
        ser.open()

    else:
        print ('The Port %d is closed' %COMPORT)


#call the serial_connection() function
serial_connection()
ser.write('open1\r\n')

但结果我收到了以下错误:

Traceback (most recent call last):
      , line 31, in <module>
        ser.write('open1\r\n')
      , line 283, in write
        data = to_bytes(data)
      File "C:\Python34\lib\site-packages\serial\serialutil.py", line 76, in to_bytes
        b.append(item)  # this one handles int and str for our emulation and ints for Python 3.x
    TypeError: an integer is required

不知道我怎么能解决这个问题。close1只是我想发送的ASCII命令的一个例子,还有status1来查看我的锁是打开的还是关闭的,等等

提前谢谢


Tags: toin命令forisportlineascii
1条回答
网友
1楼 · 发布于 2024-04-29 07:49:41

之所以会出现此问题,是因为Python3在内部将字符串存储为unicode,而Python2.x没有。PySerial期望得到一个bytesbytearray作为write的参数。在Python 2.x中,字符串类型可以满足这一要求,但在Python 3.x中,字符串类型是Unicode,因此与pySerialwrite需要的不兼容。

为了在Python 3中使用pySerial,需要使用bytearray。所以你的代码看起来应该是这样的:

ser.write(b'open1\r\n')

相关问题 更多 >