Push Button Input Code

Hello All,

I am trying to write code that activates once a push button is pressed. The idea is that I have the 5v line going in to one pin of the button and a digital pin connected on a pin of the button that is caddy corner to the 5v line so that when the button is pressed, the digital pin will see the 5 volts. I want my input pin to read the value and if it is high, then it will trigger an output pin to send a HIGH signal which will then light up an LED.

Here is what my code looks like:

void setup() { pinMode(12,INPUT); //setup the input pin pinMode(10,OUTPUT); //setup the output pin }

void loop(){ int val=0; //initialize the variable where the input value will be stored val=digitalRead(12); //read the value coming in to pin 12 if (val == HIGH){ digitalWrite(10,HIGH); //if pin 12 is reading a high value, then pin 10 will output a high value } else { digitalWrite(10, LOW); //if pin 12 is reading not reading a high value, then pin 10 will output a low value } }

The problem is that pin ten is always outputting a HIGH value and the led is staying lit at all times.

The long term goal of this project is that once the button has been pressed, an output pin will be set to HIGH for a certain amount of time to power a relay.

Button: http://www.amazon.com/microtivity-IM206-6x6x6mm-Tact-Switch/dp/B004RXKWI6/ref=sr_1_2?ie=UTF8&qid=1379628064&sr=8-2&keywords=push+button

If there is a better style/type of button for this project, please let me know.

Thanks, ARosch

ARosch: The idea is that I have the 5v line going in to one pin of the button and a digital pin connected on a pin of the button that is caddy corner to the 5v line so that when the button is pressed, the digital pin will see the 5 volts.

When the switch is open the pin is left to float. You need a pull-down resistor on the pin to be sure it reads 0 when not connected to +5V.

Brilliant, thanks so much!

Another choice is to use the pinMode INPUT_PULLUP and connect the button between the pin and Ground. The sense of the pin will be reversed (HIGH = not pressed, LOW = pressed) but since it uses the internal pull-up resistor it needs no additional hardware.

void loop(){
  int val=0; //initialize the variable where the input value will be stored
  val=digitalRead(12); //read the value coming in to pin 12

When the convention to put the { on the same line as the statement that it does with was adopted, monitors displayed limited numbers of lines. That is no longer the case.

The convention was NEVER to jam the { tight up against the statement.

There is no reason to assign val a value and then immediately overwrite that value. Assign it a value as it is declared:

  int val = digitalRead(12);

and leave out the useless comments.

Do use the space bar. It makes the code easier to read. Youhaveprobablynoticedthatspacesarehelpfulintext.Thearehelpfulincodetoo.