Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run a part of code every 5 min independently of the other commands

I want to open, stay open for 6 seconds and close one relay every 5 minutes while the rest code running normally.

For example:

GPIO.output(18, 1)
sleep(6)
GPIO.output(18, 0)
sleep(300)

But without the rest program stacks in this delay. My Python code is:

import RPi.GPIO as GPIO
from time import sleep

GPIO.setmode(GPIO.BOARD)
GPIO.setup(13, GPIO.IN, GPIO.PUD_UP)
GPIO.setup(7,GPIO.OUT)
GPIO.setup(37, GPIO.OUT)
Hologram = '/home/pi/Hologram/Hologram.mp4'

from subprocess import Popen

firstTimeOpen=0

while True:

        doorIsOpen = GPIO.input(13)

        if doorIsOpen==0 and firstTimeOpen == 0:
                        firstTimeOpen=1
                        GPIO.output(7, 0)
                        GPIO.output(37, 0)
                        sleep(0.5)

        if doorIsOpen==1 and firstTimeOpen == 1:
                GPIO.output(7, 1)
                GPIO.output(37, 1)
                omxp = Popen(['omxplayer' ,Hologram])
                sleep(87)
                GPIO.output(7, 0)
                GPIO.output(37, 0)
                firstTimeOpen=0
                sleep(0.5)
like image 338
LockNTension Avatar asked Dec 05 '25 07:12

LockNTension


2 Answers

Threads offer a convenient way to do this. I normally create a threading.Thread subclass, whose run method is the code to be run in a separate thread. So you would want something like:

class BackgroundRunner(threading.thread):
    def run(self):
        while True:
            GPIO.output(18, 1)
            sleep(6)
            GPIO.output(18, 0)
            sleep(300)

Then, before you start running your main code, use

bg_runner = BackgroundRunner()
bg_runner.start()
like image 160
holdenweb Avatar answered Dec 07 '25 21:12

holdenweb


Apart from the suggested threading methods, you can also use an interrupt using the python signal module. Interrupts are cheaper than threads, which may be more appropriate on your chosen platform.

You can find more examples here: https://docs.python.org/2/library/signal.html

As an example:

import signal, os

def handler(signum, frame):
    print 'Signal handler called with signal', signum
    handler.counter += 1

    if not handler.counter % (300 / 6):
        GPIO.output(18, 0)
    else:
        GPIO.output(18, 1)

handler.counter = 0

signal.signal(signal.ITIMER_REAL, handler)
signal.setitimer(signal.ITIMER_REAL, 0, 6)
like image 20
Hans Then Avatar answered Dec 07 '25 22:12

Hans Then