Waiting for output compare match--while loop or interrupt?

Go To Last Post
4 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

I'm using an atmega168 clocked at 20MHz. I want to use Timer1 in CTC mode to wait for a period of time between 200 and 102400 nanoseconds. In other words, I won't use the prescaler, and OCR1A will be between 4 and 2048. COM1A1 will be set, so after the time has elapsed, PB1 will be cleared automatically.

The main loop has to wait until the time is elapsed before it can continue. Is it faster/more efficient to loop until OCF1A is set, or use an interrupt handler?

It looks like AVR-GCC optimizes "loop until bit in I/O register is set" to an SBIS and an RJMP, so the flag is checked every 3 cycles (150 nanoseconds). This seems quite fast to me.

How much overhead (saving/loading registers, etc.) is involved in jumping to and from an interrupt handler?

Also, if an interrupt handler is used, and the main loop is locked in a for( ;; ){} waiting for the interrupt, how would I break out and continue execution upon return from the interrupt handler? Would I have to munge the return address on the stack?

It looks like looping until OCF1A is set is the best choice. Any other suggestions?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

With a minimum of 4 and no pre-scaler, then polling might be better. Interrupts have a minimum of something like 12 clocks to get in, so polling would be faster. And since the program has to wait anyways, there would be no advantage to using interrupts. But be sure to reset the interrupt flag manually.

Regards,
Steve A.

The Board helps those that help themselves.

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

If you are going to just wait for the event in the main loop anyway then an interrupt brings only complications with no advantage. Interrupts are useful if you can do other work in the main loop at the same time.

If you want to go the interrupt route you'll have to introduce a flag variable. The interrupt sets the flag, the main routine waits for the flag being set.

Markus

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

In pure C waiting for the flag is probably best. In ASM there should a possibility to read the timer, and depending on the timer value do an active wait excatly of the right length. This probably will not work with the minimum of 4 cycles however.