By RAN | 17 May 2024 | 0 Comments
HOW to make a Button-controlled LED with ESP32
Overview
In this lesson, we will make an extension experiment with a button and an LED. When the button is pressed and low levels are output, the LED will light up; when the button is released, the LED will go off. Then we can control a module with another module.
Components
|
|
|
---|---|---|
ESP32 Board*1 |
ESP32 Expansion Board*1 |
Keyestudio Purple LED Module*1 |
|
|
|
Keyestudio DIY Button Module*1 |
3P Dupont Wire*2 |
Micro USB Cable*1 |
Connection Diagram
Test Code
//**********************************************************************
/*
* Description : Make a table lamp.
* Auther : http//www.keyestudio.com
*/
#define PIN_LED 4
#define PIN_BUTTON 15
bool ledState = false;
void setup() {
// initialize digital pin PIN_LED as an output.
pinMode(PIN_LED, OUTPUT);
pinMode(PIN_BUTTON, INPUT);
}
// the loop function runs over and over again forever
void loop() {
if (digitalRead(PIN_BUTTON) == LOW) {
delay(20);
if (digitalRead(PIN_BUTTON) == LOW) {
reverseGPIO(PIN_LED);
}
while (digitalRead(PIN_BUTTON) == LOW);
}
}
void reverseGPIO(int pin) {
ledState = !ledState;
digitalWrite(pin, ledState);
}
//**********************************************************************
Test Result
Connect the wires according to the experimental wiring diagram, compile and upload the code to the ESP32. After uploading successfully,we will use a USB cable to power on. When the button is pressed, the LED will light up; when pressed again, the LED will go off.
Leave a Reply
Your email address will not be published.Required fields are marked. *
CATEGORIES