3

I'm trying to read an input from a switch but instead of getting 0 and 1 for closed/open, I'm getting 0 and a rapid series of 1s and 0s. Originally I tried (and failed) to simply read a rotary encoder but when I swap it for a standard rocker switch or even connect wires directly then it's the same.

This is my first time trying to get an input into an Arduino so I'm probably missing something quite straightforward.

I've got ground going to one pin of the switch and pin 2 to the other. Here's the code I'm using to see if the switch is on or off.

void setup() {
  pinMode (2, INPUT);
  Serial.begin(9600);
}

void loop() { Serial.println(digitalRead(2)); }

RowanP
  • 869
  • 6
  • 21
WillM
  • 39
  • 1

1 Answers1

10

Pins configured as INPUT are in a high impedance state and very sensitive to electrical noise from the environment, especially with wires connected to them See Arduino Tutorial

Try using INPUT_PULLUP in your pinMode statement.

Additionally you might want to investigate switch debouncing methods for when your switch is operated.

Bra1n
  • 1,028
  • 1
  • 7
  • 12