| 1 |
/* |
| 2 |
Serial Event example |
| 3 |
|
| 4 |
When new serial data arrives, this sketch adds it to a String. |
| 5 |
When a newline is received, the loop prints the string and clears it. |
| 6 |
|
| 7 |
A good test for this is to try it with a GPS receiver that sends out |
| 8 |
NMEA 0183 sentences. |
| 9 |
|
| 10 |
NOTE: The serialEvent() feature is not available on the Leonardo, Micro, or |
| 11 |
other ATmega32U4 based boards. |
| 12 |
|
| 13 |
created 9 May 2011 |
| 14 |
by Tom Igoe |
| 15 |
|
| 16 |
This example code is in the public domain. |
| 17 |
|
| 18 |
https://www.arduino.cc/en/Tutorial/BuiltInExamples/SerialEvent |
| 19 |
*/ |
| 20 |
|
| 21 |
String inputString = ""; // a String to hold incoming data |
| 22 |
bool stringComplete = false; // whether the string is complete |
| 23 |
|
| 24 |
void setup() { |
| 25 |
// initialize serial: |
| 26 |
Serial.begin(9600); |
| 27 |
// reserve 200 bytes for the inputString: |
| 28 |
inputString.reserve(200); |
| 29 |
} |
| 30 |
|
| 31 |
void loop() { |
| 32 |
// print the string when a newline arrives: |
| 33 |
if (stringComplete) { |
| 34 |
Serial.println(inputString); |
| 35 |
// clear the string: |
| 36 |
inputString = ""; |
| 37 |
stringComplete = false; |
| 38 |
} |
| 39 |
} |
| 40 |
|
| 41 |
/* |
| 42 |
SerialEvent occurs whenever a new data comes in the hardware serial RX. This |
| 43 |
routine is run between each time loop() runs, so using delay inside loop can |
| 44 |
delay response. Multiple bytes of data may be available. |
| 45 |
*/ |
| 46 |
void serialEvent() { |
| 47 |
while (Serial.available()) { |
| 48 |
// get the new byte: |
| 49 |
char inChar = (char)Serial.read(); |
| 50 |
// add it to the inputString: |
| 51 |
inputString += inChar; |
| 52 |
// if the incoming character is a newline, set a flag so the main loop can |
| 53 |
// do something about it: |
| 54 |
if (inChar == '\n') { |
| 55 |
stringComplete = true; |
| 56 |
} |
| 57 |
} |
| 58 |
} |