#include <Keypad.h>
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
const uint8_t ROWS = 4;
const uint8_t COLS = 4;
char keys[ROWS][COLS] = {
{ '1', '2', '3', 'A' },
{ '4', '5', '6', 'B' },
{ '7', '8', '9', 'C' },
{ '*', '0', '#', 'D' }
};
uint8_t colPins[COLS] = { 5, 4, 3, 2 };
uint8_t rowPins[ROWS] = { 9, 8, 7, 6 };
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
int percentageValue = 0;
int cursorPos = 0;
void setup() {
Serial.begin(9600);
lcd.init();
lcd.backlight();
lcd.clear();
lcd.print("Enter % value:");
lcd.setCursor(0, 1); // Move to the second row for input
}
void loop() {
char key = keypad.getKey();
if (key != NO_KEY) {
if (key >= '0' && key <= '9') { // Check if the key is a number
if (cursorPos < 3) { // Limit input to 3 digits
lcd.write(key); // Display key on LCD
percentageValue = percentageValue * 10 + (key - '0'); // Convert char to int and build number
cursorPos++;
}
}
else if (key == '#') { // '#' is used as 'Enter' to submit the value
// Constrain to 0-100% range
percentageValue = constrain(percentageValue, 0, 100);
// Map percentage to analog range 0-255
int analogValue = map(percentageValue, 0, 100, 0, 255);
analogWrite(A0, analogValue); // Write analog value to A0
lcd.clear();
lcd.print("Percent: ");
lcd.print(percentageValue);
lcd.print("%");
lcd.setCursor(0, 1);
lcd.print("Analog: ");
lcd.print(analogValue);
delay(2000); // Display the result for 2 seconds
// Reset for next input
lcd.clear();
lcd.print("Enter % value:");
lcd.setCursor(0, 1);
percentageValue = 0;
cursorPos = 0;
}
else if (key == '*') { // '*' is used as 'Clear' to reset the input
lcd.clear();
lcd.print("Enter % value:");
lcd.setCursor(0, 1);
percentageValue = 0;
cursorPos = 0;
}
}
}