I’m trying to implement interrupt from RB pins. But it doesn’t work

buttoncinterruptspicprogramming

I'm new to PIC programming. I made a program to get interrupt from RB pins. but it doesn't work. My code is as follows:

int flag=0;
unsigned short temp = 0;

void interrupt(void)
{   
    if(flag==2)
    flag=0 ;
    else
    flag++;   

    if (INTCON.RBIF==1)
    {
        flag=9;
        temp = PORTB;
        PORTB = temp;
        INTCON.RBIF = 0;
    }

    INTCON.INTF = 0;
}

int i,j,k,mina,minb,seca,secb,hra,hrb;
void main()
{
    IOCB=1111110;
    TRISA=0  ;
    TRISC=0  ;
    PORTB=0;
    ADCON0=0;
    TRISB=1;
    ANSELB=0;
    INTCON=1;
    INTCON.RBIE=1;
    INTCON.RBIE = 1;

    INTCON.RBIF = 0;

    INTCON.GIE = 1;
    INTCON.INTE = 1;
    INTCON.PEIE = 0;
    OPTION_REG.INTEDG = 1;
    while(1)
    {
        for(i=0;i<59;i++)
        for(j=0;j<59;j++)
        for(k=0;k<59;k++)
        {
            seca=k/10;
            secb=k%10;
            mina=j/10;
            minb=j%10;
            hra=i/10;
            hrb=i%10;

            if(flag==0)
            {
                PORTA=mask(seca);
                PORTC=mask(secb);
            }
            else if(flag==1)
            {
                PORTA=mask(mina);
                PORTC=mask(minb);
            }
            else if(flag==2)
            {
                PORTA=mask(hra);
                PORTC=mask(hrb);
            }

            Delay_ms(100);
        }
    }
}

All other sections are working, RB0 int is working too.. But the button from other inputs (RB4..RB7) are not working. The MCU I'm using is PIC16F722A.

Best Answer

In your ISR you have this:

    flag=9;
    temp = PORTB;
    PORTB = temp;

Firstly, you set flag to 9, but you're only looking at if it's 0, 1 or 2 in your main loop. So that's never going to have any effect.

And secondly, why are you reading port B then writing the value directly back to port B? What are you hoping to achieve there?

Also, I don't know what compiler you're using, but in most compilers there is a requirement to have all global variables that are used in ISRs marked as "volatile" or the compiler may optimize them out.