This post shows an example of PIC16F877A PORTB interrupt on change (IOC).
Four of the PORTB pins, RB7:RB4, have an interrupt-on-change (IOC) feature. Only pins configured as inputs can cause this interrupt to occur (i.e., any RB7:RB4 pin configured as an output is excluded from the interrupt-on-change comparison). The input pins (of RB7:RB4)
are compared with the old value latched on the last read of PORTB. The “mismatch” outputs of RB7:RB4 are OR’ed together to generate the RB port change interrupt with flag bit RBIF (INTCON<0>).
This interrupt can wake the device from Sleep. The user, in the Interrupt Service Routine, can clear the interrupt in the following manner:
a) Any read or write of PORTB. This will end the
b) Clear flag bit RBIF.
A mismatch condition will continue to set flag bit RBIF. Reading PORTB will end the mismatch condition and allow flag bit RBIF to be cleared. The interrupt-on-change feature is recommended for wake-up on key depression operation and operations where PORTB is only used for the interrupt-on-change feature. Polling of PORTB is not recommended while
using the interrupt-on-change feature.
PIC16F877A PORTB change interrupt example:
This is a small example shows how to use the interrupt-on-change feature of PIC16F877A. Circuit schematic is below:
In the circuit there are 4 buttons and 4 LEDs, when a button is pressed or depressed an interrupt occurred and the microcontroller executes the interrupt routine which turn ON or OFF an LED as shown in the video below.
PIC16F877A PORTB interrupt on change example C code:
The C code below was tested with CCS PIC C compiler version 5.051.
// PIC16F877A RB change interrupt
i = input_b();
output_d(i >> 4);
clear_interrupt(INT_RB); // Clear PORTB IOC flag bit
enable_interrupts(INT_RB); // Enable PORTB IOC
enable_interrupts(GLOBAL); // Enable global interrupts
while(TRUE) ; // Endless loop
PIC16F877A PORTB change interrupt example simulation video:
The following video shows simulation using Proteus with some descriptions.