Ex: Push-button LED states

I kept having a problem with the push-buttons while working on the exercise. The circuit was pretty simple/fast to set up but, the coding didn't seem to be perfect for quite some time. The button pushes were being recognized and read properly by the program but, they weren't corresponding to the events assigned to them. I realized that was probably due to the button bouncing.

De-bouncing: I added/edited/re-edited and then finally removed the de-bouncing code in attempts to fix the problem. Adding the de-bouncing code just made the system become much slower (it wouldn't start recognizing button-pushes until several minutes after the code had finished uploading).
Eventually, I just added a 'delay(100)' at the end of the code.Which appeared to work very good as a de-bouncer, at least for this program! ..it might not be the best way to go about it but, it's working for me for now.

Then I also went ahead and added additional effects to the states of each button-push-event:
0 pushes: no lights
1 push: green light with slow blinking
2 pushes: blue light with faster blinks
3 pushes: red light blinking very fast






MAIN LOOP AREA PRINTED BELOW:
------------------------------


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

  // compare the currState to its previous state
   if (currState != prevState)
   {
       if (currState == HIGH)
       {
         if (count == 3) count = 0;
         else  count++;
         Serial.print("number of button pushes:  ");
         Serial.println(count, DEC);
       }
       prevState = currState;   
   }
 
   if (count == 1)
   {
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, 50);
    delay(100);                  // wait for a second
    digitalWrite(ledPin3, LOW);    // set the LED off
    delay(100);                  // wait for a second
   } else
   if (count == 2)
   {
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin2, 50);
    delay(50);                  // wait for a second
    digitalWrite(ledPin2, LOW);    // set the LED off
    delay(50);
   } else
   if (count == 3)
   {
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, LOW);
    digitalWrite(ledPin1, 50);
    delay(10);                  // wait for a second
    digitalWrite(ledPin1, LOW);    // set the LED off
    delay(10);   
  
   } else
   {
    digitalWrite(ledPin1, LOW);
    digitalWrite(ledPin2, LOW);
    digitalWrite(ledPin3, LOW);  
   }
 
  delay (100);
}

No comments:

Post a Comment