Skip to content

Instantly share code, notes, and snippets.

@elktros
Last active February 6, 2021 05:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elktros/db4bf6cff30448c5ca6afad2048ff6f8 to your computer and use it in GitHub Desktop.
Save elktros/db4bf6cff30448c5ca6afad2048ff6f8 to your computer and use it in GitHub Desktop.
Simple code for demonstrating Digital Input and Digital Output in ESP8266 NodeMCU Board.
#define buttonPin 4 /* GPIO4 (D2) for Push Button */
#define ledPin 5 /* GPIO5 (D1) for LED */
int ledState = LOW; /* Variable to hold the current state of LED Pin. Initialized to LOW */
int buttonState = LOW; /* Variable to hold current state of Button Pin. Initialized to LOW */
int buttonValue; /* Variable to store state of the Button */
int lastButtonState = LOW; /* Variable to hold the previous state of the Button. Initialized to LOW */
long lastDebounceTime = 0; /* Variable to hold the last time the LED Pin was toggled */
long debounceDelay = 50; /* Debounce Time */
void setup()
{
pinMode(buttonPin, INPUT); /* Initialize Button Pin as Output */
pinMode(ledPin, OUTPUT); /* Initialize LED Pin as Input */
}
void loop()
{
buttonValue = digitalRead(buttonPin); /* Read the state of the Button into the variable: buttonValue */
/* Reset the debounce timer after button press */
if(buttonValue != lastButtonState)
{
lastDebounceTime = millis();
}
/* Use the button state after waiting for debouncing */
if((millis() - lastDebounceTime) > debounceDelay)
{
if(buttonValue != buttonState) /* Check if the button state has changed */
{
buttonState = buttonValue;
if(buttonState == HIGH) /* If the button state is HIGH, toggle the LED state */
{
ledState = !ledState;
}
}
}
digitalWrite(ledPin, ledState); /* Set the new state of the LED */
lastButtonState = buttonValue; /* Store the present button state for next loop */
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment