Electronic – arduino – How to have an Arduino wait until it receives data over serial

arduinocrobotics

So I've wired up a little robot with a sound shield and some sensors. I'm trying to write a sketch that will let check the sensors.

What I'd like for it to do is print out a little menu over serial, wait until the user sends a selection, jump to the function that matches their selection, then (once the function is done) jump back and print the menu again. Here's what I've written, but I'm not a that good of a coder, so it doesn't work. Where am I going wrong?

#include <Servo.h>
Servo steering;
Servo throttle;
int pos = 0;
int val = 0;
void setup(){
  Serial.begin(9600);
  throttle.write(90);
  steering.write(90);
  pinMode(A0, INPUT);
  pinMode(7, INPUT);
  char ch = 0;
}
void loop(){
  Serial.println("Menu");
  Serial.println("--------------------");
  Serial.println("1. Motion Readout");
  Serial.println("2. Distance Readout");
  Serial.println("3. SD Directory Listing");
  Serial.println("4. Sound Test");
  Serial.println("5. Car Test");
  Serial.println("--------------------");
  Serial.println("Type the number and press enter");
  while(char ch = 0){
  ch = Serial.read();}
  char ch;
  switch(ch)
  {
    case '1':
    motion();
  }
   ch = 0;
}
//menu over, lets get to work.
void motion(){
  Serial.println("Haha, it works!");
}

I'm pretty sure a While loop is the right thing to do, but I'm probably implementing it wrong. Can anyone shed some light on this?

Best Answer

Here are some suggestions:

  • move declaration of ch above the while loop
  • you used = instead of ==, so while( ch = 0) will loop forever, because ch = 0 will always evaluate to true. It should be while( ch == 0)
  • refactor your menu display into a DisplayMenu() function, just because it's cleaner that way, then call DisplayMenu() from loop().