#include <LiquidCrystal_I2C.h>
int columns = 16;
int rows = 2;
LiquidCrystal_I2C lcd(0x27, columns, rows);
// variable holding the button state
int buttonState;
// counter for which led to light up
int ledCounter = 1;
// variable holding previous button state
int previousButtonState = LOW;
// variable holding the LED state
int ledStateR = HIGH;
int ledStateG = LOW;
int ledStateB = LOW;
int buttonPin = 2;
const int ledPinR = 12;
const int ledPinG = 11;
const int ledPinB = 10;
// millis always stored in long
// becomes too big for int after 32,767 millis or around 32 seconds
// timestamp of a previous bounce
long previousDebounceTime = 0;
// debounce time in millis, if the LED is still quirky increase this value
long debounceDelay = 50;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPinR, OUTPUT);
pinMode(ledPinG, OUTPUT);
pinMode(ledPinB, OUTPUT);
lcd.begin(16,2);
lcd.init();
lcd.backlight();
}
bool buttonUp() {
// for now it's the same as in previous example
int reading = digitalRead(buttonPin);
// if the previous reading is different than the previous button state
if (reading != previousButtonState) {
// we'lll reset the debounce timer
previousDebounceTime = millis();
}
// if the reading is the same over a period of debounceDelay
if ((millis() - previousDebounceTime) > debounceDelay) {
// check if the button state is changed
if (reading != buttonState) {
buttonState = reading;
// toggle the LED state only when the button is released
if (buttonState == LOW) {
return true;
}
}
}
// save current reading so that we can compare in the next loop
previousButtonState = reading;
return false;
}
void loop() {
if (buttonUp()) {
ledCounter++;
}
// new code starts here
if (ledCounter > 3) {
ledCounter = 1;
}
if (ledCounter == 1) {
ledStateR = 1;
ledStateG = 0;
ledStateB = 0;
} else if (ledCounter == 2) {
ledStateR = 0;
ledStateG = 1;
ledStateB = 0;
} else if (ledCounter == 3) {
ledStateR = 0;
ledStateG = 0;
ledStateB = 1;
}
// set the LED:
digitalWrite(ledPinR, ledStateR);
digitalWrite(ledPinG, ledStateG);
digitalWrite(ledPinB, ledStateB);
lcd.setCursor(0,0);
if (ledCounter == 1) {
lcd.print("Current Led:");
lcd.setCursor(0,1);
lcd.print("Red ");
} else if (ledCounter == 2) {
lcd.print("Current Led:");
lcd.setCursor(0,1);
lcd.print("Green");
} else if (ledCounter == 3) {
lcd.print("Current Led:");
lcd.setCursor(0,1);
lcd.print("Blue ");
}
}