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= "";
}
}
}
-
1Fix your code indentation.gre_gor– gre_gor2017年03月10日 03:52:07 +00:00Commented 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/TourSDsolar– SDsolar2017年04月14日 21:52:45 +00:00Commented Apr 14, 2017 at 21:52
2 Answers 2
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?
}
-
You missing
setup()
loop here where you have to initialize serial communication. Check out my code, you will be find what I mean.Hasan– Hasan2017年03月10日 06:15:33 +00:00Commented Mar 10, 2017 at 6:15
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");
}
}
}