Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <DHT.h>
- #include <Time.h>
- #include <ESP8266WiFi.h>
- #include <ESP8266mDNS.h>
- #include <ArduinoOTA.h>
- #include <ESP8266WebServer.h>
- #include "TamaVeg_html_main.h"
- #include "TamaVeg_html_live.h"
- const char* ssid = "GPRTWIFI";
- const char* password = "senhademasiadamentesecreta";
- ESP8266WebServer server(80);
- const char* www_username = "admin";
- const char* www_password = "senhasecreta";
- const int led = 13;
- //----------RELES--------//
- #define rele_light1 5 // Pin to relay 1
- #define rele_light2 4 // Pin to relay 2
- #define rele_fan1 0 // Pin to relay 3
- #define rele_humidifier 2 // Pin to relay 4
- //-------DHT Sensors-----//
- #define DHT1_PIN 14
- #define DHTTYPE DHT11
- DHT Dht11_1(DHT1_PIN, DHTTYPE);
- float sens_HumidityAr;
- float sens_AmbTemperature ;
- //---Soil Humidity Sensor---
- #define SOIL1_PIN A0
- int sens_SoilHumidity;
- //----NTP Related------------//
- char timeServer[] = "150.161.192.1"; // time.nist.gov NTP server
- const int timeZone = -3; // Recife/America
- int localNtpPort = 8888; // local port to listen for UDP packets
- const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
- byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
- // A UDP instance to let us send and receive packets over UDP
- WiFiUDP Udp;
- // Profile -----------------------------------
- String profile_Name = String("PadraoS");
- int profile_OnTime = 5 ; // hour to turn on
- int profile_TimeOn = 12; // How many hours stay on
- int profile_Humidity = 60; // Himidity to reach
- int profile_AmbTemperature = 25; // Temperature to reach
- int profile_SoilHumidity = 50; // profile_Humiditydity of the soil to reach
- //---PWM----
- #define fanCrt1_PIN 13 //(D7)
- //Varables to auxiliate--------------------
- int dayLight[24]; // Vetor of flags to control the light, size 24, each location represent a hour of the day, filled with 0 the light should be off the hour, oposite with 1.
- int flagLight; // Flag used to determine if light are ON or OFF
- int exaustFlag; // Flag used to determine if exausts are ON or OFF
- unsigned long waitSensors = 0; // Flag to delay read sensors
- //unsigned long waitLcdInfo = 2000; // Flag to delay LDC messages
- //int lcdMsgFlag = 0; // Flag to spin the messages on LCD
- int showAux_sens_AmbTemperature;
- int showAux_sens_HumidityAr;
- char showAux_profile_Name[10] = "Default";
- char showAux_bgcolor[10];
- int liveFlag = 0;
- int light1Set = 0;
- int fan1Set = 0;
- int fanCtrl1 = 255;
- int fanCtrl2 = 255;
- String bgcolor;
- void setup() {
- Serial.begin(115200);
- // Init reles off
- pinMode (rele_light1, OUTPUT);
- pinMode (rele_light2, OUTPUT);
- pinMode (rele_fan1, OUTPUT);
- pinMode (rele_humidifier, OUTPUT);
- digitalWrite (rele_light1, HIGH);
- digitalWrite (rele_light2, HIGH);
- digitalWrite (rele_fan1, HIGH);
- digitalWrite (rele_humidifier, HIGH);
- analogWriteRange(255);
- analogWriteFreq(490);
- WiFi.mode(WIFI_STA);
- WiFi.begin(ssid, password);
- if (WiFi.waitForConnectResult() != WL_CONNECTED) {
- Serial.println("Failed to configure WiFi");
- Serial.println("Assuming is 00:00:00 on 4/4/1988"); // Put some Blink Led here!! or reset
- setTime(00, 00, 00, 04, 04, 1988); // alternative to above, yr is 2 or 4 digit yr (2010 or 10 sets year to 2010)
- //delay(1000);
- //ESP.restart();
- }
- Serial.println(WiFi.localIP());
- Udp.begin(localNtpPort);
- setSyncProvider(getNtpTime);
- SetLightVector(profile_OnTime, profile_TimeOn);
- Dht11_1.begin();
- server.on("/profile", handle_profile); //http://<ip>/profile?profName=teste3&OnTime=4&TimeOn=20&hum=60&tmpamb=25&humtr=60
- server.on("/", handle_root);
- server.onNotFound ( handleNotFound );
- server.on("/live", handle_live );
- server.begin();
- }
- void handle_profile() {
- char temp[900];
- // Value Aquisition
- server.arg("profName").toCharArray(showAux_profile_Name, server.arg("profName").length() + 1);
- profile_OnTime = server.arg("OnTime").toInt(); // Hour to turn on
- profile_TimeOn = server.arg("TimeOn").toInt(); // How many hours stay on
- profile_Humidity = server.arg("hum").toInt(); // Humidity to reach
- profile_AmbTemperature = server.arg("tmpamb").toInt(); // Amb Temperature to reach
- profile_SoilHumidity = server.arg("humtr").toInt(); // Soil Humidity to reach
- //React to the new profile
- SetLightVector(profile_OnTime, profile_TimeOn);
- if (!liveFlag)
- chkLightState();
- //Generate Response html
- snprintf (temp, 900, html_page_main, showAux_bgcolor,
- showAux_profile_Name, hour(), minute(), second(), flagLight, profile_OnTime, profile_TimeOn, showAux_sens_AmbTemperature, profile_AmbTemperature, showAux_sens_HumidityAr, profile_Humidity, sens_SoilHumidity, profile_SoilHumidity);
- //Send Html Response
- if (!server.authenticate(www_username, www_password))
- return server.requestAuthentication();
- else
- server.send ( 200, "text/html", temp );
- }
- void handle_root() {
- char temp[900];
- //profile_Name.toCharArray(showAux_profile_Name, profile_Name.length() + 1);
- snprintf (temp, 900, html_page_main,
- showAux_bgcolor, showAux_profile_Name, hour(), minute(), second(), flagLight, profile_OnTime, profile_TimeOn, showAux_sens_AmbTemperature, profile_AmbTemperature, showAux_sens_HumidityAr, profile_Humidity, sens_SoilHumidity, profile_SoilHumidity);
- if (!server.authenticate(www_username, www_password))
- return server.requestAuthentication();
- else
- server.send ( 200, "text/html", temp );
- }
- void handleNotFound() {
- String message = "File Not Found\n\n";
- message += "URI: ";
- message += server.uri();
- message += "\nMethod: ";
- message += ( server.method() == HTTP_GET ) ? "GET" : "POST";
- message += "\nArguments: ";
- message += server.args();
- message += "\n";
- for ( uint8_t i = 0; i < server.args(); i++ ) {
- message += " " + server.argName ( i ) + ": " + server.arg ( i ) + "\n";
- }
- server.send ( 404, "text/plain", message );
- }
- void handle_live() {
- char temp[900];
- // Value Aquisition
- liveFlag = server.arg("live").toInt();
- light1Set = server.arg("light1").toInt();
- fan1Set = server.arg("fan1").toInt();
- Serial.println(liveFlag);
- Serial.println(light1Set);
- Serial.println(fan1Set);
- if (liveFlag) {
- if (light1Set == 1) {
- digitalWrite(rele_light1, LOW);
- }
- else if (light1Set == 0) {
- digitalWrite(rele_light1, HIGH);
- }
- //FANS
- if (fan1Set == 1) {
- digitalWrite(rele_fan1, LOW);
- }
- else if (fan1Set == 0) {
- digitalWrite(rele_fan1, HIGH);
- }
- }
- //Generate Response html
- snprintf (temp, 900, html_page_live, showAux_bgcolor,
- hour(), minute(), second(), flagLight, profile_OnTime, profile_TimeOn, showAux_sens_AmbTemperature, profile_AmbTemperature, showAux_sens_HumidityAr, profile_Humidity, sens_SoilHumidity, profile_SoilHumidity);
- //Send Html Response
- if (!server.authenticate(www_username, www_password))
- return server.requestAuthentication();
- else
- server.send ( 200, "text/html", temp );
- }
- void loop() {
- // Update time if needed
- if (timeStatus() == timeNotSet) {
- setSyncProvider(getNtpTime);
- }
- //Handle some http conection
- server.handleClient();
- if (!liveFlag) //-----Check if the ligths state is correct and update if needed
- chkLightState();
- //--------------Read the Temp and Hum Sensors--------
- if (millis() >= waitSensors) {
- waitSensors = millis() + 3000; //if more than 30secs since last read
- readSensors();
- //Serial.println(sens_SoilHumidity);
- }
- //-----React to Temperature & Humidity with the fans-----------//
- if (!liveFlag)
- chkFanState();
- //--------React to Soil Humidity----------//
- if (profile_SoilHumidity + 10 < sens_SoilHumidity) // too much moist
- bgcolor = String("#6A80ED"); // Azul
- else if ( profile_SoilHumidity + 10 >= sens_SoilHumidity && sens_SoilHumidity > profile_SoilHumidity - 10) // +-10% = green
- bgcolor = String("#20C42B"); //Green
- else if ( profile_SoilHumidity - 10 >= sens_SoilHumidity && sens_SoilHumidity > profile_SoilHumidity - 20) // Dry
- bgcolor = String("#F3EF11"); //Yelow
- else //if ( profile_SoilHumidity-20 >= sens_SoilHumidity ) // too much Dry
- bgcolor = String("#FF0000"); //Red
- bgcolor.toCharArray(showAux_bgcolor, bgcolor.length() + 1);
- //toCharArray(showAux_profile_Name, server.arg("profName").length() + 1);
- }
- void chkFanState() {
- // Porcedure where the ajusts to temperature response are made
- // the sensor readers are compared to the profile loaded and response
- // changing the speed of fans according to the temperature and some fixed settings
- if ( exaustFlag == 0 && (sens_AmbTemperature > profile_AmbTemperature) ) { // se os fans estao desligados e temp está 1 grau acima do definido
- digitalWrite(rele_fan1, LOW); // liga os 2 fans, um no min e um no medio
- exaustFlag = 1;
- analogWrite(fanCtrl1, 64);
- analogWrite(fanCtrl2, 127);
- }
- else if ( ( exaustFlag == 1 ) && ( sens_AmbTemperature > profile_AmbTemperature + 3 ) ) { // se os fan tão ligado e a temp ta 4 graus acima do definido, fans no maximo
- analogWrite(fanCtrl1, 255);
- analogWrite(fanCtrl2, 255);
- }
- else if ( ( exaustFlag == 1 ) && ( sens_AmbTemperature > profile_AmbTemperature + 2 ) ) { // se os fan tão ligado e a temp ta 3 graus acima do definido, um max e um med
- analogWrite(fanCtrl1, 255);
- analogWrite(fanCtrl2, 127);
- }
- else if ( ( exaustFlag == 1 ) && ( sens_AmbTemperature > profile_AmbTemperature + 1 ) ) { // se os fan tão ligado e a temp ta 2 graus acima do definido, dois meds
- analogWrite(fanCtrl1, 127);
- analogWrite(fanCtrl2, 127);
- }
- else if ( ( exaustFlag == 1 ) && ( sens_AmbTemperature > profile_AmbTemperature ) ) { // se os fan tão ligado e a temp ta 1 graus acima do definido,um fraco e um med
- analogWrite(fanCtrl1, 127);
- analogWrite(fanCtrl2, 64);
- }
- else if ( ( exaustFlag == 1 ) && ( sens_AmbTemperature == profile_AmbTemperature ) ) { // se os fans estão ligados e a temp ta igual a setada, dois fraco
- analogWrite(fanCtrl1, 64);
- analogWrite(fanCtrl2, 64);
- }
- if ( exaustFlag == 1 && sens_AmbTemperature < profile_AmbTemperature ) { // se a temp esta 1 abaixo do definodo desligue os fans
- digitalWrite(rele_fan1, HIGH);
- exaustFlag = 0;
- }
- }
- void readSensors() {
- //----------DHT-----------//
- sens_HumidityAr = Dht11_1.readHumidity(true);
- sens_AmbTemperature = Dht11_1.readTemperature();
- showAux_sens_AmbTemperature = (int) sens_AmbTemperature;
- showAux_sens_HumidityAr = (int) sens_HumidityAr;
- //------Soil Humidity-----//
- sens_SoilHumidity = map(analogRead(SOIL1_PIN), 0, 1024, 0, 100);
- }
- time_t getNtpTime() {
- while (Udp.parsePacket() > 0) ; // discard any previously received packets
- Serial.println("Transmit NTP Request");
- sendNTPpacket(timeServer);
- uint32_t beginWait = millis();
- while (millis() - beginWait < 1500) {
- int size = Udp.parsePacket();
- if (size >= NTP_PACKET_SIZE) {
- Serial.println("Receive NTP Response");
- Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer
- unsigned long secsSince1900;
- // convert four bytes starting at location 40 to a long integer
- secsSince1900 = (unsigned long)packetBuffer[40] << 24;
- secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
- secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
- secsSince1900 |= (unsigned long)packetBuffer[43];
- return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
- }
- }
- Serial.println("No NTP Response :-(");
- return 0; // return 0 if unable to get the time
- }
- void sendNTPpacket(char* address) {
- // set all bytes in the buffer to 0
- memset(packetBuffer, 0, NTP_PACKET_SIZE);
- // Initialize values needed to form NTP request
- // (see URL above for details on the packets)
- packetBuffer[0] = 0b11100011; // LI, Version, Mode
- packetBuffer[1] = 0; // Stratum, or type of clock
- packetBuffer[2] = 6; // Polling Interval
- packetBuffer[3] = 0xEC; // Peer Clock Precision
- // 8 bytes of zero for Root Delay & Root Dispersion
- packetBuffer[12] = 49;
- packetBuffer[13] = 0x4E;
- packetBuffer[14] = 49;
- packetBuffer[15] = 52;
- // all NTP fields have been given values, now
- // you can send a packet requesting a timestamp:
- Udp.beginPacket(address, 123); //NTP requests are to port 123
- Udp.write(packetBuffer, NTP_PACKET_SIZE);
- Udp.endPacket();
- }
- void chkLightState() {
- if (dayLight[hour()] == 1) {
- digitalWrite(rele_light1, LOW);
- flagLight = 1;
- //Serial.println("Ligando Lampadas");
- }
- else if (dayLight[hour()] == 0) {
- digitalWrite(rele_light1, HIGH);
- flagLight = 0;
- //Serial.println("Desligando Lampadas");
- }
- }
- void SetLightVector(int I, int D) {
- //--Manipulates the dayLigth vector, wich is a
- // 24 int vector tha represents the hours of the
- // day, when a position is set to 1, in the
- // respective hour of the day the light will be On.
- //
- // Receives the Initial hour to turn on the lights and the Duration of the sun bulb
- for (int i = 0; i <= 24; i++) // Reset the vector to 0
- dayLight[i] = 0; //
- if (I + D > 24) { // if the Initial time plus Duration is bigger the 24
- for (int i = I; i <= 24; i++) // from I to 24
- dayLight[i] = 1; // full of ones
- for (int i = 1; i <= (D + I - 24); i++) // D + I - 24 = the amount of initial hours of the day to complete the time when the day turn, so if "i" is smaler
- dayLight[i] = 1; // loop ant set to one
- }
- else { // if D+I < 24
- for (int i = I; i <= I + D - 1; i++) // loop from I to I+D-1; "-1" because we need to set 1's just to the hours that the light shoud be on, and the hour to turn off should be set to 0
- dayLight[i] = 1; // example: if I = 5 and D = 12, at 17 the light must be off, so we just set one in vector util the 16 hour.
- }
- }
- void showTimeVector() { // Created for Debug
- for (int i = 1; i <= 24; i++) {
- Serial.print("POS ");
- Serial.print(i);
- Serial.print(" = ");
- Serial.println(dayLight[i]);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement