Hello,
I'm inexperienced and I need help.
When I write in serial monitor single digit number it set hours, next number sets minutes and next seconds. But when I write two-digit number it doesnt work, it sets hours and minutes with one two-digit number. It reads two-digit number as 2 characters and it isnt correctly
Thanks
int s = 0;
int m = 0;
int h = 0;
char charr;
void setup() {
Serial.begin(9600);
Serial.println("Hours");
while(h==0){
if (Serial.available() > 0) {charr = Serial.read();
h = charr-48;
Serial.println(h);}
m = charr-48;
Serial.println(m);}
}
Serial.println("Seconds ");
while(s==0){
if (Serial.available() > 0) {charr = Serial.read();
s = charr-48;
Serial.println(s);}
}
}
void loop() {
s++;
if (s > 59){s=0 ; m++;}
if (m > 59){m=0 ; h++;}
if (h > 23){h =0;}
if (h<10) {Serial.print("0");}; Serial.print(h); Serial.print(":"); if (m<10){Serial.print("0");}; Serial.print(m); Serial.print(":"); if (s<10) {Serial.print("0");};Serial.println(s);
delay(1000);
}
void loop() {
char buffer[10]; // Could be smaller...
int charsRead;
int minutes;
if (Serial.available() > 0) {
charsRead = Serial.readBytesUntil('\n', buffer, sizeof(buffer) - 1);
buffer[charsRead] = '\0'; // make it into a C string
minutes = atoi(buffer);
Serial.print("Minutes = ");
Serial.println(minutes);
}
}
More importantly, why does it work the way it does. The readBytesUntil() method reads the input stream from the Serial object until it sees a newline character (i.e., the user pressed Enter) or the buffer has 9 characters in it. It returns the number of characters read, which we save in charsRead. We need to save one element for the NULL character which terminates the C string. This code assumes you have the Newline option set in the textbox at the bottom of the Serial monitor.