Atmega2560 Usart Interrupt problem

atmegaavrcinterruptsmicrocontroller

When I send any data from serial port, RX pins are flashing but ISR is not running.
Here is my code.

#include <avr/io.h>
#include <string.h>
#include <avr/interrupt.h>
#include <util/delay.h>

#define F_CPU 16000000

volatile int NUMBER_OF_RECEIVED_BYTES = 0;

ISR(USART0_RX_vect)
{
    NUMBER_OF_RECEIVED_BYTES++;

}
int main(void)
{
    #define USART_BAUDRATE 9600
    #define UBRR_VALUE (((F_CPU / (USART_BAUDRATE * 16UL))) - 1)

    UBRR0H = (uint8_t)(UBRR_VALUE>>8);
    UBRR0L = (uint8_t)UBRR_VALUE;
    UCSR0B |= (1 << RXEN0) | (1 << TXEN0) | (1 << RXCIE0);
    UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00);
    while (NUMBER_OF_RECEIVED_BYTES == 0);
    DDRB |= (1 << DDB7);
    sei();
    while (1)
    {
        PORTB ^= (1 << PB7);
        _delay_ms(999);
    }
}

Best Answer

In your code:

  1. You increment the NUMBER_OF_RECEIVED_BYTES only in your ISR.
  2. You have a loop before sei();, waiting for NUMBER_OF_RECEIVED_BYTES not to be 0 .
  3. So your loop will be infinite, because the global interrupts are disabled and your ISR won't be called to increment your variable.

See:

while (NUMBER_OF_RECEIVED_BYTES == 0); // <---- infinite since interrupts are disabled
DDRB |= (1 << DDB7);
sei();   //<-------- thus, this line is never reached, interrupts won't be enabled

I do not know what is the purpose of this loop: while (NUMBER_OF_RECEIVED_BYTES == 0);, but you should enable interrupts before it starts.