0

I'am trying to work with the external interrupt source and I wrote a small program to test the interrupt. When I start the program RB0 is set low, and RB1 is set high. If I set RB7 high, it must be generated an interrupt that reverses the logic state of RB0 and RB1. I don't know why the interrupt doesn't work. I have configured all registers, is something missing yet? The compiler is xc16.

Thanks.

Here is the code:

#include <xc.h>
#include "setup.h"

void main(void) {

    AD1PCFG = 0xFFFF;
    TRISBbits.TRISB7=1;
    TRISBbits.TRISB0=0;
    TRISBbits.TRISB1=0;
    PORTBbits.RB0=0;
    PORTBbits.RB1=0;   

    _INT0IE= 1;    //enable interrupt on RB7
    _INT0IF = 0;    //clear status flag interrupt on RB7
    _INT0IP = 0b010;    /priority level 2 for INT0


    while(1) {
        _RB0=0;
        _RB1=1; 
    }     

}

void _ISR _INT0Interrupt(void) { 

    if(_INT0IF) {
        _INT0IF = 0;
        _RB0=1;
        _RB1=0;
    }   

}
Fire91
  • 11
  • 2
    How do you know that it is not working? The while loop in main() repeatedly undoes what the ISR did. You might miss the change if you're not observing with sufficiently high resolution. – kkrambo Mar 19 '18 at 13:28
  • 1
    Hi kkrambo, this was an example and I did not notice this trivial mistake. But I did a test with another program in which in main() there was an empty while, the ISR set RB0 at a high level. However, it does not work. I tested the program first on proteus and then in the real circuit. – Fire91 Mar 19 '18 at 14:40
  • I solved the problem! The mistake is _INT0IP = 0b010; used to set priority. It compiles without errors, but in runtime doesn't work. I tried to set bits in this way: IPC0bits.INT0IP2 = 0; IPC0bits.INT0IP1 = 1; IPC0bits.INT0IP0 = 0; and it works! – Fire91 Mar 19 '18 at 15:02
  • Where is `_INT0IP` defined? You should have set it on the `IPC0bits` struct/union too, just like you set the individual bits, i.e.: `IPC0bits.INT0IP = 2`. – vgru Mar 21 '18 at 09:05

2 Answers2

1

Write following code in your ISR as you want Simply reverse the state of RB0 & RB1 and you must Enable Global and peripheral Interrupt i.e. GIE & PIE

    void_ISR_INT0Interrupt(void){
    if(_INT0IF){
    _INT0IF=0;
    _RB0=~_RB0;
    _RB1=~_RB1;
    }
}
Wayne Yang
  • 9,016
  • 2
  • 20
  • 40
1

it is generally a good idea to write to the latch registers and not the port. When you perform a write, you are actually doing a read of the port, modifying the bit(s), and then a write. Depending on the circuitry, your port read may not reflect the same value as you think. By writing to the latch register, you will read your desired output state and write that back to the port (via the latch)

Joe Thomas
  • 325
  • 1
  • 7