Hi! I'm new to arduino and am having some trouble just trying to use a button. With this code I just want the switchState to become HIGH when the button is pressed, but when i press the button, no matter the duration, it stays on HIGH for 5-7 seconds, then flickers between HIGH and LOW for a second then stays LOW, I've tried several different buttons and pins on the arduino but the problem persists.
const int switchPin = 7;
int switchState;
void setup() {
Serial.begin(9600);
pinMode(switchPin, INPUT);
}
void loop() {
switchState = digitalRead(switchPin);
Serial.println(switchState);
}
Hello,
Can we have a schematic pls? In your code everything looks okay (with this size... hard to make big mistakes)
And also the board you are using
Hi! Welcome to the Forum.
There's nothing in your code that suggests this behaviour. Probably your button is floating. If you're not using a pull-up or pull-down resistor, change this line:
pinMode(switchPin, INPUT);
to
pinMode(switchPin, INPUT_PULLUP);
and connect one leg of the button to GND and the diagonal leg to pin 7.
The result will be consistently 1 while not pressed and 0 while pressed.
Thank you so much! Worked like a charm 
hi @timothylundgren, welcome to the forum.
With some excitement you may not even know is happening and cannot see around the moment the button becomes pressed and the moment it gets released.
Here's your sketch with some extra logic to count and report when the switch goes from pressed to not pressed and vice versa. When you hold the switch down, it will stop reporting ending up on 0. When you let the switch go, it will evntually end up reporting 1.
Try it, then bump up the baud rate to something your grandfather would be amazed by
Serial.begin(115200);
and see even more excitement, probably.
const int switchPin = 7;
int switchState;
int reportedState;
int counter;
void setup() {
Serial.begin(9600);
pinMode(switchPin, INPUT_PULLUP);
}
void loop() {
switchState = digitalRead(switchPin);
if (reportedState != switchState) {
Serial.print(counter);
Serial.print(" ");
Serial.println(switchState);
reportedState = switchState;
counter++;
}
}
You will soon need to be dealing with switch bounce.
a7