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;


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);
    while (1)
        PORTB ^= (1 << PB7);
  • \$\begingroup\$ What do you mean RX pin is flashing, is that supposed to be PB7? \$\endgroup\$ – Bence Kaulics May 13 '15 at 15:40
  • \$\begingroup\$ How do you know the interrupts are not running? \$\endgroup\$ – Jon May 13 '15 at 15:43
  • \$\begingroup\$ @BattleHamster No. I am using Arduino Mega board. And it has RX and TX LEDs to indicate that a transmission or receive occurred. \$\endgroup\$ – Zgrkpnr May 13 '15 at 15:44
  • \$\begingroup\$ @Jon I knew because if it ran then while(NUMBER_OF_RECEIVED_BYTES) line would have been passed. Bu I solved the problem, however I don't know if it was the problem but if I read UDR0 values then interrupt works. I don't know how. \$\endgroup\$ – Zgrkpnr May 13 '15 at 15:46
  • 2
    \$\begingroup\$ Without looking into the details of this part, it may be that the UART can't receive any more data until you claim that already in UDR0 by reading it or otherwise reset it. Similarly, interrupts often will not re-fire until you acknowledge their condition, so merely counting in your ISR may be insufficient to work more than once. \$\endgroup\$ – Chris Stratton May 13 '15 at 16:43

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.


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.

  • \$\begingroup\$ Well, that's a point I should have never missed. Thank you. \$\endgroup\$ – Zgrkpnr May 13 '15 at 15:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.