Last active
August 29, 2015 14:00
-
-
Save bulletmark/11126770 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import time, threading | |
import pifaceio | |
# Pressing a Piface board input pin starts a sequence of output pins + delays. | |
# Define output sequences here. Format is: | |
# in_pin: ((out_pin1, on_time), (out_pin2, on_time), [ .. ]) | |
# if out_pin = -1 then delay for on_time only. | |
# It's up to you to define/use output sequences that don't conflict. | |
# Input and output pins are numbered 0 to 7. | |
# Times are in seconds (and can be float, e.g. 0.1 sec). | |
sequences = { | |
0: ((0,4), (-1,2), (1,3), ), | |
1: ((2,4), (5,3), ), | |
} | |
# Global lock for threads | |
lock = threading.Lock() | |
# Fetch instance of and initialize PiFace board | |
pf = pifaceio.PiFace() | |
# Initialize all board pin outputs to 0 | |
pin_outputs = 0x0 | |
pf.write(pin_outputs) | |
# Currently active input pins | |
in_active = 0x0 | |
def send_output(in_pin): | |
'Runs in thread to drive output pins + delays for given input pin sequence' | |
global pin_outputs, in_active | |
for out_pin, delay in sequences[in_pin]: | |
# Set this output pin ON | |
if out_pin >= 0: | |
pin_mask = 1 << out_pin | |
with lock: | |
pin_outputs |= pin_mask | |
pf.write(pin_outputs) | |
time.sleep(delay) | |
# Set this output pin OFF | |
if out_pin >= 0: | |
with lock: | |
pin_outputs &= ~pin_mask | |
pf.write(pin_outputs) | |
with lock: | |
in_active &= ~(1 << in_pin) | |
# Forever .. | |
while True: | |
with lock: | |
inputs = pf.read() | |
# Iterate through all 8 inputs pins and start output thread if input on | |
for in_pin in range(8): | |
pin_mask = 1 << in_pin | |
if inputs & pin_mask and not (in_active & pin_mask) \ | |
and in_pin in sequences: | |
with lock: | |
in_active |= pin_mask | |
t = threading.Thread(target=send_output, args=[in_pin]) | |
t.daemon = True | |
t.start() | |
time.sleep(0.05) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment