【发布时间】: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