Code - reset counter when using switch

Hey, first post and this might be a stupid question, but I am new to programming. Using a microcontroller (mbed LPC1768) to run the program.

I wrote a code that will use 5 led lights to count to 25 in binary. What i wish to achieve is that the counter will reset and start counting from 0 when i flick a switch on the board (p13). This code works with a click button that is normally off (0). But when i use a switch that i can turn on or off. The counter just stay at 0 when the button is on (1). Can anyone help me with this problem? Should be easy to fix.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
BusOut bar(p21, p22, p23, p24, p25);
DigitalIn button(p13);

int main()
{
    unsigned char counter = 0;

    while(1) {
        if(button==0) {
            if(counter<25) {
                bar = counter;
                counter = counter + 1;
                wait(0.25);
            } else {
                bar=counter;
                counter = 0;
                wait(0.25);
            }
        } else {

            counter = 0;

            if(counter<25) {
                bar = counter;
                counter = counter + 1;
                wait(0.25);
            } else {
                bar=counter;
                counter = 0;
                wait(0.25);
            }

        }
    }
}
I'm going out on a limb but the switch may have another setting.
Have you tested the switch to make sure it's only using a 0 or 1 ?
Using a switch like this : https://www.sparkfun.com/products/8034

So i am pretty sure its even on or off. Therefor 0 or 1.

The code works when i flick the switch back and forth. Reset when the button is sending a current and start counting from zero again when i flick the switch off again.

So the problem is in the code. When the switch is on (1), the bottom half "else" will loop and always start with "counter = 0". So it will never start counting upwards again. Need to make the "counter = 0" only work once. For both "button" options.
Topic archived. No new replies allowed.