0

I'm trying figure out how to make the serial monitor printing specific content based on the user input. For instance if the user has typed '1' it should constantly print ("Hello") and when user has typed '2' it should print ("Bye") and vice versa. I'm new to programming, so I would be grateful if any can help me with this.

  String readString;

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


       void loop() 
       {

         if(Serial.available()>0)

         {
            char c = Serial.read();
            readString +=c;
            delay(2);

                   if (c == '1')
                    {
                     delay(1000);
                     Serial.println("Hello");
                     c = "";           
                    }

                                 if (c == '2')
                                  {
                                    delay(1000);
                                    Serial.println("Bye");
                                    c = "";
                                  }           
             else 
            {
             readString= "";                                                                                           
            }
          }
        }
2

2 Answers 2

3

You have most of what is needed but you have it structured incorrectly.

Because you want to print continuously, you need to split your program into 2 sections. One section deals with the serial input and the other with the printing.

The serial handling part checks if there are any characters to be read. If so, it simply stores the character that you read into a global variable.

The printing part executes every time through the loop and prints the value you want based on the global variable, which may, from time to time, change if something new arrives on the serial port.

This code is untested:

char cMode;

void loop() 
{
  if(Serial.available())
  {
    char c = Serial.read();

    if (c == '1' || c == '2')
      cMode = c;
  }

  if (cMode == '1')
    Serial.println("Hello");
  else if (cMode == '2')
    Serial.println("Bye");

  delay(1000); // to slow down the loop?
}
1
  • You missing setup() loop here where you have to initialize serial communication. Check out my code, you will be find what I mean.
    – Hasan
    Mar 10, 2017 at 6:15
1

Try out this code. It will helpful for you.

char serialData;

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

void loop()
{
  if(Serial.available())
  {
    serialData = Serial.read();

    if(serialData == '1')
    {
      Serial.println("Hello");
    }
    else if(serialData == '2')
    {
      Serial.println("Bye");
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.