#include <LiquidCrystal_I2C.h>
// constants won't change. They're used here to set pin numbers, etc.
const int buttonPin = 2;
const int ledPin = 15;
const int freq = 500; // in Hz
const int ledChannel = 0; // [0-15]
const int resolution = 8; // in bits
// variables will change:
bool currButtonStatus = false;
bool prevButtonStatus = false;
int lcdColumns = 16;
int lcdRows = 2;
int pwmVal = 0;
int count = 0;
// define the LCD
LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows);
// to refresh the display with the current pwmVal
void displayLcd() {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Medium");
lcd.setCursor(0, 1);
lcd.print("@syafiqza");
lcd.setCursor(13, 0);
lcd.print("PWM");
lcd.setCursor(13, 1);
lcd.print(pwmVal);
}
void setup() {
// initialize the button pin as an input:
pinMode(buttonPin, INPUT);
// initialize the LED pin:
ledcSetup(ledChannel, freq, resolution);
ledcAttachPin(ledPin, ledChannel);
// initialize LCD and turn on the backlight
lcd.init();
lcd.backlight();
// first display the LCD
displayLcd();
}
void loop() {
currButtonStatus = digitalRead(buttonPin);
if (currButtonStatus == HIGH) {
if (prevButtonStatus == false) {
// increment count when button pressed and set previous button state to on
count++;
prevButtonStatus = !prevButtonStatus;
}
// set the LED PWM and refresh the LCD as the pwmVal varies by [0, 127, 255]
pwmVal = (int)(floor(256 * (count % 3) / 2) - ((count % 3) > 0));
ledcWrite(ledChannel, pwmVal);
displayLcd();
} else {
// turn off all LED and set 'previous' button state to off
prevButtonStatus = false;
}
count %= 10;
}