Introduction
This post presents code that shows thread coding techniques that is useful for asynchronous processing.
The application is a motion detection program. When motion is detected an alarm will be triggered. Thread processing is used to call the function that runs the loop that lets the alarm run while waiting for the correct amount of time to elapse. When the time expires the loop stops, the alarm goes silent and the thread ends. This process runs asynchronously while the program itself continues monitoring for movement.
Variables
The variables shown here that is used by related logic are treated as global variables.
The variable alarmStartTime holds the time at which the alarm was started and will be compared against the current time to determine when the alarm has sounded for the predetermined amount of time.
As long as the thread is running it will not be allowed to be called again. the variable that governs this state is relayThreadState.
alarmStartTime = None
relayThreadState = None
Starting a Thread
The logic below is embedded in the main function that is responsible for detecting movement. This piece of code is responsible for turning on the alarm the logic for which is on a timer of sorts. That logic is in the function, ‘relayThread’, which is the process that is to run on a separate processing thread.
#Turn on relay to sound alarm.
if(relayThreadState == None):
relayThreadState = "started"
print "Turning on relay"
GPIO.output(RELAY, GPIO.HIGH)
#Start relay timer. This is a thread.
t = threading.Thread(target=relayThread)
t.start()
THis is the function “relayThread”. It will fall into a loop that executes for a period of time. After the time expires the loop ends and the thread ends. Meanwhile, the main process that launched this thread continues processing without interruption.
def relayThread():
global alarmStartTime
global relayThreadState
secondsToBeActive = 15
#Determine elapsed time
if(alarmStartTime == None):
alarmStartTime = time.time()
monitorElapsedTime = True
while(monitorElapsedTime):
elapsedTime = time.time() - alarmStartTime
#print "Elapsed time " + str(elapsedTime)
if(elapsedTime >= secondsToBeActive):
print("Alarm has been running for " + str(elapsedTime) + " seconds. Turning off relay")
GPIO.output(RELAY, GPIO.LOW)
alarmStartTime = None
monitorElapsedTime = False
relayThreadState = None
Summary
This post presented simple thread logic used to govern the start of an alarm for a motion detection program. It showed the use of global variables and the function that is launched as a thread.
Recent Comments