user9064672
user9064672

Reputation:

Python, How to create 2 loops in one script so it works

I'm trying to make two loops in the same program but it only stays on the first loop and it doesn't go to the second loop... I'm trying to make the program write the temperature in a text file without overwriting itself... There's my program:

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(18,GPIO.OUT)

os.system('modprobe w1-gpio')                              
os.system('modprobe w1-therm')                                                 
base_dir = '/sys/bus/w1/devices/'                          
device_folder = glob.glob(base_dir + '28*')[0]             
device_file = device_folder + '/w1_slave'                 
def read_temp_raw():
   f = open(device_file, 'r')
   lines = f.readlines()                                   
   f.close()
   return lines

def read_temp():
   lines = read_temp_raw()
   while lines[0].strip()[-3:] != 'YES':                   
      time.sleep(0.2)
      lines = read_temp_raw()
   equals_pos = lines[1].find('t=')                        
   if equals_pos != -1:
      temp_string = lines[1][equals_pos+2:]
      temp_c = float(temp_string) / 1000.0                 
      return temp_c

while True:
   print(read_temp())                                      
   time.sleep(0.5)
   if read_temp() > 25:
      GPIO.output(18, True)
   else:
      GPIO.output(18, False)

while True:
   f = open("temperatureFile.txt", "w")
   f.write(read_temp())
   f.close

Upvotes: 0

Views: 63

Answers (2)

DZurico
DZurico

Reputation: 617

Your program will never exit the first while loop since there is no break statement anywhere in your code. I assume what you want to do is something like this

outfile = open("temperatureFile.txt", "a")
while True:
   temp=read_temp()
   print(temp)                                      
   time.sleep(0.5)
   if temp > 25:
      GPIO.output(18, True)
   else:
      GPIO.output(18, False)
   outfile.write(temp)
outfile.close()

Upvotes: 0

tehhowch
tehhowch

Reputation: 9862

Your first loop never exits. If you want to append the temperature to a file, you should add that call inside the first loop, and get rid of the second loop entirely.

while True:
  time.sleep(0.5)
  temp = read_temp()
  with open("temperatureFile.txt", "a") as f:
    f.write(temp)
  if temp > 25:
     GPIO.output(18, True)
  else:
     GPIO.output(18, False)

Note that your original code would have continually re-written the temperature file, not append to it, since you opened it in write mode.

A better idea may be to accumulate a number of temperatures into a list, and then after some longer time than 0.5s, batch-write those values. I'll leave that as an exercise to the reader.

Upvotes: 0

Related Questions