Home › Wiring › LED with ESP32

LED with ESP32

How to connect an LED to an ESP32: the wiring, a sketch that works, and a simulator to try it in your browser before you build it.

LED wired to an ESP32 in Zen Circuit Lab

5 mm red · Vf ≈ 1.9 V @ 20 mA

Wiring

LED pinESP32
pin 1GPIO26 (through a 220 Ω resistor)
pin 2GND

Every LED needs a series resistor: 220 Ω on a 5 V Arduino gives about 13 mA; on a 3.3 V ESP32 about 6 mA.

Run it in the labFree, no account needed. The same wiring, with the sketch already on the board.

Code

From the project ESP32 water tank level meter: HC-SR04 and OLED. It also compiles in the Arduino IDE (ESP32 core 3.x) with the libraries it includes.

// Water tank level: an HC-SR04 at the top of the tank (TRIG GPIO5, ECHO GPIO18 through a 1k/2k divider, since ECHO is 5 V)
// measures the gap to the water; the OLED shows the level in %; the red LED (GPIO26) lights below 20 %.
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
Adafruit_SSD1306 display(128, 64, &Wire, -1);
const int TRIG = 5, ECHO = 18, LOW_LED = 26;
const float EMPTY_CM = 100, FULL_CM = 20;   // gap to the water when the tank is empty / full

void setup() {
  Serial.begin(115200);
  pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT); pinMode(LOW_LED, OUTPUT);
  Wire.begin(21, 22);
  if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) Serial.println("OLED not found");
}

void loop() {
  digitalWrite(TRIG, LOW); delayMicroseconds(2);
  digitalWrite(TRIG, HIGH); delayMicroseconds(10); digitalWrite(TRIG, LOW);
  unsigned long us = pulseIn(ECHO, HIGH, 30000);
  float cm = us / 58.0;
  int pct = constrain((int)((EMPTY_CM - cm) * 100 / (EMPTY_CM - FULL_CM)), 0, 100);
  digitalWrite(LOW_LED, pct < 20 ? HIGH : LOW);
  display.clearDisplay();
  display.setTextColor(SSD1306_WHITE);
  display.setTextSize(1); display.setCursor(0, 0); display.print("Water tank");
  display.setTextSize(3); display.setCursor(0, 20); display.print(pct); display.print("%");
  display.drawRect(100, 10, 24, 50, SSD1306_WHITE);
  display.fillRect(102, 58 - pct * 46 / 100, 20, pct * 46 / 100, SSD1306_WHITE);
  display.display();
  Serial.print("Gap "); Serial.print(cm, 0); Serial.print(" cm  level "); Serial.print(pct); Serial.println(" %");
  delay(500);
}

Also used in

For teachers

The project runs in the browser on a laptop or a phone, so every student can build and test it before the class touches a real board. Assign it on the teacher's page and set what counts as done: a prediction, a hidden fault found, or a passing test sheet.

Related