Datasheet

170
ATtiny828 [DATASHEET]
8371A–AVR–08/12
Note: 1. See “Code Examples” on page 7.
More advanced initialization routines can be made that include frame format as parameters, disable interrupts and so on.
However, many applications use a fixed setting of the baud and control registers, and for these types of applications the
initialization code can be placed directly in the main routine, or be combined with initialization code for other I/O modules.
17.6 Data Transmission – The USART Transmitter
The USART transmitter is enabled by setting the Transmit Enable bit (TXEN) (see “UCSRB – USART Control and Status
Register B” on page 185). When the transmitter is enabled, the normal port operation of the TxDn pin is overridden by the
USART and given the function as the transmitter’s serial output. The baud rate, mode of operation and frame format
must be set up once before doing any transmissions. If synchronous operation is used, the clock on the XCK pin will be
overridden and used as transmission clock.
17.6.1 Sending Frames with 5 to 8 Data Bits
A data transmission is initiated by loading the transmit buffer with the data to be transmitted. The CPU can load the
transmit buffer by writing to the UDR register. The buffered data in the transmit buffer will be moved to the shift register
when the it is ready to send a new frame. The shift register is loaded with new data if it is in idle state (no ongoing
transmission), or immediately after the last stop bit of the previous frame is transmitted. When the shift register is loaded
with new data, it will transfer one complete frame at the rate given by the Baud Rate Register, the U2X bit or by XCK,
depending on the mode of operation.
The following code examples show a simple USART transmit function based on polling of the Data Register Empty flag
(UDRE). When using frames with less than eight bits, the most significant bits written to UDR are ignored. The USART
has to be initialized before the function can be used. For the assembly code, the data to be sent is assumed to be stored
in register R16
C Code Example
(1)
void USART_Init( unsigned int baud )
{
/* Set baud rate */
UBRRH = (unsigned char)(baud>>8);
UBRRL = (unsigned char)baud;
/* Enable receiver and transmitter */
UCSRB = (1<<RXEN)|(1<<TXEN);
/* Set frame format: 8 data bits, 2 stop bits */
UCSRC = (1<<USBS)|(3<<UCSZ0);
}
Assembly Code Example
(1)
USART_Transmit:
; Wait for empty transmit buffer
sbis UCSRA,UDRE
rjmp USART_Transmit
; Put data (r16) into buffer, sends the data
out UDR,r16
ret