One important usage of the USART represents the implementation of a command line interface. This way, the microcontroller can receive control commands via USART. It is convenient to use the line terminator as a command delimiter, so for this use case the USART will read full lines.
This use case follows the steps:
For USART0, the default pin position for RX is Port A pin 1 (PA1). The following line sets the PA1 direction to input.
PORTA.DIR &= ~PIN1_bm;
Same as the transmitter, the receiver is enabled by witting to the USARTn.CTRLB register.
USART0.CTRLB |= USART_RXEN_bm;
Before reading the data, the user must wait for the data to be available, by polling the Receive Complete flag.
uint8_t USART0_read() { while (!(USART0.STATUS & USART_RXCIF_bm)) { ; } return USART0.RXDATAL; }
The following code snippet reads one line of data and stores it in an array. It assumes that a valid line is shorter than the array length.
The array index is reset to zero when reaching the array end, to avoid a
buffer overflow error in case of longer lines received. The characters ‘\n’ (line feed)
and ‘\r’ (carriage return) are ignored because they are part of the line terminator.
When ‘\n’ is found, the string end (NULL) is added to the command, and the function
‘executeCommand’ will call a function based on the value of the
command string.
char command[MAX_COMMAND_LEN]; uint8_t index = 0; char c; while (1) { c = USART0_readChar(); if(c != ‘\n’ && c != ‘\r’) { command[index++] = c; if(index > MAX_COMMAND_LEN) { index = 0; } } if(c == ‘\n’) { command[index] = ‘\0’; index = 0; executeCommand(command); } }
In the following code example on GitHub, the USART receives “ON” and “OFF” commands and the microcontroller controls a GPIO output. This can, for example, toggle an LED.