Using parseInt() with Arduino [Guide + Code]

Are you trying to send integers over serial using parseInt with Arduino?

Maybe you’re struggling to understand the difference between Serial.read() and Serial.parseInt(), and how they can work for you? Do you just need to know how to convert multiple digit char to integers?

Then you’re in luck! In this lesson you will learn exactly how to use parseInt from the Arduino Serial library to convert multiple characters to a single integer. Get ready!

Overview

Let’s do a quick overview of what we’ll cover.

  • A quick overview of Serial Communication
  • Serial.read() vs Serial.parseInt()
  • Code for converting chars to integers with parseInt()
  • parseInt() details, like setTimeOut(), Lookahead Mode, and ignore
  • Quick Serial Communication Review

If you watched our lesson on using serial.read(), then you already know how to take serial input and convert the chars to integers by putting all the incoming bytes into a char array. If you want to learn that method, make sure to check out the lesson on Serial.read().

That code worked great, but it was somewhat lengthy. In this lesson we are going to talk about using a function from the Serial library called parseInt().

Let’s do a quick review of how serial communication works with Arduino.

You Arduino has some hardware on it called a USART/UART that will allow you to receive data serially from a computer. It will store that data in a buffer called the serial receive buffer.

Programming Electronics Academy members, check out the Arduino Course for Absolute Beginners to practice using the Serial Library in your code.

Not a member yet?  Sign up here.

What’s a buffer?

Now if the word buffer throws you off – don’t sweat it. You can think of a buffer like a bunch of horse stalls in a stable. Some stables are big and have a bunch of stalls – you can house a bunch of horses there, other stables are quite small, and you only have room for so many horses – you can’t take in more horses than you have stalls!

A buffer is like a stable, but instead of having horse stalls, it has spaces in memory where data can be stored.

Generally speaking, a buffer is a transient place for data storage in a program. Usually, you are receiving data into a buffer, and then reading it out pretty quickly – because more data will be coming in and you need to make space for it. This is not some hard and fast rule though.

The serial receive buffer has room for 64 bytes. When data comes to your Arduino over Serial, each byte will end up in the serial receive buffer.

Programming Electronics Academy members, learn how data is stored in memory in the  Using Pointers course.

Not a member yet?  Sign up here.

It’s your job as the programmer to read the data out of the serial receive buffer and do something with the data.

But how do you do that? Turns out there are quite a few ways!

Serial.read()

If you want to take out each byte at a time, then you could use Serial.read().

When you use Serial.read() it “reads out” the first byte in the serial receive buffer. The rest of the bytes then shift over.

If your serial receive buffer was filled with “SeaBiscuit” and you call Serial.read() once then the “S” would be read out, and “eaBiscuit” would be left, every byte having shifted over, so that now the “e” is the next in line.

Serial.read() is great if you want to read in each character at a time, and maybe do some things based on different characters that come in.

But what if you want to get a whole number 1776. If you use serial.read(), you’d get a 1, and then a 7, another 7, and finally a 6. Plus, they’d be stored as individual  – not as a single integer! You don’t want one digit at time, you want all the whole number!

As I mentioned before, we talked about how to accomplish this in the last lesson using character array and the atoi() function. But there is a somewhat simpler method if all you want to do is convert the char input into an integer.

Programming Electronics Academy members, learn how to choose, install, and use Arduino libraries in the Arduino Course for Absolute Beginners Code Libraries section.

Not a member yet?  Sign up here.

Introducing Serial.parseInt()

The parseInt() function from the Serial library is made to scan down the serial receive buffer one byte at a time in search of the first valid numerical digit.

So if you have “314” in the serial receive buffer, you’d get 314 returned the first time you call Serial.parseInt().

//serial receive buffer--> "314"
int dataIn = Serial.parseInt(); //dataIn now holds 314

If you had “I ate 314 tacos” in the serial receive buffer, you’d only get 314 returned the first time you call Serial.parseInt().

//serial receive buffer--> "I ate 314 tacos"
int dataIn = Serial.parseInt(); //dataIn now holds 314

What does Serial.parseInt do with the non-numeric values in the serial receive buffer?

If the non-numeric values are only BEFORE a valid integer, it tosses them out and returns the integer and leaves the rest.

//serial receive buffer--> "I ate 314 tacos"

//1st Call
int dataIn = Serial.parseInt(); //dataIn now holds 314

//serial receive buffer--> " tacos"

What does Serial.parseInt() do if there are only non-numeric numbers in the serial receive buffer? Like “¡Arriba, arriba!”?

If all parseInt() can see in the serial receive buffer are non-numeric values, it will return a zero, and leave the values sitting in the buffer.

//serial receive buffer--> "¡Arriba, arriba!"

//1st Call
int dataIn = Serial.parseInt(); //dataIn now holds 0

//serial receive buffer--> "¡Arriba, arriba!"

If you start get a bunch of 0’s returned from parseInt() and you’re not sure why, remember that Newlines (NL) and Carriage Returns (CR) may be added when using the Serial Monitor window in the Arduino IDE (even though you won’t see them in the Send section where you enter the text).  If you don’t want these terminating characters, make sure to select No Line Ending from the drop down.

A common method of using Serial.parseInt() is to pair it with a while loop and Serial.available(), so that the only time you check for a new integer is when data has actually arrived at the serial port. (If this code structure looks odd to you, then check out the lesson we did on Serial.read() to help explain it.)

while (Serial.available() > 0)
{
  int dataIn = Serial.parseInt();

  //Do something with the data - like print it
  Serial.print(dataIn);
}

So that is how you can convert data coming in over serial from characters to integers! But there’s a couple important things to know about parseInt()…

parseInt() details

The devil is in the details, and parseInt() has a couple neat details.

The first of these interesting details is that parseInt() actually returns a long datatype, not an integer datatype! So if you have a big number coming in, you can save it to a long datatype variable.

Second is the fact that parseInt will “time out” after a given programmable set point. The default set point is 1 second (1000 milliseconds).

Let’s say for example it takes a while for your serial data to arrive at the serial port, like maybe every 300 milliseconds…

// 3 <300ms> 1 <300ms> 4 <300ms> 5 => total time to receive 3145 is 900ms

Instead of just reading in each byte as it arrives, parseInt() will wait a set amount of time before it returns an integer. To adjust this time out period, you use the Serial.setTimeout(time) function.

So in the example above, parseInt would get the 3, and wait, then get the 1 and wait, get the 4 then wait, then finally get the 5, and soon after that it would time out and return the integer 3145.

//serial receive buffer: 3 <300ms> 1 <300ms> 4 <300ms> 5 => total time to receive 3145 is 900ms

//1st Call
int dataIn = Serial.parseInt(); //dataIn now holds 3145

If the delay between incoming bytes was even longer, say 400ms, then the last digit 5 would stay in the serial receive buffer, and only get 314 the first time parseInt() was called.

// serial receive buffer:3 <400ms> 1 <400ms> 4 <400ms> 5=> total time to receive 3145 is 1200ms

//1st Call
int dataIn = Serial.parseInt(); //dataIn now holds 314

//2nd Call
dataIn = Serial.parseInt(); //dataIn now holds 5

It’s interesting to play around with the timeout period and see what results you get.

Programming Electronics Academy members, check out the Writing Functions section of the Arduino Course for Absolute Beginners to master coding your own functions.

Not a member yet?  Sign up here.

Optional parseInt() parameters

Another interesting detail of the parseInt() function is that you can call it with optional parameters.

Serial.parseInt();
Serial.parseInt(lookahead);
Serial.parseInt(lookahead, ignore);

The first parameter option is called the “lookahead mode”. There are three predetermined lookahead mode values you can send.

SKIP, SKIP_ALL, and SKIP_WHITESPACE

SKIP_ALL is the default mode which is use when you call Serial.parseInt(), but you can also use it explicitly like this:

Serial.parseInt(SKIP_ALL);

With the SKIP_ALL mode all characters other than numerical digits and minus signs are ignored as parseInt() scans down the serial receive buffer. This is the behavior we have already explored.

Using SKIP_NONE mode – nothing is skipped in the buffer as parseInt() scans down the values. If the first value in the serial receive buffer is not a numerical digit, it returns 0;

//serial receive buffer--> "You ate 314 tacos!"

//1st Call
int dataIn = Serial.parseInt(SKIP_NONE); //dataIn now holds 0

Finally, with the lookahead mode set to SKIP_WHITESPACE, then only tabs, spaces, line feeds, and carriage returns are skipped.

//serial receive buffer--> " 314 tacos!"

//1st Call
int dataIn = Serial.parseInt(SKIP_WHITESPACE); //dataIn now holds 314

This look ahead feature is pretty neat, but is there a way to ignore specific characters coming in the serial port and just get numerical values?

How to ignore characters using parseInt()

If you want to say ignore a certain character type, for example commas, or any character for that matter, you can pass an “ignore” value as a second parameter to parseInt() like so:

//serial receive buffer--> "3,142"
int dataIn = Serial.parseInt(SKIP_NONE, ','); // dataIn now holds 3142

This could come in handy if there are known characters that you don’t want to act as delimiters in your number.

A Review of using parseInt to convert char to integers

OK – wow – we covered a ton…let’s recap.

When data arrives from the serial port, it goes into the ___________________________.  Serial.read() is great, but it only reads ________________ at a time.

Serial.parseInt() can be used to convert chars in the serial receive buffer into ___________.

There are three ______________ modes: SKIP_ALL, ____________, and _____________.  The default lookahead mode is _______________.

You can ___________ a specific character in the serial receive buffer with parseInt(). The datatype that parseInt() returns is ____________.

Thanks a ton for watching and I hope you learned something useful. Make sure to check back soon for other great lessons. And if you really want to jump start your training, check out Programming Electronics Academy membership program. We have video courses that will teach you how to program Arduino to prototype the cool projects you have in mind!

installing Arduino libraries

Installing Arduino Libraries | Beginners Guide

IoT sewage project

Pumping poo! An IoT sewage project

ESP32 webOTA updates

How to update ESP32 firmware using web OTA [Guide + Code]

error message Brackets Thumbnail V1

expected declaration before ‘}’ token [SOLVED]

Compilation SOLVED | 1

Compilation error: expected ‘;’ before [SOLVED]

Learn how to structure your code

4 Comments

  1. Kalpesh on August 12, 2022 at 8:53 am

    parsefloat(SKIP_ALL) gives error SKIP_ALL not delcared. ?

    • Michael James on August 12, 2022 at 9:24 am

      Hmmm…Works on my end. Are you using Serial.parseFloat(SKIP_ALL)?

      I notice in your comment you have parsefloat(SKIP_ALL) with the F not capped, but I think you’d be getting the error on that as well.

  2. Tony on September 15, 2022 at 11:28 pm

    Hi,
    Been trying, but without any success to use a (SoftwareSerial.parseInt();) software serial rather than a classic serial, unfortunately, keep getting an error : ( SoftwareSerial) was not declared in this page.
    Seems that parseInt has been only assigned to a serial.parseInt, I guess.
    your replaying is appreciated.
    Regards.

    • Michael James on September 16, 2022 at 9:14 am

      Hi Tony, I think you’re correct. It does not look like parseInt() has been implemented with the Software Serial Library.

Leave a Comment