0

I am trying to have a script which I trigger via cron to turn a pin low and high based on a temperature, however.. I have having a couple of problems.

1 - When the script starts and it setsup the GPIO pin, it will either pull the pin high or low (depending on paramater) - there doesn't appear to be a way to tell it not to change the current state of the pin.

This is a problem because if the relay is high and the default state is low then the relay will be set low and then could change to high again very quickly after - doing this every minute is pretty hard on what the pin is controlling (same applies if the default state is high).

2 - When the script exits it cleans up the GPIO pins and changes the state of my pin. Ideally if the script turns the pin high then when it exits I want the pin to remain high. If I remove the cleanup function then the next time the script runs it says that the pin was already in use (problem?).

So the script which runs every minute looks like this.

#!/usr/bin/python
import RPi.GPIO as GPIO
import time
import random
from temp import Temp # custom object to handle the temp sensor.

def main():
    random.seed()
    GPIO.setmode(GPIO.BCM)

    PUMP_ON_TEMP = 38
    PUMP_OFF_TEMP = 30
    GPIO_PIN = 18

    try:
        t = Temp('28-00000168c492')
        GPIO.setup(GPIO_PIN, GPIO.OUT)

        current_temp = t.getTemp()
        print current_temp

        if current_temp > PUMP_ON_TEMP:
            GPIO.output(GPIO_PIN,  1)
            print "Turning the pump on! %s" % current_temp

        if current_temp < PUMP_OFF_TEMP:
                GPIO.output(GPIO_PIN,  0)
                print "Turning the pump off! %s" % current_temp

    except KeyboardInterrupt:
        pass
    finally:
        GPIO.cleanup()

if __name__ == '__main__':
    main()

This run every minute via cron. I don't want to use a loop.

I have tried to read the pin as an input first to get current hight/low state but that throws an error saying the pin needs to be setup first....

Wizzard
  • 12,582
  • 22
  • 68
  • 101
  • `I don't want to use a loop.` Why? Wouldn't that be the easiest option? – matsjoyce Jan 17 '15 at 20:46
  • @matsjoyce - If the script dies (eg fails to read the temp sensor) then I would need a monitoring script to restart my script. It also means I lose the ability to control the script via cron. For example I might just want this to run 10am to 4pm each day, so very easy to do via the cron system etc etc. – Wizzard Jan 17 '15 at 20:55
  • I am using gpiozero to control devices and have a similar issue. There is a parameter for creating the object: initial_state=None which doesn't reset an output just because you've created a reference. But it always seems to reset the value on script exit. Not useful. What's worse, when I run the script again, it knows the state I left it in, and puts the pin back to that state (as long as the script is running). – RufusVS Dec 04 '18 at 16:56

0 Answers0