Arduino UNO - read data from user
In this article, you will learn how to read and parse data from the user.
Simple example
The first example just reads text from the user and next print it on the screen (serial port monitor). In the beginning, program just checks if there is something to read. If yes, you can start reading the data. In this case, Serial.readBytes
function was used which has two jobs to do - read the text and store it in the char array. There is no conversion to anything. The second parameter of the Serial.readBytes
function is the number of chars to read, it should be less or equal to the size of the buffer array.
Important is that the buffer has to be cleared every time before reading the next data. To manage this, you can use a library function
memset
.
void setup() {
// enable serial comunication
Serial.begin(9600);
}
// buffer array
char buff[20];
void loop() {
// if there is something to read
if(Serial.available()) {
// just read it and store in the buffer
Serial.readBytes(buff, 20);
// and next print the buffer
Serial.println(buff);
// clear the buffer
memset(buff, 0, sizeof(buff));
}
delay(10);
}
Parse number example
In this example, the library Serial.parseInt
function was used to convert text from the user to the integer value. This is a very simple way to read numbers without any text operations.
To read floating-point number there is available
Serial.parseFloat
function.
void setup() {
// enable serial comunication
Serial.begin(9600);
}
void loop() {
// if there is something to read
if(Serial.available()) {
// read and convert to integer
int a = Serial.parseInt();
// print readed number
Serial.println(a);
}
delay(10);
}