arduino int to string

In Arduino int to string is converted by using the inbuilt functions! You often need to convert integers to strings for various purposes such as displaying values on an LCD screen, sending data over serial communication, or creating formatted text. Arduino provides several ways to convert an integer to a string.

Methods for arduino int to string

  1. Using String() Constructor
  2. Using itoa() Function
  3. Using sprintf() Function
  4. Manual Conversion
  5. Arduino int to string Conversion: Real-Life Scenarios

1. Using String() Constructor to convert integers to strings

The String class provides an easy way to convert an integer to a string using its constructor which is one of the main inbuilt function for int to string.

int number = 456;

void setup() {
    Serial.begin(9600);
    String str = String(number);
    Serial.println(str);  // Output: 456
}

void loop() {
    // Nothing to do here
}
arduino int to string in - declaring the number as int for 456 and in setup use the String() function with a serial channel to print the converted int to str

For more info check out: arduino.cc – String()

2. Using itoa() Function for converting ints to strings

The itoa() function is a C standard library function that converts an integer to a null-terminated string which is an inbuilt function for performing int to string.

Syntax

char* itoa(int value, char* str, int base);
  • value: The integer to be converted.
  • str: The buffer to store the resulting string.
  • base: The numerical base (e.g., 10 for decimal, 16 for hexadecimal).
int number = 123;
char buffer[10];

void setup() {
    Serial.begin(9600);
    itoa(number, buffer, 10);
    Serial.println(buffer);  // Output: 123
}

void loop() {
    // Nothing to do here
}

3. Using sprintf() Function to convert an integer to string

The sprintf() function is another C standard library function that formats and stores a series of characters and values in the array.

Syntax

int sprintf(char* str, const char* format, ...);
  • str: The buffer to store the resulting string.
  • format: The format string (e.g., “%d” for integers).
int number = 789;
char buffer[10];

void setup() {
    Serial.begin(9600);
    sprintf(buffer, "%d", number);
    Serial.println(buffer);  // Output: 789
}

void loop() {
    // Nothing to do here
}
arduino int to string in - declaring the number as int for 789 and in setup use the sprintf() function with serial channel to print the converted int to str

4. Manual Conversion of integers to strings

You can also manually convert arduino int to string by dividing the number by 10 and storing the remainders.

int number = 321;
char buffer[10];

void setup() {
    Serial.begin(9600);
    intToStr(number, buffer);
    Serial.println(buffer);  // Output: 321
}

void loop() {
    // Nothing to do here
}

void intToStr(int num, char* str) {
    int i = 0;
    bool isNegative = false;

    // Handle 0 explicitly
    if (num == 0) {
        str[i++] = '0';
        str[i] = '\0';
        return;
    }

    // Handle negative numbers
    if (num < 0) {
        isNegative = true;
        num = -num;
    }

    // Process individual digits
    while (num != 0) {
        int rem = num % 10;
        str[i++] = rem + '0';
        num = num / 10;
    }

    // If number is negative, add '-'
    if (isNegative) {
        str[i++] = '-';
    }

    str[i] = '\0';  // Append null terminator

    // Reverse the string
    reverseStr(str, i);
}

void reverseStr(char* str, int length) {
    int start = 0;
    int end = length - 1;
    while (start < end) {
        char temp = str[start];
        str[start] = str[end];
        str[end] = temp;
        start++;
        end--;
    }
}
arduino int to string in - declaring the number as int for 321 and in setup use the a custom made intToStr function with serial channel to print the converted int to str

Arduino int to string Conversion: Real-Life Scenarios

Example 1: Displaying Sensor Values on an LCD

When using an OLED to display numbers, you often need to convert integer values to strings.

int number = 111;

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
// The pins for I2C are defined by the Wire-library. 
// On an arduino UNO:       A4(SDA), A5(SCL)
// On an arduino MEGA 2560: 20(SDA), 21(SCL)
// On an arduino LEONARDO:   2(SDA),  3(SCL), ...
#define OLED_RESET     -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C ///< See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);


void setup() 
  {
    String str = String(number);
    display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
    display.clearDisplay();
    
  }

void loop() 
  {
  display.setTextSize(1.5);
  display.setTextColor(WHITE);
  display.setCursor(30,0);
  display.println("SlyAutomation!");
  display.println(str);
  display.setCursor(30,17);
  display.println("Coding with Sly!");
  display.display();
  }

int to string displayed on a arduino linked with a OLED display

This code is designed to display text on an OLED screen connected to an Arduino. It uses the Adafruit SSD1306 library to manage the display.

Variable Declaration of integer

int number = 111;
  • Declares an integer variable named number and initializes it to 111.

Include Libraries for converting the integer to string and visualise

#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
  • Includes necessary libraries:
  • SPI.h and Wire.h are for communication protocols.
  • Adafruit_GFX.h provides graphics functions.
  • Adafruit_SSD1306.h is specific to the SSD1306 OLED display.

Define Screen Parameters

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels
  • Defines constants for the screen width and height.

OLED Display Setup

#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
#define SCREEN_ADDRESS 0x3C // See datasheet for Address; 0x3D for 128x64, 0x3C for 128x32
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
  • Defines the reset pin for the OLED display. Here -1 indicates that the reset pin is shared with the Arduino reset pin.
  • Defines the I2C address of the display (0x3C for a 128×32 display).
  • Creates an instance of the Adafruit_SSD1306 display object with the specified width, height, and communication method (I2C).

Setup Function to perform the int to string conversion

void setup() 
{
  String str = String(number);
  display.begin(SSD1306_SWITCHCAPVCC, SCREEN_ADDRESS);
  display.clearDisplay();
}
  • setup() is run once when the Arduino starts.
  • Converts the integer number to a string and stores it in str (though str is not used later in this code).
  • Initializes the display with display.begin(), specifying the power source type (SSD1306_SWITCHCAPVCC) and the I2C address (SCREEN_ADDRESS).
  • Clears the display buffer with display.clearDisplay().

Loop Function to display the converted int to string

void loop() 
{
  display.setTextSize(1.5);
  display.setTextColor(WHITE);
  display.setCursor(30,0);
  display.println("SlyAutomation!");
  display.println(str);
  display.setCursor(30,17);
  display.println("Coding with Sly!");
  display.display();
}
  • loop() runs continuously after setup().
  • Sets the text size to 1.5 using display.setTextSize().
  • Sets the text color to white using display.setTextColor(WHITE).
  • Sets the cursor position to (30,0) using display.setCursor().
  • Prints “SlyAutomation!” and the value of str (111) to the display using display.println().
  • Sets the cursor position to (30,17).
  • Prints “Coding with Sly!”.
  • Finally, display.display() updates the actual display with all the text printed since the last clearDisplay().

Example 2: Displaying Sensor Values on an LCD

When using an LCD to display sensor readings, you often need to convert integer values to strings.

#include <LiquidCrystal.h>

// Initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int sensorPin = A0;  // Analog input pin for the sensor
int sensorValue = 0;

void setup() {
    lcd.begin(16, 2);  // Set up the LCD's number of columns and rows
}

void loop() {
    sensorValue = analogRead(sensorPin);  // Read the sensor value
    lcd.setCursor(0, 0);  // Set cursor to first row
    lcd.print("Sensor Value:");
    lcd.setCursor(0, 1);  // Set cursor to second row

    char buffer[10];
    itoa(sensorValue, buffer, 10);  // Convert integer to string
    lcd.print(buffer);  // Display the sensor value as a string
    delay(1000);
}

This code is designed to read an analog sensor value and display it on a 16×2 LCD connected to an Arduino. It uses the LiquidCrystal library to manage the LCD.

Include Library

#include <LiquidCrystal.h>
  • Includes the LiquidCrystal library, which provides functions to control the LCD.

Initialize LCD

// Initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
  • Creates an instance of the LiquidCrystal class named lcd.
  • Initializes the library with the interface pin numbers connected to the LCD: rs (12), enable (11), d4 (5), d5 (4), d6 (3), and d7 (2).

Declare Variables

int sensorPin = A0;  // Analog input pin for the sensor
int sensorValue = 0;
  • sensorPin is set to A0, which is the analog input pin for the sensor.
  • sensorValue is an integer variable to store the sensor reading.

Setup Function

void setup() {
    lcd.begin(16, 2);  // Set up the LCD's number of columns and rows
}
  • setup() runs once when the Arduino starts.
  • lcd.begin(16, 2) initializes the LCD with 16 columns and 2 rows.

Loop Function

void loop() {
    sensorValue = analogRead(sensorPin);  // Read the sensor value
    lcd.setCursor(0, 0);  // Set cursor to first row
    lcd.print("Sensor Value:");
    lcd.setCursor(0, 1);  // Set cursor to second row

    char buffer[10];
    itoa(sensorValue, buffer, 10);  // Convert integer to string
    lcd.print(buffer);  // Display the sensor value as a string
    delay(1000);
}
  • loop() runs continuously after setup().
  • sensorValue = analogRead(sensorPin);: Reads the analog value from the sensor connected to A0 and stores it in sensorValue.
  • lcd.setCursor(0, 0);: Sets the cursor to the beginning of the first row of the LCD.
  • lcd.print("Sensor Value:");: Prints the string “Sensor Value:” on the first row of the LCD.
  • lcd.setCursor(0, 1);: Sets the cursor to the beginning of the second row of the LCD.
  • char buffer[10];: Declares a character array buffer with a size of 10 to store the converted sensor value.
  • itoa(sensorValue, buffer, 10);: Converts the integer sensorValue to a string and stores it in buffer. The 10 indicates that the number is in base 10.
  • lcd.print(buffer);: Prints the string representation of sensorValue on the second row of the LCD.
  • delay(1000);: Pauses the loop for 1000 milliseconds (1 second) before repeating.

Example 3: Arduino int to string – Sending Data Over Bluetooth

When sending integer data over Bluetooth, converting integers to strings ensures the data is correctly transmitted.

#include <SoftwareSerial.h>

SoftwareSerial BTSerial(10, 11);  // RX, TX

int temperature = 25;

void setup() {
    Serial.begin(9600);
    BTSerial.begin(9600);
}

void loop() {
    char tempStr[10];
    itoa(temperature, tempStr, 10);  // Convert integer to string
    BTSerial.println(tempStr);  // Send the string over Bluetooth
    delay(2000);
}
arduino int to string in - declaring the number as int tempeture and in setup use the itoa() function with blue tooth serial channel to print the converted int to str

This code is designed to send a temperature value over a Bluetooth connection using an Arduino. It uses the SoftwareSerial library to handle the Bluetooth communication.

Include Library

#include <SoftwareSerial.h>
  • Includes the SoftwareSerial library, which allows serial communication on other digital pins of the Arduino.

Initialize Software Serial

SoftwareSerial BTSerial(10, 11);  // RX, TX
  • Creates an instance of the SoftwareSerial class named BTSerial.
  • Initializes BTSerial with pin 10 for receiving data (RX) and pin 11 for transmitting data (TX).

Declare Variables

int temperature = 25;
  • Declares an integer variable temperature and initializes it to 25.

Setup Function

void setup() {
    Serial.begin(9600);
    BTSerial.begin(9600);
}
  • setup() runs once when the Arduino starts.
  • Serial.begin(9600); initializes the serial communication with a baud rate of 9600 bps (bits per second). This is for debugging or communication with the Arduino’s serial monitor.
  • BTSerial.begin(9600); initializes the Bluetooth serial communication with a baud rate of 9600 bps.

Loop Function

void loop() {
    char tempStr[10];
    itoa(temperature, tempStr, 10);  // Convert integer to string
    BTSerial.println(tempStr);  // Send the string over Bluetooth
    delay(2000);
}
  • loop() runs continuously after setup().
  • char tempStr[10]; declares a character array tempStr with a size of 10 to store the converted temperature value.
  • itoa(temperature, tempStr, 10); converts the integer temperature to a string and stores it in tempStr. The 10 indicates that the number is in base 10.
  • BTSerial.println(tempStr); sends the string representation of temperature over the Bluetooth connection.
  • delay(2000); pauses the loop for 2000 milliseconds (2 seconds) before repeating.

Example 4: Logging Data to an SD Card

When logging data to an SD card, you often need to format integers as strings for readability.

#include <SPI.h>
#include <SD.h>

const int chipSelect = 4;
int dataValue = 12345;

void setup() {
    Serial.begin(9600);
    if (!SD.begin(chipSelect)) {
        Serial.println("Initialization failed!");
        return;
    }
    Serial.println("Initialization done.");
}

void loop() {
    File dataFile = SD.open("datalog.txt", FILE_WRITE);
    if (dataFile) {
        char dataStr[10];
        itoa(dataValue, dataStr, 10);  // Convert integer to string
        dataFile.println(dataStr);  // Log the string to the file
        dataFile.close();
        Serial.println("Data logged");
    } else {
        Serial.println("Error opening datalog.txt");
    }
    delay(1000);
}

This code is designed to log data to an SD card using an Arduino. It uses the SPI and SD libraries to manage the SD card operations.

Include Libraries

#include <SPI.h>
#include <SD.h>
  • Includes the SPI library for SPI communication.
  • Includes the SD library to interact with the SD card.

Define Constants and Variables

const int chipSelect = 4;
int dataValue = 12345;
  • chipSelect is a constant integer set to 4, which specifies the chip select pin used for the SD card module.
  • dataValue is an integer variable set to 12345, representing the data to be logged.

Setup Function

void setup() {
    Serial.begin(9600);
    if (!SD.begin(chipSelect)) {
        Serial.println("Initialization failed!");
        return;
    }
    Serial.println("Initialization done.");
}
  • setup() runs once when the Arduino starts.
  • Serial.begin(9600); initializes serial communication with a baud rate of 9600 bps for debugging.
  • if (!SD.begin(chipSelect)) { ... } attempts to initialize the SD card. If initialization fails, it prints “Initialization failed!” to the serial monitor and exits the setup function.
  • If initialization succeeds, it prints “Initialization done.” to the serial monitor.

Loop Function

void loop() {
    File dataFile = SD.open("datalog.txt", FILE_WRITE);
    if (dataFile) {
        char dataStr[10];
        itoa(dataValue, dataStr, 10);  // Convert integer to string
        dataFile.println(dataStr);  // Log the string to the file
        dataFile.close();
        Serial.println("Data logged");
    } else {
        Serial.println("Error opening datalog.txt");
    }
    delay(1000);
}
  • loop() runs continuously after setup().
  • File dataFile = SD.open("datalog.txt", FILE_WRITE); attempts to open the file “datalog.txt” on the SD card for writing. If the file doesn’t exist, it will be created.
  • if (dataFile) { ... } checks if the file was successfully opened.
  • char dataStr[10]; declares a character array dataStr with a size of 10 to store the converted data value.
  • itoa(dataValue, dataStr, 10); converts the integer dataValue to a string and stores it in dataStr. The 10 indicates that the number is in base 10.
  • dataFile.println(dataStr); writes the string representation of dataValue to the file, followed by a newline.
  • dataFile.close(); closes the file to ensure the data is saved.
  • Serial.println("Data logged"); prints “Data logged” to the serial monitor for confirmation.
  • else { ... } prints “Error opening datalog.txt” to the serial monitor if the file couldn’t be opened.
  • delay(1000); pauses the loop for 1000 milliseconds (1 second) before repeating.

Example 5: Formatted Output on Serial Monitor

Displaying formatted data on the Serial Monitor often requires converting integers to strings.

int distance = 150;

void setup() {
    Serial.begin(9600);
}

void loop() {
    char distanceStr[10];
    sprintf(distanceStr, "Distance: %d cm", distance);  // Format integer as string
    Serial.println(distanceStr);  // Print formatted string to Serial Monitor
    delay(1000);
}
arduino int to string in - declaring the distance as int for 150 and in setup use the sprintf() function with serial channel to print the converted int to str

This code is designed to format an integer value into a string and print it to the Serial Monitor using an Arduino.

Variable Declaration

int distance = 150;
  • Declares an integer variable named distance and initializes it to 150.

Setup Function for outputting int to string in serial

void setup() {
    Serial.begin(9600);
}
  • setup() runs once when the Arduino starts.
  • Serial.begin(9600); initializes serial communication with a baud rate of 9600 bps, allowing data to be sent to the Serial Monitor.

Loop Function to convert int to strings as serial prints

void loop() {
    char distanceStr[10];
    sprintf(distanceStr, "Distance: %d cm", distance);  // Format integer as string
    Serial.println(distanceStr);  // Print formatted string to Serial Monitor
    delay(1000);
}
  • loop() runs continuously after setup().
  • char distanceStr[10]; declares a character array distanceStr with a size of 10 to store the formatted string.
  • sprintf(distanceStr, "Distance: %d cm", distance); formats the distance value into the string “Distance: 150 cm” and stores it in distanceStr.
  • sprintf is a function that works like printf, but instead of printing the result, it stores the formatted string in a character array.
  • %d is a format specifier used to insert an integer value.
  • Serial.println(distanceStr); sends the formatted string stored in distanceStr to the Serial Monitor, where it will be displayed.
  • delay(1000); pauses the loop for 1000 milliseconds (1 second) before repeating.

Summary

This code repeatedly formats the integer distance into a string that reads “Distance: 150 cm” and prints it to the Serial Monitor every second. This is useful for monitoring values in real-time during Arduino projects.

Example 6: Arduino int to string – Web Server on ESP8266/ESP32

When serving a web page from an ESP8266 or ESP32, you may need to include integer data as part of the HTML content.

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
ESP8266WebServer server(80);

int temperature = 22;

void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.println("Connecting to WiFi...");
    }

    Serial.println("Connected to WiFi");

    server.on("/", handleRoot);
    server.begin();
}

void loop() {
    server.handleClient();
}

void handleRoot() {
    char tempStr[10];
    itoa(temperature, tempStr, 10);  // Convert integer to string

    String html = "<html><body><h1>Temperature: ";
    html += tempStr;
    html += " ℃</h1></body></html>";

    server.send(200, "text/html", html);
}

This code is designed to create a simple web server using an ESP8266 module that serves a webpage displaying the current temperature. Here’s a step-by-step explanation:

Include Libraries

#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
  • Includes the ESP8266WiFi library to manage WiFi connectivity.
  • Includes the ESP8266WebServer library to set up and manage the web server.

Define Constants and Variables

const char* ssid = "your_SSID";
const char* password = "your_PASSWORD";
ESP8266WebServer server(80);

int temperature = 22;
  • Defines constants for the WiFi SSID and password.
  • Creates an instance of ESP8266WebServer named server that listens on port 80.
  • Declares an integer variable temperature and initializes it to 22.

Setup Function for web servers using arduino int into a string

void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.println("Connecting to WiFi...");
    }

    Serial.println("Connected to WiFi");

    server.on("/", handleRoot);
    server.begin();
}
  • setup() runs once when the ESP8266 starts.
  • Serial.begin(115200); initializes serial communication with a baud rate of 115200 bps for debugging.
  • WiFi.begin(ssid, password); starts the WiFi connection using the provided SSID and password.
  • while (WiFi.status() != WL_CONNECTED) { ... } waits for the WiFi connection to be established. It checks the connection status every second and prints “Connecting to WiFi…” to the Serial Monitor until connected.
  • Once connected, it prints “Connected to WiFi” to the Serial Monitor.
  • server.on("/", handleRoot); sets up a route for the root URL ("/") and assigns the handleRoot function to handle requests to this URL.
  • server.begin(); starts the web server.

Loop Function

void loop() {
    server.handleClient();
}
  • loop() runs continuously after setup().
  • server.handleClient(); processes incoming client requests. It listens for HTTP requests and calls the appropriate handler function (in this case, handleRoot).

Handle Root Function

void handleRoot() {
    char tempStr[10];
    itoa(temperature, tempStr, 10);  // Convert integer to string

    String html = "<html><body><h1>Temperature: ";
    html += tempStr;
    html += " ℃</h1></body></html>";

    server.send(200, "text/html", html);
}
  • handleRoot() is called whenever the root URL ("/") is accessed.
  • char tempStr[10]; declares a character array tempStr with a size of 10 to store the converted temperature value.
  • itoa(temperature, tempStr, 10); converts the integer temperature to a string and stores it in tempStr. The 10 indicates that the number is in base 10.
  • Constructs an HTML string that includes the temperature value:
  • String html = "<html><body><h1>Temperature: "; starts the HTML string.
  • html += tempStr; appends the temperature string to the HTML string.
  • html += " ℃</h1></body></html>"; completes the HTML string.
  • server.send(200, "text/html", html); sends the constructed HTML string as the response to the client, with an HTTP status code of 200 (OK) and a content type of “text/html”.

making an arduino int into a string Summary

This code sets up an ESP8266 as a web server that serves a simple webpage displaying the current temperature. It connects to a WiFi network, listens for HTTP requests at the root URL, and responds with an HTML page showing the temperature.

Arduino int to string Conclusion

Converting arduino int to string is a common task that can be accomplished using several methods. Each method has its own advantages and use cases. The itoa() function is simple and efficient, the String constructor is easy to use, sprintf() is versatile for formatting, and manual conversion provides deep control over the conversion process. In addition, converting integers to strings in Arduino is crucial for many practical applications, such as displaying sensor values, transmitting data over communication interfaces, logging data, and serving web content. By mastering these conversion techniques, you can handle various scenarios effectively in your Arduino projects.

Looking for guides on:

Official Arduino Store: Visit the official Arduino online store for authentic Arduino Leonardo boards. Check their website for availability.

Online Retailers:

  • Aliexpress: Aliexpress offers generic Arduino boards, such as the:
ItemImageCost ($USD)
Leonardo R3 Development Board + USB Cable ATMEGA32U4$5.72
Arduino USB Host Shield$5.31
Arduino Leonardo R3$5.72
Arduino UNO R3 Development Board$7.36
Arduino Starter Kit$29.98
Soldering Iron Kit$18.54
Arduino Sensor Kit$17.18

2 thoughts on “arduino int to string

Leave a Reply

Your email address will not be published. Required fields are marked *