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= ""; 
 }
 }
 }
asked Mar 10, 2017 at 2:39
2
  • 1
    Fix your code indentation. Commented Mar 10, 2017 at 3:52
  • Welcome to Arduino SE. Be sure to take the tour to see how it works here: arduino.stackexchange.com/Tour Commented Apr 14, 2017 at 21:52

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?
}
answered Mar 10, 2017 at 3:47
1
  • You missing setup() loop here where you have to initialize serial communication. Check out my code, you will be find what I mean. Commented 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");
 }
 }
}
answered Mar 10, 2017 at 6:13

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.