0

I am recording voltage readings vs time. I want voltages below 10 into logfile1.txt and voltages above 10 into a second file, logfile2.txt. The following script writes the voltages below 10 into logfile1.txt okay but nothing into logfile2.txt for voltages above 10. The bottom section of my script is ignored. How can I get readings into the second log file?

    import sys, time, signal
    from time import time, sleep
    from Adafruit_ADS1x15 import ADS1x15

    ADS1115 =0x01
    adc = ADS1x15(ic=ADS1115)

    while True:
        with open('logfile1.txt', 'w') as f:
            while True:
                volts = adc.readADCDifferential01(256, 8)
                print volts
                sleep(1)
                if volts < 10:
                print >> f, time(), (volts)

        with open('logfile2.txt', 'w') as f:
            while True:
                volts = adc.readADCDifferential01(256, 8)
                print volts
                sleep(1)
                if volts > 10:
                     print >> f, time(), (volts)    
Rico
  • 329
  • 3
  • 9
  • 1
    The program has two infinite loops. The third while loop won't be hit? You should just use the logging package and add two file handlers to it. – Brian Pendleton Sep 05 '15 at 23:47
  • If you want to keep this program as is without logging, just open the two files in the first with block as done here http://stackoverflow.com/a/4617069/4080476 – Brian Pendleton Sep 05 '15 at 23:48
  • Thanks Brian, I will study your suggestion. – Rico Sep 06 '15 at 00:00

1 Answers1

3

The code involving your second log file is being ignored because the inner loop for the first log file never ends. To make your code write to both files, you'll need to combine the loops. You'll also be able to get rid of the outermost loop too:

with open('logfile1.txt', 'w') as f1, open('logfile2.txt', 'w') as f2:
    while True:
        volts = adc.readADCDifferential01(256, 8)
        print volts
        sleep(1)
        if volts < 10:
            print >> f1, time(), volts
        else: # volts >= 10
            print >> f2, time(), volts

Note that the logic for printing to the second file is slightly different than for your original code. I'm using an else which is equivalent to elif volts >= 10. If your original code had worked, a reading of exactly 10 volts would not have been logged at all, which I'm guessing was an oversight. If you want exactly 10 volt readings to go to the first file instead of the second, you can change the < 10 to <= 10.

Blckknght
  • 100,903
  • 11
  • 120
  • 169