D. Input/Output: GPIO pins
Now that we can talk to our microcontroller over the serial line it is time to interact with the
real world. Our ESP8266 is equipped with several so-called General Purpose Input Output or
in short GPIO pins. They can be used for many different applications such as sensing and
generating digital signals of the 3.3 Volt range. This is important if you plan to use an external
component with your ESP8266: hardware designed for older Arduinos often uses the 5V
(CMOS) range. Using such a device without a logic level shifter might destroy your ESP8266.
Using a GPIO pin is quite easy: first you tell the microcontroller if you want to read or write
from the pin. Then you do it. Here is the code for reading:
pinMode(PIN, INPUT);
int state = digitalRead(PIN);
Unless you want to change the mode of a pin you only need to call
note that depending on the pin you can also use
Writing to a pin is not much different:
pinMode(PIN, OUTPUT);
digitalWrite(PIN, HIGH); // or
digitalWrite(PIN, LOW);
The second statement will show a HIGH level on PIN which will be 3.3V. The third statement
will set the pin to LOW which is 0V.
What values for PIN can you use? If you are using a generic ESP8266 module (not a NodeMCU)
your pins will be labeled GPIO0, GPIO1, etc. To use pin GPIO0 you would write digitalWrite(0,
HIGH); If you are using a NodeMCU things get a little bit more complicated. The original
creators of the NodeMCU LUA firmware and the development module of the same name had
the idea to give the pins different names. They are called D0, D1, etc. That by itself would not
be confusing yet but they are not using the same digits, e.g. GPIO1 is not equal to D1. Here
is a table to map the pins:
Raw Module Name
GPIO0
GPIO1
GPIO2
GPIO3
GPIO4
NodeMCU &
Raw Module Name
Wemos Name
D3
D10
D4
D9
D2
pinMode()
INPUT_PULLUP
or INPUT_PULLDOWN.
GPIO9
GPIO10
GPIO11
GPIO12
GPIO13
once. Please
NodeMCU &
Wemos Name
D11
D12
N/A
D6
D7
Need help?
Do you have a question about the ESP8266 and is the answer not in the manual?