/* Program 4-4: Read inputs from a terminal * Examples of reading text or numerical inputs from a terminal. */ void setup() { Serial.begin(9600); } void loop() { char buffer[80]; Serial.print("Enter a message: "); getLine(buffer, sizeof(buffer)); Serial.print("\r\nThe message entered: "); Serial.println(buffer); Serial.print("Enter an integer: "); int m = getInt(); Serial.print("\r\nThe integer entered: "); Serial.println(m); Serial.print("Enter a number: "); double f = getDouble(); Serial.print("\r\nThe number entered: "); Serial.println(f); } /* read a line from the terminal until the Enter key */ int getLine(char* buffer, int len) { int n = 0; char c; do { while (!Serial.available()) { } /* wait until a char is available */ buffer[n++] = c = Serial.read(); /* store the char received */ if (c == '\r') { /* if Enter key is hit */ break; /* return */ } Serial.write(c); /* echo the char */ } while(n < len - 1); /* repeat until the buffer is full */ buffer[--n] = 0; /* terminate the string */ return n; } /* get an integer input from the terminal */ int getInt() { char buffer[80]; getLine(buffer, sizeof(buffer)); /* get a line */ return atoi(buffer); /* convert it to an integer and return */ } /* get a number input from the terminal */ double getDouble() { char buffer[80]; getLine(buffer, sizeof(buffer)); /* get a line */ return atof(buffer); /* convert it to a number and return */ }