PIC16F-7-INTERRUPT-Initialization&InterruptService Routine

by Marwen Maghrebi
void init_config(void) {
    // Port configurations
    TRISD = 0x00;  // Set PORTD as output for LEDs
    TRISA = 0x01;  // Set RA0 as input for ADC
    TRISB = 0x01;  // Set RB0 as input for button interrupt

    // ADC configuration
    ADCON0 = 0x41;  // ADC ON, Channel 0 (RA0/AN0), Fosc/8 as conversion clock
    ADCON1 = 0x8E;  // Right justify result, set Vref+ to Vdd and Vref- to Vss, AN0 as analog, rest as digital

    // UART configuration
    TXSTAbits.SYNC = 0;  // Asynchronous mode
    TXSTAbits.BRGH = 1;  // High speed
    SPBRG = 129;  // Baud rate 9600 for 20 MHz
    RCSTAbits.SPEN = 1;  // Enable serial port
    TXSTAbits.TXEN = 1;  // Enable transmission

    // Interrupt configuration
    INTCONbits.GIE = 1;  // Enable global interrupts
    INTCONbits.PEIE = 1;  // Enable peripheral interrupts
    INTCONbits.INTE = 1;  // Enable RB0/INT external interrupt
    OPTION_REGbits.INTEDG = 1;  // Interrupt on rising edge

    // Initialize LEDs state
    PORTD = 0x00;
}

void UART_send_string(const char* str) {
    while (*str) {
        while (!TXSTAbits.TRMT);  // Wait until transmit buffer is empty
        TXREG = *str++;  // Transmit character
    }
}

void __interrupt() ISR(void) {
    if (INTCONbits.INTF) {
        // External interrupt occurred
        PORTD = 0x00;  // Turn off the four LEDs
        PORTDbits.RD4 = 1;  // Turn on interrupt-specific LED (RD4)
        __delay_ms(500);
        PORTDbits.RD4 = 0;  // Turn off interrupt-specific LED (RD4)

        // Send UART message indicating interrupt execution
        UART_send_string("Interrupt executed\r\n");

        // Clear the interrupt flag
        INTCONbits.INTF = 0;
    }
}
Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?
-
00:00
00:00
Update Required Flash plugin
-
00:00
00:00