Control ESP32 GPIO Pins
The functions to be used are the same as with an Arduino. We therefore use the pinMode() function to configure a pin as a digital input or output, the digitalWrite() function to impose a voltage of 0V or 3.3V on the output and the digitalRead() function to read a logic level (either 0V or 3.3V) on the input.
The pin numbers are those indicated in the grey “GPIO” insert on the board’s pinout. Even if there is correspondence between the number GPIO pins of the ESP32 and those usually used on the Arduino, to avoid confusion, it is better not to use them and to use the native pins number of ESP32 exclusively. You should therefore avoid using A0, MOSI, SCK, SDA …
Pinout of the uPesy ESP32 Wroom Devkit board
Pin configuration for an input or an output
Configuration of the GPIO2 pin as output:
Configuration of the GPIO15 pin as input:
Reminder on pullup and pulldown resistors:
If we measure a voltage from a pin that is not connected to the ground or to a non-zero voltage, the measured value is random. This is due to the electrical noise generated by several factors (the wire behaves in particular like an antenna). The most concrete example is when you use a push button.
Pullup resistor :
Using a pullup resistor with a push button
This circuit allows to have only 2 possible voltages: 0V when the button is pressed otherwise +3.3V
When the switch is opened (button released), the + 3.3V feeds the pin of the ESP32, the measured value of the pin will give HIGH (or 1).
When the switch is closed (button pressed), the +3.3V and the pin are absorbed by the mass, the pin measurement will give LOW (or 0).
Using a pulldown resistor with a push button
This circuit allows to have only 2 possible voltages: +3.3V when you press on the button otherwise 0V
If the push button is pressed, the current goes from +3.3V to the pin of the ESP32. It will not take the path of the mass because the current always flows by the least resistive path. The ESP32 pin will receive +3.3V and will indicate HIGH (or 1).
If the push button is released, the circuit is opened. The very low residual current will be absorbed by the mass. The pin will therefore be in LOW (or 0).
All GPIO pins (except GPIO36, GPIO39, GPIO34, GPIO35 pins) have these 2 circuits “in miniature”, internally in the ESP32.
Configuration of the GPIO15 pin as input with the internal pullup resistor:
Unlike the Arduino, on the ESP32 there are internal pulldown resistors in addition.
Configuration of the GPIO15 pin as input with the internal pulldown resistor :
Set or read a voltage
To set a voltage of 3.3V at the output of pin 2 of the ESP32:
The output voltage of pins is 3.3V (and not 5V like on Arduino)
To read a voltage of a logic level of 0V or 3.3V on pin 15 of the ESP32:
To show how to use the GPIO of the ESP32, we will do a straightforward example that turns the led on when a button is pressed.
We will use the internal pullup resistors to simplify the electronic circuit.