7 Segment Display with Push Button Increment

Hello Friends, I am New to Arduino Programing and i got stuck in very strange problem :frowning:

I want to Control the Increment of Digit on 7segment with Push Button (as Input for Increment.)
Logic is when i Press Push Button it should only increment 1 in count ( Count variable to count How many Times Button is pressed). But I am not able to do it, Once i press Button it automatically start incrementing the count and Digits start displaying with given dealy :frowning:

Code:

#define A 2
#define B 3
#define C 4
#define D 5
#define E 6
#define Ff 7 // Used Ff becuase sompiler Gives Error when I used Single F
#define G 8

// Pushbutton connected to pin 9
#define BUTTON 10

int count = 0; // current display count

const byte numbers[10] = { 0b1000000, 0b1111001, 0b0100100, 0b0110000, 0b0011001, 0b0010010,
0b0000010, 0b1111000, 0b0000000, 0b0010000 };

void setup() {
pinMode(A, OUTPUT);
pinMode(B, OUTPUT);
pinMode(C, OUTPUT);
pinMode(D, OUTPUT);
pinMode(E, OUTPUT);
pinMode(Ff, OUTPUT);
pinMode(G, OUTPUT);
pinMode(BUTTON, INPUT);
lightSegments(0b1000000);
}

void loop() {
int val = digitalRead(BUTTON);
if (val == HIGH) {
count++;
if (count == 10) count = 0;
delay(200);
lightSegments(numbers[count]);

}
}

void lightSegments(byte number) {
for (int i = 0; i < 7; i++) {
int bit = bitRead(number, i);

// segments connected to Arduino pins 2-8
digitalWrite(i+2, bit);

}
}

loop() runs very often. Unless you put a delay() in there it runs at many thousands times a second.

You test the button, if it is down you increment. And then you go round the loop again. It runs very fast so as long as you hold the button down it will increment very fast. You tried to "cure" that by inserting a delay(), but found you increment 5times a second (5 time 200ms delay=1second)

When do you test if the button has been released? That is the essence of yourproblem

You logic needs to remember what the button state was last time round the loop. Only when it changes from low to high do you increm,ent. That will therefor be single count, as long as you remeber to note the new state of the button.

Look/search for "button debounce" because your next problem will be that you get 2 or 5 counts for every push. In a program that is not time critical (and yours is not at the moment) you can just add a delay(5) after a change of the button state, and it will mask the button bounce.

Have a look at example #4 here and see if it helps you to fix your code

http://www.pedroduino.com/7-segment-led-circuits/