4.3.5 How to Read Lines and Execute Valid Commands
The following code snippet reads one line of data and stores it in an array. A valid line is shorter than the array length in this example.
The array index is reset to zero when reaching the array end, to avoid a bugger 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 interpret it and change the state of the LED
.
char command[MAX_COMMAND_LEN];
uint8_t index = 0;
char c;
while(1)
{
c = getch();
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);
}
}
Using the MPLAB X Data Visualizer, ‘LED ON’ and ‘LED OFF’ commands can be sent to the board.
Use the MPLAB X Data Visualizer as described in the appendix, Send Commands from MPLAB X Data Visualizer.