// Changing a setpoint with up and a down pushbutton switches.
// https://forum.arduino.cc/t/how-to-make-setpoint-with-push-button/893568/5
/*
The circuit:
- pushbutton attached to pin 2 from ground
- the internal pullup on pin 2 is enabled
- pushbutton attached to pin 3 from ground
- the internal pullup on pin 3 is enabled
*/
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 20, 4);
// these constants won't change:
const byte upButtonPin = 2;
const byte downButtonPin = 3;
// Variables will change:
int setpoint = 0;
bool setpointChanged = false;
void setup()
{
// initialize the button pins as a input with internal pullup:
pinMode(upButtonPin, INPUT_PULLUP);
pinMode(downButtonPin, INPUT_PULLUP);
// initialize serial communication:
lcd.init();
lcd.backlight();
lcd.setCursor(0, 0);
lcd.print("Setpoint Change");
lcd.setCursor(0, 1);
lcd.print("with 2 Buttons");
delay(2000);
lcd.clear();
}
void loop()
{
checkUpButton();
checkDownButton();
if (setpointChanged == true)
{
lcd.setCursor(0, 0);
lcd.print("New Setpoint=");
lcd.setCursor(13, 0);
lcd.print(setpoint);
setpointChanged = false;
}
}
void checkUpButton()
{
boolean buttonState = 0; // current state of the button
static boolean lastButtonState = 0; // previous state of the button
static unsigned long timer = 0;
unsigned long interval = 50; // check 20 times a second
if (millis() - timer >= interval)
{
timer = millis();
// read the pushbutton input pin:
buttonState = digitalRead(upButtonPin);
// compare the buttonState to its previous state
if (buttonState != lastButtonState)
{
// if the state has changed, increment the counter
if (buttonState == LOW)
{
// if the current state is LOW then the button went from off to on:
setpoint++;
setpointChanged = true;
}
// save the current state as the last state, for next time through the loop
lastButtonState = buttonState;
}
}
}
void checkDownButton()
{
boolean buttonState = 0; // current state of the button
static boolean lastButtonState = 0; // previous state of the button
static unsigned long timer = 0;
unsigned long interval = 50; // check 20 times a second
if (millis() - timer >= interval)
{
timer = millis();
// read the pushbutton input pin:
buttonState = digitalRead(downButtonPin);
// compare the buttonState to its previous state
if (buttonState != lastButtonState)
{
// if the state has changed, increment the counter
if (buttonState == LOW)
{
// if the current state is LOW then the button went from off to on:
setpoint--;
setpointChanged = true;
}
// save the current state as the last state, for next time through the loop
lastButtonState = buttonState;
}
}
}