Search code examples
pythonpython-3.xsaveportlisten

Saving port 9600 datas in given time


I'm using Arduino and getting values from my shields and sensors. And also I send some of them to serial.println because of listening port 9600. I'm listening port 9600 and save these values to txt. After that I upload these values to database and use web services.

But I couldn't save the 9600 port in given time. Because if I didn't close the python application, it never close and never save txt file.

My code is below. I want to save txt for every 1 minutes.

How can I do it?

import serial
ser = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=1)
while 1:
    line = ser.readline()   # read a '\n' terminated line
    line2=line.decode("utf-8")
    ths = open("/Users/macproretina//Desktop/data.txt", "a")
    ths.write(line2)
ser.close()

Solution

  • You can use a simple timer to stop the loop. I cleaned up the resource management a bit, context managers are really useful.

    import threading
    from contextlib import closing
    import serial
    
    continue_looping = True
    def stopper():
        global continue_looping
        continue_looping = False
    
    timer = threading.Timer(60, stopper)
    timer.start()
    
    with open("/Users/macproretina/Desktop/data.txt", 'w') as out_file:
        with closing(serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=1)) as ser:
            while continue_looping:
                line = ser.readline()   # read a '\n' terminated line
                out_file.write(line.decode('utf-8')
                out_file.flush()
    

    It might be off a bit due to serial timeouts. Notice that you get the output written to the file if you call f.flush() in case you need that.