Help with Switch-case and functions

Hi all.

I’m currently working on a project where I set a menu to start some diferent process for monitoring and controlling some variables such as temperature (using DHT11) and a light with a “dimmer”, but those process are executed individually by accessing them using a Switch structure, I choose the options via an APP done in App Inventor, (for bugging process I have been using a serial bluetooth monitor), the case is that when I choose an option It is executed for few seconds and then it comes back to the loop function.

Can you give a look on my scketch and tell me your opinion? I’m a newby using arduino so I haven’t figured out how to make work diferent processes in one scketch.

I hope you can help me.

Thanks :smiley:

comp_bth.ino (4 KB)

You can make 'app' a static variable. In that case the loop will remember the last value. Next you need to read the input only if it is available. If nothing is available, 'app' is not changed.

void loop() {
  // remember last app value; inital value 0
  static char app = 0;
  // check if data is available
  if (Serial1.available() > 0)
  {
    // read it
    app = Serial1.read();
  }
  // process data
  switch (app) {
    case 't':
      Temp();
      break;
    case 'd':
      dimmer();
      break;
  }
}

The above will cause the same function to be executed time after time from loop().

I hope that this is sufficient to sort your problem; you might need similar modification in Temp() and dimmer(); I did not dig too deep in them to be sure.

I would suggest a few minor changes to sterretje code:

void loop() {
  // remember last app value; inital value 0
  static char app = 0;
  // check if data is available
  if (Serial1.available() > 0)
  {
    // read it
    app = tolower(Serial1.read());   // upper or lower case letters ok
  }
  // process data
  switch (app) {
    case 't':
      Temp();
      break;
    case 'd':
      dimmer();
      break;
    default:
      Serial.print("I shouldn't be here: app = "):
      Serial.println(app);
      break;
  }
}

The tolower() macro allows the user to enter 'T' or 't', 'D' or 'd', and the code performs as desired. The default case is a catchall that can be useful for debugging purposes.