#include <Keypad.h>
#include <Servo.h>
// Keypad settings
const byte ROWS = 4; // 4 rows
const byte COLS = 4; // 4 columns
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}; // Connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 7, 8, 9}; // Connect to the column pinouts of the keypad
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
// Servo settings
Servo servo1;
Servo servo2;
Servo servo3;
void setup() {
// Attach servos to respective pins
servo1.attach(10);
servo2.attach(11);
servo3.attach(12);
// Initialize servos in closed position
servo1.write(0);
servo2.write(0);
servo3.write(0);
Serial.begin(9600);
Serial.println("Vending Machine Ready. Enter item code:");
}
void loop() {
char key = keypad.getKey(); // Read keypress
if (key) { // If a key is pressed
Serial.print("Key pressed: ");
Serial.println(key);
// Dispense item based on input
if (key == '1') {
Serial.println("Dispensing Item 1");
dispenseItem(servo1);
} else if (key == '2') {
Serial.println("Dispensing Item 2");
dispenseItem(servo2);
} else if (key == '3') {
Serial.println("Dispensing Item 3");
dispenseItem(servo3);
} else {
Serial.println("Invalid Code");
}
}
}
void dispenseItem(Servo &servo) {
servo.write(90); // Open slot
delay(6000); // Wait for item to drop
servo.write(0); // Close slot
}