Program doesn't loop with Serial using switch and case

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

void loop()
{
  int pinNumber;
  int digitalState;

  switch(getSerial())
  {
  case 1:
    {
      pinNumber = getSerial();
      digitalState = getSerial();
      Serial.print("Pin: ");
      Serial.print(pinNumber);
      Serial.print("; S: ");
      Serial.println(digitalState);

      pinMode(pinNumber, OUTPUT);
      switch (digitalState)
      {
        case 33:
          digitalWrite(pinNumber, HIGH);
          break;
          
        case 44:
          digitalWrite(pinNumber, LOW);
          break;
      }
      break;
    }
  }
}

int getSerial()
{
  int d = 0;
  int b;

  while (b != '/')
  {
    b = Serial.read(); 
    
    if (b == -1)  // no char available
    {
      delay(1);  // just long enough to get a char in?
    }
    else if ((b >= '0') && (b <= '9'))
    {
      d = (d * 10) + (b - '0');
    }
  }

  return d;
}

This works for me. The problem was in the getSerial() function - your tests for validity of the character received were not correct:

  • What is returned by the Serial.read() when there are no characters waiting?
  • You need to check if the characters read was between '0' and '9' or the formula will not work.

I have also restructured to code to be in line with more standard programming practices.

What is also clear is that if you want to be able to specify the pin number you need to set the mode to output when you know the pin number from the serial stream, not just in setup(), unless you are restricting the pin number to a few pins.