Is my button having errors?

I'm currently working on a project, where a press of a button turns on an led, and depressing it turns it off, as in the image:
Code diagram
and yes, here's the code:

const int buttonPin = 2;  // Pin connected to the button
const int ledPin = 8;   // Pin connected to the LED

int buttonState = 0;    // Current state of the button
int lastButtonState = 0;// Previous state of the button

void setup() {
  pinMode(ledPin, OUTPUT);  // Set LED pin as output
  pinMode(buttonPin, INPUT_PULLUP); // Set button pin as input with internal pull-up resistor
}

void loop() {
  buttonState = digitalRead(buttonPin);  // Read the button state

  // Check if the button state has changed (to prevent multiple readings in a single press)
  if (buttonState != lastButtonState) {
    if (buttonState == LOW) {  // Button is pressed
      digitalWrite(ledPin, HIGH);  // Turn LED on
    } else {  // Button is released
      digitalWrite(ledPin, LOW);  // Turn LED off
    }
  }

  lastButtonState = buttonState;  // Store the current button state for comparison next time
}

the linkage (i am making it first in Tinkercad circut design)

I am having an error where the button, no matter if you press it or not, the led is always off

First of all try diagonal terminals.

Wire the switch as S3 below,

Then look for a LOW for a switch pressed.

You are using INPUT_PULLUP, the button should be connected to GND, not 5V.

ITS FIXED, thanks

1 Like

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