/*Lab Test Jul 2024
*Name: Heng Chen Gui
*Class:DEEC1
*Date:19 JuLY 2024
*/
char led_green = 18;
char led_green_state = LOW;
long led_green_previous_millis = 0;
int led_green_interval = 750;
int adc_interval = 1500;
long adc_previous_millis = 0;
#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* hostname = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
const char* espClientName = "esp32Client_2709909U"; // yourStudentID must be unique
int PORTNUM = 1883;
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) ) //, mqttUser, mqttPassword) )
{
Serial.println("Connected");
MQTTSubscribe();
}
else
{
Serial.print("Failed with state ");
Serial.print(client.state() );
delay(1000);
}
}
}
void MQTTSubscribe()
{
}
void setup_MQTT()
{
client.setServer(hostname, PORTNUM);
}
void setup() {
// put your setup code here, to run once:
{
pinMode(led_green, OUTPUT);
Serial.begin(115200);
setup_wifi();
setup_MQTT();
}
}
void loop() {
// put your main code here, to run repeatedly:
if ( !client.connected() )
{
connectMQTT();
}
client.loop();
long current_millis = millis();
if ( current_millis - led_green_previous_millis >= led_green_interval)
{
led_green_previous_millis = current_millis;
//now reverse the led's state
if (led_green_state == LOW)
led_green_state = HIGH;
else
led_green_state = LOW;
digitalWrite (led_green, led_green_state);
}
//adc
if ( current_millis - adc_previous_millis >= adc_interval)
{
adc_previous_millis = current_millis;
//read ADC value
int adc_value;
adc_value = analogRead(A5);
Serial.print("ADC"); Serial.println(adc_value);
delay(5000);
char str[4];
sprintf(str, "%d", adc_value);
//have your own topic and publish str into topic
client.publish ("IOT/ROOM3/2709909U", str);
if (adc_value < 2500)
client.publish ("IOT/ROOM3/2709909U", "Alert");
else if (adc_value >=2500)
client.publish ("IOT/ROOM3/2709909U", "OK");
}
}