/* Lab Trial Test
* Name: Xu Dong
* Class: DEEC1
* Date:16-Jan-2025
*/
#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
#define ADC_IN 33
#define ADC_REF 3.3
int GLED=18;
long previousMillis = 0; // will store last time LED
int interval = 2000;// interval at which to blink (milliseconds)
int state = LOW;
long previousMillisADC = 0; // will store last time LED
int intervalADC = 1000;// interval at which to blink (milliseconds)
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* hostname = "broker.hivemq.com";
//const char* hostname = "broker.emqx.io";
//const char* hostname = "test.mosquitto.org";
WiFiClient espClient;
PubSubClient client(espClient);
const char* espClientName = "S10251651"; // 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(2000);
}
}
}
void callback(String topic, byte* Payload, unsigned int length)
{
String payload;
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] );
payload += (char)Payload[i];
}
/// Handle your topics and payload here
// Example
if (topic == "Trial2/S10251651")
{
if (payload == " ")
{
}
else if (payload == " ")
{
}
}
}
void MQTTSubscribe()
{
client.subscribe(" ");
}
void setup_MQTT()
{
client.setServer(hostname, PORTNUM);
client.setCallback(callback);
}
void setup()
{
Serial.begin(9600);
delay(5000);
pinMode( GLED , OUTPUT);
setup_wifi();
setup_MQTT();
}
void loop()
{
if ( !client.connected() )
{
connectMQTT();
}
client.loop();
long currentMillis = millis();
if ( currentMillis - previousMillis >= interval)
{
previousMillis = currentMillis;
if ( state == LOW)
{
state = HIGH;
digitalWrite( GLED , LOW);
}
else
{
state = LOW;
digitalWrite( GLED , HIGH);
}
}
long currentMillisADC = millis();
if ( currentMillisADC - previousMillisADC >= intervalADC)
{
previousMillisADC = currentMillisADC;
int adcRes = analogRead(ADC_IN);
delay(10);
Serial.println(adcRes);
float voltage= (float)adcRes*ADC_REF/4095;
Serial.println(voltage);
char snum[5];
itoa(adcRes, snum, 10);
client.publish("Trial2/S10251651",snum);
}
}