noob here
So what I am trying to do is output a different number depending on the number of button presses e.g. for 1 button press it should output 1 and so forth. After that I only really want the outputs for 1 to 4 presses. I am using these inputs for a game. Right now, it does work and counts up until 4 and then resets back to 0. The problem that I am having is it continues after 1 click to 2 clicks; what I want it to do is count 1 click when its clicked once, twice when its clicked twice etc. I am trying to use a debouncing code to distinguish between single tap, double tap, triple tap etc @VE7JRO kindly provided a great solution to this problem, albeit it was for one button. I am trying to adjust the code to accommodate 2 separate buttons (on separate pins), but it is giving me an error.
This is the code:
#include <Bounce2.h>
// Connect both buttons in series with one connection
// to GND and the other to a digital pin.
const int buttonPin1 = 2;
const int buttonPin2 = 3;
class Button
{
private:
int m_buttonPin1;
int m_buttonPin2;
int m_counter;
unsigned long m_buttonPressTimeout;
unsigned long m_previousMillis;
public:
Button(int button):
m_buttonPin1(buttonPin1),
m_buttonPin2(buttonPin2),
m_counter(0),
m_buttonPressTimeout(1500), // Button press timeout 500 ms.
m_previousMillis(0){}
void Update()
{
int valA = digitalRead(button1); // read button stateint
int valB = digitalRead(button2); // read button state
if (valA == LOW &&valB == LOW)
{
if(m_counter > 0 && millis() - m_previousMillis >= m_buttonPressTimeout)
{
Serial.print("Count from Update() just before it's re-set to 0 = ");
Serial.println(GetCounter());
m_counter = 0;
}
}
void IncrementCounter(){
m_counter++;
if(m_counter > 4){m_counter = 4;}
if(m_counter == 1){
m_previousMillis = millis();
}
}
byte GetCounter(){
return m_counter;
}
};
Bounce button1Debouncer = Bounce();
Bounce button2Debouncer = Bounce();
Button MyButton(buttonPin1);
Button MyButton(buttonPin2);
void setup(){
Serial.begin(9600);
pinMode(buttonPin1, INPUT_PULLUP);
button1Debouncer.attach(buttonPin);
button1Debouncer.interval(5);
pinMode(buttonPin2, INPUT_PULLUP);
button2Debouncer.attach(buttonPin);
button2Debouncer.interval(5);
}
void loop(){
// Call the Update function as fast as possible.
MyButton.Update();
// Button pressed.
if(button1Debouncer.update() && button2Debouncer.update())
{
if(button1Debouncer.fell() && button2Debouncer.fell()){
MyButton.IncrementCounter();
Serial.print("Count from Button Debouncer = ");
Serial.println(MyButton.GetCounter());
}
}
}
}
The error is: "'buttonPin1' is not a type", I do not understand this error as it didn't give that error for when a single button was used.
PIND
, so you read pin 0 to 7 (advanced). Or, when I analyze your code, you just want to be notified of changes, you can use interrupts. – Adriano Nov 15 at 10:15