Arduino Char to Int

  1. Convert char to int Using the Simple Method in Arduino
  2. Convert char to int Using the toInt() Function in Arduino
  3. Convert char to int Using the Serial.parseInt() Function in Arduino

This tutorial will discuss three methods to convert a char into an int. The first method is the simple method where we can only convert one char at a time. The second method is to use the toInt() function and the third is to use the Serial.parseInt() function.

Convert char to int Using the Simple Method in Arduino

This method can only convert a single char into an int. You need to subtract a zero of type char from the char to convert it into an int.

void loop{
    char someChar = '2';  // variable to store char
    int someInt = someChar - '0';
}

In the above code, someChar is a variable of type char to store the char to be converted. You can change its value to the given char variable. someInt is a variable of type int to store the result of the conversion. If the given variable is not a single char, then use the below methods.

Convert char to int Using the toInt() Function in Arduino

In this method, first, you will convert the given char into a string and then use the toInt() function to convert the string into an int.

void loop(){
    char someChar = '123';
    String stringOne = String('a');// converting a constant char into a String
    stringOne.toInt();
}

In the above code, someChar is a variable of type char to store the given char. stringOne is a variable of type String. If the string does not start with a valid number, the conversion won’t be possible, and a zero will be returned. Check the link for more information.

Convert char to int Using the Serial.parseInt() Function in Arduino

You can use this method if you are reading input from a serial port of an Arduino and want to convert the received input into an Int.

void loop(){
    
    if (Serial.available()>0){      
         int valA = Serial.parseInt();
  }
}

Parsing will stop if no value has been read or a non-digit is read. If no valid input is read until timeout, then 0 will be returned. See Serial.setTimeout() to set the timeout of the serial. Check this link for more information about Serial.parseInt() function.

Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Arduino Integer

  • Convert Integer to String in Arduino