I have connected a two terminal button with an ESP8266, one terminal to the D0 and another to the 3V and uploaded the following code.
// ESP8266 Fixed Button Counter
// Properly detects each button press and increments count
const int buttonPin = D0; // Pin where button is connected
int count = 0; // Counter variable initialized to 0
int buttonState = 1; // Current button state
int lastButtonState = 1; // Previous button state (1 = not pressed, 0 = pressed)
void setup() {
// Initialize serial communication at 9600 baud
Serial.begin(9600);
// Set button pin as input with internal pull-up resistor
pinMode(buttonPin, INPUT_PULLUP);
// Read initial button state
lastButtonState = digitalRead(buttonPin);
Serial.println("ESP8266 Button Counter - Fixed Version");
Serial.println("Button connected to D0");
Serial.println("Press button to increment counter...");
Serial.println();
Serial.print("Initial Count: ");
Serial.println(count);
Serial.print("Button State: ");
Serial.println(lastButtonState);
Serial.println();
}
void loop() {
// Read current button state
buttonState = digitalRead(buttonPin);
// Debug: Print button state changes
if (buttonState != lastButtonState) {
Serial.print("Button changed from ");
Serial.print(lastButtonState);
Serial.print(" to ");
Serial.println(buttonState);
// Check if button was pressed (changed from 1 to 0)
if (lastButtonState == 1 && buttonState == 0) {
count++;
Serial.print("*** Button PRESSED! Count: ");
Serial.println(count);
}
// Check if button was released (changed from 0 to 1)
if (lastButtonState == 0 && buttonState == 1) {
Serial.println("Button RELEASED");
}
// Update last button state
lastButtonState = buttonState;
// Debounce delay
delay(50);
}
// Small delay to prevent excessive polling
delay(10);
}
The code simply increment the count variable everytime the button is pressed. It works fine but I noticed an interference when I touch the staple pins(I use these to make my circuit look cleaner) on the breadboard.
I tried adding a resistor to solve this problem but it didn't worked well.
Please suggest some possible solutions.