71 lines
2.7 KiB
Python
71 lines
2.7 KiB
Python
|
import pifacedigitalio
|
||
|
import time
|
||
|
|
||
|
button_count = 8
|
||
|
longpress_delay = 0.4
|
||
|
verylongpress_delay = 2
|
||
|
shortpress_count_max_delay = 0.5
|
||
|
inter_press_max_delay = 1
|
||
|
pin_last_rise_date = [0]*button_count
|
||
|
pin_last_shortpress = [0]*button_count
|
||
|
pin_shortpress_count = [0]*button_count
|
||
|
pifacedigital = pifacedigitalio.PiFaceDigital()
|
||
|
|
||
|
def switch_pressed(event):
|
||
|
pin_last_rise_date[event.pin_num] = 0
|
||
|
time.sleep(0.02)
|
||
|
if pifacedigitalio.digital_read(event.pin_num) != 0:
|
||
|
pin_last_rise_date[event.pin_num] = time.time()
|
||
|
|
||
|
def switch_unpressed(event):
|
||
|
if pin_last_rise_date[event.pin_num] != 0:
|
||
|
press_time = time.time() - pin_last_rise_date[event.pin_num]
|
||
|
if press_time < longpress_delay:
|
||
|
switch_shortpressed(event)
|
||
|
elif longpress_delay <= press_time and press_time < verylongpress_delay:
|
||
|
switch_longpressed(event)
|
||
|
else:
|
||
|
switch_verylongpressed(event)
|
||
|
pin_last_rise_date[event.pin_num] = 0
|
||
|
|
||
|
def switch_longpressed(event):
|
||
|
shortpress_delay = pin_last_rise_date[event.pin_num] - pin_last_shortpress[event.pin_num]
|
||
|
if shortpress_delay > inter_press_max_delay:
|
||
|
pin_shortpress_count[event.pin_num] = 0
|
||
|
elif pin_shortpress_count[event.pin_num] == 1:
|
||
|
event.chip.output_pins[event.pin_num].toggle()
|
||
|
elif pin_shortpress_count[event.pin_num] == 2:
|
||
|
for i in range(button_count):
|
||
|
event.chip.output_pins[i].turn_on()
|
||
|
|
||
|
def switch_verylongpressed(event):
|
||
|
shortpress_delay = pin_last_rise_date[event.pin_num] - pin_last_shortpress[event.pin_num]
|
||
|
if shortpress_delay > inter_press_max_delay:
|
||
|
pin_shortpress_count[event.pin_num] = 0
|
||
|
for i in range(button_count):
|
||
|
event.chip.output_pins[i].turn_off()
|
||
|
elif pin_shortpress_count[event.pin_num] == 1:
|
||
|
for i in range(button_count):
|
||
|
event.chip.output_pins[i].turn_on()
|
||
|
|
||
|
def switch_shortpressed(event):
|
||
|
now = time.time()
|
||
|
if pin_shortpress_count[event.pin_num] == 0:
|
||
|
pin_last_shortpress[event.pin_num] = now
|
||
|
shortpress_delay = now - pin_last_shortpress[event.pin_num]
|
||
|
print(shortpress_delay)
|
||
|
if shortpress_delay > shortpress_count_max_delay:
|
||
|
pin_shortpress_count[event.pin_num] = 1
|
||
|
else:
|
||
|
pin_shortpress_count[event.pin_num] += 1
|
||
|
pin_last_shortpress[event.pin_num] = now
|
||
|
print(["count:", pin_shortpress_count[event.pin_num]])
|
||
|
|
||
|
if __name__ == "__main__":
|
||
|
pifacedigitalio.init()
|
||
|
listener = pifacedigitalio.InputEventListener(chip=pifacedigital)
|
||
|
for i in range(button_count):
|
||
|
listener.register(i, pifacedigitalio.IODIR_ON, switch_pressed)
|
||
|
listener.register(i, pifacedigitalio.IODIR_OFF, switch_unpressed)
|
||
|
listener.activate()
|