Swordfish Code Snippet - Interrupt PORTB

PORTB interrupts are used for instantaneous response for changes to Pins 4, 5, 6, 7 on PORTB. Further more, the interrupt will even wake the PIC from a Sleep instruction, so your device can be in low power mode (the PIC can draw as low as 0.1u Amps while in Sleep mode), and be instantly awoken when there is a change on PORTB.

One precaution to be aware of is not to forget to read the contents of PORTB within the ISR (Interrupt Service Routine). This is a hardware requirement to clear the mismatch condition that triggers the PORTB interrupt flag. The following program shows how to create a PORTB interrupt routine, that puts the PIC to Sleep after enabling the interrupt, and upon any pin change on PORTB 7:4, the PIC will wake up (thanks to the PORTB interrupt) and the change will be mirrored to PORTC.


An Example


A bigger version of the schematic in the video..


Note the PIC's power supply/oscillator are not shown. Also, PORTB Internal Pullups could be enabled so that external resistors are not required (switches would then pull down)

The Code

Device = 18F452
Clock = 20
Interrupt PORTB_Change()
 Save(0) // Save the system variables
 If RBIF = 1 Then // Check if the interrupt was a PORTB change
 RBIF = 0
 WREG = PORTB // Be sure to read the contents of PORTB to
 // clear the mismatch
 // PORTB 7:4 has changed, do what you want here...
 PORTC = PORTB // In this case, I am making PORTC = PORTB
 Restore // Restore the system variables
End Interrupt
Sub PORTB_Interrupts(Control As Boolean) // Small routine to enable/disable PORTB Interrupts.
 If Control = True Then //
 RBIE = 1 //
 Enable(PORTB_Change) //
 Else //
 RBIE = 0 //
 Disable(PORTB_Change) //
 EndIf //
End Sub
Inline Sub Sleep()
 End ASM
End Sub
// Start Of Program...
TRISB = %11110000 // Make PORTB7:4 all inputs
TRISC = %00000000 // Make PORTC all outputs
PORTB_Interrupts(True) // Enable PORTB interrupts
While True // Infinite loop
 Sleep // Put the PIC to sleep and wait for a change
 // on PORTB 7:4

Forum Activity

  • No posts to display.

Member Access