Wednesday, July 6, 2011


I fixed the bouncing issue! I read a tutorial online that helped me figure it out, but I had to modify their method because theirs wasn't actually debouncing, though it the method seemed to make sense. I used the following code:

void loop() {
    if(switchState != switchState2){
        ledState = 1 - ledState;

So there are two variables for the state of the switch: switchState and switchState2. By storing both of them 10 milliseconds apart and comparing them, you can kind of ignore those erratic few milliseconds where the current is bouncing around from 0 to 1. The tutorial I found suggested comparing them to make sure they were the same (i.e. if(switchState==switchstate2)...), but that really didnt work very well, so I altered the if statement to allow the rest of the LED switching code to run only if the two switchState values were different. This results in the LED state changing only when the program finds a 10 millisecond period where it starts as one switchState and ends as another. Functionally, this means that the led switches from red to yellow or yellow to red (and stays that way until the next button press) only when you release the button after pressing it.

Now that I've proved the concept using just the push button on the breadboard I can try incorporating the pendulum switch I was thinking about before. I'll post a pic if I get a chance.

P.S. I hope the stuff I wrote makes sense, its kind of hard to describe code verbally. I'm not even sure if I can explain things 100% correctly.

No comments:

Post a Comment