Electronic – Software interrupt vs function

arminterruptsstm32

After about 3 years of working with MCUs still I don't know what's the use of Software interrupts? I have done several jobs with STM32 and I have never used the software interrupts. Indeed this is a big question to me:

Why when we can use a simple function to do a task, should we use a software interrupt? What are the differences between a software interrupt and a function?

Every time you like, you can call a function (that you have written for your job). There ought to be some benefits to using a software interrupt instead of a simple function. I'm not sure but I think there is a benefit for software interrupts: you can assign a priority for a software interrupt, then you can give a higher priority to the software interrupt to avoid the hardware interrupt breaking your task.

Best Answer

The main difference between a function and a software interrupt is what is known as context.

  • A function runs within the context of your main program.
  • An interrupt runs within the context of the interrupt handler.

On a simple system this may be no real difference, and software interrupts may simply be used as a convenient way of providing library routines hard coded in ROM - you don't need to know the address of every routine, only the ID code and the main entry point. This makes your code more portable.

However, on more complex systems the software interrupt may run in a completely different environment, known as the kernel context. Normally your application would run in a protected user context which has limited access to resources. Only when running in the kernel context can you perform the more complicated tasks - indeed some systems even limit which instructions can be executed, so you need a mechanism to trigger code in the kernel context - and for that an interrupt is used.