Go Down

Topic: How to distinguish which button was pressed first (Read 538 times) previous topic - next topic

apocalyps

Hi!

I'm a newbie and needs some help how to program my Arduino. I have connected two LEDs (see attached schematics (only one LED visible on the drawing)). I want to be able to see which of the two circuit breakers that was hit first. My current sketch only allows me to lit the LEDs (i.e when pressing the first switch, one of the LEDs light up and when pressing the other the other LED lights up and the first one becomes inactivated (and vice versa)). I would like to be able to see afterwards which of the two circuit breakers that was hit first. I would like a sketch that only lights up the first LED and thereafter prevents the second LED to light up, no matter how many times the two circuit breakers are hit after the initial hit.

Cheers Martin

My sketch:

void setup() {               
 
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
 
  pinMode(2, INPUT);
  pinMode(4, INPUT);
}

void loop() {
  if (digitalRead(2) == LOW) {
    digitalWrite(13, HIGH);
    digitalWrite(12, LOW);   
  }
  if (digitalRead(4) == LOW) {
    digitalWrite(12, HIGH);
    digitalWrite(13, LOW);   
  }
}

Grumpy_Mike

Read the how to use this forum sticky post to find out how to post code.

When you detect a button is pressed and you turn the led on have a loop that holds the code until that button is released. Look at the while program structure.

apocalyps

Code: [Select]
void setup() {               
 
  pinMode(13, OUTPUT);
  pinMode(12, OUTPUT);
 
  pinMode(2, INPUT);
  pinMode(4, INPUT);
}

void loop() {
  if (digitalRead(2) == LOW) {
    digitalWrite(13, HIGH);
    digitalWrite(12, LOW);   
  }
  if (digitalRead(4) == LOW) {
    digitalWrite(12, HIGH);
    digitalWrite(13, LOW);   
  }
}

Grumpy_Mike

Code: [Select]
void loop() {
  if (digitalRead(2) == LOW) {
    digitalWrite(13, HIGH);
    digitalWrite(12, LOW);
while( digitalRead(2) == HIGH) { }
  }
  if (digitalRead(4) == LOW) {
    digitalWrite(12, HIGH);
    digitalWrite(13, LOW);
while( digitalRead(4) == HIGH) { } 
  }
}

Will hold the LED on until released.
There are more complex ways to do it by setting a Boolean variable.
Code: [Select]

void loop() {
static boolean one = false;
static boolean two = false;
  if (digitalRead(2) == LOW && two == false) {
    digitalWrite(13, HIGH);
    digitalWrite(12, LOW);
    one = true;
  }

  if (digitalRead(4) == LOW && one == false) {
    digitalWrite(12, HIGH);
    digitalWrite(13, LOW);
    two = true;
  }
if (digitalRead(4) == HIGH) {
    two = false;
   }

if (digitalRead(2) == HIGH) {
    one = false;
   }

}


Untested - but should keep the LED on until another button is pushed.

apocalyps

Thank!

This helped alot. I think it works now.

Thanks again

//Martin

Go Up