【问题标题】:Sending ASCII Command using PySerial使用 PySerial 发送 ASCII 命令
【发布时间】:2015-07-02 22:43:38
【问题描述】:

我正在尝试发送以下 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 来查看我的锁是打开还是关闭等。

提前致谢

【问题讨论】:

    标签: python python-3.x serial-port hardware pyserial


    【解决方案1】:

    出现此问题是因为 Python 3 在内部将其字符串存储为 unicode,但 Python 2.x 没有。 PySerial 期望获得bytesbytearray 作为write 的参数。在 Python 2.x 中,字符串类型对此很好,但在 Python 3.x 中,字符串类型是 Unicode,因此与 pySerial write 需要的不兼容。

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

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

    【讨论】:

    • 谢谢你做得很好。如果您不介意,还有一个问题 1) 我如何能够打印出收到的结果,例如如果我键入 status1 它应该返回 close1/open1 而另一个更简单的问题是 if ( ser.isOpen() == False): 不完全检查端口是否打开,因为即使没有任何连接,它也会绕过该行并尝试发送一个显然返回错误的命令,谢谢
    • @Jon220,我建议您尝试一下,如果遇到困难,请提出一个新问题。
    猜你喜欢
    • 2021-11-14
    • 1970-01-01
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 2018-12-31
    • 2021-04-30
    • 2014-01-07
    • 1970-01-01
    相关资源
    最近更新 更多