python - pi 到 arduino 串行通信上的名称错误

标签 python serial-port

嗨,我有以下代码,但不断收到此错误消息:

名称错误:名称“序列”未定义

我已经从许多教程中复制了这段代码,但它不起作用,有人可以告诉我为什么吗?

from serial import*
ser = serial.Serial('/dev/ttyACM0', 9600)

while 1:
    ser.readline()

最佳答案

当您以这种方式导入时:

from serial import *

您正在导入内容,就好像它们是在实际文件中声明的一样。来自 Python 文档:

This imports all names except those beginning with an underscore (_). Note that in general the practice of importing * from a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions.

所以你可以像这样调用Serial:

ser = Serial('/dev/ttyACM0', 9600)
<小时/>

如果您不想以这种方式导入它(您可能会在覆盖字段或已使用的标识符时遇到问题),您可以使用:

import serial

ser = serial.Serial('/dev/ttyACM0', 9600)

关于python - pi 到 arduino 串行通信上的名称错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21165896/

相关文章:

c# - 如何在关闭前等待串口清空

node.js - 使用 Node 串行读取串行端口

c# - C# 和 java write() 之间的区别

python - requirements.txt 中的安装时依赖项

python - 检查 self.__class__ 的目的是什么?

python - panda3d python 导入错误

serial-port - 树莓派 sim900 默认上网

python - 在 Python 中通过 os.system 在命令行上执行 MySQL 查询

Python:通过 SSH 隧道连接到 Azure PostgreSQL 实例

serial-port - Kubuntu 18.04 中的拨出组成员拒绝访问/dev/ttyUSB0