Search code examples
arduinobitwise-operatorsavratmelavr-gcc

Why I get different result from serial port after this bitwise operation?


I am trying to learn AVR programming with Arduino. But there is an issue when ı try to activate the usart register bits.

UBRR0H = (BRC >> 8);
    UBRR0L = BRC;
    UCSR0B |= (1<<TXEN0);
    UCSR0C |= (1<<UCSZ01) | (1<<UCSZ01) ;
    while(1) //infinite loop
    {
        UDR0 = 'H';
        _delay_ms(1000);
    }

When ı use | operator to activate TXEN and Some bit frames it activates and prints 'H' to my Serial port. That is the result that i want!

UCSR0B = (1<<TXEN0);
UCSR0C = (1<<UCSZ01) | (1<<UCSZ01) ;

when ı use like this, I get 'È' to my serial port!

Why is that? What is the problem?


Solution

  • UCSR0C = (1<<UCSZ01) | (1<<UCSZ01);

    There might be 2 problems here:

    • The statement above sets one bit in UCSR0C, notice that UCSZ01 is specified twice. So this might be a typo, but even if not, it's confusing at least.

    • We don't know which device you are using, so we have to guess here. Assuming it's something like ATmega48/88/168/328, the reset status of UCSR0C is 0b00000110, i.e. bits UCSZ00 and UCSZ01 are set!

      Thus UCSR0C = (1<<UCSZ01) will set UCSZ00 to zero, while UCSR0C |= (1<<UCSZ01) does not and UCSZ00 will stay at its previous value.