You did not specify the kind of Arduino you are using but, based on another another recent question of yours, I will assume it is an AVR-based Arduino Arduino.
You cannot have an interrupt automatically triggered by a variable reaching reaching zero. What you can do, instead, is trigger an interrupt by software software, by toggling a pin that is configured both as an output and as an an interrupt source:
However, if you do that, you will discover that interrupts are slow.
slow; Awfullyawfully slow compared with a simple if
test:
digitalWrite()
itself is awfully slow. This can be overcome by using using direct port access, but that is still two cycles for toggling the the pin in each direction.You will looselose an extra cycle in the pin synchronizer.
Once the IRQ is raised, the CPU needs four cycles to prepare itself for for servicing it.
The interrupt vector is a
jmp
instruction, which takes 3 cycles.The ISR then has to save every single register it is going to use, including including the status register. That takes two cycles per register. And And there are quite a lot of registers to save...
This ISR, which is provided by the Arduino core, will then look for the the interrupt handler you provided with
attachInterrupt()
. This also also involves checking that the pointer to the handler is not zero (the kind of test you seem to be worried about). It then has tocall
(4 cycles) your handler, which will have toret
urn (4 cycles) to the ISR. You could avoid this indirection by defining the the ISR yourself instead of relying onattachInterrupt()
.Once the job is done, all the saved registers have to be restored (2 cycles times many register), and the
reti
instruction (4 cycles) is is issued in order to restore control to the interrupted program.Last but not least, since
amp
will be modified in interrupt context context, you will have to qualify it asvolatile
. This keyword prevents prevents the compiler tofrom perform optimizations that are unsafe in this this situation, and you will loose a lot of time to these missed optimization optimization opportunities.
The whole sequence takes 3 cycles, irrespective of whether the if
condition condition was true or false. That is at least one order of magnitude
faster faster than the interrupt-based solution.