Go Down

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



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.


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

if bValue1 == bValue2 ......


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


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


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);

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);
        digitalWrite(ledPin, LOW);
        digitalWrite(ledPin, HIGH);
        digitalWrite(ledPin, LOW);
        preState = reading;
  else  {preState = reading;}


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