Code in Python locking in time (Running in Rasbian)

1

I made a code in python, but it hangs after a while running, can anyone help me to optimize it so it does not crash?

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import serial
import time

locations=['/dev/ttyACM0']

while 1:
        arquivo = open('temperaturaumidade.txt','r')
        conteudo = arquivo.readlines()



        for device in locations:  
                try:  
                        print "Trying...",device
                        arduino = serial.Serial(device, 9600) 
                        break
                except:  
                        print "Failed to connect on",device   

        try:
            time.sleep(1)
            conteudo.append(arduino.readline())
            print arduino.readline()
            conteudo.append('\n')
            arquivo = openarquivo = open('temperaturaumidade.txt','w')
            arquivo.writelines(conteudo)



        except:  
            print "Failed to read!" 

        arquivo.close()
    
asked by anonymous 30.08.2016 / 21:06

1 answer

0

Well, let's break it down. The main problem is that you are performing multiple file accesses at the same time, just like serial ports.

The serial port identification can be performed outside the while loop, as the port will not change.

As for the txt file, you do not need to read all the lines when you just want to add new content, you can open it in append mode, which adds new values to the end of the file.

An example of what the code looks like with some modifications:

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import serial
import time

locations=['/dev/ttyACM0']

# Identifica a porta serial e efetuando a conexao com o arduino
for device in locations:  
    try:  
         print "Trying...",device
         arduino = serial.Serial(device, 9600) 
         break
    except:  
        print "Failed to connect on",device
while 1:
    try:
        time.sleep(1)
        # note o modo a+
        arquivo = open('temperaturaumidade.txt','a+')
        valor = "%s\n"%(arduino.readline())
        print(valor)
        arquivo.write(valor)
    except:  
        print "Failed to write!" 
    arquivo.close() #Fecha o arquivo para que ele esteja disponivel para outros processos
    
10.03.2017 / 05:54