Description
This work will make it easier: arduino/Arduino#1595
The general idea would be to add a sysex command to attach or detach an interrupt on a specified pin. The pin must be valid. This is where the referenced pull request comes into play.
Here is one possible approach:
0: START_SYSEX
1: ATTACH_INTERRUPT
2: pin number (implemenation should validate)
3: mode (low | change | rising | falling | high) *only Arduino Due supports high
4: type (trigger [default], pulseWidth, other ideas?) *type would resolve to a particular callback function in the firmata implementation
5: END_SYSEX
0: START_SYSEX
1: DETACH_INTERRUPT
2: pin number
3: END_SYSEX
The response would depend on the type (byte 4). By default you would get the pin number and the value. However other types such as pulse width could be specified. In this case the response would include the pin number and the pulse width. The type would support various use cases such as rotary encoders, ping type sonar sensors, photo interrupts, button presses, etc.
The interrupt handler needs to execute as quickly as possible so for the default type a flag would be set in the handler and the associated pin value would be recorded. The response would be sent in the next iteration of the main loop after the handler function returns. With something more complex like a pulse width, a change flag would be set in the interrupt handler and the pulse width would be recorded. The response would be sent in the main loop on the next iteration.
// example response
0: START_SYSEX
1: PIN_INTERRUPT
2: pin number
3: type (trigger, pulseWidth, etc) - may not be necessary since the type would be know on the client side
4: value bits 0 6 (number of bytes in value depends on response type)
5: value bits 7-13
n: ...
n+1 END_SYSEX
Another approach is to use a single PIN_INTERRUPT command (byte 1) and then ATTACH, DETACH and RESPONSE sub commands (byte 2).