Swordfish Code Snippet - Interrupt Context Saving

swordfish

Context Saving and Restoring is vital for interrupts, as the program could get pulled from  anywhere at any time. What this means is that the system variables/registers are backed up at the start of the Interrupt Handler, and then when the Interrupt is complete, they are all restored again.

 

This can be a little memory demanding, so you only want to back up what you need to. Consider this, your Interrupt uses a function that is also used during your Main Program loop. What happens if the interrupt occurs during the function when it was called from the main program loop? Well without context saving, the program would become unstable and unreliable. Consider;

 

Dim Counter As Word
 
// get value function...
Function GetValue(pValue As Byte) As LongWord
 Result = pValue * pValue * pValue
End Function 
 
// some interrupt...
Interrupt MyInt()
 Dim Value As LongWord
 Value = GetValue(10)
End Interrupt
.
.
.
// part of main program Loop...
Enable(MyInt)
While True
 If PORTB.0 = 1 Then
 Counter = GetValue
 EndIf
Wend

 

Well, as you can see, this could lead to serious problems. We have to back up system registers and any variables used within the Function 'GetValue'. How? It's easy with Swordfish!

 

Save(0) will back up all of the system variables default to Swordfish. To back up shared functions/procedure variables, simply add them to the Context Save. ie, Save(0, GetValue). Now when the interrupt occurs, everything will be backed up that is in use within the ISR. And when finished, everything is restored with the commands Restore.

 

Dim Counter As Word
 
// get value function...
Function GetValue(pValue As Byte) As LongWord
 Result = pValue * pValue * pValue
End Function 
 
// some interrupt...
Interrupt MyInt()
 Dim Value As LongWord
 Save(0, GetValue)
 Value = GetValue(10)
 Restore
End Interrupt
.
.
.
 
// part of main program Loop...
Enable(MyInt)
While True
 If PORTB.0 = 1 Then
 Counter = GetValue(10)
 EndIf
Wend

 

Search for "swordfish interrupt" here at digital-diy.com, or check the Swordfish help file for more information regarding interrupts.

Forum Activity

Member Access