ES-2Pemula

ESP32 LED Control with Push Button (Push)

The LED lights up when the button is pressed and turns off when released. Shows how the ESP32's digital input pin and internal pull-up resistor are used. The INPUT_PULLUP mode eliminates the need for an external resistor.

4.6(36)
57 selesai
ESP32 LED Control with Push Button (Push)
Just like a doorbell: the light stays on while you press and goes off when you let go. The ESP32 keeps listening to the button; while it's held down the LED is on, and the moment you release it the LED turns off. You see in the simplest way how the board senses a touch from the outside world.

Video

Gambar Rajah Litar

ESP32 LED Control with Push Button (Push) - Gambar Rajah Litar

Kod Sumber

C++ (Arduino IDE)
1// ─────────────────────────────────────────
2//   BlueGrays · bluegrays.com
3//   ESP32 LED Control with Push Button (Push)
4// ─────────────────────────────────────────
5// The LED stays on while the button is held down and turns off when it is
6// released. The button pin uses the internal pull-up (INPUT_PULLUP), so no
7// external resistor is needed.
8//
9// Pins:
10//   GPIO 5 -> Red LED (with a 220 ohm resistor)
11//   GPIO 4 -> Button (other leg to GND)
12
13const int LED_PIN = 5;      // LED output
14const int BUTTON_PIN = 4;   // Button input
15
16void setup() {
17  pinMode(LED_PIN, OUTPUT);
18  pinMode(BUTTON_PIN, INPUT_PULLUP);  // Reads HIGH when not pressed
19}
20
21void loop() {
22  // A pressed button pulls the pin to GND: LOW = pressed
23  if (digitalRead(BUTTON_PIN) == LOW) {
24    digitalWrite(LED_PIN, HIGH);
25  } else {
26    digitalWrite(LED_PIN, LOW);
27  }
28}
29

Soalan Lazim

How do you connect a button using INPUT_PULLUP?

One leg of the button is connected to a GPIO pin, and the other to GND. The internal pull-up resistor keeps the pin at HIGH; when the button is pressed, the pin is pulled down to GND and reads LOW. No external resistor is required.

Why is logic turning upside down?

When the pull-up resistor is used, the value reads HIGH when the button is not pressed and LOW when it is pressed. Therefore, the condition 'if (digitalRead(button) == LOW)' in the code indicates that the button has been pressed.

Which pins do not have internal pull-ups?

GPIO 34, 35, 36, and 39 are input pins only and do not have internal pull-up or pull-down resistors. If you plan to use a button on these pins, you must add an external 10 kΩ resistor.

Can I replace the button with a touch sensor?

Yes, the ESP32 has built-in touch pins (e.g., GPIO 4, 13, 14, 15, 27). You can use `touchRead()` to detect a touch on a wire or metal plate as if it were a button.