Site icon Mechatronics Learning

GPIO Pins and Digital I/O: NodeMCU Beginners’ Guide

Get Started-nodemcu-3-gpio-ditgial-i_o

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.

esp8266-pinout-mechatronics-learning.com

Digital Input and Output Explained

Controlling an LED with NodeMCU

Let’s start by controlling an LED using digital output.

Components Required:

Circuit Setup:

nodemcu-LED-circuit-diagram

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:

Circuit Setup:

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!

Exit mobile version