Pushbutton as Switch

Print

/*

This example demonstrates the use of pinMode(INPUT_PULLUP). It reads a digital
input on pin A5 and ON the LED connected to 31 When pushbutton is pressed
then activate the LED again pressed deactivate the LED.

The circuit:

- momentary switch attached from pin A5 to ground
- First Press LED on second Press LED on and so on

Unlike pinMode(INPUT), there is no pull-down resistor necessary. An internal
20K-ohm resistor is pulled to 5V. This configuration causes the input to read
HIGH when the switch is open, and LOW when it is closed.

*/

bool flag;
void setup() {
//start serial connection
Serial.begin(115200);
//configure pin 2 as an input and enable the internal pull-up resistor
pinMode(A5, INPUT_PULLUP);
pinMode(31, OUTPUT);

digitalWrite(31,LOW ); // Relay off
}

void loop() {


//read the pushbutton value into a variable
int Val = digitalRead(A5);

//print out the value of the pushbutton
Serial.print("\n Value");
Serial.print(Val);

// Keep in mind the pull-up means the pushbutton's logic is inverted. It goes
// HIGH when it's open, and LOW when it's pressed. Turn on pin 8,9 when the
// button's pressed, and off when it's not:


if (Val != HIGH) {
if(flag !=HIGH)
flag =HIGH;
else
flag =LOW;
}

//print out the value of the pushbutton
Serial.print("\n Flag");
Serial.print(flag);

if(flag==HIGH)
digitalWrite(31,HIGH);
if(flag==LOW)
digitalWrite(31,LOW);

delay(1000);
}