18F Code Snippet - Interrupt Context Saving

    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

    See the Swordfish help file/forum for more information regarding interrupts.

 Skip Navigation Links.

Collapse Site Tutorial IndexSite Tutorial Index
Expand 16F PIC Examples16F PIC Examples
Collapse 18F PIC Examples18F PIC Examples
LED's
Switches
Expand 7 Segment Displays7 Segment Displays
LCD's
Expand 7 Segment Displays7 Segment Displays
ADC
ADC (Another Example)
EEPROM's
DS1307
Expand RS232 and UARTRS232 and UART
DS18B20
External ADC
Hall Effect Sensor
Pulse Width Modulation (PWM)
Infrared UART
Swordfish Modules
Collapse Code SnippetsCode Snippets
SF Libraries
18F Transition Guide
Internal Oscillator
PLL
Structures
Multi Tasking
Expand Internal TimersInternal Timers
Collapse InterruptsInterrupts
Intro
Context Saving
PORTB
Priority
Expand Handy TipsHandy Tips