#include <WiFi.h>
#include <PubSubClient.h>
#include <DHT.h>
const char* ssid = "Wokwi-GUEST"; // WiFi SSID
const char* password = "";
// Azure IoT Hub connection string
const char* connectionString = "HostName=HealthcareBot.azure-devices.net;DeviceId=ESP32;SharedAccessKey=o5L9hqkOrTu3XDgUUGLkdc0WD0OrYqu3LAIoTFxRmsE="; // connection string
// Sensor pin definitions
#define DHTPIN 15 // Pin where the DHT22 is connected
#define PIRPIN 13 // Pin where the PIR sensor is connected
#define LDRPIN 14 // Digital pin where the LDR is connected
#define LEDPIN 25 // Pin where the LED is connected
#define TEMPPIN 32 // Analog pin where the LM35/TMP36 is connected
// DHT Sensor
#define DHTTYPE DHT22 // DHT22 (AM2302)
DHT dht(DHTPIN, DHTTYPE);
// Wi-Fi client and MQTT client
WiFiClient espClient;
PubSubClient client(espClient);
// State variables
bool sendingMessage = true; // Start sending messages by default
int messageId = 0;
unsigned long lastMsgTime = 0;
// Function to parse the connection string
void parseConnectionString(const char* connStr, char* hostName, char* deviceId, char* deviceKey) {
char* token;
char* rest = const_cast<char*>(connStr);
while ((token = strtok_r(rest, ";", &rest))) {
if (strncmp(token, "HostName=", 9) == 0) {
strcpy(hostName, token + 9);
} else if (strncmp(token, "DeviceId=", 9) == 0) {
strcpy(deviceId, token + 9);
} else if (strncmp(token, "SharedAccessKey=", 16) == 0) {
strcpy(deviceKey, token + 16);
}
}
}
// Function to blink the LED
void blinkLED() {
digitalWrite(LEDPIN, HIGH); // Turn LED on
delay(500); // Wait 500 ms
digitalWrite(LEDPIN, LOW); // Turn LED off
}
// Callback when a message is received
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
// Print message content
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
blinkLED();
}
// Reconnect to MQTT broker
void reconnect() {
// Parse the connection string
char hostName[100], deviceId[100], deviceKey[100];
parseConnectionString(connectionString, hostName, deviceId, deviceKey);
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Client ID for MQTT connection
String clientId = String("ESP8266Client-") + String(deviceId);
if (client.connect(clientId.c_str(), deviceId, deviceKey)) {
Serial.println("connected");
client.subscribe("devices/healthcarebot/messages/devicebound/#"); // Subscribe to device-specific messages
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
delay(5000);
}
}
}
// Setup function
void setup() {
// Start the serial communication
Serial.begin(115200);
// Initialize the DHT sensor
dht.begin();
// Initialize pins
pinMode(LEDPIN, OUTPUT);
pinMode(PIRPIN, INPUT);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Parse the connection string
char hostName[100];
parseConnectionString(connectionString, hostName, nullptr, nullptr);
// Set the MQTT server and callback function
client.setServer(hostName, 1883);
client.setCallback(callback);
}
// Function to get and send the sensor data
void sendMessage() {
if (!sendingMessage) return;
messageId++;
float humidity = dht.readHumidity();
float dhtTemperature = dht.readTemperature();
int ldrValue = analogRead(LDRPIN);
bool motionDetected = digitalRead(PIRPIN);
// Read the temperature from LM35/TMP36
int tempValue = analogRead(TEMPPIN);
// Convert the analog reading (which ranges from 0 - 4095) to a voltage (0 - 3.3V for ESP32)
float voltage = tempValue * (3.3 / 4095.0);
// Convert the voltage to temperature (assuming 10mV per degree Celsius for TMP36)
float lm35Temperature = (voltage - 0.5) * 100.0; // For TMP36
// float lm35Temperature = voltage * 100.0; // For LM35, uncomment if using LM35 sensor
if (isnan(humidity) || isnan(dhtTemperature)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
// Create JSON payload
String payload = "{";
payload += "\"messageId\":"; payload += messageId; payload += ",";
payload += "\"deviceId\":\"ESP8266 Client\",";
payload += "\"dhtTemperature\":"; payload += dhtTemperature; payload += ",";
payload += "\"lm35Temperature\":"; payload += lm35Temperature; payload += ",";
payload += "\"humidity\":"; payload += humidity; payload += ",";
payload += "\"lightLevel\":"; payload += ldrValue; payload += ",";
payload += "\"motionDetected\":"; payload += motionDetected;
payload += "}";
// Publish to the IoT Hub
Serial.print("Sending message: ");
Serial.println(payload);
if (client.publish("devices/your-device-id/messages/events/", payload.c_str())) {
Serial.println("Message sent to Azure IoT Hub");
blinkLED();
} else {
Serial.println("Failed to send message to Azure IoT Hub");
}
}
// Main loop function
void loop() {
// Reconnect if disconnected
if (!client.connected()) {
reconnect();
}
client.loop();
// Send a message every 2 seconds
unsigned long now = millis();
if (now - lastMsgTime > 2000) {
lastMsgTime = now;
sendMessage();
}
}