Im new to the Arduino environment and wrote up a sketch that count 0-9 with the pres of a button and display the number on a 7 segment display however I need help dealing with the signal noise and press delay my code is posted below if anyone has any recommendation on a fix it would be greatly appreciated.
I would like to know if I am implementing Debouncing in the correct way because when i run the sketch there is alot of delay between when i press the button and when the 7-segment display changes
thank you
// Counts from 0-9 on 7 segment Display
// Uses Pins 2 -8
byte seven_seg_digits[10][7] = { { 1,1,1,1,1,1,0 }, // = 0
{ 0,1,1,0,0,0,0 }, // = 1
{ 1,1,0,1,1,0,1 }, // = 2
{ 1,1,1,1,0,0,1 }, // = 3
{ 0,1,1,0,0,1,1 }, // = 4
{ 1,0,1,1,0,1,1 }, // = 5
{ 1,0,1,1,1,1,1 }, // = 6
{ 1,1,1,0,0,0,0 }, // = 7
{ 1,1,1,1,1,1,1 }, // = 8
{ 1,1,1,0,0,1,1 } // = 9
};
int displayNum = 0;
int buttonPin = 12;
int buttonState; // current reading of button
int lastButtonState = LOW; // previous reading of input
// Long variables which are used to store debounce time
long lastDebounceTime = 0; // last time output pin was toggled
long debounceDelay =70; // the debounce time
// turns the dot off
void writeDot(byte dot){
digitalWrite(9,0);
}
void sevenSegWrite(byte digit){
byte pin = 2;
for(byte segCount = 0; segCount < 7; ++segCount){
digitalWrite(pin,seven_seg_digits[digit][segCount]);
++pin;
}
}
void setup() {
Serial.begin(9600);
pinMode(2,OUTPUT);
pinMode(3,OUTPUT);
pinMode(4,OUTPUT);
pinMode(5,OUTPUT);
pinMode(6,OUTPUT);
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
}
void loop(){
int reading = digitalRead(buttonPin); //reads the button
Serial.println(reading); // prints its state to serial monitor
delay(1000);
// if the switch has changes due to noise
if(reading != lastButtonState){
lastDebounceTime = millis(); //resets debouncing timer
}
if(( millis() - lastDebounceTime) > debounceDelay){
// if the reading has been their for longer than the debounce time this is the state
if(reading != buttonState){
buttonState = reading;
if (buttonState == HIGH){
sevenSegWrite(displayNum);
displayNum++;
}
}
}
lastButtonState = reading;
}