Hallo
Ich habe in meiner Sketchkiste einen Sketch, für eine ähnliche Aufgabenstellung, gefunden, den ich ein bißchen angepasst habe. Im wesentlichen enthält der Sketch zwei Objekte, eins für den Button und eins für die Befehle und eine entsprechende Methode für die Datenverarbeitung.
/* BLOCK COMMENT
ATTENTION: This Sketch contains elements of C++.
https://www.learncpp.com/cpp-tutorial/
https://forum.arduino.cc/t/push-button-mit-mehreren-funktionen/927103
*/
#define ProjectName "Push-Button mit mehreren Funktionen"
//======================================================================================
// USER FUNCTIONS
void keinBefehl() {
Serial.println(__func__);
}
void befehl1() {
Serial.println(__func__);
}
void befehl2() {
Serial.println(__func__);
}
void befehl3() {
Serial.println(__func__);
}
//======================================================================================
// HARDWARE SETTINGS
// YOU MAY NEED TO CHANGE THESE CONSTANTS TO YOUR HARDWARE AND NEEDS
constexpr byte ButtonPin {A0}; // portPin o---|button|---GND
// CONSTANT DEFINITION
enum {Button_};
constexpr byte Input_[] {ButtonPin};
// FORWARD DECLARATION USING FUNCTION PROTOTYPE
void keinBefehl();
void befehl1();
void befehl2();
void befehl3();
// VARIABLE DECLARATION AND DEFINITION
unsigned long currentTime;
struct BUTTON {
byte pin;
bool statusQuo;
int counter;
int call;
unsigned long stamp;
unsigned long duration;
} button_ {Input_[Button_], false, 0, 0, 0, 20};
struct TASK {
void (*exec)();
} tasks[] {
{keinBefehl},
{befehl1},
{befehl2},
{befehl3},
};
// -------------------------------------------------------------------
void setup() {
Serial.begin(9600);
Serial.println(F("."));
Serial.print(F("File : ")), Serial.println(__FILE__);
Serial.print(F("Date : ")), Serial.println(__DATE__);
Serial.print(F("Project: ")), Serial.println(ProjectName);
pinMode (LED_BUILTIN, OUTPUT); // used as heartbeat indicator
// https://www.learncpp.com/cpp-tutorial/for-each-loops/
for (auto Input : Input_) pinMode(Input, INPUT_PULLUP);
}
void loop () {
currentTime = millis();
digitalWrite(LED_BUILTIN, (currentTime / 500) % 2);
// button debouncing
if (currentTime - button_.stamp >= button_.duration) {
button_.stamp=currentTime;
bool stateNew = !digitalRead(button_.pin);
// state change detection
if (button_.statusQuo != stateNew) {
button_.statusQuo = stateNew;
enum {Released, Pressed};
enum {Idle, Tasks};
// action on new button state
switch (stateNew) {
case Released:
button_.call = Idle;
break;
case Pressed:
button_.call = Tasks + button_.counter;
++button_.counter %= (sizeof(tasks) / sizeof(tasks[0]) - Tasks);
break;
}
}
}
// execute selected task
tasks[button_.call].exec();
// for test purposes only
delay (250);
}
Viel Spass damit beim Spielen.
Ich wünsche ein geschmeidges Wochenende und viel Spass beim Programmieren in C++.