Languages
[Edit]
EN

Arduino UNO - read data from user

13 points
Created by:
Noname
2430

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);
}

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Arduino

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join