//https://docs.arduino.cc/built-in-examples/digital/Debounce/
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define I2C_ADDR 0x27
#define LCD_COLUMNS 16
#define LCD_LINES 2
LiquidCrystal_I2C lcd(I2C_ADDR, LCD_COLUMNS, LCD_LINES);
int led=4;
int b = 2;
int val=0,led_num=0;
int ledstate=LOW; //initial value ledState
int buttonState; // the current reading from the input pin
int lastButtonState = LOW;
unsigned long lastDebounceTime = 0; // the last time the output pin was toggled
unsigned long debounceDelay = 70;
void setup()
{
pinMode(led,OUTPUT);
pinMode(b, INPUT);
lcd.begin(16,2);
lcd.backlight();
}
void loop(){
//read the value of the button when pressed
int reading = digitalRead(b);
// check to see if you just pressed the button
// (i.e. the input went from LOW to HIGH), and you've waited long enough
// since the last press to ignore any noise:
// If the switch changed, due to noise or pressing:
if (reading != lastButtonState) {
// reset the debouncing timer
lastDebounceTime = millis();
}
if ((millis() - lastDebounceTime) > debounceDelay) {
// whatever the reading is at, it's been there for longer than the debounce
// delay, so take it as the actual current state:
// if the button state has changed:
if (reading != buttonState) {
buttonState = reading;
// only toggle the LED if the new button state is HIGH
if (buttonState == HIGH) {
ledstate = !ledstate;
if(buttonState){ //button is pressed
led_num=led_num+1; //add 1 to the led_num variable
}
if (led_num==1){
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" Mode 1 ");
}
else if (led_num==2){
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" Mode 2 ");
}
else if (led_num==3){
lcd.clear();
lcd.setCursor(0,0);
lcd.print(" Mode 3 ");
//reset the led_num variable to 0
led_num=0; }
}
}
}
// set the LED:
digitalWrite(led, ledstate);
lastButtonState = reading;
// save the reading. Next time through the loop, it'll be the lastButtonState:
}
/*
void loop(){
//read the value of the button when pressed
val=digitalRead(b);
//in this example, the value of the button when pressed is 1
if(val==1){
//reverse the current state of the ledstate variable
ledstate=!ledstate;
//the ledstate variable controls the HIGH or LOW state
digitalWrite(led,ledstate);
if (ledstate==HIGH){
lcd.clear(); //erase all text on the lcd
lcd.setCursor(0,0);
lcd.print("LED is ON");}
else{
lcd.clear();
lcd.setCursor(0,0);
lcd.print("LED is OFF");
}
//wait .5 second before the next reading
delay(500);
}
}*/