Python/Arduino串口通信

标签 python serialization arduino

我们正在尝试从 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/

相关文章:

c++ - 相同代码在不同设备上的不同行为

Python 解析嵌套 XML 并扁平化数据

python - FTP服务器不使用套接字将数据发送到Python中的代理

python - 在列表上迭代函数,并附加返回值

python - Angular.js 中基于 OpenID 连接的身份验证与 (drf oidc) Django 休息框架后端

json - 在 JSON 中序列化和反序列化 Clojure::namespaced-keywords

security - 与不安全的设备通信 : Security by Abstraction Vs HTTP HTTPS callback

c - Bluez编程

python - 使用 python 的加密模块反序列化公钥

php - Magento session 在哪里序列化?