Interrupts or Polled?

Embedded electronics often depends on the input from several sources. What’s the best way to obtain the new state of the input?

  • Constantly look and ask for the value?
  • Or tell it to come back when it’s changed?

Since constantly looking and asking for the value ties up the processor, it’s often better to use an interrupt and make it come back to us when it’s changed. This frees up the processor to do other things, there’s no need to wait anymore.

Interrupt Service Routines (ISRs) or interrupt handlers should be short, ideally simply setting a flag and returning. The set flag should be picked up in the main loop and cleared appropriately.

Using interrupts have some huge advantages over a polled method. These include:

Pros?

Near perfect timing of events / very little latency for input processing

Since the ISR is executed asynchronously to the main code, you can process data as soon as it happens. This is important where timings need to be very extremely accurate.

Frees up CPU

You can do other things while you wait for input.

Cons?

Increased code complexity

Sometimes, waiting has it’s advantages though. It makes it so much simpler to write and understand. Sometime events have to be synchronous too, for example, if you’re reading from a file you should wait for it to finish before trying to access the data (or it won’t be there!).

Interrupts can make it difficult to debug

If you have asynchronous events happening and global variables / registers being changed out of code sequence, it can be hard to know where a bug/problem lies if it occurs. This is why you should keep the ISRs as simple as possible, setting a flag and having the main loop call the necessary function.

In saying all this, polled and interrupt methods have their place. I don’t use interrupts all the time, I only use it when it’s necessary or when a big improvement in speed can be obtained. One isn’t other than the better, and both methods are useful.

Conflicts with shared resources

You can potentially run into resource conflicts. Simultaneous resource access can be a problem. (Two functions trying to output to the UART at the same time) you might end up with “Hello World” + “My name is:” = “HellMy name is:o World”

What do you guys think of this?

What do you use polling for?

What do you use interrupts for?

Advertisements