Below is my code in part_1_button:
#include "Button.h"
Button buttonOne(33, 1);
Button buttonTwo(34, 3);
Button buttonThree(35, 5);
Button buttonFour(36, 6);
void setup() {
Serial.begin(9600);
buttonOne.pressHandler(onPress);
buttonOne.releaseHandler(onRelease);
buttonTwo.pressHandler(onPress);
buttonTwo.releaseHandler(onRelease);
buttonThree.pressHandler(onPress);
buttonThree.releaseHandler(onRelease);
buttonFour.pressHandler(onPress);
buttonFour.releaseHandler(onRelease);
}
void loop() {
buttonOne.process();
buttonTwo.process();
buttonThree.process();
buttonFour.process();
}
void onPress(int buttonNumber) {
Serial.print(buttonNumber);
Serial.println(" pressed");
}
void onRelease(int buttonNumber) {
Serial.print(buttonNumber);
Serial.println(" released");
}
Below is my code in Button.cpp
#include "Arduino.h"
#include "Button.h"
Button::Button(int _buttonPin, int _buttonNum)
{
buttonPin = _buttonPin;
buttonNum = _buttonNum;
buttonState = 0;
lastButtonState = 0;
pinMode(buttonPin, INPUT);
}
void Button::process()
{
lastButtonState = buttonState;
buttonState = digitalRead(buttonPin);
if (lastButtonState == LOW && buttonState == HIGH) {
pressCallback(buttonNum);
usbMIDI.sendNoteOn(59 + buttonNum, 127, 1);
delay(5);
}
if (lastButtonState == HIGH && buttonState == LOW) {
releaseCallback(buttonNum);
usbMIDI.sendNoteOff(59 + buttonNum, 0, 1);
delay(5);
}
}
void Button::pressHandler(void (*f)(int)) //button down
{
pressCallback = *f;
}
void Button::releaseHandler(void (*f)(int)) //button release
{
releaseCallback = *f;
}
Below is my code in Button.h
#ifndef Buttons_h
#define Buttons_h
#include "Arduino.h"
class Button
{
public:
Button(int _buttonPin, int _buttonNum);
void process();
void pressHandler(void (*f)(int));
void releaseHandler(void (*f)(int));
void (*pressCallback)(int);
void (*releaseCallback)(int);
private:
int buttonPin;
int buttonNum;
bool buttonState;
bool lastButtonState;
};
#endif
The variables pressCallBack and releaseCallBack are functioning as a variable while being a function. In the code in Button.cpp the pressCallBack and releaseCallBack is being used as a function in the “Button :: process()” section of the code. Then in the bottom section it is used is a variable which is used in both codes in Button.h and part_1_button.