I'm working on an interpreter, so I started with the serial event example from the IDE:
String inputString = ""; // a String to hold incoming data
bool stringComplete = false; // whether the string is complete
void setup() {
// initialize serial:
Serial.begin(9600);
// reserve 200 bytes for the inputString:
inputString.reserve(200);
}
void loop() {
// print the string when a newline arrives:
if (stringComplete) {
Serial.println(inputString);
// clear the string:
inputString = "";
stringComplete = false;
}
}
/*
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() {
while (Serial.available()) {
// get the new byte:
char inChar = (char)Serial.read();
// add it to the inputString:
inputString += inChar;
// if the incoming character is a newline, set a flag so the main loop can
// do something about it:
if (inChar == '\n') {
stringComplete = true;
}
}
}
but I'm just not a fan of the String or the std::string classes, so I revised it a bit:
const uint16_t input_buffer_size = 256;
char input_char;
char input_buffer[input_buffer_size] = "";
uint8_t input_buffer_index = 0;
bool input_available = false;
void setup() {
Serial.begin(115200);
}
void loop() {
if (input_available) {
Serial.println(input_buffer);
input_buffer[0] = 0;
input_buffer_index = 0;
input_available = false;
}
}
void serialEvent() {
while (Serial.available()) {
input_char = (char)Serial.read();
if (input_char == '\n') {
input_available = true;
input_buffer[input_buffer_index] = 0;
} else if (input_buffer_index < input_buffer_size){
input_buffer[input_buffer_index++] = input_char;
} else {
input_available = true;
input_buffer[input_buffer_size - 1] = 0;
Serial.flush();
}
}
}
There are threads that incorporate a start and stop character, but as this is just for serial monitor input, I didn't see any of that as necessary for this application.
Did I miss anything important?