Button pressed when not pressed. (Code Bug)

Hello, I am new to this hole coding platform but am trying to learn. A project I was working on needed a button, so I tried to wire it up to a buzzer first to test but it just keeps looping. I have tried messing with the code, watching videos, and unpluging the button. But it just keeps looping. I do not think this is a problem with the button as like I said, the problem persisted even when it was unpluged. and yes, I reset the board. Dose anyone know what might be going on? Sorry for any errors in the code as i just started and its only a test pice of code really.

int B = 9;
int C = 8;
int D = 7;
int E = 6;
int F = 5;
int G = 4;
const int button = 12 ;    //button pin
int buzzer = 13;     //buzzer pin
f
![Screenshot from Serial Monitor..|148x280](upload://9dVipeD8dDE2gjhMpYfpkhctfO1.png)
loat Buz = 500;     //amount of time buzzer, well, buzzes

void setup() {
  // put your setup code here, to run once:
   Serial.begin(9600);
  pinMode(A, OUTPUT);
  pinMode(A, OUTPUT);
  pinMode(A, OUTPUT);
  pinMode(A, OUTPUT);
  pinMode(A, OUTPUT);
  pinMode(A, OUTPUT);
  pinMode(A, OUTPUT);
  pinMode(13, OUTPUT);
  pinMode(12, INPUT);
  digitalWrite(button,LOW);

}

void loop() {
  // put your main code here, to run repeatedly:

  int buttonTest = digitalRead(button == HIGH);
  if (buttonTest==HIGH)
  {
digitalWrite(buzzer,HIGH);
Serial.println("ButtonActive");
  }
  else{
    Serial.println("ButtonDeactive");
    digitalWrite(buzzer,LOW);
  }
}```

button == HIGH evaluates to 12 == HIGH, which evaluates to 12 == 0x01, which evalutes to 0.

So your statement tries to do a digitalRead on pin 0, the serial Rx pin, which I'm sure is not what you want. I have no idea what that will return.

If you want to read the state of the button pin, do
int buttonTest = digitalRead(button);

Also, I hope you have a pull up or pull down resistor on your button (depending on how you have it wired) so that the button pin is not floating when the button is not pressed.

Start with the Examples built into the IDE, then the board specific examples. Also get a copy of the Arduino Cookbook and work through it front to back.

I think that you have a lot of learning in noticing details, in paying attention.

If you look too long a certain way at your code, you fixate and won’t see what you should. In setup, you set pin A over and over.

If you get stuck, walk away and do something else then go back with fresh eyes. Built-up stress can blind you, lock you on one path.

Try only printing when the button state CHANGES and maybe print millis() to show when it was detected. When loop() runs fast enough you will detect contact bounce of the button, a rite of passage here is your first button debounce code. That’s one step beginners need to learn.

These archived Arduino Foundations have what anyone new needs to know to start in short lessons. The pins and the code specific to Arduino you need all so quick and easy.

I understand what I did wrong, now it just kinda swiches on and off, also it dose that even when PIN 12 has nothing in it. Also I do a resistor, not sure if its right but i will figure it out when the code is fixed.

Thanks, I didn't even realize that I forgot to set up ABCDEFG. Also I added a delay so the Serial Monitor was not over ran by prints. Not 100% sure what you were saying but like I said I am new so forgive me.

Hi @cage1903 !

Some comments to your sketch

/*

  Can you explain the purpose of the variables B to G?

  The values 4 to 9 sound like they are ment for
  digital pins of an Arduino Uno, but is this true?

  Do you consider to add e.g. some LEDs to it?

*/
int B = 9;
int C = 8;
int D = 7;
int E = 6;
int F = 5;
int G = 4;

/*

  If "button" is the pin where your pushbutton is wired to
  the input pin it has to be set up as an INPUT by the pinMode() 
  function!

  Be aware that - depending on your button wiring - it may be of advantage
  to set the pin mode to INPUT_PULLUP! It means that the pin will be held 
  constantly HIGH by a resistor inside the controller. The button has to be
  connected with one side to the pin and the other side to GND in that case!

  If the button is pressed it will draw the pin voltage to Ground.

*/

const int button = 12 ;    //button pin

/*
  
  A buzzer shall be wired to pin 13. We can assume that
  it is an active buzzer (one that itself makes a sound while it 
  is triggered). 

*/

int buzzer = 13;     //buzzer pin

/*
  The floating point variable Buz seems to be thought to control
  the time the buzzer shall sound when it was triggered

  However it is not used up to know and it will require some
  reasonable logic to do so! E.g. the trigger for the buzzer
  must be set only once when the button has been pressed 
  and should only work again after the button has been 
  released before it is pressed again.

  A common issue with buttons is that they tend to "bounce"
  which means: When pressed they may quickly change their
  state between closed/open/closed/open/closed ... within
  a few miliseconds. As a controller can check the state
  quickly (if not hindered by the developer ;-) ) this 
  may lead to unwanted behaviour. Mechanical buttons usually
  have to be "debounced" which can be done by hard- or software.
  There are proven routines to do this by code!

  
*/

float Buz = 500;     //amount of time buzzer, well, buzzes

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
/*
   Looks like Copy and Paste to set A to OUTPUT several times.
   No need to be so rude to a innocent pin ... ;-)

*/
  pinMode(A, OUTPUT);
  pinMode(A, OUTPUT);
  pinMode(A, OUTPUT);
  pinMode(A, OUTPUT);
  pinMode(A, OUTPUT);
  pinMode(A, OUTPUT);
  pinMode(A, OUTPUT);
/*
  As buzzer is already declared to point us to pin 13
  we should use the variable name or better use a constant
  so that the compiler can check whether someone tries
  to change the value during the program flow.

*/
  pinMode(13, OUTPUT);


/*
  See comments above for buzzer and button
*/

  pinMode(12, INPUT);
  digitalWrite(button, LOW);

}

void loop() {
  // put your main code here, to run repeatedly:

  int buttonTest = digitalRead(button == HIGH);
  if (buttonTest == HIGH)
  {
    digitalWrite(buzzer, HIGH);
    Serial.println("ButtonActive");
  }
  else {
    Serial.println("ButtonDeactive");
    digitalWrite(buzzer, LOW);
  }
}

There is more to it but I hope this may already give you some basic information ...

As a complete beginner you might search the net for "arduino cookbook by Michael Margolis". It will help you to climb the first steps before you start to dive deeper into C++.

[Edit:] You may or may not be aware of the online Arduino simulator Wokwi ... It might give you a great opportunity to analyze and test existing solutions. Here one that is roughly based on your sketch:

https://wokwi.com/projects/457651223100920833

Code
/*
  Forum: https://forum.arduino.cc/t/button-pressed-when-not-pressed-code-bug/1433858/5
  Wokwi: https://wokwi.com/projects/457651223100920833

  2026/03/05
  ec2021

  This is one out of thousands of possible solutions.

  An LED is used instead of a buzzer as the Wokwi buzzer is a passive device that requires
  the tone library (or at least additional code to create a sound).

  The "Debouncing" si inherent as the code does not react to bouncing
  while buzzerActive is true (which happens with the first falling edge of the button signal).

  So one can keep the buzzer buzzing by continousely pressing the button without releasing it.

*/

constexpr byte buttonPin {12} ;
constexpr byte buzzerPin  {13};
constexpr unsigned long  buzzerInterval {500};    // The time in milliseconds the buzzer shall be active after being triggered

unsigned long triggerTime = 0;      // The time when the button switches from HIGH to LOW
boolean buzzerActive = false;

void setup() {
  Serial.begin(115200);
  pinMode(buzzerPin, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop() {
  int buttonTest = digitalRead(buttonPin);
  if (buttonTest == LOW && !buzzerActive)
  {
    buzzerActive = true;
    triggerTime = millis();
    digitalWrite(buzzerPin, HIGH);
    Serial.println("ButtonActive");
  };
  if (buzzerActive && millis() - triggerTime >= buzzerInterval)
  {
    buzzerActive = false;
    Serial.println("ButtonDeactive");
    digitalWrite(buzzerPin, LOW);
  }
}

Just FYI…Did you add a delay with the delay(x)? Or did you add delay using a millis() timer? I do a lot of my serial prints either on edge detection for 1 serial print or in a millis() based timer if I want a lot of prints.

The delay() will actually prevent any further code from running until the delay runs out. So if you push or a release a button while the delayed interval is still active, the code won’t respond. This can make buttons feel sluggish or unresponsive.

The millis() will record a time and just countdown until the time is up, allowing other parts of code to run “simultaneously.” Thus, while the millis() based debounce timer is running, or other millis() based timers are running, other code is still allowed to work.

Just so you know…if you are learning, you might as well learn how to time things. Millis() is easy once you play with it some.

When an Arduino first powers up, all the pins are set to be inputs that are known as floating inputs. This means that any electrical fields in your environment can produce random readings on that input.

Normally you use the setup function to define pins you want to use as inputs, but it is not necessary. However you can define the input as having an internal pullup resistor.

So I would expect to see pin 12 in the setup function to be defined as

pinMode(12, INPUT_PULLUP);

This means that pin 12 will produce a steady high signal when you read it. To make it read a low you simply connect the pin to ground , via a pushbutton, and read it.

So to look for a press look for a low on this line. If you see a high you will know the button is not pressed. Use the digitalRead(12); to read this pin.

Forget about so called debouncing this signal until you need to do it. A lot of people on this forum seem to be fixated in debouncing every input, where as most of the time delays in other parts of the code render this unnecessary.

You can check on all the functions the Arduino has to offer if you use the Help menu and choose the Reference option.

To see the basic examples chose File -> Examples > 01 Basics.
Also look at the other sections of basic examples covering other topics.
You have a lot of help from the Arduino system itself.

I would entitle this advice as “How to confuse a beginner’

Give him a break and let him crawl before trying to get him to sprint.

I tested my code, and it worked, ruffly fine but it worked. On wokwi that is.

Also I am not sure I know what you mean.

Would be nice if you could post a link to the Wokwi project where your code works ...

Ok, the code works, kinda, it dose turn off and on but kinda jankly. Comparied to my board... its a lot better.

I'm a little bit confused... The link goes to exactly the code I wrote as an example for you...

If the button is pressed the sketch switches the led on for 500 msec and then off again (if the button has been released).

Did you read the comments in my post 7?
What do you expect the code to do?

When I was learning the very basics I had problems with debouncing buttons. I thought the delay function was awesome and easy. But I eventually found out that it caused problems. And I also found out that multiple readings from the bounce causes problems. You are correct that a button can be debounced by default because of the other delays in the code. I wasn't asking the OP to start sprinting. Simply suggesting that if you're going to add a delay, then do it in a way that won't interfere with anything else. At least that problem is eliminated by default. I figured that was a long ways from sprinting. Maybe a hair past crawling and pulling up on the coffee table.

I must have linked the wrong link.

Also, the delays do nothing to fox the buttons.

Start small. Just write a basic sketch to get the button to work. Forget about the buzzer for now. You can use the built in LED to test the button. If the button is pressed, light the LED, if the button is released, turn off the LED. When you can do that and get it to perform exactly like you want, add in more functionality. Do it a piece at a time. Use the examples in the IDE if needed. They are very helpful.

By the way, there doesn’t seem to be any “right” way to code something, for the most part. At least for hobbyists. Arguably there are “better” ways. But different people have different styles and different levels of experience. That results in different codes to achieve the same result.

What problems?

Yes you were!

You are forgetting that this guy is an absolute beginner, unaware of even the most basic operations of an Arduino. My Post #9 was an attempt to show him where he could get help on line.

Please try and understand these things and not to forget you had to learn these things yourself once.