Go Down

Topic: How to store button values(Trigger)? (Read 271 times) previous topic - next topic


This is the program which i found in Arduino Forum for Controlling a LED using a Push Button.
int ledPin = 12;                // LED is connected to pin 12
int switchPin = 2;              // switch is connected to pin 2
int val;                        // variable for reading the pin status

void setup() {
  pinMode(ledPin, OUTPUT);      // Set the LED pin as output
  pinMode(switchPin, INPUT);    // Set the switch pin as input

void loop(){
  val = digitalRead(switchPin);   // read input value and store it in val
  if (val == HIGH) {               // check if the button is pressed
    digitalWrite(ledPin, LOW);   // turn LED on
  if (val == LOW) {              // check if the button is not pressed
    digitalWrite(ledPin, HIGH);    // turn LED off

Now i would like to know how to store the value of the Button Input in Memory. For eg: If i press the Button it should store the value as HIGH and give the HIGH signal to LED and wait till i press the button again to Send LOW signal to LED. In simple words, it should turn ON and OFF the LED by remebering the Button Trigger


For eg: If i press the Button it should store the value as HIGH

You are already doing this, storing the value in val. Why is this not sufficient?

val is going to be overwritten on every pass through loop.

It isn't clear what you want to do.


Oh, you want a latch.
Try this:

Boolean latch= false;

If(ButtonPress == HIGH) {
latch = !latch;

digitalWrite(LEDpin, latch ? HIGH : LOW);

This is the very compact way to do it.
My GitHub:

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131