2
\$\begingroup\$

I have some problems to fully understand how interrupts on e.g. Arduinos/AVR are used in practice. Lets assume I want to generate a time-critical signal like PWM and at the same time be able to respond to inputs from buttons. Both should be implemented with interrupts.

How can I assure that the PWM signal doesn't get messed up when the button is triggered and therefore another (not signal related) interrupt-routine is running? Similar to this, how can interrupt-based libraries like 'wire' assure that no requests are lost while other (maybe also interrupt-based) code (implemented by me or other libs) is running?

\$\endgroup\$
  • \$\begingroup\$ Why would you implement PWM with interrupts when AVRs are perfectly capable of doing them in hardware? \$\endgroup\$ – Ignacio Vazquez-Abrams May 12 '14 at 5:49
  • \$\begingroup\$ Take this just as an example, please. Two tasks, with one being time-critical and the other one anything else. \$\endgroup\$ – dominik May 12 '14 at 6:03
2
\$\begingroup\$

It's easy: you can't. And it's platform dependant.

Some microcontrollers have multi priorities interrupt controllers, so that if a low priority ISR is running and an higher interrupt is fired the micro stops servicing the low one, saves the context, services the high priority one and then gets back to the lower priority routine. For your example you would probably set the PWM to high priority and the buttons to low priority, waiting a handful of us for a human is not a big deal.

Generally speaking, if a micro controller does not have a priority enabled interrupt controller, an ISR is not interruptible. If a button gets pressed and after some clock cycles the timer wraps so it's time to toggle the PWM pin well... The pin will wait. The interrupt request bit is set and when the micro is done servicing the buttons he will return to the main routine and then go back to serve the new request. If more than one request occur while servicing another... That's platform dependant. There can be a fixed or programmable order, they can be served FCFS or maybe even randomly.

The key is: keep your ISRs short, and by short I mean short. The shorter, the better. Or, in this specific case, serve the not critical task by polling. You can have your nice while(1) and check the buttons inside there, and do whatever you need to do with your input, and generate PWM via interrupt.

And the final advise: don't use arduino. If you write all your code you know what it does and how it behaves. Atmel micros can be programmed in "vanilla" c or asm, and in my opinion that's way better.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.