Hi!
I have a simple issue with "Serial Monitor"; I need to read the input String from Serial Monitor but cannot. Any help would be appreciated.
Here is the code that I have already tried:
String input, output;
char in;
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.print("Please enter inputs and press enter at the end:\n");
while(Serial.available()>0){
if(Serial.read()=='\n'){
continue;
}
else{
in = Serial.read();
input = String(in);
}
}
Serial.println(input);
while(true);
}
Aminoo:
I have a simple issue with "Serial Monitor"; I need to read the input String from Serial Monitor but cannot. Any help would be appreciated.
What do you want?
For a non-blocking loop() function combined with a short-blocking read function you could use that:
char* serialString()
{
static char str[21]; // For strings of max length=20
if (!Serial.available()) return NULL;
delay(64); // wait for all characters to arrive
memset(str,0,sizeof(str)); // clear str
byte count=0;
while (Serial.available())
{
char c=Serial.read();
if (c>=32 && count<sizeof(str)-1)
{
str[count]=c;
count++;
}
}
str[count]='\0'; // make it a zero terminated string
return str;
}
void setup() {
Serial.begin(9600);
}
void loop()
{
static boolean needPrompt=true;
char* userInput;
if (needPrompt)
{
Serial.print("Please enter inputs and press enter at the end:\n");
needPrompt=false;
}
userInput= serialString();
if (userInput!=NULL)
{
Serial.print("You entered: ");
Serial.println(userInput);
Serial.println();
needPrompt=true;
}
}
The non-blocking loop() code would allow doing other things while waiting for user input. Such as blinking LEDs for example.
But when receiving from Serial there will be a short 64ms delay, to keep the code for the serialString() relatively simple. But could be changed to zero delay if needed.
Be careful: This simple input code only works with the Arduino "Serial Monitor", but not with a "serial terminal program".