0

I have this Arduino code that will print 1 in the serial monitor and even prints two 1's. I haven't even pushed or clicked the push button, yet it already is already set to HIGH and even activates to HIGH 2 times per loop

/* C++ code */
int MODE = 0;
void setup()
{
 Serial.begin(9600);
 pinMode(2, OUTPUT);
 pinMode(3, OUTPUT);
 pinMode(4, OUTPUT);
 pinMode(7, INPUT);
}
void loop()
{
 int isPushed = digitalRead(7);
 if (isPushed == HIGH) {
 Serial.println(digitalRead(7));
 if (MODE == 0) {
 MODE = 1;
 } else if (MODE == 1) {
 MODE = 0;
 }
 }
 if (MODE == 0) {
 redGreenBlue();
 } else if (MODE == 1) {
 blink();
 }
}
void redGreenBlue(){
 digitalWrite(2, HIGH);
 delay(200);
 digitalWrite(2, LOW);
 delay(200);
 digitalWrite(3, HIGH);
 delay(200);
 digitalWrite(3, LOW);
 delay(200);
 digitalWrite(4, HIGH);
 delay(200);
 digitalWrite(4, LOW);
 delay(200);
}
void blink(){
 //Serial.println("working");
 digitalWrite(2, HIGH);
 digitalWrite(3, HIGH);
 digitalWrite(4, HIGH);
 delay(200);
 digitalWrite(2, LOW);
 digitalWrite(3, LOW);
 digitalWrite(4, LOW);
 delay(200);
}

This was supposed to be a LED light changer, from blue,green,red to all white when button is pushed

Edgar Bonet
45.1k4 gold badges42 silver badges81 bronze badges
asked Mar 19 at 23:02
2
  • 2
    research floating input Commented Mar 20 at 0:42
  • 1
    it seems like some hw noise across that digital input pin. Did you add any pull down circuit across that pin so that when the hw is powered the signal across the pin will low from hardware and when button is pressed, pin will be in active high state. Commented Mar 20 at 6:01

1 Answer 1

0

You'll need a pull-down resistor to avoid noise pickup giving you false readings. You'll also need a delay from when you first detect a change on that pin, to let the button settle down (search for "contact bounce") before you act on its state change (try 50ms for first guess). Otherwise your code will see many rapid, changes, known as "contact bounce" or "chatter", and again, you'll see some strange behavior from your code. There are other ways to deal with contact bounce but a delay is the simplest.

answered Mar 21 at 15:11

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.