5 Receive Control Commands
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:
- Configure the USART peripheral same as for the first use case
- Enable the receiver
- Read and store the incoming data until the end of line
- Check if the received data are a valid command; if so, execute it
How to Enable the Receiver and Receive Data
For USART1, the default pin position for RX is Port C pin 1 (PC1). The following line sets the PC1 direction to input.
PORTC.DIR &= ~PIN1_bm;
Same as the transmitter, the receiver is enabled by witting to the USARTn.CTRLB register.
USART1.CTRLB |= USART_RXEN_bm;
Before reading the data, the user must wait for the data to be available by polling the Receive Complete Interrupt Flag, RXCIF.
uint8_t USART1_read()
{
while (!(USART1.STATUS & USART_RXCIF_bm))
{
;
}
return USART1.RXDATAL;
}
How to Read a Line
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; /* This delay invalidates the initial noise on the TX line, after device reset. */ _delay_ms(10); while (1) { c = USART1_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, which can, for example, toggle an LED.
An MPLAB MCC generated code example for AVR128DA48 with the same functionality as the one described in this section can be found here: