The last few days i have been breaking my virtue on a problem I’m having with the serial library.
I started programming a piece of code where user input through the serial monitor is read in using Serial.readString() on an Arduino Uno. When the code became too long and the Uno’s memory too small I switched to an Arduino Due.
Oddly enough, the code stopped working, without any changes made.
Since then I’ve tried multiple possible solutions without any succes. I’ve listed what I’ve done below:
- Used Serial.readStringUntil(’\n’); instead
- Moved the String definition inside the loop()
- Tried reading the input character per character using a loop function
- Tested the Serial.readString() function in a piece of example code (Which worked fine) [Example code: see below
My code:
boolean switchState = 0;
boolean previous = 0;
//String spell ="";
char symbol[20];
int i = 0;
int l=0;
void setup() {
// Define the switch pin
pinMode(0, INPUT);
// Set up serial communication to enable word entries
delay(500);
Serial.begin(9600);
delay(500);
Serial.println("Power On.");
}
void loop() {
// Read Serial data when it's available
Serial.println("Please enter a valid word to spell: "); //Prompt User for input
while (Serial.available()==0) { //Wait for user input
}
String spell = Serial.readString(); //Read user input into spell
Serial.print("The word you entered is: "); Serial.print(spell);
l = spell.length();
//Serial.println(l); //Debug
spell.toCharArray(symbol,l); //Convert the string to an array of characters.
for(i=0;i<(l-1);i++){
Serial.print("Letter");Serial.print(i);Serial.print(": "); Serial.println(symbol[i]); Debug
}
}
Example code used:
/*
String indexOf() and lastIndexOf() functions
Examples of how to evaluate, look for, and replace characters in a String
created 27 July 2010
by Tom Igoe
http://arduino.cc/en/Tutorial/StringIndexOf
This example code is in the public domain.
*/
void setup() {
Serial.begin(9600);
Serial.println("\n\nStream.readString() and readStringUntil() functions:");
// Set a long timeout so the user has chance to write things
// before the calls to read them time out
Serial.setTimeout(15000UL);
Serial.println("You will have up to 15 seconds to type your message before it times out.\n");
}
void loop() {
Serial.println("Send a message over serial:");
String stringOne = Serial.readString();
Serial.print("Received the string >>");
Serial.print(stringOne);
Serial.println("<<");
Serial.println();
Serial.println("Now send a message over serial containing the letter 'g':");
String stringTwo = Serial.readStringUntil('g');
Serial.print("Received the string >>");
Serial.print(stringTwo);
Serial.println("<<");
Serial.println();
// do nothing while true:
while(true);
}
Does any of you know how I can solve this issue ?