Simple Serial Communication

Introduction

Sometimes you might want to have live communication with your microcontroller, it might want to tell you something, or you might want to tell it something. Either way, this possible through what is called serial communication.

Short Example of Serial Menu Communication

Code


void setup() {
  // initialize serial so that we can communicate with the Arduino 
  Serial.begin(9600); 
  Serial.println("Gimme your numbers!"); // A little start message is printed in the serial
}

void loop() {
  // if there's any serial available/open, read it:

  while (Serial.available() > 0) {

    // Reads an integer (whole number) and saves it as 'MenuOption'  
    int MenuOption = Serial.parseInt();

    // In case the user types something that isn't an integer, the Arduino will automatically return '0'. That's why we're now only looking at valid user input
    
    if (MenuOption != 0) {
      Serial.print("I got this number: ");
      Serial.println(MenuOption);
      // look for the next valid integer in the incoming serial stream:
      if (MenuOption == 1) {
        Serial.println("Hey, lets do this one thing!");
      }
      else if (MenuOption == 2) {
        Serial.println("Hey, lets do another thing!");
      }
      else if (MenuOption == 3) {
        Serial.println("Hey, lets do this last thing!");
      }
      else {
        Serial.print("...and I don't know what to do with it");
      }
    }
  }
}

Articles mentioning this page