I have a code with a connection to serial port:

// Set baud rate
// Disable USART rate doubler (arduino bootloader leaves it enabled...)
UCSR0A &= ~(1 << U2X0);
// Set async, no parity, 1 stop, 9bit
UCSR0C = (0<<UMSEL01)|(0<<UMSEL00)|(0<<UPM01)|(0<<UPM00)|(0<<USBS0)|(1<<UCSZ01)|(1<<UCSZ00);
UCSR0B |= (1<<UCSZ02); // 9bit
// Enable rx/tx
UCSR0B |= (1<<RXEN0)|(1<<TXEN0);

I see the comments but I want to know exactly what does these chunks means. Is there any complete documentation about these symbols?


Take a look in the datasheet under the "20. USART0" section:


I will list the names of the registers, what they are called, and then what your code is doing specifically:

  • UBRR0H and UBRR0L together form the baud rate divider. Your program probably uses F_CPU and <util/setbaud.h> to calculate a divider and set the baud rate. For more information see Table 20-12.
  • UCSR0A "USART Control and Status Register n A" -- This line is enabling the U2X0 which doubles the transmission speed
  • UCSR0C "USART Control and Status Register n C" -- This line is enabling the UCSZ01 and UCSZ00 bits to set parity check to "Enabled, Odd Parity". See Table 20-9. This line has extra information, all the statements with 0<< actually do nothing.
  • USCR0B " USART Control and Status Register n B" -- This line is setting the UCSZ02 bit which is described here: "The UCSZn2 bits combined with the UCSZn1:0 bit in UCSRnC sets the number of data bits (Character SiZe) in a frame the Receiver and Transmitter use. " This basically allows you to select 9 bit wide serial if you would like (8 bit is more common)
  • The final USCR0B line enables tx and rx
| improve this answer | |
  • Thanks a lot! How can I setup which arduino mega rx/tx port (0-usb, or 1,2,3-gpio) will it use? – asiniy Mar 31 '15 at 14:02
  • @asiniy: By changing the numeral in the symbol. All 4 USARTs work exactly the same way. – Ignacio Vazquez-Abrams Mar 31 '15 at 17:33
  • Should I use USCR1B for gpio rx1/tx1? – asiniy Mar 31 '15 at 18:16

I strongly recommend you to read the datasheet. You are confusing UART module with GPIO module. Once you use one pin for one purpose (say serial comunication) you cannot use it for another thing (say general I/O to read a physical button state). Of course it is possible if you write your code in a way it changes all the registers (the ones you call "symbols") on excecution time. But just be carefull that the routines that used those pins for UART don't execute meanwhile!

| improve this answer | |

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.