I want to send messages via UART interface, I had the following program:
#ifndef F_CPU
#error "F_CPU has to be defined"
#endif
#ifndef CONSOLE_BAUD
#pragma message "CONSOLE_BAUD was not defined, using 9600"
#define CONSOLE_BAUD 9600
#endif
#define UBRR_VALUE F_CPU/16/CONSOLE_BAUD-1
// init
UBRRH = (unsigned char)(UBRR_VALUE >> 8);
UBRRL = (unsigned char)UBRR_VALUE;
UCSRB = (1 << TXEN);
UCSRC = (1 << URSEL) | (1 << USBS) | (3 << UCSZ0);
// send
while (!(UCSRA & (1 << UDRE)));
UDR = 'A';
This doesn't work. The HEX being sent is 00
.
I changed that to the following:
#ifndef F_CPU
#error "F_CPU has to be defined"
#endif
#ifndef CONSOLE_BAUD
#pragma message "CONSOLE_BAUD was not defined, using 9600"
#define CONSOLE_BAUD 9600
#endif
#define UBRR_VALUE F_CPU/16/CONSOLE_BAUD-1
// init
unsigned int ubrr = UBRR_VALUE; // changed
UBRRH = (unsigned char)(ubrr >> 8); // changed
UBRRL = (unsigned char)ubrr; // changed
UCSRB = (1 << TXEN);
UCSRC = (1 << URSEL) | (1 << USBS) | (3 << UCSZ0);
// send
while (!(UCSRA & (1 << UDRE)));
UDR = 'A';
And it started to work. Why is that? What's the difference between assigning the preprocessor directive directly to UBRRX and having an intermediary variable?
// EDIT The question was marked as a duplicate although I had no chance to find the linked duplicate, since I did not see the issue (lack of parentheses) in the first place. I think that marking my question as a duplicate is unfair.