Skip to content

Instantly share code, notes, and snippets.

@marcozecchini
Last active December 3, 2018 12:42
Show Gist options
  • Save marcozecchini/2b974079443384951bac524c99193ca7 to your computer and use it in GitHub Desktop.
Save marcozecchini/2b974079443384951bac524c99193ca7 to your computer and use it in GitHub Desktop.
#!/usr/local/bin/python
#https://docs.python.org/2/library/multiprocessing.html
#https://www.geeksforgeeks.org/synchronization-pooling-processes-python/
import multiprocessing
import RPi.GPIO as GPIO
import os
import time
GPIO.setmode(GPIO.BCM)
#define the pins that goes to the circuit
photosensor_pin = 7
#process that always checks the state of the photosensor and eventually count
def runCounter(photosensor_pin, lock):
#setup gpios
GPIO.setup(photosensor_pin, GPIO.IN)
while True:
count_trigger = True
while (GPIO.input(photosensor_pin) == GPIO.HIGH):
continue
#count if needed
if (counter_trigger):
lock.adquire()
counter.value += 1
lock.release()
count_trigger = False
if __name__ == "__main__":
#Main process to interact with the program
try:
# initial counter (in shared memory)
counter = multiprocessing.Value('i', 0)
#lock to access counter shared variable
lock = multiprocessing.lock()
counterProcess = multiprocessing.Process(target=runCounter, args=(photosensor_pin, lock))
counterProcess.start()
# Main loop
while True:
cmd = input("Pass a command among \"Count\" \"Exit\"")
if (cmd == "Count"):
lock.adquire()
print("Counter value is {0}".format(counter.value))
lock.release()
if (cmd == "Exit"):
#TODO save the context
break
except KeyboardInterrupt:
pass
finally:
GPIO.cleanup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment