Go Down

Topic: Debounce + StateChange [SOLVED] (Read 906 times) previous topic - next topic

illbatt

Hi,

why do you use "complicated code" for a simple task.

If you need to "debounce" you can simply read the value, wait and read again (thats what you do anyway).
If the value is the same both times use it otherwise discard it.

Example:

bValue1 = analogRead(pBUTTONhb);
delay(50);
bValue2 = analogRead(pBUTTONhb);

if bValue1 == bValue2 ......

ash901226

illbatt yes you could, btw is that from the ladyada 5th lesson tutorial?

anyway what this code did is that it will reach almost instantaneously so it wont make you wait in your brief window of opening for you to be able to control your circuit

illbatt

No, thats my own (have never read that tutorial).
Did'nt understand what you mean in your last sentence.

peetsyo

Thanks for watching, i got the solution.
When switch goes on, blinks twice.

Code: [Select]
const int buttonPin = 2;   
const int ledPin =  13;     

int currState = 0;           
int preState = 0;   
int reading = 0;
int prepreState =0;
long lastDebounceTime = 0; 
long debounceDelay = 1500;   

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  reading = digitalRead(buttonPin);

if (reading != currState) {
   lastDebounceTime = millis();
   currState = reading;
}
   
  if (reading != preState) {
if ( millis() - lastDebounceTime > debounceDelay ){
    if (reading == HIGH){
      if (preState == LOW){
        digitalWrite(ledPin, HIGH);
        delay(500);
        digitalWrite(ledPin, LOW);
        delay(500);
        digitalWrite(ledPin, HIGH);
        delay(500);
        digitalWrite(ledPin, LOW);
        preState = reading;
      }
    }
  else  {preState = reading;}
}
}
}

UKHeliBob

delay() does what it says.  It delays execution of the next instruction.  That may or may not be important, but in some circumstances it is important not to do block loop() from executing as often as possible such as when reading a sensor, hence the 'Blink without delay' technique which allows loop() to run continuously and not be blocked which gives the effect of doing 2 (or more) things at once.
Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

Go Up