#include <WiFi.h>
#include <PubSubClient.h>
#define GREEN_BUTTON_PIN 27 // GPIO pin for the green button
#define RED_BUTTON_PIN 25 // GPIO pin for the red button
#define MOTOR_PIN 13 // GPIO pin to control the motor
#define GREEN_LED_PIN 18 // GPIO pin for the green LED
#define RED_LED_PIN 23 // GPIO pin for the red LED
#define CLOSE_DELAY 5000 // Delay in milliseconds for the gate to remain open
const char* ssid = "your_SSID"; // Your WiFi SSID
const char* password = "your_PASSWORD"; // Your WiFi Password
const char* mqtt_server = "broker_address"; // MQTT Broker address
WiFiClient espClient;
PubSubClient client(espClient);
const char* espClientName = "esp32Client_Seankck"; // yourStudentID must be unique
int PORTNUM = 1883;
void setup_wifi() {
delay(10);
Serial.begin(115200);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void callback(char* topic, byte* message, unsigned int length) {
String messageTemp;
for (int i = 0; i < length; i++) {
messageTemp += (char)message[i];
}
Serial.print("Message arrived on topic: ");
Serial.print(topic);
Serial.print(". Message: ");
Serial.println(messageTemp);
if (String(topic) == "gate/control") {
if (messageTemp == "open") {
openGate();
} else if (messageTemp == "close") {
closeGate();
}
}
}
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
if (client.connect("ESP32Client")) {
Serial.println("connected");
client.subscribe("gate/control");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
void openGate() {
digitalWrite(MOTOR_PIN, HIGH);
digitalWrite(GREEN_LED_PIN, HIGH);
digitalWrite(RED_LED_PIN, LOW);
}
void closeGate() {
static unsigned long closeStartTime = 0;
static bool gateClosing = false;
closeStartTime = millis();
gateClosing = true;
digitalWrite(GREEN_LED_PIN, LOW);
digitalWrite(RED_LED_PIN, HIGH);
while (gateClosing && millis() - closeStartTime < CLOSE_DELAY) {
// Wait for the delay
}
if (gateClosing) {
digitalWrite(MOTOR_PIN, LOW);
digitalWrite(RED_LED_PIN, LOW);
gateClosing = false;
}
}
void setup() {
pinMode(GREEN_BUTTON_PIN, INPUT_PULLUP);
pinMode(RED_BUTTON_PIN, INPUT_PULLUP);
pinMode(MOTOR_PIN, OUTPUT);
pinMode(GREEN_LED_PIN, OUTPUT);
pinMode(RED_LED_PIN, OUTPUT);
digitalWrite(MOTOR_PIN, LOW);
digitalWrite(GREEN_LED_PIN, LOW);
digitalWrite(RED_LED_PIN, LOW);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
if (digitalRead(GREEN_BUTTON_PIN) == LOW) {
openGate();
}
if (digitalRead(RED_BUTTON_PIN) == LOW) {
closeGate();
}
}