Circuit for 2 wires acting as a switch when they touch to ligh the builtin led - pullup/pulldown - ESP8266/ESP32

Hello,

I'm more into programming than electronics, that I wish to understand better.

The ESP8266 has a builtin led.
I wish with 2 wires of 1m to connect them to a modeMCUv2 board(USB powered) so that when the bare ends touch, the builtin light is on, otherwise off.

Before "frying a board", I wish to know if the following would be correct.
I understand that there might be some input pin floating state problem.

It's unclear to me, if the code will solve it, or it does not need physical resistor.
const int switchPin = D3;
pinMode(switchPin, INPUT_PULLUP);

First, would this circuit be correct?

  1. Connect one wire to the D3 pin on the ESP8266 NodeMCUv2 board.
  2. Connect other wire to 3V3 on the ESP8266 NodeMCUv2 board.

When the wires do not touch, there is no loop between D3 and 3V3, so no voltage, a digitalRead(switchPin) will read LOW?
However, when the wires do touch, then there is a loop btw D3 and 3V3, a digitalRead(switchPin) will read HIGH?

Thanks for helping in this basic circuit.

#include <Arduino.h>

const int switchPin = D3;      // Digital pin connected to the bare end of the wire
const int builtInLed = LED_BUILTIN; // Built-in LED pin on NodeMCUv2 board

void setup() {
    pinMode(switchPin, INPUT_PULLUP);  // Set the switch pin as input with pull-up
    pinMode(builtInLed, OUTPUT); // Set the built-in LED pin as an output
    digitalWrite(builtInLed, LOW); // Turn off the built-in LED
    Serial.begin(115200);
}

void loop() {
    int switchState = digitalRead(switchPin);

    if (switchState == LOW) {
        digitalWrite(builtInLed, HIGH); // Turn on the built-in LED
        Serial.println("Switch is ON - LED is lit");
    } else {
        digitalWrite(builtInLed, LOW); // Turn off the built-in LED
        Serial.println("Switch is OFF - LED is off");
    }

    delay(1000);
}

What you are creating is a simple switch. Connect one wire to pin D3 and the other to GND rather than 3.3V and use INPUT_PULLUP in pinMode() so that the pin is held HIGH when the contacts are not closed so is always in a known state

When the state of D3 is HIGH the switch is open. When it is LOW it is closed. Adjust the program logic appropriately

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.