Go Down

Topic: Bounce (and Bounce 2) Library Official Question Forum (Read 68121 times) previous topic - next topic

dfitterman

What does the preprocessor directive #define BOUNCE_WITH_PROMPT_DETECTION change in the behavior of the Bounce2 library?

cattledog

The three debounce methods available with Bounce2 are in the .cpp file in the .update method.

Code: [Select]
bool Bounce::update()
{
#ifdef BOUNCE_LOCK_OUT
    state &= ~_BV(STATE_CHANGED);
    // Ignore everything if we are locked out
    if (millis() - previous_millis >= interval_millis) {
        bool currentState = digitalRead(pin);
        if ((bool)(state & _BV(DEBOUNCED_STATE)) != currentState) {
            previous_millis = millis();
            state ^= _BV(DEBOUNCED_STATE);
            state |= _BV(STATE_CHANGED);
        }
    }
    return state & _BV(STATE_CHANGED);

#elif defined BOUNCE_WITH_PROMPT_DETECTION
    // Read the state of the switch port into a temporary variable.
    bool readState = digitalRead(pin);

    // Clear Changed State Flag - will be reset if we confirm a button state change.
    state &= ~_BV(STATE_CHANGED);

    if ( readState != (bool)(state & _BV(DEBOUNCED_STATE))) {
      // We have seen a change from the current button state.

      if ( millis() - previous_millis >= interval_millis ) {
// We have passed the time threshold, so a new change of state is allowed.
// set the STATE_CHANGED flag and the new DEBOUNCED_STATE.
// This will be prompt as long as there has been greater than interval_misllis ms since last change of input.
// Otherwise debounced state will not change again until bouncing is stable for the timeout period.
state ^= _BV(DEBOUNCED_STATE);
state |= _BV(STATE_CHANGED);
      }
    }

    // If the readState is different from previous readState, reset the debounce timer - as input is still unstable
    // and we want to prevent new button state changes until the previous one has remained stable for the timeout.
    if ( readState != (bool)(state & _BV(UNSTABLE_STATE)) ) {
// Update Unstable Bit to macth readState
        state ^= _BV(UNSTABLE_STATE);
        previous_millis = millis();
    }
    // return just the sate changed bit
    return state & _BV(STATE_CHANGED);

#else
    // Read the state of the switch in a temporary variable.
    bool currentState = digitalRead(pin);
    state &= ~_BV(STATE_CHANGED);

    // If the reading is different from last reading, reset the debounce counter
    if ( currentState != (bool)(state & _BV(UNSTABLE_STATE)) ) {
        previous_millis = millis();
        state ^= _BV(UNSTABLE_STATE);
    } else
        if ( millis() - previous_millis >= interval_millis ) {
            // We have passed the threshold time, so the input is now stable
            // If it is different from last state, set the STATE_CHANGED flag
            if ((bool)(state & _BV(DEBOUNCED_STATE)) != currentState) {
                previous_millis = millis();
                state ^= _BV(DEBOUNCED_STATE);
                state |= _BV(STATE_CHANGED);
            }
        }

    return state & _BV(STATE_CHANGED);
#endif
}


The way I understand the three methods

BOUNCE_LOCK_OUT
This method only allows a digital read at a timed interval from the last reading, and accepts the value.


BOUNCE_WITH_PROMPT_DETECTION
This method, take a digital reading when the method is called, but only accepts the value if the time is greater than the debounce interval from the previous reading.

Both these methods are "prompt", but can accept a false positive due to noise on the input.

DEFAULT

The default method requires the reading to be unchanged(stable) for the debounce interval interval. This method is noise resistant, but only accepts the value at the end of a timed interval.

arduino9208

#62
Dec 08, 2017, 05:36 am Last Edit: Dec 08, 2017, 05:42 am by arduino9208
Hi all,
I need help .
I have one source code and trying to compile with version 1.01 but can't compile .
Please help .

Source code :-

// Arduino 1.01

#include <Servo.h>
#include "Bounce.h"

#define MINARMDEG 0
#define MAXARMDEG 84
#define MINLIDDEG 0
#define MAXLIDDEG 21
#define WAIT 4

Servo servoArm; // Servo Object for Arm
Servo servoLid; // Servo Object for Lid

const int ledPin = 13;      // LED Pin
const int powerPin = 2;     // Power Pin
const int servoArmPin = 4;  // Servo Arm
const int servoLidPin = 19; // Servo Lid
const int switchMaster = 3; // Master Switch
const int switchFun = 8;    // Switch between Standard and Fun
int armPos = MAXARMDEG;     // position of arm
int lidPos = MAXLIDDEG;     // position of lid
int valSwitchFun = HIGH;    // Value of the fun switch
int valSwitch = HIGH;       // Value of the master switch
int play;                   // animation
int first = 0;              // first animation (animation has not been interrupted)

Bounce bouncerMaster = Bounce(switchMaster, 10);


void setup() {pinMode(BUTTON,INPUT);
 pinMode(LED,OUTPUT);
 // Read fun switch
 pinMode(switchFun, INPUT);
 int valSwitchFun = digitalRead(switchFun);
 if (valSwitchFun == HIGH) { // fun mode: get random animation
   randomSeed(analogRead(0));
   play = random(0, 11);
 } else {
   play = 8;        // standard mode: set standard animation
 }

 pinMode(powerPin, OUTPUT);
 digitalWrite(powerPin, HIGH);

 pinMode(ledPin, OUTPUT);
 digitalWrite(ledPin, LOW);

 pinMode(switchMaster, INPUT);

 servoArm.attach(servoArmPin);  // attache servo to servo object
 servoArm.write(0);

 servoLid.attach(servoLidPin);  // attache servo to servo object
 servoLid.write(0);
}


void loop() {
  // Update the debouncer
 bouncer.update ( );

// Get the update value
int value = bouncer.read();

// Turn on or off the LED
if ( value == HIGH) {
  digitalWrite(LED, HIGH );
} else {
   digitalWrite(LED, LOW );
}

}

 valSwitch = bouncerMaster.read(); // get master switch position
 if (valSwitch == HIGH)
 {
   if (first == 1) { // run standard animation if first animation has been interrupted
     play = 0;
   }

   armPos = MAXARMDEG;
   lidPos = MAXLIDDEG;

   switch(play) { // opening animation
   case 0: // Standard
     moveLid(lidPos, 0);
     moveArm(armPos, 0);
     break;
   case 1:
     moveLid(lidPos, 20);
     moveArm(42, 50);
     moveArm(armPos, 0);
     break;
   case 2:
     moveLid(lidPos, 0);
     moveArm(42, 0);
     moveArm(armPos-14, 50);
     moveArm(armPos+14, 0);
     break;
   case 3:
     moveLid(lidPos, 0);
     moveArm(armPos, 0);
     break;
   case 4:
     moveLid(lidPos, 50);
     myDelay(500);
     moveLid(0, 0);
     myDelay(500);
     moveLid(lidPos+10, 0);
     moveArm(42, 50);
     moveArm(armPos, 0);
     break;
   case 5:
     moveLid(lidPos, 0);
     moveArm(armPos, 0);
     break;
   case 6:
     moveLid(lidPos, 50);
     moveArm(armPos-14, 50);
     moveArm(armPos+14, 0);
     break;
   case 7:
     moveLid(lidPos, 0);
     moveArm(armPos-7, 0);
     moveArm(0, 0);
     moveLid(0, 0);
     myDelay(1000);
     moveLid(lidPos, 0);
     moveArm(42, 50);
     moveArm(armPos+7, 0);
     break;
   case 8:
     moveLid(lidPos, 0);
     myDelay(500);
     moveArm(armPos, 0);
     break;
   case 9:
     moveLid(lidPos, 5);
     myDelay(300);
     moveLid(0, 4);
     myDelay(200);
     moveLid(14, 4);
     moveLid(0, 4);
     moveLid(14, 4);
     moveLid(0, 4);
     moveLid(14, 4);
     moveArm(armPos, 0);
     break;
   case 10:
     moveLid(14, 4);
     myDelay(100);
     moveLid(0, 0);
     myDelay(1000);
     moveLid(lidPos, 0);
     moveArm(armPos, 0);
     break;
   }
 }
 else // closing animation
 {
   first = 1;

   armPos = MINARMDEG;
   lidPos = MINLIDDEG;

   switch(play) {
   case 0: // Standard
     moveArm(armPos, 0);
     moveLid(lidPos, 0);
     break;
   case 1:
     moveArm(armPos, 0);
     moveLid(lidPos, 0);
     break;
   case 2:
     moveArm(armPos, 0);
     moveLid(lidPos, 0);
     break;
   case 3:
     myDelay(3000);
     moveArm(armPos, 0);
     moveLid(lidPos, 0);
     break;
   case 4:
     moveArm(armPos, 0);
     moveLid(lidPos, 0);
     break;
   case 5:
     moveArm(60, 2);
     moveArm(84, 2);
     moveArm(60, 2);
     moveArm(84, 2);
     moveArm(armPos, 0);
     moveLid(lidPos, 0);
     break;
   case 6:
     moveArm(armPos, 50);
     moveLid(lidPos, 0);
     delay(500);
     break;
   case 7:
     moveArm(armPos, 50);
     moveLid(lidPos, 0);
     break;
   case 8:
     moveArm(armPos, 0);
     moveLid(lidPos, 0);
     break;
   case 9:
     moveArm(armPos, 0);
     moveLid(lidPos, 0);
     break;
   case 10:
     moveArm(60, 50);
     moveArm(armPos, 0);
     moveLid(lidPos-14, 0);
     break;
   }
 }

 valSwitch = digitalRead(switchMaster);
 // Power off
 if (servoArm.read() == MINARMDEG && servoLid.read() == MINLIDDEG && valSwitch == LOW) {
   digitalWrite(powerPin, LOW);
   for(;;); // for debugging with power over USB-to-serial-adapter
 }
}

// move arm to position within the specified time
void moveLid(int degree, int speed) {
 int curDegree = servoLid.read();
 while (curDegree != degree) {
   if (curDegree < degree) {
     curDegree++;
   }
   else {
     curDegree--;
   }
   servoLid.write(curDegree);
   delay(WAIT + speed);
   int curVal = digitalRead(switchMaster);
   if (curVal != val) {
     break;
   }
 }
}

// move lid to position within the specified time
void moveArm(int degree, int speed) {
 int curDegree = servoArm.read();
 while (curDegree != degree) {
   if (curDegree < degree) {
     curDegree++;
   }
   else {
     curDegree--;
   }
   servoArm.write(curDegree);
   delay(WAIT + speed);
   int curVal = digitalRead(switchMaster);
   if (curVal != val) {
     break;
   }
 }
}

// delay (can be interrupted by manual switch change)
void myDelay(int msec) {
 long myTime = 0;
 do {
   delay(1);
   myTime++;
   int curVal = digitalRead(switchMaster);
   if (curVal != val) {
     break;
   }
 }
 while(myTime <= msec);
}

Dhanson06

Hi,

I am having trouble getting the debounce function to work.  I am using a photoresistor to detect the difference between the black of the rubber and the white lettering on the sidewall of a car tire that is spinning to determine revolutions and ultimately detect speed of wheel.  Since the white writing has spaces of black in the lettering the photoresistor picks up on this and jumps back and forth for the readings of black and white multiple times, essentially tricking the wheel counter into thinking that it has turned many more times than it actually has.  I figured that the debounce function would be best (better than a delay since I am also going to have to calculate time for speed) to basically ignore jumping around within 1/3 of a second after initially detecting the white lettering. 

Any suggestions on what I am doing wrong would be greatly appreciated, as well if there is a better way of doing this.  As a note, when the photoresistor is near black it has a value below 125 and when it sees white it goes about 125 (after constraining and calibrating), which I then had it trigger a digitalwrite signal to an LED every time it when above 125 so that the counter can just count LED HIGH signals.

Here is the sketch:


const int photocellPin = 0;     // the photoresistor with 10K pulldown to A0
const int LEDpin = 2;          // connect LED to pin 2 so that interrupt 0 works
const int wheeldiameter=0.002030641; //in miles

#include <LiquidCrystal.h>
const int rs = 12, en = 11, d4 = 5, d5 = 7, d6 = 3, d7 = 6;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

#include <Bounce2.h>
Bounce debouncer1=Bounce();

int sensorValue = 0;         // the photoresistor value
int sensorMin = 1023;        // minimum sensor value
int sensorMax = 0;           // maximum sensor value
unsigned int wheelcounter=0;


const float pulsesPerMile=492.46;
float wheelfrequency;       
float wheelspeed;
float wheeldistance=0;
const float convertMph=pulsesPerMile/492.46;  // the wheel rotates this many times to equal 1 mile distance
float mph;               





void setup(void) {
 pinMode(LEDpin, OUTPUT);
 debouncer1.attach(LEDpin);
 debouncer1.interval(333);
 
  lcd.begin(16, 2);

  lcd.setCursor(0,0); // Sets the cursor to col 0 and row 0
  lcd.print("Wheel Speed"); // Prints to LCD
  lcd.setCursor(0,1); // Sets the cursor to col 1 and row 0
  lcd.print("Calibrating Light"); // Prints to LCD

  Serial.begin(9600); 

  // turn on LED to signal the start of the calibration period:
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);

  // calibrate during the first five seconds
  // calibration from https://www.arduino.cc/en/Tutorial/Calibration
  while (millis() < 5000) {
    sensorValue = analogRead(photocellPin);

    // record the maximum sensor value
    if (sensorValue > sensorMax) {
      sensorMax = sensorValue;
    }

    // record the minimum sensor value
    if (sensorValue < sensorMin) {
      sensorMin = sensorValue;
    }
  }
 

  // signal the end of the calibration period
  digitalWrite(13, LOW);
lcd.clear();
}
 
void loop(void)
{   
  Serial.print(" Photo Resistor Value ");
  // read the sensor:
  sensorValue = analogRead(photocellPin);

  // apply the calibration to the sensor reading
  sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);

  // in case the sensor value is outside the range seen during calibration
  sensorValue = constrain(sensorValue, 0, 255);
  Serial.println(sensorValue);
 
  // if statement to detect black or white on wheel:
  if (sensorValue < 125) //Threshold value set in middle of calibrated value, set in middle of 0-255 range to trigger either white or black
    digitalWrite (LEDpin,LOW);
  else
    {digitalWrite(LEDpin, HIGH);
      wheelcounter=wheelcounter+1;
     }


Serial.println(wheelcounter);

lcd.setCursor(0,0); // Sets the cursor to col 0 and row 0
lcd.print("Distance: "); // Prints to LCD
lcd.print(wheeldistance); // Prints value to LCD
lcd.setCursor(0,1); // Sets the cursor to col 1 and row 0
lcd.print("Speed (mph): "); // Prints to LCD
lcd.print(mph); // Prints value to LCD

delay(10);
  } 


krypton18

#64
Jan 07, 2018, 11:35 pm Last Edit: Jan 08, 2018, 12:01 am by krypton18
Yes, but you will have to learn to use arrays.  It looks to me like you would have an array of six Bounce objects, numbered 0 through 5.
Code: [Select]

//
// untested
//
Bounce * debouncer = new Bounce[6] ; // Creates an array and fills it with six Bounce objects.
//
// Now instead of using debouncer03, you will use debouncer[3]
// For example:  debouncer[3].attach(buttonPins[3]) ;
// Of course, a for-loop would really simplify the use of attach and of interval.
//


I've tried your instructions and they perfectly worked, this fact has avoided me from writing a lot of redundant code. Thank you.
If anyone is intersted, I've done an example program that shows how to manage multiple buttons, in the array form, for turn ON a Buzzer by pressing any button defined.
p.s. The program has been tested on an Arduino Uno Rev3
Code: [Select]

//This Program turns ON a BUZZER when you press any button defined

#include <Bounce2.h>

const uint8_t BUTTON_PIN[] = {4, 5, 6};

const uint8_t NUMBUTTONS = sizeof(BUTTON_PIN) / sizeof(BUTTON_PIN[0]);

const int BuzzerPin = 3;

// Instantiate Bounce objects
Bounce * debouncer = new Bounce[NUMBUTTONS];

void setup(void)
{
  //Setup buttons as inputs and the Bounce instances for each of them :
  for (uint8_t b = 0; b < NUMBUTTONS; b++) {
    pinMode(BUTTON_PIN[b], INPUT);            //setup current button as input
    debouncer[b].attach(BUTTON_PIN[b]);       //setup the bounce instance for the current button
    debouncer[b].interval(100);              // interval in ms
  }

  //Setup the BUZZER :
  pinMode(BuzzerPin, OUTPUT);
}

void loop(void)
{

  int value=LOW;

  uint8_t b;

  // Update the Bounce instances :
  for (b = 0; b < NUMBUTTONS; b++)  debouncer[b].update();

  // Get the updated value :
  for (b = 0; b < NUMBUTTONS && value == LOW; b++)  if (debouncer[b].read() == HIGH) value = 230;

  // Turn on or off the BUZZER as determined by the state :
  analogWrite(BuzzerPin, value);

}

vaj4088


chopperaddict

#66
Jan 24, 2018, 04:46 pm Last Edit: Jan 24, 2018, 04:55 pm by chopperaddict
I have tried the following out, but it causes my mega to reboot constantly

Bounce * debouncer = new Bounce[6] ; // Creates an array and fills it with six Bounce objects.
//
// Now instead of using debouncer03, you will use debouncer[3]
// For example:  debouncer[3].attach(buttonPins[3]) ;
// Of course, a for-loop would really simplify the use of attach and of interval.
//
The declaration works, but as soon as I use debouncer
  • .attach or .interval it all goes belly up


Any  suggestions would be welcomed ?

Ian

cattledog

Quote
Any suggestions would be welcomed ?
1) Post a simplified example of your code which compiles and demonstrates the problem.


lukpuch


krypton18

#69
Mar 10, 2018, 12:35 pm Last Edit: Mar 10, 2018, 01:00 pm by krypton18
How can I use it with PCF8574 ?
As far as I know, the bounce2 library was exclusively made for Arduino based boards or at limit for the Wiring boards.
Hence, you just can't execute a library for a device that was not planned to work with it. You should search elsewhere your topic, e.g. try to googling PCF8574 debounce library.

Quote
Any  suggestions would be welcomed ?

Ian
Try to load my above written code example in your MEGA board, change some PIN addresses if you need it, and then report back whether it's working or not.

Guys, please don't be generic in your questions. Explain, in details, the problems that you experience, and then we can discuss on how to solve them.

vaj4088

 A PCF8574 is an I2C bus device to read eight inputs.  A similar problem would arise if a shift register was used to read inputs.  Perhaps a way to use the library with a variable (instead of a pin number) is needed?


krypton18

Perhaps a way to use the library with a variable (instead of a pin number) is needed?
I think it's not possibile, without a modification in the library. The library at the end always uses a digitalread function. Certain, It could be useful the possibility to use the library also for debouncing a generic variable that can be acquired as input in various way.

nickrobinson

I can't work out how to include debouncer within my void loop, where I use an array to go through the switches. Any clues or comments much appreciated. I'm still new to this and finding my way through trial and (mostly) error.

Code: [Select]
#include <MIDI.h>
#include <midi_Defs.h>
#include <midi_Message.h>
#include <midi_Namespace.h>
#include <midi_Settings.h>

MIDI_CREATE_DEFAULT_INSTANCE();

// Constants   
#define SWITCH1 19
#define SWITCH2 18
#define SWITCH3 17
#define SWITCH4 16
#define SWITCHES 4    // how many switches?
#define BOUNCEDELAY 200

byte seven_seg_digits[10][7] = {
  { 1,1,1,1,1,1,0 },  // = 0
  { 0,1,1,0,0,0,0 },  // = 1
  { 1,1,0,1,1,0,1 },  // = 2
  { 1,1,1,1,0,0,1 },  // = 3
  { 0,1,1,0,0,1,1 },  // = 4
  { 1,0,1,1,0,1,1 },  // = 5
  { 1,0,1,1,1,1,1 },  // = 6
  { 1,1,1,0,0,0,0 },  // = 7
  { 1,1,1,1,1,1,1 },  // = 8
  { 1,1,1,0,0,1,1 }   // = 9
  };

// Variables:
int currentSwitch = 0;
int switches[SWITCHES] = { SWITCH1, SWITCH2, SWITCH3, SWITCH4};
int switchState[SWITCHES] = { HIGH, HIGH, HIGH, HIGH };   // Initial state of switch is high due to internal pullup
int bank = 0;

void setup()
{
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT); 

MIDI.begin(1); 
Serial.begin(31250);       
Serial.flush();

for( currentSwitch = 0; currentSwitch < SWITCHES; currentSwitch++ )
  {
  pinMode( switches[currentSwitch], INPUT );          // Set pin for switch
  digitalWrite( switches[currentSwitch], HIGH );      // Turn on internal pullup
  }
}

void loop()
{
   
for ( currentSwitch = 0; currentSwitch < SWITCHES; currentSwitch++ )
  {
  if ( (digitalRead(switches[currentSwitch]) != switchState[currentSwitch] ) && (switchState[currentSwitch] == HIGH) )
    {   // if a switch has changed
      switch( currentSwitch )
      {
      case 0:      // bank down
          bank--;    // decrement bank number
          if (bank < 0) {bank = 9;} // roll round
          break;
      case 1:    // bank up
          bank++;   // increment bank number       
          if (bank >9) {bank = 0;}  // roll round
          break;
      case 2:      //      send midi
          MIDI.sendNoteOn(38,127,1);  // Send a Note
          delay(100);    // Wait
          MIDI.sendNoteOff(38,0,1);   // Stop the note
          break;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
      }     
      sevenSegWrite(bank);    // show bank number
      delay( BOUNCEDELAY );
    }
    switchState[currentSwitch] = digitalRead( switches[currentSwitch] );
  }  // end switch checking loop
}   // end void loop


void sevenSegWrite(byte digit) {
  byte pin = 2;
  for (byte segCount = 0; segCount < 7; ++segCount) {
    digitalWrite(pin, seven_seg_digits[digit][segCount]);
    ++pin;
  }
}

tof

Check out the following example : https://github.com/thomasfredericks/Bounce2/blob/master/examples/bounce_multiple/bounce_multiple.ino


I can't work out how to include debouncer within my void loop, where I use an array to go through the switches. Any clues or comments much appreciated. I'm still new to this and finding my way through trial and (mostly) error.

Code: [Select]
#include <MIDI.h>
#include <midi_Defs.h>
#include <midi_Message.h>
#include <midi_Namespace.h>
#include <midi_Settings.h>

MIDI_CREATE_DEFAULT_INSTANCE();

// Constants   
#define SWITCH1 19
#define SWITCH2 18
#define SWITCH3 17
#define SWITCH4 16
#define SWITCHES 4    // how many switches?
#define BOUNCEDELAY 200

byte seven_seg_digits[10][7] = {
  { 1,1,1,1,1,1,0 },  // = 0
  { 0,1,1,0,0,0,0 },  // = 1
  { 1,1,0,1,1,0,1 },  // = 2
  { 1,1,1,1,0,0,1 },  // = 3
  { 0,1,1,0,0,1,1 },  // = 4
  { 1,0,1,1,0,1,1 },  // = 5
  { 1,0,1,1,1,1,1 },  // = 6
  { 1,1,1,0,0,0,0 },  // = 7
  { 1,1,1,1,1,1,1 },  // = 8
  { 1,1,1,0,0,1,1 }   // = 9
  };

// Variables:
int currentSwitch = 0;
int switches[SWITCHES] = { SWITCH1, SWITCH2, SWITCH3, SWITCH4};
int switchState[SWITCHES] = { HIGH, HIGH, HIGH, HIGH };   // Initial state of switch is high due to internal pullup
int bank = 0;

void setup()
{
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT); 

MIDI.begin(1); 
Serial.begin(31250);       
Serial.flush();

for( currentSwitch = 0; currentSwitch < SWITCHES; currentSwitch++ )
  {
  pinMode( switches[currentSwitch], INPUT );          // Set pin for switch
  digitalWrite( switches[currentSwitch], HIGH );      // Turn on internal pullup
  }
}

void loop()
{
   
for ( currentSwitch = 0; currentSwitch < SWITCHES; currentSwitch++ )
  {
  if ( (digitalRead(switches[currentSwitch]) != switchState[currentSwitch] ) && (switchState[currentSwitch] == HIGH) )
    {   // if a switch has changed
      switch( currentSwitch )
      {
      case 0:      // bank down
          bank--;    // decrement bank number
          if (bank < 0) {bank = 9;} // roll round
          break;
      case 1:    // bank up
          bank++;   // increment bank number       
          if (bank >9) {bank = 0;}  // roll round
          break;
      case 2:      //      send midi
          MIDI.sendNoteOn(38,127,1);  // Send a Note
          delay(100);    // Wait
          MIDI.sendNoteOff(38,0,1);   // Stop the note
          break;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
      }     
      sevenSegWrite(bank);    // show bank number
      delay( BOUNCEDELAY );
    }
    switchState[currentSwitch] = digitalRead( switches[currentSwitch] );
  }  // end switch checking loop
}   // end void loop


void sevenSegWrite(byte digit) {
  byte pin = 2;
  for (byte segCount = 0; segCount < 7; ++segCount) {
    digitalWrite(pin, seven_seg_digits[digit][segCount]);
    ++pin;
  }
}


Thomas Ouellet Fredericks

windy1023

#74
Jul 25, 2018, 02:35 pm Last Edit: Jul 25, 2018, 02:36 pm by windy1023
Hi, can someone help me ?

I was looking at the code of the file <Bounce2.cpp> and I found this in the function update():

------------------------------------------------------------------------------------------------------

#else
    // Read the state of the switch in a temporary variable.
    bool currentState = readCurrentState();
   

    // If the reading is different from last reading, reset the debounce counter
    if ( currentState != getStateFlag(UNSTABLE_STATE) ) {
        previous_millis = millis();
         toggleStateFlag(UNSTABLE_STATE);
    } else
        if ( millis() - previous_millis >= interval_millis ) {
            // We have passed the threshold time, so the input is now stable
            // If it is different from last state, set the STATE_CHANGED flag
            if (currentState != getStateFlag(DEBOUNCED_STATE) ) {
                previous_millis = millis();
                 
                 changeState();
            }
        }

-----------------------------------------------------------------------------------------------

I'm not sure what the red line is for. I know it resets the counter, but I don't think anything will go wrong without it, because if the state changes, we will first enter the green part, right?

Go Up