I am a new Arduino user who is learning the basics of coding. I apologize beforehand for any inconvenience I may cause with my question.
I have been working on a sample program that asks the user for their name, then displays a greeting. After that, it asks them how many sides a die has and then randomly prints a number in that die. Everything in the program seems to be working fine until the last print statement, where it is not printing fully, and only part of the string is being printed.
I have posted the code below for reference
// C++ code
//
void setup()
{
randomSeed(analogRead(A0));
Serial.begin(9600);
Serial.setTimeout(1000);
}
void loop()
{
Serial.println("Enter your name");
String sample = "Hello ";
while(sample.equals("Hello ")){
sample += Serial.readString();
}
Serial.println(sample);
Serial.println("Enter how many sides to the die");
long int num;
while(true){
num = Serial.readString().toInt();
if(num != 0){
break;
}
// Serial.println("test");
// delay(1000);
}
Serial.println(num);
Serial.println("The dice rolled a " + random(1, num + 1));
delay(1000);
}
Also, If it offers any help, note that I am running this program on tinkercad and not on the actual Arduino IDE
Yes, thank you. This solution seems to fix the problem. But may I know why this problem arose in the first place? Does it have to do something with memory?
It has to do with the fact that Serial.println() is not designed to do what you told it to do
If you really want to combine several things in a single print statement then there are ways to do it but it may involve writing more code in any case, so why bother ?
char buffer[40]; //somewhere to build the string
sprintf(buffer,"The dice rolled a %d/n", random(1, num + 1)); //build the string
Serial.print(buffer); //print the string
Some boards, such as the ESP32 also let you print several strings at once. Which board are you using ?
The problem is that "The dice rolled a " is not a C++ "String", and therefore you cannot append to it with the + operator. Instead, it's what usually called a "C string", which is a pointer to an array of char. When you "add" an integer to a pointer, you increment the pointer to point somewhere in the middle of the array ("The Dice"+4 will give you "Dice")
Serial.println("The dice rolled a " + String(random(1, num + 1)));
should also fix it!
C can be tricky! It's not an ideal language for beginners. Too many "gotchas". But it was chosen for Arduino because, back then, no other language was efficient enough to run on such on such humble hardware. But the times they are a-changin'.
As a beginner I would try to make each line of code as simple as possible. It wasn't until I had some experience that I would start to combine things.
And even with some experience I choose to keep each line simple (and readable) allowing the compiler to do any optimization.