# How to delay properly inside ISR

I am currently working on a little code which needs to react fast. Here is what I am trying to accomplish:

Using a sine wave phase detector I am detecting every zero crossing and feeding that pulse into the Arduino.

Using an ISR the Arduino detects this zero crossing pulse using RISING. Once one pulse has been detected AND I have pressed a button, I need there to be a delay of 0 - 10ms before switching on an output.

If I don't use an ISR and set a delay of up to 10ms inside the loop, it won't really be 10ms and it will be some other delay, nothing consistent. (I checked with an oscilloscope).

Only when using an ISR and using delayMicrosenconds() inside the ISR I can delay the output consistently for up to 10 ms everytime.

Now I have read that doing this is wrong...Even though it works perfectly. Which better way could I use?

Thanks!

EDIT: While 100% accuracy may not be possible, it needs to be as precise as possible. More important is the repeatability. Using my method I could reproduce the outcome everytime with an accuracy in the nano seconds range.

• how critical is those 10 ms really? Mar 4, 2018 at 12:25
• If your program has nothing else to do during these 10 ms, and if you don't care about the Arduino timekeeping (`millis()` and `micros()`) getting off, and if you don't use libraries that rely on interrupts, then your method should be OK. Mar 4, 2018 at 12:26
• Those 10ms need to be 100% exact. I need to switch on an output which drives a TRIAC. The TRIAC will then turn on an electronic ballast at exactly the desired sine phase. I.e. if I delay for 5ms, the TRIAC will switch on AC at exactly 90° Mar 4, 2018 at 12:28
• “100% exact” is not achievable in the real world. Not with an Arduino nor with the most precise equipment available on earth. Mar 4, 2018 at 12:31
• The question of @ratchetfreak is very relevant because single cycle accuracy, while achievable, will require somewhat complex low-level programming. If you can live with a few 10 µs of jitter, then the problem is much easier. Please, edit your question to provide a reasonable answer to that question. Mar 4, 2018 at 12:37