Hi all, (i hope i have chosen the correct catagory)
I have recently started learning C++ with the learncpp website (awesome website), and i finaly made it to chapter 14 (classes).
Just for practice i wrote a small class for two buttons and as a result the serial monitor should print “Button”. It worked, but i couldn’t get only the rising edge so it would keep printing “Button” while i held the button down.
So i cheated a little bit and looked in the library of ezButton and adjusted my class and now it works like a charm.
But i can’t seem to figure out why it works correctly (only reacting to a rising edge).
As far as i can see the conditions for a “true” in my buttonPressed() function don’t seem to change while i hold the button down.
Can someone please explain to me what i’m missing here?
Thank you.
class Button {
private:
int m_pinNumber{};
bool m_pullup{ false };
bool m_pressed{ false };
int m_previousSteadyState{};
int m_lastSteadyState{};
int m_lastBouncyState{};
unsigned long m_lastDebounceTime{ 0 };
unsigned long m_debounceDelay{ 50 };
public:
Button(int pin, bool pullup)
: m_pinNumber{ pin }, m_pullup{ pullup } {
if (m_pullup) {
pinMode(m_pinNumber, INPUT_PULLUP);
} else {
pinMode(m_pinNumber, INPUT);
}
m_previousSteadyState = digitalRead(m_pinNumber);
m_lastSteadyState = m_previousSteadyState;
m_lastBouncyState = m_previousSteadyState;
}
bool buttonPressed() {
if (m_previousSteadyState == 1 && m_lastSteadyState == 0) {
return true;
} else {
return false;
}
}
void buttonLoop() {
int buttonRead = digitalRead(m_pinNumber); //Read button pin
if (buttonRead != m_lastBouncyState) { //Button changed
m_lastDebounceTime = millis(); //Reset debounce timer
m_lastBouncyState = buttonRead;
}
if (millis() - m_lastDebounceTime > m_debounceDelay) { //reading longer then debounce time
m_previousSteadyState = m_lastSteadyState;
m_lastSteadyState = buttonRead;
}
}
}; // class Button
Button knop(26, true);
Button knop2(25, false);
void setup() {
Serial.begin(115200);
}
void loop() {
knop.buttonLoop();
knop2.buttonLoop();
if (knop.buttonPressed()) {
Serial.println("Button");
}
if (knop2.buttonPressed()) {
Serial.println("Button 2");
}
}
