Question

I am very very new to Python and I could use your help. I made a small program that reads an analog signal from the serial port and dumps it into a file. However, even though the reading is very precise, sometimes it dumps unnecessary/undetermined characters into the file:

This is a dump from a 500 line file; check the 2nd value: 466 þ466 466 466

So, basically the problem is I have no idea how to filter this input from the readings. I've been reading a bit from the documentation in the regular expressions section, but I can't properly handle/manipulate the result. As you can see the "purifystring" function is very incomplete...

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;

So even though that may not be the best approach, I'm opened to suggestions. I am trying to make my output file to have a value per line ranging from 0 to 1023. The data I get from reading the serial is a string something like '812\n'.

Thanks in advance!

Was it helpful?

Solution

To make the job in a simple way (ie without regular expression ;) ) try this :

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())

this way, you will filter only the digits of the received data. (isdigit())

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top