Guest User

ESP8266 Web + mq

a guest
Aug 27th, 2020
254
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.05 KB | None | 0 0
  1. /*********
  2. Rui Santos
  3. Complete project details at http://randomnerdtutorials.com
  4. *********/
  5.  
  6. // Including the ESP8266 WiFi library
  7. #include <ESP8266WiFi.h>
  8. #include "DHT.h"
  9. #include <PubSubClient.h>
  10. // Uncomment one of the lines below for whatever DHT sensor type you're using!
  11. //#define DHTTYPE DHT11 // DHT 11
  12. //#define DHTTYPE DHT21 // DHT 21 (AM2301)
  13. #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
  14. #define mqtt_server "192.168.1.64"
  15. #define mqtt_user "homeassistant"
  16. #define mqtt_password "welcome"
  17.  
  18. #define humidity_topic "sensor/humidity_bedroom"
  19. #define temperature_topic "sensor/temperature_bedroom"
  20.  
  21.  
  22. // Replace with your network details
  23. const char* ssid = "thessid";
  24. const char* password = "thepassword";
  25. const int sensor_pin = A0;
  26. // Web Server on port 80
  27. WiFiServer server(80);
  28. WiFiClient espClient;
  29. PubSubClient client(espClient);
  30. // DHT Sensor
  31. const int DHTPin = 5;
  32. const int MoistPin = 4;
  33. const int ledPin = 13;
  34. // Initialize DHT sensor.
  35. DHT dht(DHTPin, DHTTYPE);
  36. bool isconnected=false;
  37. // Temporary variables
  38. static char celsiusTemp[7];
  39. static char fahrenheitTemp[7];
  40. static char humidityTemp[7];
  41. float moisture_reading;
  42. float moisture_percentage;
  43. // only runs once on boot
  44.  
  45.  
  46.  
  47. void setup() {
  48. Serial.setDebugOutput(true);
  49. // Initializing serial port for debugging purposes
  50. Serial.begin(115200);
  51. delay(10);
  52.  
  53. dht.begin();
  54.  
  55. // Connecting to WiFi network
  56. Serial.println();
  57. //Wifi.disconnect();
  58.  
  59. // WiFi.disconnect(true);
  60.  
  61. // hotspot scan
  62.  
  63. //Serial.printf("Wi-Fi mode set to WIFI_STA %s\n", WiFi.mode(WIFI_STA) ? "" : "Failed!");
  64.  
  65. //scan_hotspot() ;
  66.  
  67. delay(1);
  68. WiFi.begin(ssid, password);
  69.  
  70.  
  71. Serial.print("Attempting to connect to WIFI network, SSID: ");
  72. Serial.println(ssid);
  73. Serial.println("");
  74. Serial.print("Password: ");
  75. Serial.println(password);
  76.  
  77. if (WiFi.status() == WL_NO_SHIELD) {
  78. Serial.println("WiFi shield not present");
  79. // don't continue:
  80. while (true);
  81. }
  82. pinMode(ledPin, OUTPUT);
  83. pinMode(MoistPin, OUTPUT);
  84.  
  85. while (WiFi.status() != WL_CONNECTED) {
  86. //while (WiFi.waitForConnectResult() != WL_CONNECTED) {
  87. //while (WiFi.localIP().toString() == "0.0.0.0") {
  88. //delay(250);
  89.  
  90.  
  91. // digitalWrite(ledPin, HIGH);
  92. // delay(250);
  93. // digitalWrite(ledPin, LOW);
  94. Serial.print(WiFi.localIP().toString());
  95.  
  96. Serial.println(".");
  97. Serial.println(WiFi.status());
  98. delay(500);
  99. }
  100. Serial.println("");
  101. Serial.println("WiFi connected");
  102.  
  103. // Starting the web server
  104. server.begin();
  105. Serial.println("Web server running. Waiting for the ESP IP...");
  106. delay(10000);
  107.  
  108. // Printing the ESP IP address
  109. Serial.println(WiFi.localIP());
  110. Serial.println("Setting MQ server.");
  111. client.setServer(mqtt_server, 1883);
  112. }
  113.  
  114.  
  115.  
  116.  
  117.  
  118. void reconnect() {
  119. // Loop until we're reconnected
  120. while (!client.connected()) {
  121. Serial.print("Attempting MQTT connection...");
  122. // Attempt to connect
  123. // If you do not want to use a username and password, change next line to
  124. // if (client.connect("ESP8266Client")) {
  125. if (client.connect("ESP8266Client_bedroom", mqtt_user, mqtt_password)) {
  126. Serial.println("connected");
  127. isconnected=true;
  128. } else {
  129. Serial.print("failed, rc=");
  130. isconnected=false;
  131. Serial.print(client.state());
  132. Serial.println(" try again in 15 seconds");
  133. // Wait 5 seconds before retrying
  134. delay(15000);
  135. }
  136. }
  137. }
  138.  
  139. bool checkBound(float newValue, float prevValue, float maxDiff) {
  140. return !isnan(newValue) &&
  141. (newValue < prevValue - maxDiff || newValue > prevValue + maxDiff);
  142. }
  143.  
  144. long lastMsg = 0;
  145. float temp = 0.0;
  146. float hum = 0.0;
  147. float moist = 0.0;
  148. float diff = 0.01;
  149.  
  150.  
  151.  
  152. void loop() {
  153. // Listenning for new clients
  154. WiFiClient clientweb = server.available();
  155. if (clientweb) {
  156. Serial.println("New client");
  157. // bolean to locate when the http request ends
  158. boolean blank_line = true;
  159. while (clientweb.connected()) {
  160. if (clientweb.available()) {
  161. char c = clientweb.read();
  162.  
  163.  
  164.  
  165.  
  166. if (c == '\n' && blank_line) {
  167. // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
  168.  
  169. // Read temperature as Celsius (the default)
  170. float t = dht.readTemperature();
  171. // Read temperature as Fahrenheit (isFahrenheit = true)
  172. float f = dht.readTemperature(true);
  173. // Check if any reads failed and exit early (to try again).
  174. float h = dht.readHumidity();
  175.  
  176.  
  177.  
  178.  
  179. if (isnan(h) || isnan(t) || isnan(f)) {
  180. Serial.println("Failed to read from DHT sensor!");
  181. strcpy(celsiusTemp,"Failed");
  182. strcpy(fahrenheitTemp, "Failed");
  183. strcpy(humidityTemp, "Failed");
  184. }
  185. else{
  186. // Computes temperature values in Celsius + Fahrenheit and Humidity
  187. float hic = dht.computeHeatIndex(t, h, false);
  188. dtostrf(hic, 6, 2, celsiusTemp);
  189. float hif = dht.computeHeatIndex(f, h);
  190. dtostrf(hif, 6, 2, fahrenheitTemp);
  191. dtostrf(h, 6, 2, humidityTemp);
  192. // You can delete the following Serial.print's, it's just for debugging purposes
  193.  
  194.  
  195.  
  196.  
  197.  
  198.  
  199. Serial.print("Humidity: ");
  200. Serial.print(h);
  201. Serial.print(" %\t Temperature: ");
  202. Serial.print(t);
  203. Serial.print(" *C ");
  204. Serial.print(f);
  205. Serial.print(" *F\t Heat index: ");
  206. Serial.print(hic);
  207. Serial.print(" *C ");
  208. Serial.print(hif);
  209. Serial.print(" *F");
  210. Serial.print("Humidity: ");
  211. Serial.print(h);
  212. Serial.print(" %\t Temperature: ");
  213. Serial.print(t);
  214. Serial.print(" *C ");
  215. Serial.print(f);
  216. Serial.print(" *F\t Heat index: ");
  217. Serial.print(hic);
  218. Serial.print(" *C ");
  219. Serial.print(hif);
  220. Serial.println(" *F");
  221. }
  222. clientweb.println("HTTP/1.1 200 OK");
  223. clientweb.println("Content-Type: text/html");
  224. clientweb.println("Connection: close");
  225. clientweb.println();
  226. // your actual web page that displays temperature and humidity
  227. clientweb.println("<!DOCTYPE HTML>");
  228. clientweb.println("<html>");
  229. clientweb.println("<head></head><body><h3>");
  230. clientweb.println(celsiusTemp);
  231. //client.println("*C</h3><h3>Temperature in Fahrenheit: ");
  232. //client.println(fahrenheitTemp);
  233. clientweb.println("*C</h3><h3>Humidity: ");
  234. clientweb.println(humidityTemp);
  235. clientweb.println("%</h3>");
  236. clientweb.println("</body></html>");
  237. break;
  238. }
  239. if (c == '\n') {
  240. // when starts reading a new line
  241. blank_line = true;
  242. }
  243. else if (c != '\r') {
  244. // when finds a character on the current line
  245. blank_line = false;
  246. }
  247. }
  248. }
  249. // closing the client connection
  250. delay(1);
  251. clientweb.stop();
  252. Serial.println("Client disconnected.");
  253. }
  254.  
  255.  
  256. if (!client.connected()) {
  257.  
  258. reconnect();
  259. }
  260. client.loop();
  261.  
  262. long now = millis();
  263. if (now - lastMsg > 30000) {
  264. lastMsg = now;
  265.  
  266.  
  267.  
  268. float newTemp = dht.readTemperature();
  269. float newHum = dht.readHumidity();
  270.  
  271.  
  272. temp = newTemp;
  273. Serial.print("New temperature:");
  274. Serial.println(String(temp).c_str());
  275. client.publish(temperature_topic, String(temp).c_str(), true);
  276.  
  277.  
  278. hum = newHum;
  279. Serial.print("New hum:");
  280. Serial.println(String(hum).c_str());
  281. client.publish(humidity_topic, String(hum).c_str(), true);
  282. }
  283. }
Advertisement
Add Comment
Please, Sign In to add comment