1 |
|
2 |
|
3 | #include <Wire.h>
|
4 | #include <Adafruit_SHT31.h>
|
5 | #include <ESP8266WiFi.h>
|
6 | #include <PubSubClient.h>
|
7 | #include <SPI.h>
|
8 |
|
9 | // Replace with your WiFi credentials
|
10 | const char* ssid = "Test123";
|
11 | const char* password = "Test123";
|
12 |
|
13 | // Replace with your MQTT broker details
|
14 | const char* mqtt_server = "Test123";
|
15 | const int mqtt_port = 1883;
|
16 | const char* mqtt_topic = "sensor_data";
|
17 |
|
18 | // Create an instance of the SHT85 sensor
|
19 | Adafruit_SHT31 sht;
|
20 |
|
21 | // Create an instance of the WiFi client
|
22 | WiFiClient espClient;
|
23 |
|
24 | // Create an instance of the MQTT client
|
25 | PubSubClient client(espClient);
|
26 |
|
27 | void setup() {
|
28 | // Start the serial communication
|
29 | Serial.begin(9600);
|
30 |
|
31 | // Connect to Wi-Fi
|
32 | WiFi.begin(ssid, password);
|
33 | while (WiFi.status() != WL_CONNECTED) {
|
34 | delay(1000);
|
35 | Serial.println("Connecting to WiFi...");
|
36 | }
|
37 | Serial.println("Connected to WiFi");
|
38 |
|
39 | // Connect to MQTT broker
|
40 | client.setServer(mqtt_server, mqtt_port);
|
41 |
|
42 | // Initialize the SHT85 sensor
|
43 | if (!sht.begin(0x44)) {
|
44 | Serial.println("SHT85 not found. Check wiring!");
|
45 | while (1);
|
46 | }
|
47 | }
|
48 |
|
49 | void loop() {
|
50 | // Read sensor data
|
51 | float temperature = sht.readTemperature();
|
52 | float humidity = sht.readHumidity();
|
53 |
|
54 | // Print sensor data to Serial Monitor
|
55 | Serial.print("Temperature: ");
|
56 | Serial.print(temperature);
|
57 | Serial.print(" °C, Humidity: ");
|
58 | Serial.print(humidity);
|
59 | Serial.println(" %");
|
60 |
|
61 | // Publish sensor data to MQTT
|
62 | if (client.connect("ESP8266Client")) {
|
63 | char tempStr[10];
|
64 | char humStr[10];
|
65 | dtostrf(temperature, 4, 2, tempStr);
|
66 | dtostrf(humidity, 4, 2, humStr);
|
67 |
|
68 | client.publish(mqtt_topic, tempStr);
|
69 | //client.publish(mqtt_topic, humStr);
|
70 |
|
71 | client.disconnect();
|
72 | }
|
73 |
|
74 | // Wait for a while before reading the sensor again
|
75 | delay(5000);
|
76 | }
|