#include <Keypad.h>
#include <WiFi.h>
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
// WiFi credentials
#define WLAN_SSID "Wokwi-GUEST"
#define WLAN_PASS ""
// Adafruit IO credentials
#define AIO_SERVER "io.adafruit.com"
#define AIO_SERVERPORT 1883
#define AIO_USERNAME "rihadatul11"
#define AIO_KEY "aio_fxzP90F1TT8zqKgIQgmzFYdCxQbc"
// Relay pin
#define RELAY_PIN 23
WiFiClient client;
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
Adafruit_MQTT_Publish lampTimePublisher = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/syringepump.keypad");
// Keypad setup
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] = {21, 19, 18, 5};
byte colPins[COLS] = {17, 16, 15, 14};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
String inputString = "";
unsigned long lampDuration = 0;
void connectToWiFi() {
WiFi.begin(WLAN_SSID, WLAN_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
}
void connectToAdafruitIO() {
int8_t ret;
while ((ret = mqtt.connect()) != 0) {
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
}
Serial.println("Adafruit IO Connected!");
}
void setup() {
Serial.begin(115200);
pinMode(RELAY_PIN, OUTPUT);
digitalWrite(RELAY_PIN, LOW); // Ensure the lamp is off initially
connectToWiFi();
connectToAdafruitIO();
}
void loop() {
mqtt.processPackets(10000);
if (!mqtt.ping()) {
mqtt.disconnect();
connectToAdafruitIO();
}
char key = keypad.getKey();
if (key == '#') {
lampDuration = inputString.toInt();
Serial.print("Lamp duration set to: ");
Serial.print(lampDuration);
Serial.println(" seconds");
// if (!lampTimePublisher.publish((uint32_t)lampDuration)) {
// Serial.println("Failed to publish lamp duration");
// } else {
// Serial.println("Lamp duration published");
// }
inputString = "";
controlLamp(lampDuration);
} else if (key == '*') {
inputString = "";
Serial.println("Input cleared");
} else {
inputString += key;
Serial.print("Current input: ");
Serial.println(inputString);
}
delay(100);
}
void controlLamp(unsigned long duration) {
digitalWrite(RELAY_PIN, HIGH); // Turn on the lamp
delay(duration * 1000); // Keep the lamp on for the specified duration
digitalWrite(RELAY_PIN, LOW); // Turn off the lamp
Serial.println("Lamp turned off");
}