Advertisement
DrAungWinHtut

Serial Communication

Feb 15th, 2022
304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  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.   Serial.println("Please enter R in cm");
  30. }
  31.  
  32. void loop() {
  33.   // print the string when a newline arrives:
  34.   if (stringComplete) {
  35.     float r;
  36.     r = inputString.toFloat();
  37.     float a = 3.14 * r * r;
  38.     Serial.print("The Area is = ");
  39.     Serial.println(a);
  40.     // clear the string:
  41.     inputString = "";
  42.     stringComplete = false;
  43.   }
  44. }
  45.  
  46. /*
  47.   SerialEvent occurs whenever a new data comes in the hardware serial RX. This
  48.   routine is run between each time loop() runs, so using delay inside loop can
  49.   delay response. Multiple bytes of data may be available.
  50. */
  51. void serialEvent() {
  52.   while (Serial.available()) {
  53.     // get the new byte:
  54.     char inChar = (char)Serial.read();
  55.     // add it to the inputString:
  56.     inputString += inChar;
  57.     // if the incoming character is a newline, set a flag so the main loop can
  58.     // do something about it:
  59.     if (inChar == '\n') {
  60.       stringComplete = true;
  61.     }
  62.   }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement