Electronic – PIC 18F2550 External Interrupt Problem

embeddedinterruptspic

I am working on a basic PIC based circuit to improve myself. What I want to do is to make LED's on one by one, every time I press the push button. I am using external interrupt to do this.However, I am in trouble with the push button which I use at RB0. INT0 external interrupt should occur every time I push the button but it never happens. But I am not sure about it. It might be caused by something else. I will be glad if anyone helps me to solve it. Circuit and codes are below.

#include "newheader.h"
#include <pic18f2550.h>
#define _XTAL_FREQ 4000000

int intCount = 0;

void main(void) {
TRISB = 0x01;
TRISC = 0x00;

INTCONbits.PEIE = 1;
INTCONbits.INT0IF=0;
INTCONbits.INT0IE = 1;
INTCONbits.GIE = 1;
INTCON2bits.INTEDG0 = 1;
INTCON2bits.NOT_RBPU = 0;
while(1);

}

void __interrupt() isr(void){
if(INTCONbits.INT0IF==1){
    INTCONbits.GIE = 0;
    __delay_ms (50);
    if (LATBbits.LB0 && intCount == 0){
        __delay_ms (50);
        PORTCbits.RC7 = 1 ;
    }
    if (LATBbits.LB0 && intCount == 1){
        __delay_ms (50);
        PORTCbits.RC6 = 1 ;
    }
    if (LATBbits.LB0 && intCount == 2){
        __delay_ms (50);
        PORTCbits.RC2 = 1 ;
    }
    if (LATBbits.LB0 && intCount == 3){
        __delay_ms (50);
        PORTCbits.RC1 = 1 ;
    }
    if (LATBbits.LB0 && intCount == 4){
        __delay_ms (50);
        PORTCbits.RC0 = 1 ;
    }
    if (LATBbits.LB0 && intCount == 5){
        __delay_ms (50);
        PORTC = 0x00 ;
        intCount = 0;
    }
    INTCONbits.INT0IF=0;
}
intCount++;
}

Circuit

Best Answer

PIC18F I/O ports have a Latch register for output, and a PORT register for input. Writing to the PORT address writes to the Latch register.

Diagram from PIC18F2550 datasheet)

enter image description here

To test a pin state you must read the PORT register. Therefore to read the state of the button you should change each occurrence of LATBbits.LB0 to PORTBbits.RB0.

Writing to PORT bits is OK, just realize that to write an individual bit the MCU must first read the PORT register, then change the bit, and finally write the result back to the register (this is called a 'read modify write' operation). If any pins other than the one you are modifying are being forced low or high by external circuitry (eg. Base of a transistor or a 'large' capacitor) then the corresponding Latch bits will be set to the pin values, overriding what was previously in the Latch. This can cause output bits to flip unexpectedly. To ensure that output bits do not get disturbed it is best to reference the Latch register when manipulating bits, eg. LATCbits.LC7 = 1.