Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*********
- Rui Santos
- Complete project details at http://randomnerdtutorials.com
- *********/
- // Including the ESP8266 WiFi library
- #include <ESP8266WiFi.h>
- #include "DHT.h"
- #include <PubSubClient.h>
- // Uncomment one of the lines below for whatever DHT sensor type you're using!
- //#define DHTTYPE DHT11 // DHT 11
- //#define DHTTYPE DHT21 // DHT 21 (AM2301)
- #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
- #define mqtt_server "192.168.1.64"
- #define mqtt_user "homeassistant"
- #define mqtt_password "welcome"
- #define humidity_topic "sensor/humidity_bedroom"
- #define temperature_topic "sensor/temperature_bedroom"
- // Replace with your network details
- const char* ssid = "thessid";
- const char* password = "thepassword";
- const int sensor_pin = A0;
- // Web Server on port 80
- WiFiServer server(80);
- WiFiClient espClient;
- PubSubClient client(espClient);
- // DHT Sensor
- const int DHTPin = 5;
- const int MoistPin = 4;
- const int ledPin = 13;
- // Initialize DHT sensor.
- DHT dht(DHTPin, DHTTYPE);
- bool isconnected=false;
- // Temporary variables
- static char celsiusTemp[7];
- static char fahrenheitTemp[7];
- static char humidityTemp[7];
- float moisture_reading;
- float moisture_percentage;
- // only runs once on boot
- void setup() {
- Serial.setDebugOutput(true);
- // Initializing serial port for debugging purposes
- Serial.begin(115200);
- delay(10);
- dht.begin();
- // Connecting to WiFi network
- Serial.println();
- //Wifi.disconnect();
- // WiFi.disconnect(true);
- // hotspot scan
- //Serial.printf("Wi-Fi mode set to WIFI_STA %s\n", WiFi.mode(WIFI_STA) ? "" : "Failed!");
- //scan_hotspot() ;
- delay(1);
- WiFi.begin(ssid, password);
- Serial.print("Attempting to connect to WIFI network, SSID: ");
- Serial.println(ssid);
- Serial.println("");
- Serial.print("Password: ");
- Serial.println(password);
- if (WiFi.status() == WL_NO_SHIELD) {
- Serial.println("WiFi shield not present");
- // don't continue:
- while (true);
- }
- pinMode(ledPin, OUTPUT);
- pinMode(MoistPin, OUTPUT);
- while (WiFi.status() != WL_CONNECTED) {
- //while (WiFi.waitForConnectResult() != WL_CONNECTED) {
- //while (WiFi.localIP().toString() == "0.0.0.0") {
- //delay(250);
- // digitalWrite(ledPin, HIGH);
- // delay(250);
- // digitalWrite(ledPin, LOW);
- Serial.print(WiFi.localIP().toString());
- Serial.println(".");
- Serial.println(WiFi.status());
- delay(500);
- }
- Serial.println("");
- Serial.println("WiFi connected");
- // Starting the web server
- server.begin();
- Serial.println("Web server running. Waiting for the ESP IP...");
- delay(10000);
- // Printing the ESP IP address
- Serial.println(WiFi.localIP());
- Serial.println("Setting MQ server.");
- client.setServer(mqtt_server, 1883);
- }
- void reconnect() {
- // Loop until we're reconnected
- while (!client.connected()) {
- Serial.print("Attempting MQTT connection...");
- // Attempt to connect
- // If you do not want to use a username and password, change next line to
- // if (client.connect("ESP8266Client")) {
- if (client.connect("ESP8266Client_bedroom", mqtt_user, mqtt_password)) {
- Serial.println("connected");
- isconnected=true;
- } else {
- Serial.print("failed, rc=");
- isconnected=false;
- Serial.print(client.state());
- Serial.println(" try again in 15 seconds");
- // Wait 5 seconds before retrying
- delay(15000);
- }
- }
- }
- bool checkBound(float newValue, float prevValue, float maxDiff) {
- return !isnan(newValue) &&
- (newValue < prevValue - maxDiff || newValue > prevValue + maxDiff);
- }
- long lastMsg = 0;
- float temp = 0.0;
- float hum = 0.0;
- float moist = 0.0;
- float diff = 0.01;
- void loop() {
- // Listenning for new clients
- WiFiClient clientweb = server.available();
- if (clientweb) {
- Serial.println("New client");
- // bolean to locate when the http request ends
- boolean blank_line = true;
- while (clientweb.connected()) {
- if (clientweb.available()) {
- char c = clientweb.read();
- if (c == '\n' && blank_line) {
- // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
- // Read temperature as Celsius (the default)
- float t = dht.readTemperature();
- // Read temperature as Fahrenheit (isFahrenheit = true)
- float f = dht.readTemperature(true);
- // Check if any reads failed and exit early (to try again).
- float h = dht.readHumidity();
- if (isnan(h) || isnan(t) || isnan(f)) {
- Serial.println("Failed to read from DHT sensor!");
- strcpy(celsiusTemp,"Failed");
- strcpy(fahrenheitTemp, "Failed");
- strcpy(humidityTemp, "Failed");
- }
- else{
- // Computes temperature values in Celsius + Fahrenheit and Humidity
- float hic = dht.computeHeatIndex(t, h, false);
- dtostrf(hic, 6, 2, celsiusTemp);
- float hif = dht.computeHeatIndex(f, h);
- dtostrf(hif, 6, 2, fahrenheitTemp);
- dtostrf(h, 6, 2, humidityTemp);
- // You can delete the following Serial.print's, it's just for debugging purposes
- Serial.print("Humidity: ");
- Serial.print(h);
- Serial.print(" %\t Temperature: ");
- Serial.print(t);
- Serial.print(" *C ");
- Serial.print(f);
- Serial.print(" *F\t Heat index: ");
- Serial.print(hic);
- Serial.print(" *C ");
- Serial.print(hif);
- Serial.print(" *F");
- Serial.print("Humidity: ");
- Serial.print(h);
- Serial.print(" %\t Temperature: ");
- Serial.print(t);
- Serial.print(" *C ");
- Serial.print(f);
- Serial.print(" *F\t Heat index: ");
- Serial.print(hic);
- Serial.print(" *C ");
- Serial.print(hif);
- Serial.println(" *F");
- }
- clientweb.println("HTTP/1.1 200 OK");
- clientweb.println("Content-Type: text/html");
- clientweb.println("Connection: close");
- clientweb.println();
- // your actual web page that displays temperature and humidity
- clientweb.println("<!DOCTYPE HTML>");
- clientweb.println("<html>");
- clientweb.println("<head></head><body><h3>");
- clientweb.println(celsiusTemp);
- //client.println("*C</h3><h3>Temperature in Fahrenheit: ");
- //client.println(fahrenheitTemp);
- clientweb.println("*C</h3><h3>Humidity: ");
- clientweb.println(humidityTemp);
- clientweb.println("%</h3>");
- clientweb.println("</body></html>");
- break;
- }
- if (c == '\n') {
- // when starts reading a new line
- blank_line = true;
- }
- else if (c != '\r') {
- // when finds a character on the current line
- blank_line = false;
- }
- }
- }
- // closing the client connection
- delay(1);
- clientweb.stop();
- Serial.println("Client disconnected.");
- }
- if (!client.connected()) {
- reconnect();
- }
- client.loop();
- long now = millis();
- if (now - lastMsg > 30000) {
- lastMsg = now;
- float newTemp = dht.readTemperature();
- float newHum = dht.readHumidity();
- temp = newTemp;
- Serial.print("New temperature:");
- Serial.println(String(temp).c_str());
- client.publish(temperature_topic, String(temp).c_str(), true);
- hum = newHum;
- Serial.print("New hum:");
- Serial.println(String(hum).c_str());
- client.publish(humidity_topic, String(hum).c_str(), true);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment