// https://forum.arduino.cc/t/how-to-make-setpoint-with-push-button/893568
#define ProjectName "how to make setpoint with push button"
// CONSTANT DEFINITION
// you may need to change these constants to your hardware
const byte Input_[] {12, 13};
const byte Output_[] {10};
// VARIABLE DECLARATION
enum {One, Two, Three, Four};
enum {Value, Min, Max, Trigger};
int setPoint[] {0, 0, 30, 24};
enum {Up, Down};
struct BUTTON { // declare an object
int name; // member name
byte pin; // pin address
bool state; // and state
}
buttons [] { // make two button objects
{Up, Input_[One], 1}, // state =1 due to pinMode = INPUT_PULLUP
{Down, Input_[Two], 1},
};
// FUNCTIONS
void setup() {
Serial.begin(115200);
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);
for (auto Input : Input_)pinMode(Input, INPUT_PULLUP);
for (auto Output : Output_)pinMode(Output, OUTPUT);
Serial.print("Button 1 is on Pin");
Serial.println((Input_)[One]);
Serial.print("Button 2 is on Pin");
Serial.println((Input_)[Two]);
}
void loop ()
{
unsigned long currentTime = millis();
digitalWrite(LED_BUILTIN, (currentTime / 500) % 2); // make heartbeat
for (auto &button : buttons)
{
bool stateNew = digitalRead(button.pin); // read state
if (button.state != stateNew)
{ // state changed ?
Serial.println(button.name);
Serial.println(stateNew);
button.state = stateNew; // save new state
if (!stateNew) { // is button pressed ?
switch (button.name)
{ // which button is pressed ?
case Up:
setPoint[Value]++;
if (setPoint[Value] > setPoint[Max]) setPoint[Value] = setPoint[Max];
Serial.println("Up");
break;
case Down:
setPoint[Value]--;
if (setPoint[Value] < setPoint[Min]) setPoint[Value] = setPoint[Min];
Serial.println("Down");
break;
}
digitalWrite(Output_[One], setPoint[Value] >= setPoint[Trigger]); // male output
Serial.println(setPoint[Value]);
}
}
}
delay (20); // bad delay to debounce :)
}