11 years, 1 month ago.

how can i code without wait() counting switch?

Question is bellow..

Create a system which counts the number of times a digital switch is pressed or changed, and lights an LED when 10 instances have been counted.

#include "mbed.h"
 
DigitalOut rled(p5);
DigitalOut gled(p6);
DigitalIn switch_input(p7);
 
int main() {
    
    int count = 0;
    rled = 0;
    gled = 0;
 
    while(count < 10) {
        if(switch_input == 1){
            int check_value = switch_input;
            
            wait(0.0025); // why? url : http://mbed.org/media/uploads/4180_1/switch_bounce.jpg

            while(check_value){
                if(check_value - switch_input == 1){
                count++;
                check_value = 0;
                }
            }
        }
    }
 
    rled = 1;
    gled = 1;
 
}

I want to debug this code without wait(0.0025) but i don't know how to coding.

This graph shows why wait(0.0025) needs in this code

http://mbed.org/media/uploads/4180_1/switch_bounce.jpg

How could i debug this code without wait()?

In this time i use Editing tips ~ thank you !

3 Answers

11 years, 1 month ago.

You should use a non blocking systeme like the Debounced lib of Warwick Racing http://mbed.org/users/WarwickRacing/code/Debounced/file/8992c13bbb9b/DebouncedIn.cpp

11 years, 1 month ago.

Very good that you try to avoid the (horrible) "wait". The good way is to let system tick poll every 5 to 10 msec the switch input. Store this value. When it remains unchanged for more then 2 subsequent polls, then you may assume that the value is stable. The bounce time can be up to 20 msec, It depends on switch quality/type.

Some code suggestions: http://hackaday.com/2010/11/09/debounce-code-one-post-to-rule-them-all/

11 years, 1 month ago.

When you test the input in a tight loop like you do, your program will see every transition of the input. When you however sample the input at intervals longer than your debounce time (but shorter than the toggle speed of the switch), you are usually safe. Suppose your debounce time is 200us and the toggle speed is max 10 per second (i.e. 100ms), then any sample time between 200us and 100ms will do, choose e.g. 1ms. In your graph, samples will initially be high, after the switch the sample will be high or low depending on the exact position of the sample. When it is low, the switch is detected correctly and the next sample will be after the debounce and will also be low. When it is high, the switch is not detected (although it was pressed) but the next sample will again be after the debounce time and will be low. So in this case the press of the switch is detected 1 sample (or max 1ms) late which is generally acceptable. This is easily implemented with a Ticker but my guess is that DebounceIn works in a similar way.