【问题标题】:filtering input from serial port data从串口数据过滤输入
【发布时间】:2011-11-12 19:24:46
【问题描述】:

我对 Python 非常陌生,我可以使用您的帮助。 我做了一个小程序,从串口读取模拟信号并将其转储到文件中。然而,即使读取非常精确,有时它也会将不必要/未确定的字符转储到文件中:

这是一个 500 行文件的转储;检查第二个值: 466 þ466 466 466

所以,基本上问题是我不知道如何从读数中过滤此输入。我一直在阅读正则表达式部分的文档,但我无法正确处理/操作结果。如您所见,“purifystring”功能非常不完整......

import serial
import re

#this is the pain...
def purifystring(string):

    regobj = re.match("^([0-9]+)$")
    result = regobj.find(string)

#start monitoring on ttyACM0 at 9600 baudrate
ser = serial.Serial('/dev/ttyACM0', 9600)

#the dump file
filename = 'output.txt'

#save data to file
f = open(filename, 'w')
counter = 0;
while counter < 500:

    analogvalue = ser.readline()

    #need to clean the input before writing to file...
    #purifystring(analogvalue)

    #output to console (debug)
    f.write(analogvalue)

    counter += 1

f.close()

print 'Written '+ str(counter)+' lines to '+filename;

因此,即使这可能不是最好的方法,我也愿意接受建议。我试图让我的输出文件每行的值从 0 到 1023。我从读取序列中获得的数据是一个类似于 '812\n' 的字符串。

提前致谢!

【问题讨论】:

    标签: python regex serial-port input-filtering


    【解决方案1】:

    要以简单的方式完成工作(即没有正则表达式;))试试这个:

    def purifystring(string_to_analyze):    # string is a really bad variable name as it is a python module's name
       return "".join(digit for digit in string_to_analyze if digit.isdigit())
    

    这样,您将只过滤接收到的数据的数字。 (isdigit())

    【讨论】:

    • 谢谢!这削减了我的要求。但是,如果您不介意,我想进一步分解一下:根据我阅读的内容,您遍历输入的每个数字并将其与 isdigit() 进行匹配,然后将结果与“自身”连接' 正确的?另一方面,我忘了提及,我不能只返回有效数字,因为它必须是有效的“结果”。更准确地说:我将从这些数据中生成一个图表,所以在尝试了你所说的(有效)之后,我发现了一些损坏的数据值,如 778、778、7780、778(检查 3),这可能是由过滤错误的输入,比如 778、77ª8、778?
    • @Tobias :当我在“77ª8”上尝试 isdigit() 循环时,我得到 778,而不是 7780,它应该是别的东西,但是如果检测到错误的输入会更加困难它们也是由数字组成的......
    猜你喜欢
    • 2020-03-30
    • 2013-02-02
    • 2020-03-07
    • 2015-06-24
    • 2015-11-16
    • 2017-09-10
    • 2019-07-24
    • 2014-02-23
    • 1970-01-01
    相关资源
    最近更新 更多