Detect pin state on start, and allow to continue after script exit

半城伤御伤魂 提交于 2019-12-13 05:12:52

问题


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....

来源:https://stackoverflow.com/questions/28003977/detect-pin-state-on-start-and-allow-to-continue-after-script-exit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!