Calls a function when the value of an input pin changes @param pin GPIO pin @param parent typically use "this" @param method name of sketch method to call @param mode when to call: GPIO.CHANGE, GPIO.FALLING or GPIO.RISING @see noInterrupts @see interrupts @see releaseInterrupt @webref
(int pin, PApplet parent, String method, int mode)
| 100 | * @webref |
| 101 | */ |
| 102 | public static void attachInterrupt(int pin, PApplet parent, String method, int mode) { |
| 103 | if (irqThreads.containsKey(pin)) { |
| 104 | throw new RuntimeException("You must call releaseInterrupt before attaching another interrupt on the same pin"); |
| 105 | } |
| 106 | |
| 107 | enableInterrupt(pin, mode); |
| 108 | |
| 109 | final int irqPin = pin; |
| 110 | final PApplet irqObject = parent; |
| 111 | final Method irqMethod; |
| 112 | try { |
| 113 | irqMethod = parent.getClass().getMethod(method, int.class); |
| 114 | } catch (NoSuchMethodException e) { |
| 115 | throw new RuntimeException("Method " + method + " does not exist"); |
| 116 | } |
| 117 | |
| 118 | // it might be worth checking how Java threads compare to pthreads in terms |
| 119 | // of latency |
| 120 | Thread t = new Thread(new Runnable() { |
| 121 | public void run() { |
| 122 | boolean gotInterrupt = false; |
| 123 | try { |
| 124 | do { |
| 125 | try { |
| 126 | if (waitForInterrupt(irqPin, 100)) { |
| 127 | gotInterrupt = true; |
| 128 | } |
| 129 | if (gotInterrupt && serveInterrupts) { |
| 130 | irqMethod.invoke(irqObject, irqPin); |
| 131 | gotInterrupt = false; |
| 132 | } |
| 133 | // if we received an interrupt while interrupts were disabled |
| 134 | // we still deliver it the next time interrupts get enabled |
| 135 | // not sure if everyone agrees with this logic though |
| 136 | } catch (RuntimeException e) { |
| 137 | // make sure we're not busy spinning on error |
| 138 | Thread.sleep(100); |
| 139 | } |
| 140 | } while (!Thread.currentThread().isInterrupted()); |
| 141 | } catch (Exception e) { |
| 142 | // terminate the thread on any unexpected exception that might occur |
| 143 | System.err.println("Terminating interrupt handling for pin " + irqPin + " after catching: " + e.getMessage()); |
| 144 | } |
| 145 | } |
| 146 | }, "GPIO" + pin + " IRQ"); |
| 147 | |
| 148 | t.setPriority(Thread.MAX_PRIORITY); |
| 149 | t.start(); |
| 150 | |
| 151 | irqThreads.put(pin, t); |
| 152 | } |
| 153 | |
| 154 | |
| 155 | /** |
nothing calls this directly
no test coverage detected