Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用PySerial发送ASCII命令_Python_Python 3.x_Serial Port_Hardware_Pyserial - Fatal编程技术网

Python 使用PySerial发送ASCII命令

Python 使用PySerial发送ASCII命令,python,python-3.x,serial-port,hardware,pyserial,Python,Python 3.x,Serial Port,Hardware,Pyserial,我正在尝试发送以下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.bau

我正在尝试发送以下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
回溯(最近一次呼叫最后一次):
,第31行,在
ser.write('open1\r\n')
,第283行,以书面形式
数据=到字节(数据)
文件“C:\Python34\lib\site packages\serial\serialutil.py”,第76行,以字节为单位
b、 append(item)#这个函数为我们的仿真处理int和str,为python3.x处理int
TypeError:需要一个整数
我不知道如何才能解决这个问题。close1只是我想发送的ASCII命令的一个示例。还有status1,用于查看我的锁是打开的还是关闭的,等等


提前感谢

出现此问题是因为Python 3在内部将其字符串存储为unicode,而Python 2.x则没有。PySerial希望获得
字节
字节数组
作为
写入
的参数。在Python2.x中,字符串类型适合这种情况,但在Python3.x中,字符串类型是Unicode,因此与pySerial
write
所需的内容不兼容

为了将pySerial与Python3一起使用,您需要使用。因此,您的代码应该如下所示:

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

谢谢你,效果很好。如果您不介意的话,还有一个问题1)我怎样才能打印出收到的结果,例如,如果我键入status1,它应该返回close1/open1,而另一个更简单的问题是if(ser.isOpen()==False):不完全检查端口是否打开,因为即使未连接任何东西,它也会绕过该行并尝试发送一个明显返回错误的命令thanks@Jon220,我建议你尝试一下,如果你卡住了,可以问一个新问题。