I wanted to create a function that I could use whenever I wanted to print a String on LCD 16x2 i2c.
But when I add numbers to String the function breaks, And got stuck.
This is the function
The String user is a String that I use in void loop and and changes it to whenever I want to print.
You are trying to concatenate an int with a String and whilst I know very little about Strings because I generally don't use them, such a concatenation is unlikely to work
Does user="there is "+books+"In this room"; even compile ?
One of your lines won't compile for me. Please show a small sketch that compiles with those lines.
void setup()
{
Serial.begin(115200);
String user;
user = "hello world how are you today?";
Serial.println(user);
int books = 32;
user = "there is " + books + "In this room";
Serial.println(user);
}
void loop() {}
Arduino: 1.8.13 (Mac OS X), Board: "Arduino Uno"
/Users/john/Documents/Arduino/sketch_may19a/sketch_may19a.ino: In function 'void setup()':
sketch_may19a:10:30: error: invalid operands of types 'const char*' and 'const char [13]' to binary 'operator+'
user = "there is " + books + "In this room";
~~~~~~~~~~~~~~~~~~~~^~~~~~~~~~~~~~~~
exit status 1
invalid operands of types 'const char*' and 'const char [13]' to binary 'operator+'
yes, either call String() to convert the number into a String you can concatenate or do it in chunks
String message;
int books = 32;
void setup()
{
Serial.begin(115200);
message.reserve(50); // limit heap fragmentation risk (in general, here it's not really needed)
message = "there are " + String(books) + " books in this room";
Serial.println(message);
message = "there are ";
message += books; // this knows how to deal with concatenation with an integer
message += " books in this room";
Serial.println(message);
}
void loop() {}
I'd be careful about using String
you could also just print things separately and you'll save memory...
int books = 32;
void setup()
{
Serial.begin(115200);
Serial.print(F("there are "));
Serial.print(books);
Serial.println(F(" books in this room"));
}
void loop() {}
I used chunks, But the problem was that after I create the String I do not get the result I want on the LCD.
I want to use String for a few more things this is why I use it.