ESP32 - Button - LED
The button is a basic component and widely used in many ESP32 projects. It is simple to use. However, it may make the beginners confuse, due to mechanical, physical issues and ways to use it as well. This tutorial makes it easy for the beginners
We are going to learn how to:
-
Turn on LED if button is pressing.
-
Turn off LED if button is NOT pressing.
Video Tutorial
you can watch this video tutorial
Hardware Required
1 | × | ESP-WROOM-32 Dev Module | |
1 | × | Micro USB Cable | |
1 | × | push button | |
1 | × | LED | |
1 | × | 220 ohm resistor | |
1 | × | Breadboard | |
5 | × | Jumper Wires |
Wiring Diagram
Schematic Diagram
Image is developed using Fritzing. Click to enlarge image
Breadboard Connections
ESP32 Code
const int buttonPin = 2; // the number of the pushbutton pin const int ledPin = 21; // the number of the LED pin int buttonState = 0; // variable for reading the pushbutton status void setup() { pinMode(ledPin, OUTPUT); // initialize the LED pin as an output: pinMode(buttonPin, INPUT_PULLUP); // initialize the pushbutton pin as an input: } void loop() { buttonState = digitalRead(buttonPin); // read the state of the pushbutton value: if (buttonState == HIGH) { // check if the pushbutton is pressed. If it is, the buttonState is HIGH: digitalWrite(ledPin, HIGH); // turn LED on: } else { digitalWrite(ledPin, LOW); // turn LED off: } }
Quick Steps
- power up your board
- Open Arduino IDE
- Select the right board
- Select the right port
- Copy the above code and open with Arduino IDE
- Click Upload button on Arduino IDE to upload code to ESP32
- Press and keep pressing the button several seconds
- See the changes you made
Code Explanation
-
configure an ESP32's pin to digital input mode by using pinMode() function.
-
Read the pin state by using digitalRead(pinNumber)
Read the line-by-line explanation in comment lines of source code!
Book Tutorial
We are considering to make the book tutorials. If you think the book tutorials are essential, you can download it. download book
See Also
References
※ NOTE THAT:
Some components works on 3.3v and others works on 5v!