如何使用Python 3.3和pyserial向arduino发送5位数字(奇怪的错误)
作者:互联网
‘你好,
经过几个小时尝试不同的事情后,我有点迷失了.我已经包含了我的代码.我正在尝试为arduino获取5位数字,但是尝试发送数字范围时出现错误.我不是一个经验丰富的程序员,但是我已经放弃了使用arduino的很多经验.我可以毫无问题地从Arduino收到信息.
一段测试代码:
import serial
import time
import struct
ser = serial.Serial(
port='COM15',\
baudrate=9600,\
parity=serial.PARITY_NONE,\
stopbits=serial.STOPBITS_ONE,\
bytesize=serial.EIGHTBITS,\
timeout=0)
time.sleep(3)
print("connected to: " + ser.portstr)
#this will store the line
bline = []
while True:
ser.write(10128)
time.sleep(1)
ser.write(10000)
time.sleep(1)
ser.close()
错误:
connected to: COM15
Traceback (most recent call last):
File "C:/Users/Danny/Documents/arachnoid-0.5/testreceive.py", line 19, in <module>
ser.write(10128)
File "C:\Python33\lib\site-packages\serial\serialwin32.py", line 283, in write
data = to_bytes(data)
File "C:\Python33\lib\site-packages\serial\serialutil.py", line 75, in to_bytes
for item in seq:
TypeError: 'int' object is not iterable
>>>
解决方法:
由于串行通信是针对字节的,因此您需要将int转换为字节字符串.在python 3中,这需要进行编码.
我相信应该这样做:
ser.write(str(10128).encode())
标签:pyserial,serial-port,typeerror,python 来源: https://codeday.me/bug/20191122/2060381.html