Calls a function when the value of an input pin changes The sketch method provided must accept a single integer (int) parameter, which is the number of the GPIO pin that the interrupt occured on. As this method might be called at any time, including when drawing to the display
(int pin, PApplet parent, String method, int mode)
| 116 | * @webBrief Calls a function when the value of an input pin changes |
| 117 | */ |
| 118 | public static void attachInterrupt(int pin, PApplet parent, String method, int mode) { |
| 119 | if (irqThreads.containsKey(pin)) { |
| 120 | throw new RuntimeException("You must call releaseInterrupt before attaching another interrupt on the same pin"); |
| 121 | } |
| 122 | |
| 123 | enableInterrupt(pin, mode); |
| 124 | |
| 125 | final int irqPin = pin; |
| 126 | final PApplet irqObject = parent; |
| 127 | final Method irqMethod; |
| 128 | try { |
| 129 | irqMethod = parent.getClass().getMethod(method, int.class); |
| 130 | } catch (NoSuchMethodException e) { |
| 131 | throw new RuntimeException("Method " + method + " does not exist"); |
| 132 | } |
| 133 | |
| 134 | // it might be worth checking how Java threads compare to pthreads in terms |
| 135 | // of latency |
| 136 | Thread t = new Thread(new Runnable() { |
| 137 | public void run() { |
| 138 | boolean gotInterrupt = false; |
| 139 | try { |
| 140 | do { |
| 141 | try { |
| 142 | if (waitForInterrupt(irqPin, 100)) { |
| 143 | gotInterrupt = true; |
| 144 | } |
| 145 | if (gotInterrupt && serveInterrupts) { |
| 146 | irqMethod.invoke(irqObject, irqPin); |
| 147 | gotInterrupt = false; |
| 148 | } |
| 149 | // if we received an interrupt while interrupts were disabled |
| 150 | // we still deliver it the next time interrupts get enabled |
| 151 | // not sure if everyone agrees with this logic though |
| 152 | } catch (RuntimeException e) { |
| 153 | // make sure we're not busy spinning on error |
| 154 | Thread.sleep(100); |
| 155 | } |
| 156 | } while (!Thread.currentThread().isInterrupted()); |
| 157 | } catch (Exception e) { |
| 158 | // terminate the thread on any unexpected exception that might occur |
| 159 | System.err.println("Terminating interrupt handling for pin " + irqPin + " after catching: " + e.getMessage()); |
| 160 | } |
| 161 | } |
| 162 | }, "GPIO" + pin + " IRQ"); |
| 163 | |
| 164 | t.setPriority(Thread.MAX_PRIORITY); |
| 165 | t.start(); |
| 166 | |
| 167 | irqThreads.put(pin, t); |
| 168 | } |
| 169 | |
| 170 | |
| 171 | /** |
nothing calls this directly
no test coverage detected