Debounce while other button is pressed

const int buttonPin = 3;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin
const int ledPin1 = 12;     // the number of the LED pin
const int InPin = 4;        //  Input of DigitalPin

// Variables will change:
int ledState = LOW;         // the current state of the output pin
int ledState1 = LOW;        // the current state of the output pin
int lastButtonState = HIGH;   // the previous reading from the input pin
int buttonState = LOW;             // the current reading from the input pin


int pinState;         // current state of the button


// the following variables are unsigned long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.

unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers

void setup() {

  //initialize serial communication at 9600 bits per second:
  Serial.begin(9600);

  pinMode(buttonPin, INPUT_PULLUP);  
  pinMode(ledPin, OUTPUT);
  pinMode(ledPin1, OUTPUT);
  pinMode(InPin, INPUT_PULLUP);


  // set initial LED to off
  digitalWrite(ledPin, ledState);
  digitalWrite(ledPin1, ledState1);
}

void loop () {

  pinState = digitalRead(InPin);


  if (pinState == LOW) {

  debounce();

  }
  else if (pinState == HIGH) {
    
    digitalWrite(ledPin, LOW);
    digitalWrite(ledPin1, LOW);

    debounce();

  }
}

void debounce()

{
  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonPin);


  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH),  and you've waited
  // long enough since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;


      // only toggle the LED if the new button state is HIGH
      if (buttonState == LOW) {

        ledState = !ledState;
        ledState1 = !ledState1;

        digitalWrite(ledPin, ledState);
        digitalWrite(ledPin1, ledState1);

      } else 

        digitalWrite(ledPin, LOW);
        digitalWrite(ledPin1, LOW);


    }
  }

 
  // it'll be the lastButtonState:
  lastButtonState = reading;
  
}

Hello I wan't to make this code working, but then release button "InPin" and holding pressed again debounce on buttonPin starts to work only from secont time... The code should work like this: Then button InPin is pressed, led1 and led2 turn ON/OFF with debounce buttonPin. Aftere releasing InPin button leds should go off and buttonPin should not work either.

How to integrate "state change detect" for InPin ?

Just read the two pins one after the other with digitalRead on two successive lines

Then do your debounce routine on both of them. Actually I think it is a state-change you are trying to detect - rather than simply debouncing. The simplest way to avoid bounce is to have a short interval (maybe 50 millisecs) between successive reads of the same pin.

If you don't want to do a state-change test for a pin then have a variable that identifies whether to skip the test.

...R

Listen to Robin2.
Read the switches every ~50ms.

Try something like this:

//                        C h e c k S w i t c h e s ( )
//======================================================================
//switches are checked every debounceDelay milli seconds
//no minimum switch press time is validated with this code (i.e. No glitch filter)
void CheckSwitches()
{
  byte thisState;

  //******************************************
  //check if this switch has changed state
  thisState = digitalRead(MySwitch);

  if (thisState != lastMySwitchState)
  {
    //update to the new switch state
    lastMySwitchState = thisState;

    //This switch position has changed, let's do some stuff

    //"HIGH condition code"
    //switch goes from LOW to HIGH
    if (thisState == HIGH)
    {
      //Do some HIGH stuff here
    }

    //"LOW condition code"
    //switch goes from HIGH to LOW
    else
    {
      //We will toggle a LED
      digitalWrite(TestLED, !digitalRead(TestLED));
    }

  } //END of MySwitch code
  //******************************************


  //******************************************
  //similar code for other switches goes here
  //******************************************


} //END of             C h e c k S w i t c h e s ( )

.

int  TestLED = 13;
int MySwitch = 3;

int  TestLED1 = 12;
int MySwitch1 = 4;

int lastMySwitchState = 0;
int thisState;

int lastMySwitchState1 = 0;
int buttonState;
int ledState = 0;
int ledState1 = 0;

unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers


void setup() {
  
pinMode(MySwitch, INPUT_PULLUP);
pinMode(TestLED, OUTPUT);
pinMode(MySwitch1, INPUT_PULLUP);
pinMode(TestLED1, OUTPUT);
digitalWrite(TestLED, ledState);
digitalWrite(TestLED1, ledState1);
}


//switches are checked every debounceDelay milli seconds
//no minimum switch press time is validated with this code (i.e. No glitch filter)

void loop() {

CheckSwitches();
  
}


void CheckSwitches()
{
  byte thisState;

  //******************************************
  //check if this switch has changed state
  thisState = digitalRead(MySwitch);

  if (thisState != lastMySwitchState)
  {
    //update to the new switch state
    lastMySwitchState = thisState;

    //This switch position has changed, let's do some stuff

    //"HIGH condition code"
    //switch goes from LOW to HIGH
    if (thisState == HIGH)
    {
      digitalWrite(ledState, LOW);
      digitalWrite(ledState1, LOW);
       
    }
   

  } //END of MySwitch code
  //******************************************


  //******************************************
  //similar code for other switches goes here
  //******************************************
//read the button pin, if pressed will be high, if not pressed will be low
  int reading = digitalRead(MySwitch1);
  //in the case that the reading is not equal to the last state set the last debounce time to current millis time
  if (reading != lastMySwitchState1)  {
    lastMySwitchState1 = millis();
  }
  
  //check the difference between current time and last registered button press time, if it's greater than user defined delay then change the LED state as it's not a bounce
  if ((millis()-lastDebounceTime) > debounceDelay) {
    if (reading != buttonState) {
      buttonState = reading;
    if (buttonState == LOW) {
      ledState = !ledState;
      ledState1 = !ledState1;
      
      }
    }
  }
  
  //set the LED
  digitalWrite(TestLED, ledState);
   digitalWrite(TestLED1, ledState1);

  //save the reading. next time through the loop the state of the reading will be known as the lastButtonState
  lastMySwitchState1 = reading;

    
  
  
} //END of             C h e c k S w i t c h e s ( )

Now I can’t make other button work as debounce for toggle the leds on/off. Now sometimes it works, but most of the time dont work as it should. I guess i did something wrong now.

vartaliotas:
The code should work like this: Then button InPin is pressed, led1 and led2 turn ON/OFF with debounce buttonPin. Aftere releasing InPin button leds should go off and buttonPin should not work either.

can you clarify this?

on press of buttonA LEDs toggle

on press of buttonB What happens?

it seems you want to dis regard buttonB presses if LEDs from buttonA are lit...

no?

int lastMySwitchState = 0;
int lastMySwitchState1 = 0;

Do you count this way? Uh-huh, one, two...

If you can't, or won't, use arrays, at least number ALL the variables that look like they belong together.

You read the state of one switch and store the reading in thisState. You read the state of the other switch and store it in reading. What? Consistency is a good thing.

You then compare the values in thisState and reading. They are from different switches. There is NO basis for comparing the values.

The code you adapted for debouncing switches uses three variables to determine if a switch is now pressed and was pressed n milliseconds ago. How many variables are needed to determine that? TWO!

I think you need to start over.

If first switch is pressed (HIGH) second start to work as a push button (with debounce) and toogle the leds on/off. Then first pin gets released(LOW) both of leds go off and second button stops working.

I want to make a simple rear fog lamp controller for my car. But it’s harder than i thought. I just need a right example and somehow i will make it.

I think you will make this a lot easier if you start by ignoring the bounce problem and just leave a short interval between reading the switches. And then (for testing) leave a full second between each switch press.

As I said earlier, you need to read the two switches at the same time and save there states. Then you can look at the save d values and decide what to do.

If switch A is OFF then everything is turned off, regardless of switch B
And the led only toggles if switch A is ON and switch B has changed from OFF to ON - so you need a variable to record the previous value of switch B

As you are using INPUT_PULLUP your switches will read LOW when pressed.

...R

If it's possible maybe u have an example something of this , I'am new to programing and used a lot of examples but still , I'm in a big trouble nothing else.

vartaliotas:
If it's possible maybe u have an example something of this ,

Sorry, no I don't.

But if you take it step by step following what I said in Reply #7 I think you will get there without too much need for coffee.

...R

It has been mentioned several times to read the switches at an interval.
50ms usually works for PB switch denouncing.

Do you fully understand the millis() BWD technique?

.

Im a newbie here , i know why millis is used , but don't actualy understand how to integrete in my code now.

Study this example:

Ask questions if you don’t know what is happening.

// millis() returns the current run time (in ms) since the last restart.

//**********************************************************************
unsigned long blockingMillis; //The time when this Timer was (re)started
unsigned long SwitchMillis;   //The time when this Timer was (re)started

const unsigned long blockingInterval = 500;  //1/2 second
const unsigned long debounceInterval = 50;   //50ms


const byte blockingLED = 13;
const byte testLED     = 8;

const byte ToggleSwitch = 2; //pushing the switch puts a LOW on the pin
byte lastToggleSwitchState;  //the last state the switch was in


//                            s e t u p ( )
//======================================================================
void setup()
{
  Serial.begin(9600);

  pinMode(testLED, OUTPUT);
  pinMode(blockingLED, OUTPUT);

  pinMode(ToggleSwitch, INPUT_PULLUP);

} //END of:                   s e t u p ( )


//                             l o o p ( )
//======================================================================
void loop()
{
  //******************************************
  //Some code to check for blocking code, LED should flash at 1 Hertz rate.
  if (CheckTimer(blockingMillis, blockingInterval))
  {
    //Toggle the Blocking LED
    digitalWrite(blockingLED, !digitalRead(blockingLED));
  }


  //******************************************
  //Put other non-blocking stuff here
  //******************************************


  //******************************************
  //Is it time to check the switches?
  if (CheckTimer(SwitchMillis, debounceInterval))
  {
    //it is now time to read the switches
    CheckSwitches();
  }


} //END of:                    l o o p ( )


//======================================================================
//                          F U N C T I O N S
//======================================================================


//                        C h e c k T i m e r ( )
//======================================================================
// Used when actions are needed 'after' a period of time.
boolean CheckTimer(unsigned long &lastMillis, const unsigned long Interval)
{
  //lastMillis = the time this "timer" was (re)started
  //Interval   = interval/delay (mS) we are looking for. 

  //Is this timer enabled and has it expired?
  if (millis() - lastMillis >= Interval)
  {
    lastMillis = millis();
    //or use
    //lastMillis += Interval;    //get ready for the next iteration

    //This Timer did expired
    return true;
  }

  //This timer did not expire
  return false;

} //END of:               C h e c k T i m e r ( )

//                     C h e c k S w i t c h e s ( )
//======================================================================
// No minimum switch press time is validated with this code (i.e. No glitch filter).
// For de-bounce, call this function every ~50ms.
// You add code to this function to handle all configured switches
void CheckSwitches()
{
  byte switchPosition;

  //******************************************
  //check if this switch has changed state
  switchPosition = digitalRead(ToggleSwitch);

  if (switchPosition != lastToggleSwitchState)
  {
    //update to the new switch state
    lastToggleSwitchState = switchPosition;

    //This switch position has changed, let's do some stuff

    //"HIGH condition code"          <-----<<<<<
    //Switch went from LOW to HIGH
    if (switchPosition == HIGH)
    {
      //Do some HIGH stuff here
    }

    //"LOW condition code"           <-----<<<<<
    //Switch went from HIGH to LOW
    else
    {
      digitalWrite(testLED, !digitalRead(testLED));  //toggle the testLED
    }

  } //END of:    ToggleSwitch code

  //******************************************
  // Similar code for other switches goes here
  //******************************************

} //END of:            C h e c k S w i t c h e s ( )


//======================================================================
//                            END OF CODE
//======================================================================

Also, from your recent post, you /seem/ to be looking for this...

Button 1 (enable), allows you to toggle the LED states with Button 2 each time Button 2 is pressed.

-then- (not sure which of these)

When Button 1 is released, Button 2 is ignored, LlEDs stay as they are...
-or-
When Button 1 is released, Button 2 is ignored - AND the LEDs go off as well.

// millis() returns the current run time (in ms) since the last restart.

//**********************************************************************

unsigned long SwitchMillis;   //The time when this Timer was (re)started


const unsigned long debounceInterval = 50;   //50ms


const byte testLED     = 12;
const byte ToggleSwitch1 = 4; //pushing and holding the switch puts a LOW on the pin
const byte ToggleSwitch = 3; //pushing the switch puts a LOW on the pin

byte lastToggleSwitchState;  //the last state the switch was in



//                            s e t u p ( )
//======================================================================
void setup()
{
  Serial.begin(9600);

  pinMode(testLED, OUTPUT);
  pinMode(ToggleSwitch1, INPUT_PULLUP);     // using internal PULL UP.

  pinMode(ToggleSwitch, INPUT_PULLUP);

} //END of:                   s e t u p ( )


//                             l o o p ( )
//======================================================================
void loop()
{
  //******************************************
  
  


  //******************************************
  //Put other non-blocking stuff here
  //******************************************


  //******************************************
  //Is it time to check the switches?
  if (CheckTimer(SwitchMillis, debounceInterval))
  {
    //it is now time to read the switches
    CheckSwitches();
  }

  while (digitalRead(ToggleSwitch1) == HIGH)  // if Pin is LOW  ToggleSwitch1 is working 

  if (digitalRead(ToggleSwitch1) == LOW)

  {
  
  }
  else                
  {
    digitalWrite(testLED, LOW);
    digitalWrite(ToggleSwitch, HIGH);
  }



} //END of:                    l o o p ( )


//======================================================================
//                          F U N C T I O N S
//======================================================================


//                        C h e c k T i m e r ( )
//======================================================================
// Used when actions are needed 'after' a period of time.
boolean CheckTimer(unsigned long &lastMillis, const unsigned long Interval)
{
  //lastMillis = the time this "timer" was (re)started
  //Interval   = interval/delay (mS) we are looking for. 

  //Is this timer enabled and has it expired?
  if (millis() - lastMillis >= Interval)
  {
    lastMillis = millis();
    //or use
    //lastMillis += Interval;    //get ready for the next iteration

    //This Timer did expired
    return true;
  }

  //This timer did not expire
  return false;

} //END of:               C h e c k T i m e r ( )

//                     C h e c k S w i t c h e s ( )
//======================================================================
// No minimum switch press time is validated with this code (i.e. No glitch filter).
// For de-bounce, call this function every ~50ms.
// You add code to this function to handle all configured switches
void CheckSwitches()
{
  byte switchPosition;

  //******************************************
  //check if this switch has changed state
  switchPosition = digitalRead(ToggleSwitch);

  if (switchPosition != lastToggleSwitchState)
  {
    //update to the new switch state
    lastToggleSwitchState = switchPosition;

    //This switch position has changed, let's do some stuff

    //"HIGH condition code"          <-----<<<<<
    //Switch went from LOW to HIGH
    if (switchPosition == HIGH)
    {
      //Do some HIGH stuff here
    }

    //"LOW condition code"           <-----<<<<<
    //Switch went from HIGH to LOW
    else
    {
      digitalWrite(testLED, !digitalRead(testLED));  //toggle the testLED
    }

  } //END of:    ToggleSwitch code

  //******************************************
  // Similar code for other switches goes here
  //******************************************

   


} //END of:            C h e c k S w i t c h e s ( )


//======================================================================
//                            END OF CODE
//======================================================================

Allright i came to this state and now it’s working as I wan’t, but I’m feeling it’s writen wrong way. Should I keep it this way or do something else ?

Helpful hints here...

const byte ToggleSwitch1 = 4; //pushing and holding the switch puts a LOW on the pin
const byte ToggleSwitch = 3; //pushing the switch puts a LOW on the pin
:::
pinMode(ToggleSwitch1, INPUT_PULLUP); // using internal PULL UP.
pinMode(ToggleSwitch, INPUT_PULLUP);

No need to have near-identical names - better to make them clearly descriptive (e.g. TOGGLE_ENABLE, and TOGGLE_STATE) or something... (are they really toggle switches? The operation looks like momentary buttons.)
Names are free, and descriptive names are worth their weight in electrons!

It would be nice to put your while() block in parentheses - even tho' the structure is correct, its hard to read without balanced {} around the if() {} else {} block. And the line-spacing / indentation is all over the place.
Parentheses are free too!

// millis() returns the current run time (in ms) since the last restart.

//**********************************************************************

unsigned long SwitchMillis;   //The time when this Timer was (re)started


const unsigned long debounceInterval = 50;   //50ms

const byte Relay     = 13;   Toggle Relay
const byte testLED     = 12;  Toggle testLED
const byte InPin = 4; //If it pressed  second button starts to work.
const byte ToggleSwitch = 3; //pushing the switch puts a LOW on the pin

byte lastToggleSwitchState;  //the last state the switch was in



//                            s e t u p ( )
//======================================================================
void setup()
{
  Serial.begin(9600);

  pinMode(testLED, OUTPUT);
  pinMode(Relay, OUTPUT);
  pinMode(InPin, INPUT_PULLUP);     // using internal PULL UP. If it pressed  second button starts to work.
  pinMode(ToggleSwitch, INPUT_PULLUP);

} //END of:                   s e t u p ( )


//                             l o o p ( )
//======================================================================
void loop()
{

  //Is it time to check the switches?
  if (CheckTimer(SwitchMillis, debounceInterval))
  {
    //it is now time to read the switches
    CheckSwitches();
  }

  while (digitalRead(InPin) == HIGH)  // if Pin is LOW  ToggleSwitch1 is working

    if (digitalRead(InPin) == LOW)

    {
    }
    
    else
    
    {
      digitalWrite(testLED, LOW);
      digitalWrite(Relay, LOW);
      digitalWrite(ToggleSwitch, HIGH);
    }



} //END of:                    l o o p ( )


//======================================================================
//                          F U N C T I O N S
//======================================================================


//                        C h e c k T i m e r ( )
//======================================================================
// Used when actions are needed 'after' a period of time.
boolean CheckTimer(unsigned long &lastMillis, const unsigned long Interval)
{
  //lastMillis = the time this "timer" was (re)started
  //Interval   = interval/delay (mS) we are looking for.

  //Is this timer enabled and has it expired?
  if (millis() - lastMillis >= Interval)
  {
    lastMillis = millis();
    //or use
    //lastMillis += Interval;    //get ready for the next iteration

    //This Timer did expired
    return true;
  }

  //This timer did not expire
  return false;

} //END of:               C h e c k T i m e r ( )

//                     C h e c k S w i t c h e s ( )
//======================================================================
// No minimum switch press time is validated with this code (i.e. No glitch filter).
// For de-bounce, call this function every ~50ms.
// You add code to this function to handle all configured switches
void CheckSwitches()
{
  byte switchPosition;

  //******************************************
  //check if this switch has changed state
  switchPosition = digitalRead(ToggleSwitch);

  if (switchPosition != lastToggleSwitchState)
  {
    //update to the new switch state
    lastToggleSwitchState = switchPosition;

    //This switch position has changed, let's do some stuff

    //"HIGH condition code"          <-----<<<<<
    //Switch went from LOW to HIGH
    if (switchPosition == HIGH)
    {
      //Do some HIGH stuff here
    }

    //"LOW condition code"           <-----<<<<<
    //Switch went from HIGH to LOW
    else
    {
      digitalWrite(testLED, !digitalRead(testLED));  //toggle the testLED
      digitalWrite(Relay, !digitalRead(Relay));  //toggle Relay
    }

  } //END of:    ToggleSwitch code

  //******************************************
  // Similar code for other switches goes here
  //******************************************




} //END of:            C h e c k S w i t c h e s ( )


//======================================================================
//                            END OF CODE
//======================================================================

Dont know why , but it’s working as it should with no glitch at this moment.

    if (digitalRead(InPin) == LOW)

    {
    }
   
    else

should be

    if (digitalRead(InPin) != LOW)
 while (digitalRead(InPin) == HIGH)  // if Pin is LOW  ToggleSwitch1 is working

    if (digitalRead(InPin) != LOW)
    
    {
      digitalWrite(testLED, LOW);
      digitalWrite(Relay, LOW);
      digitalWrite(ToggleSwitch, HIGH);
    }

Did it :stuck_out_tongue: