Dear All,
Peace and blessing be upon you from Allah SWT. I am not an expert on Arduino. However, I am trying to code an educational robot for my lecture and I am facing problems in serial communication as follows. This is what I want to do: I want to send some serial commands for the robot to do something for one of the commands it should wait for the subsequent command and read that command and take action accordingly. To test this concept I have created the following sample code but it is not working.
int newval = 0;// initialize newval and str
String str = "";
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() { // put your main code here, to run repeatedly:
if(Serial.available()) //check if there is any data
{
str = Serial.readString(); //save the incoming data in the string
if (str == "Test"){ //check if
Serial.println("This is the first response");
}
if (str == "Test2")// check if Test2
{
Serial.println("Input some number.");
if (Serial.available())/// should look for the second incoming data and print accordingly, however it does not go thru the code.
{
//newval = 4;
newval = Serial.read();
Serial.println(newval);
}
}
}
}
I will highly appreciate if someone can help me with this problem.
Or add a trim function to trim the invisible carriage return and/or line feed from the serial input.
str = Serial.readString(); //save the incoming data in the string
str.trim(); // trim invisible white space characters
If there is nothing available in the second
if (Serial.available())
"Test" would have to be entered again to get to that part of the program.
You could use while(Serial.available() == 0); to wait for serial input. Not the best way to do it though.
The code looks like this:
int newval = 0;// initialize newval and str
String str = "";
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() // put your main code here, to run repeatedly:
{
if (Serial.available()) //check if there is any data
{
str = Serial.readString(); //save the incoming data in the string
str.trim(); // trim off invisible characters
if (str == "Test") //check if
{
Serial.println("This is the first response");
}
if (str == "Test2")// check if Test2
{
Serial.println("Input some number.");
while (Serial.available()== 0); // wait for the second incoming data and print accordingly, however it does not go thru the code.
{
//newval = 4;
newval = Serial.read();
Serial.println(char(newval)); // char converts ASCII code to character
}
}
}
}
That is not the best way to wait for serial input. If you do a search for "arduino wait for user serial input", you should get some better ways.
You should try to stay away from using the String class. The, easily misused, String class can cause memory problems. See the evils of Strings page.