Pages: [1]   Go Down
Author Topic: 5  momentary switches, exclusive on  (Read 463 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 23
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

how would I go about having 5 momentary switches being read "on" when pressed (and staying on)  and turning off the previously on switch, so there would only be one switch on at any given time?
Logged

Austin, TX USA
Offline Offline
God Member
*****
Karma: 4
Posts: 997
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

So only the last pushed button is "logically" on, even if one of the other buttons is still being held down?
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 23
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

yes, last switch pushed. All others go off if held down. Naturally I would throw debouncing in there; software (if practical) or HW (I have a bunch of 555's laying around)
Logged

Austin, TX USA
Offline Offline
God Member
*****
Karma: 4
Posts: 997
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Ex--

The code below tracks the state of the 5 pins and makes a note of which was pressed last.  The "button_down" variable stores the most recently pressed button pin number (or -1 if none are pressed).  In the case where button 1 is pressed and held then button 2 pressed and released, it does not record that button 1 is still active.  If this is a problem, it can be tweaked.

Is this something like what you were hoping for?

Mikal

byte pin_state[5] = {HIGH, HIGH, HIGH, HIGH, HIGH};
byte switch_pins[5] = {2, 3, 4, 5, 6};
unsigned long last_push_time[5] = {0, 0, 0, 0, 0};
int button_down = -1;

void setup()
{
  for (int i=0; i<5; ++i)
    pinMode(switch_pins, INPUT);
}

void loop()
{
  unsigned long now = millis();
  for (int i=0; i<5; ++i)
  {
    byte newstate = digitalRead(switch_pins);
    if (newstate != pin_state) // did the pin change state?
    {
      if (newstate == HIGH && now - last_push_time > 200) // debouncing
      {
        pin_state = HIGH;
        if (button_down == switch_pins)
          button_down = -1;
      }
      
      else if (newstate == LOW)
      {
        pin_state = LOW;
        button_down = switch_pins;
        last_push_time = now;
      }
    }
  }
  
  /* At this point the variable "button_down" contains the pin number
    for the most recently pressed button, or -1 if no buttons are down.
    This assumes that a button press causes the pin state to drop "LOW".
 */
}
Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 23
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Thank you, thats what I was hoping to do,. I was afraid, as a newb that I wouldnt be able to debounce and detect without more nested loops. You have also provided me an extremely useful tutorial on the millis() call, thanks.
Logged

Pages: [1]   Go Up
Jump to: