In this lesson, we will learn how to use the GPIO (General Purpose Input/Output) pins of the NodeMCU board for digital input and output. This will help you control components like LEDs and read inputs from devices like push buttons.
Overview of NodeMCU’s GPIO Pins
NodeMCU has multiple GPIO pins that can be used for various purposes, such as digital input, digital output, PWM, I2C, SPI, etc.
- Digital I/O Pins: 0 to 16 (Not all pins are usable for general purposes; some are reserved for special functions.)
- Analog Input: A0 (0V to 3.3V)
- PWM Pins: Any GPIO pin
- Special Pins: GPIO0, GPIO2, and GPIO15 are used for boot mode selection.

Digital Input and Output Explained
- Digital Output: Setting a GPIO pin HIGH or LOW to control components like LEDs or relays.
- Digital Input: Reading HIGH or LOW states from devices like push buttons or switches.
Controlling an LED with NodeMCU
Let’s start by controlling an LED using digital output.
Components Required:
- NodeMCU
- LED
- 220-ohm Resistor
- Breadboard and Jumper Wires(How to use)
Circuit Setup:
- Connect the anode (+) of the LED to D4 (GPIO2) through a 220-ohm resistor.
- Connect the cathode (-) of the LED to GND.

Code Example:
void setup() {
pinMode(D4, OUTPUT); // Set D4 as output (GPIO2)
}
void loop() {
digitalWrite(D4, HIGH); // Turn LED on
delay(1000); // Wait for a second
digitalWrite(D4, LOW); // Turn LED off
delay(1000); // Wait for a second
}
Upload the code to your NodeMCU; the LED should start blinking every second.
Reading Digital Input (Using a Push Button)
Now, let’s read input from a push button.
Components Required:
- NodeMCU
- Push Button(How to use)
- 10k-ohm Resistor
- Breadboard and Jumper Wires
Circuit Setup:
- Connect one terminal of the push button to D3 (GPIO0).
- Connect the other terminal to GND.
- Use a 10k-ohm pull-up resistor between D3 and 3.3V.
Code Example:
int buttonState = 0; // Variable for storing the button state
void setup() {
pinMode(D3, INPUT); // Set D3 as input (GPIO0)
Serial.begin(115200); // Start serial communication
}
void loop() {
buttonState = digitalRead(D3); // Read the state of the push button
if (buttonState == HIGH) {
Serial.println("Button is not pressed");
} else {
Serial.println("Button is pressed");
}
delay(500); // Wait for a moment before reading again
}
Upload the code and open the Serial Monitor to see the messages printed when the button is pressed or released.
Code Explanation
In the LED control example, we used the pinMode()
function to set a pin as output and digitalWrite()
to control its state.The button reading example, we used digitalRead()
to detect whether the button is pressed or not.
In the next lesson, we will explore using analog inputs with NodeMCU. Stay tuned!