infinite loop in switch case using serial commands

Hi all,

I want to run 2 functions using switch case with help of serial commands. example, If I enter 1 in serial window, start() has to run infinitely. when I enter 0, start() has to terminate and st() has to run. Please help me out to complete this step. Please find the sample code below.

//void st();
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
}

void start() {
  while (1) {
    Serial.println("start");
  }
}
void st() {

  Serial.println("stop");
}

void loop() {
  // put your main code here, to run repeatedly:
  if (Serial.available() > 0) {
    int inByte = Serial.read();
    bool x = 0;
    switch (inByte) {
      case '1':
        start();
        break;
        
      case '0':
        st();
        break;
    }
  }
}

why is there a loop in your start() function? once you enter 1 it will loop forever

I thought serial command 0 will break terminate that infinite loop.

As soon as '1' is received, you device is basically bricked, because "start()" never returns. "loop()" is being endlessly repeated, so you do not need the while loop. Look at this pseudo-code which illustrates how to do it:

currentCommand = NONE;

loop {
  if serial.available then currentCommand = serial.read;
  switch currentCommand {
    if '1' then do_something;
    if '0' then {
      do_stop;
      currentCommand = NONE;
    }
  }
}

Danois90: As soon as '1' is received, you device is basically bricked, because "start()" never returns. "loop()" is being endlessly repeated, so you do not need the while loop. Look at this pseudo-code which illustrates how to do it:

currentCommand = NONE;

loop {   if serial.available then currentCommand = serial.read;   switch currentCommand {     if '1' then do_something;     if '0' then {       do_stop;       currentCommand = NONE;     }   } }





Ok, I'll try dude

A minor rearrangement of your program will fix the problem

byte inByte;

void setup()
{
  Serial.begin(9600);
}

void start()
{
  Serial.println("start");
}

void st()
{
  Serial.println("stop");
  inByte = 0;
}

void loop()
{
  if (Serial.available() > 0)
  {
    inByte = Serial.read();
  }
  switch (inByte)
  {
    case '1':
      start();
      break;
    case '0':
      st();
      break;
  }
}

UKHeliBob: A minor rearrangement of your program will fix the problem

byte inByte;

void setup() {   Serial.begin(9600); }

void start() {   Serial.println("start"); }

void st() {   Serial.println("stop");   inByte = 0; }

void loop() {   if (Serial.available() > 0)   {     inByte = Serial.read();   }   switch (inByte)   {     case '1':       start();       break;     case '0':       st();       break;   } }

Great dude :) it works :) Thanks a lot.

Great dude :) it works :)

Do you understand the changes that I made and why they were necessary ?