使用 Arduino 的 Python 脚本无法正确读取数据

标签 python arduino pyserial temperature

我的 Python 脚本有问题。它正在工作,但有些问题。我是 Python 新手,所以我找不到任何解决方案:(

我的脚本通过 pySerial 连接到 Arduino 板,并读取温度数据。连接正常,但终端中显示的数据或保存在 TXT 文件(使用 Cron)中的数据是错误的:

2013-03-16 13:40:01 166.8
2013-03-16 13:41:02 1617.

它应该在哪里:

2013-03-16 13:40:01 16.68
2013-03-16 13:41:02 16.17

我的Python脚本:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# pytemp.py

import serial
import time

ser = serial.Serial('/dev/ttyACM0',9600, timeout=10)
read = ser.read(5)
comp = read.split()
ser.close();
print time.strftime("%Y-%m-%d %H:%M:%S"), comp[0]

我正在使用Python3.3和pySerial 2.6。在原始版本中有:

read = ser.readline(eol=/r)

但据我所知,在 2.5+ eol 命令中不再起作用。我不知道如何编辑我的脚本以始终正确地打印数据。

最佳答案

根据documentation ,使用Python 2.6以上版本时确实不再支持eol参数。

请忽略我之前使用 FileLike 的建议。这也没有在 python 2.6+ 中使用!

如何处理数据取决于数据的外观。由于您没有给我们提供原始数据的示例,我将使用 this page 中的格式。举个例子。

上述示例中数据的格式为:

t: 2012.11.18 19:39:03 50A93957 +024.50 0189
t: 2012.11.18 19:39:13 50A93961 +024.50 0189
t: 2012.11.18 19:39:23 50A9396B +024.50 0188

每一行都有以下列:

  • 日期和时间
  • 十六进制原始日期和时间
  • 温度值(摄氏度)
  • 原始温度值(十六进制)

您会注意到每个测量值都以“t:”开头,并且有六个由空格分隔的项目。因此,在这种情况下,我将运行一个如下所示的循环:

import serial
import time

buffer = bytes()
ser = serial.Serial('/dev/ttyACM0',9600, timeout=10)
while buffer.count('t:') < 2:
    buffer += ser.read(30)
ser.close();
# Now we have at least one complete datum. Isolate it.
start = buffer.index('t:')
end = buffer.index('t:', start+1)
items = buffer[start:end].strip().split()
print items[1], items[2], items[4]

举个例子。请注意,您可能会从一行数据的中间开始读取。您不能假设您从一行的开头开始阅读。

In [23]: buffer = '39:03 50A9\r\nt: 2012.11.18 19:39:13 50A93961 +024.50 0189\r\nt: 2012.11.18 19:39:23 50A9396B +024.50 0188'

让我们检查一下我们能找到多少个“t:”。 (您也可以搜索“\r\n”。重要的是您有一些东西可以用来分隔行)

In [24]: buffer.count('t:')
Out[24]: 2

由于我们有两个分隔符,因此我们至少有一个数据点。让我们隔离完整的数据点。

In [25]: buffer.index('t:')
Out[25]: 12

In [26]: buffer.index('t:', 12+1)
Out[26]: 58

这就是我们希望看到的。完整的数据点:

In [27]: buffer[12:58+1].strip().split()
Out[27]: ['t:', '2012.11.18', '19:39:13', '50A93961', '+024.50', '0189', 't']

In [28]: items = buffer[12:59].strip().split()

In [29]: print items[1], items[2], items[4]
2012.11.18 19:39:13 +024.50

关于使用 Arduino 的 Python 脚本无法正确读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15458577/

相关文章:

python - 从 python 3 中的用户输入中计算二元组?

python - 无法通过 RFCOMM 连接到设备,因为 'Resource Busy'

python - 如何从串口完全读取数据?

python - 我是否正确使用 ctypes 来 pythonify 这个结构?

Python - 当 url 可能被重写时确定正确的基本 url

python - 找不到文件错误python

c# - 通过C#从Arduino读取串行数据

xcode - 设置 Xcode 以使用 Arduino

c - Arduino 远程控制 socket 的问题

python - 当我在 Python 中刷新串行缓冲区时,它停止读取