I have a python script running in the background 24/7 on a Raspberry Pi. It waits for a GPIO input (IR sensor high for 10s) and triggers a GPIO output (SMS trigger to a router). It uses a locked thread, to avoid multiple threads overlapping. Works fine.
I would like to turn on/off a different GPIO pin (mains relay) from the command line. As the input to the background script might occur randomly, can I assume that the OS takes care that in such a case the two scripts don't interfere? I have checked this post
Control GPIO pin from multiple python scripts using RPi.GPIO
from which I would indeed assume that as long as GPIO commands are not conflicting it should be ok.
Here is the code, though I believe it to be irrelevant, as the question is how the OS does multithreading. Apparently everything works fine, but I cannot test for every possible time overlap of the two scripts.
background script
from subprocess import call
from gpiozero import Button
from signal import pause
from datetime import datetime
import RPi.GPIO as gpio
import threading
import time
TIMEOUT=60 # wait 60s before triggering another SMS
ok_time=0 # define global variable ok_time
lock = threading.Lock() # define global variable lock between threads
with lock:
ok_time = time.time() # read time
def trigger_SMS():
global lock, ok_time
with lock:
thr_ok_time = ok_time
if time.time() > thr_ok_time: # first time thru true
with lock: # read shared global with lock
ok_time = time.time() + TIMEOUT # thereafter if is true after TIMEOUT
gpio.output(23,1) # raise output to router interface
rout_time = time.time() # reads time
while(time.time() < (rout_time+1)):
pass # 1 s pulse, sleep() suspends thread
gpio.output(23,0)
sms_log = open('/home/gander/goslings/sms_log.txt','a')
smstriggertime = datetime.now()
dt_string = smstriggertime.strftime("%d/%m/%Y %H:%M:%S")
sms_log.write(dt_string)
sms_log.write('\n')
sms_log.close() # else does nothing, TIMEOUT not elapsed
gpio.setmode(gpio.BCM) # standard pin numbering
gpio.setup(17, gpio.IN) # pin 17 input from optocoupler, (board pin 11)
gpio.setup(23, gpio.OUT, initial=0) # pin 23 output to router, (board pin 16)
alarm_signal = Button(17, hold_time=2)
alarm_signal.when_held = trigger_SMS # when sensor line held, trigger SMS
pause() # suspends processing of the calling thread
shell script
import RPi.GPIO as gpio
gpio.setmode(gpio.BCM) # standard pin numbering
gpio.setup(24, gpio.OUT, initial=0) # pin 24 output to relay, (board pin 18)
gpio.output(24,1) # raise output to relay
print "POWER ON"
Thanks (and apologies if the above appears dumb to multitasking experts).
Pierre