I am trying to put together a project for a class using Arduino and am more or less teaching myself how to put it all together. I've run into a bit of a wall trying to figure out the push button portion of this project. I am trying to read from an analog pin what the power input is but I am getting a fluctuating pattern even with the power off. For the record this is more of a test code while I figure out the situation, so I apologize if it is a bit messy.
Here is the pattern that was sent to the serial monitor:
const int buttonPin = A1; //pushbutton connected to digital pin 3
void setup() {
pinMode(buttonPin,INPUT); //set pushbutton as an input
Serial.begin(9600);
}
void loop() {
int buttonState; //variable for whether button is pressed or off
buttonState = analogRead(buttonPin); //placing button state into variable
//Declare whether button is pressed or not
Serial.print("Button State:");
Serial.print(buttonState);
Serial.println();
delay(2000);
}
If the pin is not connected to anything than it is said to be "floating" - you cannot assume it's value to be 0. You need to also make sure that the voltage you are trying to measure has a common Ground with the Arduino. Also make sure that you don't expose the input pin to too much voltage or current or you will fry the Arduino.
This is how you should be connecting your button.
Each example caters for the fact that you should not leave an input pin you are using, open circuit.
The 10K resistors make sure the input is HIGH or LOW when the button is open circuit.