我有一个 Arduino 连接了 2 个 DS18B20
温度传感器。我对 python 非常(非常)陌生。我正在寻找一种方法来读取串行输入并将其解析为 sqlite 数据库,但这超出了我自己的范围。为什么在尝试将串行端口定义为变量时出现错误?
首先是 sys.version
2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)]
我目前,只是从串行连接程序读取输入。
from serial import serial
import time
# open serial port
ser = serial.Serial('/dev/tty.usbmodem621',9600,timeout=2)
ser.open()
while True:
print('dev 0' + ser.read())
pass
ser.close()
我目前无法编译它。我为这个错误找到的大多数结果都告诉我添加 from serial import serial
,但在这种情况下它没有用。
错误。
$ python ser.py
Traceback (most recent call last):
File "ser.py", line 1, in <module>
from serial import serial
File "/Users/frankwiebenga/serial.py", line 8, in <module>
AttributeError: 'module' object has no attribute 'Serial'
另外,如果我只使用import serial
,我也会得到同样的错误
$ python ser.py
Traceback (most recent call last):
File "ser.py", line 1, in <module>
import serial
File "/Users/frankwiebenga/serial.py", line 8, in <module>
AttributeError: 'module' object has no attribute 'Serial'
此外,根据评论。创建了名为 something.py
的新文件,无论使用 import serial
还是 from serial import serial
仍然会出现相同的错误。
$ python something.py
Traceback (most recent call last):
File "something.py", line 1, in <module>
from serial import serial
ImportError: No module named serial
当运行我的 bash 脚本时,我得到了一个有效的输出,所以我知道它不是 Arduino 代码。
输出:
Requesting temperatures...DONE
Device 0: 25.62
Device 1: 25.75
Requesting temperatures...DONE
Device 0: 25.62
Device 1: 25.81
重击:
while true # loop forever
do
inputline="" # clear input
# Loop until we get a valid reading from AVR
until inputline=$(echo $inputline | grep -e "^temp: ")
do
inputline=$(head -n 1 < /dev/tty.usbmodem621)
done
echo "$inputline"
done
最佳答案
您需要使用import serial
。 serial
是模块的名称,它不包含名为 serial
的属性。
http://pyserial.sourceforge.net/shortintro.html#opening-serial-ports
关于python从arduino读取串行输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12117669/