Arduino Core and ESP32 APIs
The Arduino Core for ESP32 allows you to program ESP32 microcontrollers using familiar Arduino functions and C++.
Instead of writing low-level hardware instructions for every task, you can use APIs (Application Programming Interfaces) to control GPIO pins, read sensors, manage timers, communicate over serial, connect to Wi-Fi, and interact with other hardware.
In this lesson, you will learn how the Arduino-ESP32 core works, explore its most useful APIs, and build practical examples for IoT projects.
1. What Is the Arduino Core for ESP32?
The Arduino Core for ESP32 is a software framework that lets you develop applications for ESP32-family microcontrollers using the Arduino programming model.
It provides functions and libraries for interacting with hardware and system features.
For example:
#include <Arduino.h> void setup() { pinMode(2, OUTPUT); digitalWrite(2, HIGH); } void loop() { }
This program configures GPIO 2 as an output and sets it HIGH.
Without a hardware abstraction framework, you would need to work much closer to the chip's registers and low-level drivers.
What Does the Arduino Core Provide?
The Arduino-ESP32 core includes APIs for:
- GPIO input and output.
- Analog-to-digital conversion (ADC).
- Pulse-width modulation (PWM).
- Serial communication.
- Timing and delays.
- I2C and SPI communication.
- Wi-Fi and supported Bluetooth features.
- Hardware timers and interrupts.
- Persistent configuration storage.
- Networking and HTTP-related functionality through supported libraries.
The exact APIs available depend on the ESP32 chip, board, core version, and installed libraries.
2. How the Arduino Core Works
An Arduino ESP32 sketch generally contains two main functions:
void setup() { // Runs once during normal sketch startup } void loop() { // Runs repeatedly }
setup()
The setup() function runs once when the sketch starts.
It is commonly used to:
- Initialize Serial communication.
- Configure GPIO pins.
- Initialize sensors and displays.
- Set up Wi-Fi.
- Initialize application state.
loop()
The loop() function is repeatedly called by the Arduino framework.
It is commonly used to:
- Read sensors.
- Update actuators.
- Check button inputs.
- Process commands.
- Update application state.
On ESP32, the Arduino framework operates on top of ESP-IDF and FreeRTOS. The framework manages the underlying execution environment, so you usually do not need to create an RTOS task for a basic Arduino sketch.
Important: A long blocking operation inside loop() can delay other application work. Use non-blocking timing and appropriate asynchronous APIs when your project needs to remain responsive.
3. Including the Arduino Core
For a typical Arduino-ESP32 sketch, include:
#include <Arduino.h>
This header provides the core Arduino declarations used by functions such as:
pinMode(); digitalWrite(); digitalRead(); analogRead(); millis(); micros(); delay(); Serial.begin();
Arduino IDE automatically includes the Arduino core declarations in many .ino sketches. Explicitly including Arduino.h is good practice in ordinary .cpp files and makes dependencies clear.
4. GPIO APIs
GPIO stands for General-Purpose Input/Output.
GPIO pins allow the ESP32 to interact with external hardware such as:
- LEDs.
- Push buttons.
- Relays.
- Buzzers.
- Digital sensors.
- Motor driver control inputs.
The most common GPIO APIs are pinMode(), digitalWrite(), and digitalRead().
4.1 pinMode()
This function configures a GPIO pin's operating mode.
Syntax:
pinMode(pin, mode);
Common modes include:
INPUT: Configures the pin as an input.OUTPUT: Configures the pin as an output.INPUT_PULLUP: Enables an internal pull-up where supported.INPUT_PULLDOWN: Enables an internal pull-down where supported.
Example:
pinMode(2, OUTPUT); pinMode(4, INPUT); pinMode(5, INPUT_PULLUP);
Not every pin supports every feature in the same way. Consult the documentation for your particular chip and board.
4.2 digitalWrite()
This function sets a digital output HIGH or LOW.
Syntax:
digitalWrite(pin, value);
Example:
digitalWrite(2, HIGH); digitalWrite(2, LOW);
HIGH and LOW represent the output logic levels. ESP32 GPIO is generally 3.3 V logic and is not designed to tolerate 5 V directly.
Do not drive motors, high-current loads, or relay coils directly from GPIO pins. Use suitable driver circuits and power supplies.
4.3 digitalRead()
This function reads a digital input.
Syntax:
int state = digitalRead(pin);
It returns HIGH or LOW.
Example:
const int BUTTON_PIN = 4; void setup() { Serial.begin(115200); pinMode(BUTTON_PIN, INPUT_PULLUP); } void loop() { int buttonState = digitalRead(BUTTON_PIN); if (buttonState == LOW) { Serial.println("Button pressed"); } delay(100); }
With INPUT_PULLUP, a button connected between GPIO 4 and GND normally reads HIGH when released and LOW when pressed.
This example does not implement button debouncing, so a mechanical button may produce multiple rapid state changes.
5. Complete GPIO Example: LED and Button
This example combines digital input and output.
#include <Arduino.h> const int LED_PIN = 2; const int BUTTON_PIN = 4; void setup() { Serial.begin(115200); pinMode(LED_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT_PULLUP); } void loop() { bool pressed = (digitalRead(BUTTON_PIN) == LOW); digitalWrite(LED_PIN, pressed ? HIGH : LOW); if (pressed) { Serial.println("Button is pressed"); } delay(50); }
How It Works
- The LED pin is configured as an output.
- The button pin is configured as an input with a pull-up.
- The program reads the button state.
- The LED turns on while the button is pressed.
- Serial Monitor reports the pressed state.
GPIO 2 and GPIO 4 are example pins. Check your development board's pinout before connecting hardware.
6. Analog Input APIs
Analog sensors can produce voltages that vary with a physical quantity, such as light intensity or a potentiometer's position.
The ESP32's ADC converts an analog input voltage into a digital reading.
6.1 analogRead()
Syntax:
int value = analogRead(pin);
Example:
#include <Arduino.h> const int SENSOR_PIN = 34; void setup() { Serial.begin(115200); } void loop() { int value = analogRead(SENSOR_PIN); Serial.print("ADC reading: "); Serial.println(value); delay(500); }
On classic ESP32 devices, the default Arduino ADC reading is commonly 12-bit, producing values from 0 to 4095. Other ESP32-family chips or configurations may differ.
The reading is not automatically a calibrated voltage or physical measurement.
6.2 analogReadResolution()
This API selects the resolution used for analog readings where supported.
Example:
analogReadResolution(12);
For a 12-bit reading, the nominal digital range is 0–4095.
Changing the resolution changes the digital representation; it does not change the sensor's actual voltage.
6.3 analogSetAttenuation()
On supported ESP32 targets and core versions, this function configures ADC attenuation.
Example:
analogSetAttenuation(ADC_11db);
The available attenuation settings and voltage ranges vary by chip and core version. Do not assume that a particular ADC configuration makes a pin safe for any voltage.
Safety note: Never apply a voltage above the permitted GPIO input range. Use appropriate voltage dividers, level shifting, or signal conditioning when necessary.
7. PWM APIs for LED Brightness
Pulse-width modulation (PWM) controls the average power delivered to a load by switching a digital signal on and off rapidly.
It is useful for:
- Adjusting LED brightness.
- Controlling compatible motor driver inputs.
- Generating control signals for supported devices.
The Arduino-ESP32 core provides LEDC APIs for hardware PWM.
Basic LEDC Functions
On current Arduino-ESP32 3.x releases, the common API includes:
ledcAttach(pin, frequency, resolution)ledcWrite(pin, duty)
Older Arduino-ESP32 2.x examples often use a different API based on ledcSetup(), ledcAttachPin(), and channel numbers.
Check your installed core version before combining examples from different versions.
Example: LED Brightness
#include <Arduino.h> const int LED_PIN = 2; const int PWM_FREQUENCY = 5000; const int PWM_RESOLUTION = 8; void setup() { Serial.begin(115200); if (!ledcAttach(LED_PIN, PWM_FREQUENCY, PWM_RESOLUTION)) { Serial.println("PWM setup failed"); } } void loop() { for (int duty = 0; duty <= 255; duty++) { ledcWrite(LED_PIN, duty); delay(10); } for (int duty = 255; duty >= 0; duty--) { ledcWrite(LED_PIN, duty); delay(10); } }
Understanding the Parameters
LED_PIN: GPIO pin connected to the LED.PWM_FREQUENCY: PWM frequency in hertz.PWM_RESOLUTION: Number of bits used for the duty value.duty: PWM duty value.
With 8-bit resolution, the duty value ranges from 0 to 255.
A duty value of 0 corresponds to 0% duty, while 255 corresponds to the maximum duty setting for this resolution.
This example uses delay() during the fade. A non-blocking version can use millis() when other operations must continue during the fade.
8. Timing APIs
Timing functions allow you to control how often tasks run.
8.1 delay()
Pauses the current Arduino task for a specified number of milliseconds.
delay(1000);
This waits approximately one second.
Use delays for simple demonstrations, startup pauses, and situations where blocking is acceptable. Avoid long delays in responsive applications.
8.2 millis()
Returns the number of milliseconds since the current sketch started.
unsigned long currentTime = millis();
It is useful for scheduling actions without waiting inside a delay.
Non-Blocking LED Example
#include <Arduino.h> const int LED_PIN = 2; unsigned long previousMillis = 0; const unsigned long INTERVAL_MS = 1000; bool ledState = false; void setup() { Serial.begin(115200); pinMode(LED_PIN, OUTPUT); } void loop() { unsigned long currentMillis = millis(); if (currentMillis - previousMillis >= INTERVAL_MS) { previousMillis = currentMillis; ledState = !ledState; digitalWrite(LED_PIN, ledState ? HIGH : LOW); Serial.println(ledState ? "LED ON" : "LED OFF"); } // Other tasks can run here. }
The subtraction-based comparison works correctly across the normal unsigned millis() rollover, provided the interval is handled appropriately.
8.3 micros()
Returns the number of microseconds since the sketch started.
unsigned long startTime = micros(); // Operation being measured unsigned long elapsedTime = micros() - startTime;
Use it for short timing measurements where its resolution and accuracy are suitable. It is not a substitute for a hardware timer when precise timing guarantees are required.
9. Serial Communication APIs
Serial communication is essential for debugging and sending data between a computer and an ESP32.
The main Arduino Serial object is commonly used through the USB-to-UART interface or a board's USB serial implementation, depending on the hardware and configuration.
9.1 Serial.begin()
Initializes serial communication.
Serial.begin(115200);
The number 115200 is the baud rate for a conventional UART serial connection. Some USB CDC configurations behave differently, depending on the board and settings.
9.2 Serial.print() and Serial.println()
Print text or values.
Serial.print("Temperature: "); Serial.println(28.5);
print() continues on the same line, while println() appends a line ending.
9.3 Serial.available() and Serial.read()
These APIs allow your program to receive serial input.
Example:
#include <Arduino.h> void setup() { Serial.begin(115200); Serial.println("Type a character:"); } void loop() { if (Serial.available() > 0) { char received = Serial.read(); Serial.print("Received: "); Serial.println(received); } }
This reads one available byte at a time. Serial Monitor line endings may produce additional characters, so account for them when processing commands.
10. I2C APIs
I2C is a serial communication protocol commonly used with sensors, RTC modules, and displays.
The Arduino Wire library provides I2C functionality.
Include the header:
#include <Wire.h>
Initialize the bus:
Wire.begin(SDA_PIN, SCL_PIN);
The SDA and SCL pins depend on the board and your wiring. Many classic ESP32 development boards commonly use GPIO 21 for SDA and GPIO 22 for SCL, but these are not universal defaults for every ESP32 target.
Basic I2C Scanner
#include <Arduino.h> #include <Wire.h> const int SDA_PIN = 21; const int SCL_PIN = 22; void setup() { Serial.begin(115200); Wire.begin(SDA_PIN, SCL_PIN); Serial.println("Scanning I2C bus..."); int devicesFound = 0; for (uint8_t address = 1; address < 127; address++) { Wire.beginTransmission(address); uint8_t error = Wire.endTransmission(); if (error == 0) { Serial.print("Device found at address 0x"); if (address < 16) { Serial.print("0"); } Serial.println(address, HEX); devicesFound++; } } Serial.print("Devices found: "); Serial.println(devicesFound); } void loop() { }
This scanner attempts to identify responding I2C addresses. It cannot identify every device model, and some devices may not respond to a simple address probe.
11. SPI APIs
SPI is a synchronous communication protocol used by devices such as RFID readers, displays, and some storage modules.
The Arduino SPI library provides basic SPI functionality.
Include:
#include <SPI.h>
Initialize the bus:
SPI.begin();
The default pin mapping depends on the target and board configuration. You can specify suitable pins when supported:
SPI.begin(SCK_PIN, MISO_PIN, MOSI_PIN, SS_PIN);
A device-specific library usually handles the detailed SPI transactions. Make sure its configuration matches the wiring, voltage levels, and supported SPI mode.
SPI generally uses clock, controller-out/controller-in data lines, and a chip-select signal for each selected device. Exact terminology and signal direction depend on the role of each SPI participant.
12. Wi-Fi APIs
The ESP32 Arduino Wi-Fi library provides APIs to connect to wireless networks and inspect the connection state.
Include:
#include <WiFi.h>
Common APIs include:
WiFi.mode()WiFi.begin()WiFi.status()WiFi.localIP()WiFi.disconnect()
Example: Connect to Wi-Fi
#include <Arduino.h> #include <WiFi.h> const char* ssid = "YOUR_WIFI_NAME"; const char* password = "YOUR_WIFI_PASSWORD"; void setup() { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); Serial.println("Connecting to Wi-Fi..."); } void loop() { if (WiFi.status() == WL_CONNECTED) { Serial.print("Connected. IP address: "); Serial.println(WiFi.localIP()); delay(5000); } else { Serial.println("Waiting for Wi-Fi..."); delay(1000); } }
This example prints the IP address every five seconds after connection. It does not implement an explicit reconnection strategy.
For a more responsive application, avoid repeatedly blocking with long delays. Track connection state and react to changes.
Keep credentials out of public repositories and logs.
13. Bluetooth APIs
ESP32-family chips have different wireless capabilities. Some support Bluetooth Classic and Bluetooth Low Energy (BLE), while others support BLE only.
For supported targets, Classic Bluetooth serial can be used through:
#include <BluetoothSerial.h>
A basic example for a compatible ESP32 target is:
#include <Arduino.h> #include <BluetoothSerial.h> BluetoothSerial SerialBT; void setup() { Serial.begin(115200); if (!SerialBT.begin("ESP32_Device")) { Serial.println("Bluetooth initialization failed"); return; } Serial.println("Bluetooth started"); } void loop() { if (SerialBT.available()) { char received = SerialBT.read(); Serial.print("Received: "); Serial.println(received); SerialBT.write(received); } }
This example requires a target that supports the BluetoothSerial implementation. It is not suitable for every ESP32-family chip.
For BLE, use an appropriate BLE library and its documented server, service, characteristic, and advertising APIs.
14. Persistent Storage APIs
Variables stored in RAM are generally lost when the ESP32 restarts or loses power.
The Preferences library provides convenient key-value storage using the ESP32's non-volatile storage system on supported targets.
Include:
#include <Preferences.h>
Example: Save a Counter
#include <Arduino.h> #include <Preferences.h> Preferences preferences; void setup() { Serial.begin(115200); preferences.begin("app", false); int bootCount = preferences.getInt("count", 0); bootCount++; preferences.putInt("count", bootCount); Serial.print("Boot count: "); Serial.println(bootCount); preferences.end(); } void loop() { }
Each time the program starts, it reads the previous count, increments it, and stores the new value.
Writing to non-volatile storage has a finite endurance. Avoid writing rapidly in every loop iteration; save only when necessary.
15. Hardware Interrupt APIs
Interrupts allow supported hardware events to trigger a callback instead of requiring the main loop to poll continuously.
The Arduino API commonly uses:
attachInterrupt(digitalPinToInterrupt(pin), callback, mode);
Common trigger modes include:
RISINGFALLINGCHANGE
The supported modes depend on the target and pin.
Example: Count Button Events
#include <Arduino.h> const int BUTTON_PIN = 4; volatile unsigned long eventCount = 0; void IRAM_ATTR onButtonChange() { eventCount++; } void setup() { Serial.begin(115200); pinMode(BUTTON_PIN, INPUT_PULLUP); attachInterrupt( digitalPinToInterrupt(BUTTON_PIN), onButtonChange, FALLING ); } void loop() { static unsigned long lastReportedCount = 0; unsigned long count; noInterrupts(); count = eventCount; interrupts(); if (count != lastReportedCount) { Serial.print("Button events: "); Serial.println(count); lastReportedCount = count; } delay(20); }
Important Interrupt Rules
- Keep interrupt service routines short.
- Do not call
Serial.print()from an interrupt handler. - Avoid blocking functions and operations that are not interrupt-safe.
- Use appropriate synchronization when sharing data between an interrupt and the main program.
volatileprevents certain compiler optimizations but does not by itself make compound operations atomic.- Mechanical buttons need debouncing.
The IRAM_ATTR macro is commonly used for ESP32 interrupt handlers, but exact interrupt constraints depend on the chip and framework configuration. For high-rate events, consider hardware peripherals or a carefully designed task-based architecture.
16. Watchdog and System APIs
ESP32 applications run on a system that includes scheduling, watchdog mechanisms, and other platform services.
A watchdog helps detect situations where tasks fail to make progress as expected.
You should design application code to avoid long blocking operations, unbounded loops, and operations that prevent required system tasks from running.
For most Arduino projects:
- Keep the main loop responsive.
- Use finite operations where practical.
- Check network and sensor errors.
- Avoid disabling watchdog protection to hide design problems.
- Use ESP-IDF documentation when you need direct control over lower-level system facilities.
Low-level watchdog APIs can vary across ESP-IDF and Arduino-ESP32 versions, so consult the documentation matching your installed core before using them.
17. Arduino Core APIs vs. ESP-IDF APIs
The Arduino Core for ESP32 is built on top of ESP-IDF, Espressif's development framework.
| Feature | Arduino Core | ESP-IDF |
|---|---|---|
| Programming style | Arduino APIs and C++ | Native ESP-IDF APIs, commonly C and C++ |
| GPIO | pinMode(), digitalWrite() | GPIO driver APIs |
| Serial/UART | Serial and related objects | UART driver |
| Wi-Fi | WiFi.h | Native Wi-Fi APIs |
| RTOS access | Available indirectly or through supported interfaces | Direct FreeRTOS integration and ESP-IDF facilities |
| Learning curve | Generally simpler for beginners | More detailed control and configuration |
| Best fit | Many sensor, maker, and IoT projects | Applications needing extensive system-level control |
You do not have to choose only one approach in every project. Arduino-ESP32 applications can use compatible ESP-IDF facilities, but mixing frameworks and APIs requires attention to initialization, resource ownership, configuration, and version compatibility.
18. Troubleshooting Common API Problems
GPIO Does Not Work
Check:
- Whether the pin exists on your board.
- Whether it is input-only or reserved for another purpose.
- Whether the correct pin mode was configured.
- Whether the wiring and ground connections are correct.
- Whether the external circuit uses compatible voltage levels.
ADC Reading Is Unexpected
Check:
- Whether the sensor output is connected to an ADC-capable pin.
- Whether the input voltage is within the permitted range.
- Whether the attenuation and resolution settings are appropriate.
- Whether the sensor requires calibration.
- Whether the selected GPIO is affected by board-specific hardware.
PWM Code Does Not Compile
Check:
- Your installed Arduino-ESP32 core version.
- Whether the example uses the 2.x or 3.x LEDC API.
- Whether the pin and PWM settings are supported.
- Whether the LEDC initialization succeeded.
Wi-Fi Does Not Connect
Check:
- The SSID and password.
- The network band and security compatibility.
- Whether the selected chip supports the required Wi-Fi mode.
- Signal strength and access point availability.
- Serial output for connection status.
Library Header Is Missing
Check:
- Whether the library is installed.
- Whether the include name is correct.
- Whether the library supports your board and framework.
- Whether your build environment is using the intended dependency version.
19. Best Practices for ESP32 API Usage
- Check your exact ESP32 chip and development board documentation.
- Use the Arduino-ESP32 documentation for the installed core version.
- Avoid assuming all ESP32-family chips have identical peripherals.
- Use non-blocking timing for responsive applications.
- Keep interrupt handlers short.
- Validate sensor values before acting on them.
- Avoid excessive writes to flash-based storage.
- Use appropriate drivers for motors, relays, and other loads.
- Never apply 5 V directly to an ESP32 GPIO unless the exact pin and hardware documentation explicitly permits it.
- Keep Wi-Fi credentials and secrets out of public repositories.
- Check API return values where available.
- Test hardware features independently before combining them into a large project.
20. Practice Exercises
Beginner
- Configure a GPIO as an output and blink an LED.
- Read a button using
INPUT_PULLUP. - Print an ADC reading from a potentiometer.
- Measure elapsed time using
millis(). - Receive a character from Serial Monitor and respond to it.
Intermediate
- Control LED brightness using LEDC PWM.
- Scan an I2C bus and identify a connected device address.
- Connect an ESP32 to Wi-Fi and print its local IP address.
- Store a configuration value using
Preferences. - Build a non-blocking program that reads a sensor every second.
Advanced
- Design an event-driven application that uses GPIO interrupts safely.
- Compare Arduino GPIO functions with the corresponding ESP-IDF driver APIs.
- Create a project that reads an I2C sensor and publishes measurements over Wi-Fi.
- Investigate the differences between LEDC APIs in Arduino-ESP32 2.x and 3.x.
- Build a smart alert system that combines sensor inputs, a buzzer, and network reporting.
Summary
The Arduino Core for ESP32 provides a practical way to control hardware and build IoT applications using C++.
In this lesson, you learned about:
- The Arduino framework and its execution model.
- GPIO input and output APIs.
- ADC and analog readings.
- LEDC PWM.
- Timing with
delay(),millis(), andmicros(). - Serial communication.
- I2C and SPI.
- Wi-Fi and supported Bluetooth APIs.
- Persistent storage with
Preferences. - Hardware interrupts.
- The relationship between Arduino-ESP32 and ESP-IDF.
- Troubleshooting and hardware safety.
Key takeaway: Arduino APIs simplify ESP32 development, but reliable applications still require an understanding of the underlying hardware, chip-specific capabilities, API versions, and resource limitations.