Go Down

Topic: time delay in interrupt (Read 765 times) previous topic - next topic

doug metzler

I have what I thought was a simple task, to insert a short time delay in a signal (in this case the output from a hall sensor (signal transition every 9ms)) via the use of an interrupt and a simple loop:

Code: [Select]

void HAInt()
{
   for (unsigned long i = 0;i<5;i++);
   digitalWrite(HAOut, digitalRead(HAInt3));
}

  attachInterrupt(3, HAInt, CHANGE);


Interestingly, no matter what number I put in the for loop (5, 50, 500, 5000, 50000, 500000) it has no effect on when the digitalWrite event occurs.  Could this be because the compiler sees that the for loop does nothing and optimizes it out?

Since I can't use delay() functions in interrupts what is the proper method of inserting a time delay?

Thank you,

DougM

Coding Badly

Interestingly, no matter what number I put in the for loop (5, 50, 500, 5000, 50000, 500000) it has no effect on when the digitalWrite event occurs.  Could this be because the compiler sees that the for loop does nothing and optimizes it out?


Yup.

Quote
Since I can't use delay() functions in interrupts what is the proper method of inserting a time delay?


The proper method of delaying in an ISR is to not do it.

Quote
a short time delay in a signal (in this case the output from a hall sensor (signal transition every 9ms))


Are you hoping to get a 9 millisecond delay in your ISR?

doug metzler

re:

>
> Are you hoping to get a 9 millisecond delay in your ISR?
>
no, I really don't know but I'm guessing the range could be anywhere from 20uS to 2mS

I've got 3 signals I need to condition.  I realize that putting delays in ISR's isn't good, but this is a proof of concept, not a final implementation.  the final implementation will use a hardware delay - I am using Arduino to determine what that delay is.

Thanks,

DougM

Coding Badly

I'm guessing the range could be anywhere from 20uS to 2mS


Just to be clear...  20 us is probably OK.  2 milliseconds will absolutely cause problems.

Use the avr-libc delay functions...
http://www.nongnu.org/avr-libc/user-manual/group__util__delay.html

doug metzler

Nice!

final (pertinent parts of)code:

Code: [Select]

#define F_CPU 16000000UL  // 16 MHz

#include <util/delay.h>

attachInterrupt(3, HAInt, CHANGE);

void HAInt()
{
   _delay_us (hallDelay);
   digitalWrite(HAOut, digitalRead(HAInt3));
}


Thanks so much!

DougM

Coding Badly


There is no need to include this...
Code: [Select]
#define F_CPU 16000000UL  // 16 MHz
I suggest removing it.

You are welcome!

Go Up