#include <LiquidCrystal.h>
#include <Keypad.h>
#include <RotaryEncoder.h>
// Initialize the LCD with the specified pins
LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
// Keypad configuration
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
{'1', '2', '3', 'A'},
{'4', '5', '6', 'B'},
{'7', '8', '9', 'C'},
{'*', '0', '#', 'D'}
};
byte rowPins[ROWS] = {2, 3, 4, 5};
byte colPins[COLS] = {6, A0, A1, A2};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Rotary encoder configuration
#define ENCODER_CLK A3
#define ENCODER_DT A4
#define ENCODER_SW A5
RotaryEncoder encoder(ENCODER_CLK, ENCODER_DT);
// Variables for dispensing
int mlToDispense = 0;
bool dispensing = false;
unsigned long dispensingStartTime = 0;
void setup() {
Serial.begin(9600); // Initialize serial communication for debugging
lcd.begin(16, 2);
displayWelcomeMessage();
displayEnterQuantity();
}
void loop() {
char key = keypad.getKey();
if (!dispensing && key) {
if (key >= '0' && key <= '9') {
mlToDispense = mlToDispense * 10 + (key - '0');
lcd.print(key);
} else if (key == '#') {
startDispensing();
} else if (key == '*') {
mlToDispense = 0;
displayEnterQuantity();
}
}
if (dispensing) {
if (millis() - dispensingStartTime >= 4000) { // Dispense for 4 seconds
stopDispensing();
}
}
}
void displayWelcomeMessage() {
lcd.clear();
lcd.print("Welcome to");
lcd.setCursor(0, 1);
lcd.print("Milk Dispenser!");
delay(2000); // Display message for 2 seconds
}
void displayEnterQuantity() {
lcd.clear();
lcd.print("Enter quantity");
lcd.setCursor(0, 1);
lcd.print("of milk: ");
}
void startDispensing() {
Serial.println("Dispensing started"); // Debug statement
lcd.clear();
lcd.print("Dispensing ");
lcd.print(mlToDispense);
lcd.print(" ml");
dispensingStartTime = millis();
dispensing = true;
// Here you would turn on the pump or valve
attachInterrupt(digitalPinToInterrupt(ENCODER_CLK), readEncoder, CHANGE);
attachInterrupt(digitalPinToInterrupt(ENCODER_DT), readEncoder, CHANGE);
Serial.println("Interrupts attached"); // Debug statement
}
void stopDispensing() {
// Here you would turn off the pump or valve
lcd.clear();
lcd.print(mlToDispense);
lcd.print(" ml dispensed");
lcd.setCursor(0, 1);
lcd.print("Thank you!");
Serial.println("Dispensing stopped"); // Debug statement
dispensing = false;
mlToDispense = 0;
delay(10000); // Display message for 10 seconds
detachInterrupt(digitalPinToInterrupt(ENCODER_CLK));
detachInterrupt(digitalPinToInterrupt(ENCODER_DT));
Serial.println("Interrupts detached"); // Debug statement
displayEnterQuantity();
}
void readEncoder() {
encoder.tick();
}