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
1 Answer 1
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.
floating input