In this section, we'll cover how to handle digital inputs and outputs using the ESP32 with the Arduino IDE. This includes reading the state of a push button and controlling an LED.
Before you start this tutorial we encourage you to also look at the basic ESP32 led blink tutorial.
Components Needed
- ESP32 Board
- 5mm LED
- 330 Ohm resistor
- Pushbutton
- 10k Ohm resistor
- Breadboard
- Jumper wires
Circuit Assembly
1. Connect the LED:
- Attach the anode (long leg) of the LED to GPIO 16 of the ESP32.
- Connect the cathode (short leg) of the LED to one end of the 330 Ohm resistor.
- Connect the other end of the 330 Ohm resistor to the ground (GND) pin on the ESP32.
2. Connect the Pushbutton:
- One leg of the pushbutton goes to GPIO 4 on the ESP32.
- The opposite leg of the pushbutton connects to a 10k Ohm pull-down resistor that is connected to the ground (GND).
- The same leg of the pushbutton that connects to the resistor also connects to the 3.3V power rail.
Schematic Diagram
The following shows the circuit diagram:
ESP32 Program Code
With the circuit assembled, upload the following code to the ESP32 using the Arduino IDE:
// set pin numbers const int buttonPin = 4; // the number of the pushbutton pin const int ledPin = 16; // the number of the LED pin // variable for storing the pushbutton status int buttonState = 0; void setup() { Serial.begin(115200); // initialize the pushbutton pin as an input pinMode(buttonPin, INPUT); // initialize the LED pin as an output pinMode(ledPin, OUTPUT); } void loop() { // read the state of the pushbutton value buttonState = digitalRead(buttonPin); Serial.println(buttonState); // check if the pushbutton is pressed. // if it is, the buttonState is HIGH if (buttonState == HIGH) { // turn LED off digitalWrite(ledPin, LOW); } else { // turn LED on digitalWrite(ledPin, HIGH); } }
Testing Your Project
After uploading the code, test your circuit:
- The LED should light up when you press the pushbutton.
- The LED should turn off when you release the pushbutton.
If you are having trouble uploading code to the ESP32 board then read this tutorial on How to Solve ESP32 Error in Arduino IDE.
Summary
In this section, you've learned how to read digital inputs and control digital outputs with the ESP32 using the Arduino IDE. This foundational knowledge allows you to create various interactive projects by integrating different sensors and actuators with the ESP32.