Jon*_*220 7 python hardware serial-port pyserial python-3.x
我正在尝试发送以下ASCII命令:close1
使用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')
Run Code Online (Sandbox Code Playgroud)
但结果我收到以下错误:
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
Run Code Online (Sandbox Code Playgroud)
不知道我怎么能解决这个问题.close1只是我要发送的ASCII命令的一个例子,还有status1来查看我的锁是打开还是关闭等.
提前致谢
出现此问题是因为 Python 3 在内部将其字符串存储为 unicode,但 Python 2.x 没有。PySerial 期望获得bytes或bytearray作为参数write。在 Python 2.x 中,字符串类型可以解决这个问题,但在 Python 3.x 中,字符串类型是 Unicode,因此与 pySerialwrite需要的不兼容。
为了将 pySerial 与 Python 3 一起使用,您需要使用bytearray。所以你的代码看起来需要像这样:
ser.write(b'open1\r\n')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15676 次 |
| 最近记录: |