/*
* Lab Trial Test 2
* Name: Nas
* Room: 06-03-0004
* Date: 18/7/2025
* Requirements:
* 1. Blink the red LED every 2 seconds.
* 2. When the MQTT topic /<your_student_id>/y_led receives an "on" payload, turn on yellow LED.
* 3. When the same topic receives an "off" payload, turn off the yellow LED.
* 4. Every 2 seconds, publish potentiometer's raw value to MQTT topic <your_student_id>/pot/raw
*/
#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
unsigned long previousMillis = 0;
int interval = 2000;
int state = LOW;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* hostname = "broker.hivemq.com";
const int portnum = 1883;
WiFiClient espClient;
PubSubClient client(espClient);
const char* espClientName = "<a_Uniqud_ID>";
void setup_wifi() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println();
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("Given IP by the router to ESP32 is ");
Serial.println(WiFi.localIP());
}
void connectMQTT() {
while(!client.connected()) {
Serial.println("Connecting to MQTT ...");
if (client.connect(espClientName)) {
Serial.println("Connected");
MQTTSubscribe();
}
else {
Serial.print("Failed with state ");
Serial.print(client.state() );
delay(2000);
}
}
}
void callback(const char *topic, byte *payload, unsigned int length) {
String message;
Serial.print("Message received in topic: ");
Serial.print(topic);
Serial.print(" length is: ");
Serial.println(length);
Serial.print("Data received from broker: ");
for (int i=0; i<length; i++) {
Serial.print((char)payload[i]);
message += (char)payload[i];
}
Serial.println();
if (String(topic) == "_____") { // TODO 1
if (message == "____") { // TODO 2a
____________; // TODO 2b
}
else if (message == "____") { // TODO 3a
____________; // TODO 3b
}
}
}
void MQTTSubscribe() {
client.subscribe("__________________"); // TODO 4
}
void setup_MQTT() {
client.setServer(hostname, portnum);
client.setCallback(callback);
}
void setup() {
Serial.begin(115200);
pinMode(___, OUTPUT); // TODO 5a
pinMode(___, OUTPUT); // TODO 5b
pinMode(___, INPUT); // TODO 6
setup_wifi();
setup_MQTT();
}
void loop() {
if (!client.connected()) {
connectMQTT();
}
client.loop();
unsigned long currentMillis = millis();
if (currentMillis-previousMillis >= interval) {
previousMillis = currentMillis;
if (state == LOW) {
state = ____; // TODO 7a
digitalWrite(____, ____); // TODO 7b
}
else {
state = ____; // TODO 8a
digitalWrite(____, ____); // TODO 8b
}
int val = analogRead(___); // TODO 9
char str[6];
sprintf(str, "%d", val);
client.publish("____________", str); // TODO 10
}
}