The functions to be used are the same as with an Arduino. We use the
method to configure a pin as a digital input or output, the
function to impose a voltage
of 0V or 3.3V
on the output and the
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 a link between the number of 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 …
Configuration of the GPIO2 pin as output:
Configuration of the GPIO15 pin as input:
The measured value is random if we measure a voltage from a pin that is not connected to the ground or a non-zero voltage. 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.
Two ways to eliminate noise and get reliable measurements :
With a pull-up resistor
This circuit allows only two 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, and 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).
With a pull-down resistor
This circuit allows you to have only two possible voltages: +3.3V when you push 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 indicate HIGH (or 1).
If the push button is released, the circuit is opened. The mass will absorb the very low residual current. The pin will therefore be in LOW (or 0).
All GPIO pins (except GPIO36, GPIO39, GPIO34, and GPIO35 pins) have these two circuits internally in the ESP32.
Configuration of the GPIO15 pin as input with the internal pull-up resistor:
Configuration of the GPIO15 pin as input with the internal pull-down resistor :
Unlike the Arduino, on the ESP32, there are internal pull-down resistors.
To set a voltage of 3.3V at the output of pin 2 of the ESP32:
pinMode(2, OUTPUT); // set the pin as output digitalWrite(2, HIGH)
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:
pinMode(15, INPUT); // set the pin as input digitalRead(15);