Interrupts vs. digitalRead

Dear All,

I would like to have my spark monitor a magnetic button (Switch1) and a push button (Switch2).

I am currently doing this in my loop() reading eachtime the state of the two with digitalRead and if the status changes, different functions are called consequently. (status does not change frequently)

What is the advantage of using instead the interrupts such as:
attachInterrupt(D0, doOpenFunc, RISING);
attachInterrupt(D0, doCloseFunc, FALLING);
attachInterrupt(D1, doOn, RISING);
attachInterrupt(D1, doOff, FALLING);

making my “do” functions update some variables to be analyzed anyhow in the loop()… where I can have eventual delays…

is there a smarter way of using this or making this monitoring system?
Thank you

The basic idea for Interrupts is that, irregardless of which line of code is running right now, the moment an interrupt is detected, it will jump to the routine written to handle an interrupt.

For detection in a loop, IF your loop is rather lengthy or has some form of delay() and even blocking code, even though the switch is triggered, your code doesn’t detect as you don’t happen to be at the code which checks the status of the switches. :smiley:

@d82k, polling is usually more than enough if, as @kennethlimcp mentioned, your loop() polls enough enough. There is clickButton library in the IDE which allows you to set a button debounce time but also detect single and multiple clicks. It uses polling. :smile: