过滤串口数据输入

2 投票
1 回答
2304 浏览
提问于 2025-04-17 06:10

我刚开始学习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'这样的字符串。

谢谢大家的帮助!

1 个回答

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()的方法。

撰写回答