I am making a program that reads an input from a Serial Monitor and then checks if the inputted number is odd or even. However when I test 123456789, the modulus statement returns -1.
void setup() {
Serial.begin(9600);
}
void loop() {
String userInput = Serial.readString();
if (userInput != nullptr) {
int number = userInput.toInt();
if (number != 0) {
Serial.println(number % 2);
if (number % 2 == 1) {
Serial.println("Odd");
}
else {
Serial.println("Even");
}
}
}
}
Most "high-level" languages after C deal with "objects" using "references". A pointer in the general sense is a kind of reference. But C and C++ are explicit about it -- an object and a pointer to it are two distinctly different things. For example
uint8_t number;
String text;
The uint8_t is a single byte, and the String varies by platform, maybe 6 to 16 bytes. You can try sizeof to tell you. (In addition to the memory used by the object to store the length, there's also the memory for the actual string chars and NUL terminator, allocated on the heap. The larger objects implement Small String Optimization: short strings are stored "inside" the object, and therefore do not fragment the heap.) The bytes have some location in memory -- unless they have been put in a register -- but you don't have to deal with that location directly, unless you want to.
readString does not return a String* (pointer-to-String), it returns a String. Therefore, you always get something, even if it's an empty string, represented by 6-to-16 bytes; but never nullptr.
However, I could not get any warning about the ineffective comparison, even though I cranked up the Compiler warning level to All on a few different boards.
Is a very bad thing to use because it has to wait until all the string has been read in, or the timer limit has been exceeded. By default the timer limit is set to one second. So unless you set the time out limit for this function it will always take a second. Which is not very fast.
Thank you for being the only response that actually gives a solution rather than trying to explain on how another part of the code is working in an inefficient way.