user2587726
user2587726

Reputation: 338

Arduino buttonstate not staying low

I am trying to wire up a simple switch to an Arduino, as per the code below, for use in a model trainset.

When the buttonState is high, Serial.print(buttonState) shows 111111111, however, the problem I have is when buttonState should be low: Serial.print(buttonState) "flickers" between 0 and 1 like so: 000111100000101000111001.

Why is it doing this and how do I stop it? I assumed it was connections but when I simply use a wire between the 2 ports, plugging it in for on and unplugging for off I still get this issue.

int RED=6;
int YELLOW=5;
int GREEN=3;
int relaytrig = 10; // trigger on pin 10
int powertoswitch = 9; // powertoswitch
int buttonPin = 12; // switch the button comms with
int buttonState = 0; 

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  // inputs
  // switch input
  pinMode(buttonPin,INPUT);
  // outputs
  // powerforswitch
  pinMode(powertoswitch,OUTPUT);
  // track power
  pinMode(relaytrig, OUTPUT);
  //signal outputs
  pinMode(RED,OUTPUT);
  pinMode(YELLOW,OUTPUT);
  pinMode(GREEN,OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  digitalWrite(powertoswitch,HIGH);
  buttonState = digitalRead(buttonPin);
  
  if (buttonState == HIGH) {
    digitalWrite(relaytrig,LOW);
    digitalWrite(GREEN,LOW);
    digitalWrite(RED,HIGH);
    digitalWrite(YELLOW,LOW);
    Serial.print(buttonState);
  } else if (buttonState == LOW) {
    digitalWrite(relaytrig,HIGH); 
    digitalWrite(GREEN,HIGH);
    digitalWrite(RED,LOW);
    digitalWrite(YELLOW,LOW);
    Serial.print(buttonState);
  }
}

Upvotes: 1

Views: 198

Answers (1)

ocrdu
ocrdu

Reputation: 2183

Unplugging it leaves the input pin floating, and noise etc. can make a floating input pin take any value.

Depending on your connection, you need a pull-down or a pull-up resistor on the pin to make it a 1 or a 0 when nothing is connected to it.

From the code, I assume the switching wire is between 5 V (or 3.3 V for some Arduinos) and an input pin. If I'm right, you need to put a, say, 10 kΩ resistor from that input pin to ground. This will keep it 0 when there is no wire connected.

BTW you are using an IO pin (9 aka powertoswitch) to provide the plus for the switch; there's no need and you shouldn't.

Connect one end of the switch to 5 V (or 3.3 V for some Arduinos), and the other end to the input pin. Connect the input pin with the resistor to ground (GND).

There's a picture here, but they use pin 2 as the input pin, and you use pin 12.

Also, your button or wire may need debouncing, but that is another matter.

Upvotes: 1

Related Questions