我们正在尝试从 Python 与 Arduino 进行通信,但在从 Python 写入串行端口时遇到问题
import serial
import time
ser = serial.Serial('/dev/ttyUSB0', 9600, timeout=1)
time.sleep(2)
user_input = 'L'
while user_input != 'q':
user_input = input('H = on, L = off, q = quit' )
byte_command = user_input.encode()
print(byte_command)
ser.writelines(byte_command) # This line gives us the error.
time.sleep(0.5) # wait 0.5 seconds
print('q entered. Exiting the program')
ser.close()
以下是我们收到的错误:
返回长度(数据) 类型错误:“int”类型的对象没有 len()
最佳答案
你的代码可以在我的电脑上运行。我认为您尝试使用的函数 (writelines
) 是不久前添加到 pyserial 中的,因此您可能正在运行过时的版本。
无论如何,据我所知,writelines
是从文件处理类继承的,您实际上不需要将它用于您想要执行的操作。事实上,我认为它甚至没有很好的记录
只需将其更改为:
ser.write(byte_command)
如果您愿意,您可以查看您拥有和/或更新的 pyserial 版本。
要检查您的版本,请运行:pip3 list | grep 序列号
如果您没有 3.4 版本,可以使用以下命令进行更新:pip3 install pyserial --upgrade
考虑 writelines
如何处理文件(例如,参见 here ),您的错误实际上可能与您拥有的核心 Python 有关(供您引用,我正在运行 Python 3.7.3) .
关于Python/Arduino串口通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56651673/