I have made a simple arrangement, in which PIN2 is connected to +5V through a switch. Also PIN2 is connected to ground through a 10K resistor. Aim of the project is, when button is pressed it should send digit '2' to serial monitor, also button should not transmit digit for next 2seconds.
int buttonPin = 2;
byte bpState = LOW;
const int period = 2000;
unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
void setup() {
// put your setup code here, to run once:
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
currentMillis = millis();
if (digitalRead(buttonPin) == HIGH)
{
if (currentMillis - previousMillis >= period)
{
digitalWrite(buttonPin, bpState);
previousMillis = currentMillis;
}
Serial.println(2);
}
}
Now the problem is, when button is pressed, about fifty 2's are appearing in monitor even if I change the int period value. Though bouncing is gone when delay(200) is used instead of millis(), but I think I can't use delay as I'm planning modify the project with multiple buttons.
Your print statement is not controlled by the timing if-statement... It's outside that set of brackets and it will print ever time through the loop whenever the button is high, as fast as the loop can run.
// put your main code here, to run repeatedly:
That's a useless comment... It's a helpful instruction to you when you start writing your code, but doesn't apply once you've started writing the program and you should remove it (or change it).
It would be OK to say "// This loops runs repeatedly", but we already know that and after you've written a few Arduino sketches you'll know it too.
Your comments should tell us something helpful/useful or they should help someone to understand your program or for you to understand it if you go-back to it months later.
int buttonPin = 2;
bool waiting = false;
const int period = 2000;
unsigned long currentMillis = 0;
unsigned long previousMillis = 0;
void setup() {
// put your setup code here, to run once:
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
currentMillis = millis();
if (digitalRead(buttonPin) == HIGH && waiting == false )
{
// inital button press, report it
Serial.println(2);
waiting = true;
previousMillis = currentMillis;
}
if ( waiting == true && currentMillis - previousMillis >= period)
{
// wait period is over
waiting = false;
}
}