ESP32 - Pullup Resistor
We are going to learn how to:
-
How to use pull-up resistors.
Video Tutorial
you can watch this video tutorial
Hardware Required
1 | × | ESP-WROOM-32 Dev Module | |
1 | × | Micro USB Cable | |
1 | × | Breadboard | |
1 | × | pushbutton | |
1 | × | 10K Resistor | |
n | × | Jumbers |
Wiring Diagram
Schematic Diagram
With a pull-up resistor, the input pin will read a high state when the button is not pressed. In other words, a small amount of current is flowing between VCC and the input pin (not to ground), thus the input pin reads close to VCC. When the button is pressed, it connects the input pin directly to ground. The current flows through the resistor to ground, thus the input pin reads a low state.
※ NOTE THAT:
Keep in mind, if the resistor wasn’t there, your button would connect VCC to ground, which is very bad and is also known as a short.
Breadboard Connections
ESP32 Code
const int BUTTON_PIN = 19; // GIOP19 pin connected to button // Variables will change: int lastState = LOW; // the previous state from the input pin int currentState; // the current reading from the input pin void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); // initialize the pushbutton pin input // the pull-up input pin will be HIGH when the switch is open and LOW when the switch is closed. pinMode(BUTTON_PIN, INPUT); } void loop() { // read the state of the switch/button: currentState = digitalRead(BUTTON_PIN); if(lastState == HIGH && currentState == LOW) Serial.println("The button is pressed"); else if(lastState == LOW && currentState == HIGH) Serial.println("The button is released"); // save the the last state lastState = currentState; }
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!
※ NOTE THAT:
Since pull-up resistors are so commonly needed, many MCUs, like the ESP32, have internal pull-ups that can be enabled and disabled. To enable internal pull-ups on ESP32, you can use the following line of code in your setup() function:
pinMode(5, INPUT_PULLUP); // Enable internal pull-up resistor on pin 5
Book Tutorial
We are considering to make the book tutorials. If you think the book tutorials are essential, you can download it. download book