If, each time you change the connection, you get a short sequence of high and low and after a few milliseconds the value stabilises on the correct signal, then that is caused by Switch bounce as it opens or closes. You need to implement debounce logic in the s/w on the D1.
const int triggerPin = D4; // Pin to monitor
bool isTriggered = false; // Flag to track trigger status
bool triggerState = LOW; // Current state of the trigger pin
bool lastTriggerState = LOW; // Previous state of the trigger pin
long debounceDelay = 50; // Debounce delay time in milliseconds
long lastDebounceTime = 0; // Time of the last pin state change
void setup() {
Serial.begin(115200);
pinMode(triggerPin, INPUT_PULLUP);
// Read the state of the trigger pin
int reading = digitalRead(triggerPin);
// Check if the current state of the trigger pin is different from the previous state
if (reading != lastTriggerState) {
// Reset the debounce timer
lastDebounceTime = millis();
}
// Check if the debounce delay has passed
if ((millis() - lastDebounceTime) > debounceDelay) {
// Check if the current state of the trigger pin is different from the stored state
if (reading != triggerState) {
triggerState = reading;
// Check for trigger transition from low to high
if (triggerState == HIGH) {
Serial.println(20);
isTriggered = true;
// Add your message or data to send here
} else {
// Check for trigger transition from high to low
Serial.println(50);
isTriggered = false;