67 lines
2.0 KiB
C++
67 lines
2.0 KiB
C++
/*
|
|
=======================================================
|
|
Serial Input Capability using the Serial Event Function
|
|
=======================================================
|
|
*/
|
|
#define SERIAL_INPUT_MAX_LENGTH 30
|
|
|
|
void handleInputBuffer( const char* input_buffer );
|
|
void serialEvent();
|
|
|
|
char serial_input_buffer[SERIAL_INPUT_MAX_LENGTH+1]; // holds incoming data
|
|
int serial_input_buffer_index = 0;
|
|
|
|
/*
|
|
SerialEvent occurs whenever a new data comes in the
|
|
hardware serial RX. This routine is run between each
|
|
time loop() runs, so using delay inside loop can delay
|
|
response. Multiple bytes of data may be available.
|
|
*/
|
|
void serialEvent() {
|
|
bool serial_input_buffer_complete = false;
|
|
|
|
while (Serial.available()) {
|
|
// get the new byte and add it to the buffer
|
|
serial_input_buffer[serial_input_buffer_index] = (char) Serial.read();
|
|
|
|
// if the incoming character is a newline, set a flag
|
|
// so we can
|
|
if ( serial_input_buffer[serial_input_buffer_index] == '\n'
|
|
|| serial_input_buffer[serial_input_buffer_index] == '\0'
|
|
|| serial_input_buffer_index == SERIAL_INPUT_MAX_LENGTH
|
|
) {
|
|
serial_input_buffer_complete = true;
|
|
serial_input_buffer[serial_input_buffer_index] = '\0';
|
|
break;
|
|
}
|
|
|
|
// Increase the index
|
|
serial_input_buffer_index++;
|
|
}
|
|
|
|
if ( serial_input_buffer_complete ) {
|
|
handleInputBuffer( serial_input_buffer );
|
|
|
|
// Reset flag and buffer
|
|
serial_input_buffer_complete = false;
|
|
serial_input_buffer_index = 0;
|
|
}
|
|
}
|
|
|
|
/*
|
|
* Handle a command, make sure this is short as serialEvent() uses this function
|
|
*/
|
|
void handleInputBuffer( const char* input_buffer ){
|
|
// Handle Incoming Line
|
|
for ( int i = 0; i < STR_MAX_LENGTH ; i++ ) {
|
|
// Stop copying when null character found.
|
|
if ( input_buffer[i] == '\0' || input_buffer[i] == '\n') {
|
|
break;
|
|
}
|
|
|
|
line_buffer[line_buffer_write][i] = input_buffer[i];
|
|
}
|
|
|
|
line_buffer_write = ((line_buffer_write + 1 ) % LINE_BUFFER_SIZE );
|
|
}
|