Simple Button Issues

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:

Button State:1023
Button State:1023
Button State:0
Button State:0
Button State:0
Button State:1023
Button State:1023
Button State:0
Button State:0
Button State:0
Button State:1023

This is my code:

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);
}

Your post was MOVED to its current location as it is more suitable.

What do you mean by that?

How is the button connected? Do you have a diagram?

I mean I have no power going to the circuit at all. The power source is off and disconnected. I can look into making a diagram though.

But you are powering the Arduino via the USB cable?

Yes

You need to show your circuit... if you are USB connected then there obviously is power going to the circuit.

Document.pdf (867.4 KB)

Here is my diagram. I'm confused, power shouldn't be going to my circuit from A1 since it is set as an input.. Right?

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.

HI, @parker7771
Please read the post at the start of any forum , entitled "How to use this Forum".

This will help with advice on how to present your code and problems.

@parker7771 diagram


It would be better to post jpg pictures.

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.


PS. You need to have lots of 10K resistors in your kit of parts.

Tom... :grinning: :+1: :coffee: :australia: