This example demonstrates how to use buttons, callback functions and changing text variables.
#include <LiquidCrystal.h>
#include "Button.h"
const byte LCD_RS = 12;
const byte LCD_E = 11;
const byte LCD_D4 = 5;
const byte LCD_D5 = 4;
const byte LCD_D6 = 3;
const byte LCD_D7 = 2;
LiquidCrystal lcd(LCD_RS, LCD_E, LCD_D4, LCD_D5, LCD_D6, LCD_D7);
const bool pullup = true;
Button left(A0, pullup);
Button right(7, pullup);
Button up(8, pullup);
Button down(9, pullup);
Button enter(10, pullup);
const byte pwmPin = 6;
byte pwmLevel = 0;
const byte ledPin = LED_BUILTIN;
bool ledState = LOW;
char* ledState_text;
const byte analogPin = A5;
unsigned short analogValue = 0;
LiquidLine welcome_line2(0, 1,
"Buttons example");
LiquidLine analog_line(0, 0,
"Analog: ", analogValue);
LiquidLine ledState_line(0, 1,
"LED is ", ledState_text);
LiquidLine pwm_line(0, 0,
"PWM level: ", pwmLevel);
void pwm_up() {
if (pwmLevel < 225) {
pwmLevel += 25;
} else {
pwmLevel = 250;
}
analogWrite(pwmPin, pwmLevel);
}
void pwm_down() {
if (pwmLevel > 25) {
pwmLevel -= 25;
} else {
pwmLevel = 0;
}
analogWrite(pwmPin, pwmLevel);
}
void setup() {
Serial.begin(250000);
pinMode(analogPin, INPUT);
pinMode(ledPin, OUTPUT);
pinMode(pwmPin, OUTPUT);
lcd.begin(16, 2);
pwm_line.attach_function(1, pwm_up);
pwm_line.attach_function(2, pwm_down);
menu.add_screen(welcome_screen);
menu.add_screen(screen2);
menu.add_screen(pwm_screen);
}
void loop() {
if (right.check() == LOW) {
Serial.println(F("RIGHT button pressed"));
menu.next_screen();
}
if (left.check() == LOW) {
Serial.println(F("LEFT button pressed"));
menu.previous_screen();
}
if (up.check() == LOW) {
Serial.println(F("UP button pressed"));
menu.call_function(1);
}
if (down.check() == LOW) {
Serial.println(F("DOWN button pressed"));
menu.call_function(2);
}
if (enter.check() == LOW) {
Serial.println(F("ENTER button pressed"));
menu.switch_focus();
}
static unsigned long lastMillis = 0;
static unsigned int period = 2000;
if (millis() - lastMillis > period) {
lastMillis = millis();
Serial.print("LED turned ");
if (ledState == LOW) {
ledState = HIGH;
ledState_text = (char*)"ON";
Serial.println(ledState_text);
menu.update();
} else {
ledState = LOW;
ledState_text = (char*)"OFF";
Serial.println(ledState_text);
menu.update();
}
digitalWrite(ledPin, ledState);
analogValue = analogRead(analogPin);
static unsigned short lastAnalogValue = 0;
if (analogValue != lastAnalogValue) {
lastAnalogValue = analogValue;
menu.update();
}
}
}