/*
Lab Trial Test 2
Name: Yoong Hor Meng
Class: MINDEF
Date: 17-Jan-2025
*/
#include <WiFi.h>
#include <PubSubClient.h> /* Remember to add the PubSubClient lirary */
/* Red LED */
int RedLED = 22;
int RedLED_state = 0; // LOW
long RedLED_prev_ms = 0;
/* Potential meter */
int Pot = 33; // ADC2 is used by WiFi
long Pot_prev_ms = 0;
/* Green LED */
int GrnLED = 23;
long GrnLED_prev_ms = 0;
/* Topic */
char *topic_pot = "DEIOT/room/yhm_12345678";
/* MQTT */
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
/* Callback function for MQTT messages */
void mqttCB(char *topic, byte *message, unsigned int length) {
/* Compare the received topic to our subscribed topic */
if (strcmp(topic, topic_pot) == 0) {
/* Convert incoming message bytes to a String */
String msg = String((char*)message).substring(0, length);
/* Convert the message to an integer */
int value = msg.toInt();
/* Debugging */
Serial.print("Received message: ");
Serial.println(value);
/* Turn green LED on if value < 1000 */
if (value < 1000) {
digitalWrite(GrnLED, 1);
} else {
digitalWrite(GrnLED, 0);
}
}
}
/* This function run once */
void setup() {
Serial.begin(115200);
pinMode(RedLED, OUTPUT); // Red LED
pinMode(Pot, INPUT); // Potential meter
pinMode(GrnLED, OUTPUT); // Green LED
/* Wifi */
WiFi.mode(WIFI_STA); // Set ESP32 to station mode
WiFi.begin("Wokwi-GUEST", ""); // SSID, password
Serial.print("Connecting to WiFi ...");
// Keep on trying to connect ...
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
/* ... WiFi is connected */
Serial.println("connected.");
/* MQTT */
mqttClient.setServer("broker.hivemq.com", 1883); // Hostname, port number
mqttClient.setKeepAlive(60); // Keep-alive interval in seconds
mqttClient.setSocketTimeout(60); // Socket timeout in seconds
mqttClient.setCallback(mqttCB);
mqttClient.connect("yhm_1234xx"); // Make sure you give it an unique ID
Serial.print("Connecting to MQTT ...");
// Try to connect to MQTT server ...
while (!mqttClient.connected()) {
Serial.print("+");
delay(500);
}
/* ... MQTT is connected */
Serial.println("connected.");
/* Subscribe to topic(s) */
mqttClient.subscribe(topic_pot);
}
/* This function run continously */
void loop() {
long curr_ms = millis();
/* Red LED blinks every second*/
if (curr_ms - RedLED_prev_ms >= 1000) {
RedLED_prev_ms = curr_ms;
RedLED_state = !RedLED_state;
digitalWrite(RedLED, RedLED_state);
}
/* Read potential meter every 2 seconds */
if (curr_ms - Pot_prev_ms >= 2000) {
Pot_prev_ms = curr_ms;
int value = analogRead(Pot);
Serial.print("Analog input: ");
Serial.println(value);
/* Convert int to String */
String potStr = String(value);
mqttClient.publish(topic_pot, potStr.c_str());
}
mqttClient.loop(); // Handle incoming and outgoing MQTT messages
}