I am new to Arduino and C. I have writeen a sketch to check, whether a year is a leap year.
In order to allow user input I have added a function to read the serial monitor, like so:
int ReadLine(char str[]) {
char c;
int index = 0;
while (true) {
if (Serial.available() > 0) {
c = Serial.read();
Serial.print("Received char: ");
Serial.println(c, HEX);
if (c != '\n') {
Serial.print("Debug (ReadLine | if > char): ");
Serial.println(c);
str[index++] = c;
} else {
Serial.print("Debug (ReadLine | if > else): ");
Serial.println(c);
str[index] = '\0'; // null termination character
break;
}
Serial.print("Debug (ReadLine | str): ");
Serial.println(str);
Serial.print("Debug (ReadLine | index): ");
Serial.println(index);
}
}
return index;
}
The problem is that I never reach the ‘else’ part when checking for the new line character.
Entering: 2012, I expect to see with Serial.println(c, HEX) the output as: 32 30 31 32 0D 0A, with oD being the \n terminator.
I have not added input validation or other fancy stuff (and am aware the sketch loops forever to read the serial port), I simply wanted to understand serial.read to build bigger projects.
What am I doing wrong in this sketch?
Any help appreciated.