18F Code Snippet - Interrupt PORTB
PORTB
interrupts are used for instantaneous response for changes to Pins 7, 6, 5, 4 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 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.

Note the PIC's power supply/oscillator are not shown
Click here to watch this circuit in action
Device = 18F452
Clock = 20
Dim
RBIF As INTCON.0,
RBIE As INTCON.3
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 missmatch
// PORTB 7:4 has changed, do what you want here...
PORTC = PORTB // In this case, I am making PORTC = PORTB
EndIf
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()
ASM
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
Wend

 | Site Tutorial Index |
|  | 16F PIC Examples |
|  | 18F PIC Examples |
| |  | 7 Segment Displays |
| |  | 7 Segment Displays |
| |  | RS232 and UART |
| |  | Code Snippets |
| | |  | Internal Timers |
| | |  | Interrupts |
|  | Handy Tips |