+static byte out_pulse;
+#define OUT_PULSE_WIDTH 100
+static byte debounce;
+#define DEBOUNCE_THRESHOLD 3
+static byte pressed;
+static u16 press_timer;
+#define LONG_PRESS 500
+static byte second_timer;
+static byte unlocked;
+#define UNLOCK_SECONDS 20
+
+ISR(TIM0_COMPA_vect)
+{
+ if (out_pulse) {
+ if (!--out_pulse)
+ PORTB &= ~B(PB4);
+ }
+
+ if (!second_timer) {
+ second_timer = 100;
+ if (unlocked)
+ unlocked--;
+ }
+ second_timer--;
+
+ if (PINB & B(PB3)) {
+ // Switch open
+ if (debounce)
+ debounce--;
+ else
+ pressed = 0;
+ } else {
+ // Switch closed
+ if (debounce < DEBOUNCE_THRESHOLD)
+ debounce++;
+ else
+ pressed = 1;
+ }
+
+ if (unlocked) {
+ if (!(second_timer & 7))
+ PORTB ^= B(PB0);
+ if (pressed) {
+ if (out_pulse < 2)
+ out_pulse = 2;
+ PORTB |= B(PB4);
+ unlocked = UNLOCK_SECONDS;
+ }
+ } else {
+ if (!pressed) {
+ PORTB |= B(PB0);
+ press_timer = 0;
+ } else {
+ PORTB &= ~B(PB0);
+ if (press_timer < LONG_PRESS) {
+ press_timer++;
+ if (press_timer == LONG_PRESS) {
+ out_pulse = OUT_PULSE_WIDTH;
+ PORTB |= B(PB4);
+ unlocked = UNLOCK_SECONDS;
+ }
+ }
+ }
+ }
+}
+