/*
Forum: https://forum.arduino.cc/t/serial-input-ang-receive-int-question/1188479
Wokwi: https://wokwi.com/projects/381293653101267969
*/
constexpr char LF = 10; // ASCII for Line Feed
constexpr char CR = 13; // ASCII for Carriage Return
char incomingByte;
long value;
boolean valid;
void setup()
{
Serial.begin(57600);
message();
}
void loop()
{
if (Serial.available())
{
incomingByte = Serial.read();
switch (incomingByte)
{
// digits are decoded and added to value
case '0' ... '9':
valid = true;
value = value * 10 + incomingByte - '0';
break;
// In case of LF or CR and after in minimum one valid input
// value is printed. Then the input message is called
// where also value and valid are reset
case LF:
case CR:
if (valid) {
Serial.println(value);
message();
}
break;
// If any other characters are detected an error message is printed,
// the Serial buffer is cleared and the input message is called
default:
// all other characters lead to an error message
Serial.print("Error: You used a non-digit character:\t");
Serial.println(incomingByte);
SerialClear();
message();
break;
}
}
}
void message(){
Serial.println("Please input an integer value:");
value = 0; // Reset the sum
valid = false; // Reset validity
}
void SerialClear(){
while (Serial.available()) {
char garbage = Serial.read();
}
}