“你好, 几个小时尝试了不同的事情,我有点不知所措。我已经包括了我的代码。我想给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中,需要对其进行编码。
我认为应该这样做:
您需要将字符串传递给
write
,而不是int
。如有必要,要获得5位始终带前导零的数字:
加法使其成为一个6位数字,
[-5:]
将结果的最后5位数字切掉。当然,这是一种老套的方法,我总是忘记如何使用format
来正确地完成它。相关问题 更多 >
编程相关推荐