· 6 years ago · Oct 28, 2019, 08:36 PM
1#include <ESP8266WiFi.h>
2#include <time.h>
3#include <OneWire.h>
4#include <DallasTemperature.h>
5
6int const reedswitch = 12; // Pino 6 Pluv
7const int oneWireBus = 14; // Pino 5 Temp
8
9const char* ssid = "Escr. Mobile";
10const char* senha = "xCt6M6B5";
11
12//Data Hora
13int timezone = -4;
14int dst = 0;
15
16int val = 0;
17int antigo_val = 0;
18int contador = 0; //Contagem comutaçao
19float dados;
20String horadia;
21//String hora = 16;
22
23
24String apiKey = "G1BMBS0R40F2SJKK"; //Write API Key
25const char *servidor_destino = "api.thingspeak.com";
26
27//Temp
28OneWire oneWire(oneWireBus);
29DallasTemperature sensors(&oneWire);
30
31void setup() {
32
33 pinMode (reedswitch, INPUT_PULLUP);//pullup usado para resistores
34 Serial.begin(115200);
35 sensors.begin();//Temp
36 digitalWrite(12, HIGH);
37 WiFi.enableAP(0);
38
39 Serial.print("\n");
40 Serial.print("Conectando a rede : ");
41 Serial.println(ssid);
42 WiFi.begin(ssid, senha);
43
44 while (WiFi.status() != WL_CONNECTED) {
45 delay(500);
46 Serial.print(".");
47 }
48 Serial.println("WiFi conectado");
49 Serial.print(WiFi.localIP());
50 Serial.print("\n\n");
51
52 //pegar hra
53 configTime(timezone * 3600, dst * 0, "pool.ntp.org", "time.nist.gov");
54}
55
56void loop() {
57 WiFiClient cliente;
58 cliente.connect(servidor_destino, 80);
59
60 //temp
61 sensors.requestTemperatures();
62 float t = sensors.getTempCByIndex(0);
63
64 val = digitalRead(reedswitch); //Lendo o Status atual do pino do redswitch
65
66 time_t now;
67 struct tm * timeinfo;
68 time(&now);
69 timeinfo = localtime(&now);
70 horadia = (timeinfo->tm_hour);
71 //Serial.println(horadia);
72
73 if (horadia == "9") {
74 dados = 0 * 0;
75 delay(6000);
76 }
77 if ((val == LOW) && (antigo_val == HIGH)) {
78 delay(10);
79
80 contador = contador + 1;
81 antigo_val = val; //Valor antigo vale o atual
82 dados = (contador * 0.25);
83 Serial.print("Medida de chuva: ");
84 Serial.print(dados);
85 Serial.println(" mm");
86 }
87 else {
88 antigo_val = val;
89 };
90
91 if (cliente.connect(servidor_destino, 80)) {
92
93 String postStr = apiKey;
94 postStr += "&field1=";
95 postStr += String(dados);
96 postStr += "&field2=";
97 postStr += String(t);
98 postStr += "\r\n\r\n";
99 cliente.print("POST /update HTTP/1.1\n");
100 cliente.print("Host:api.thingspeak.com\n");
101 cliente.print("Connection:close\n");
102 cliente.print("X-THINGSPEAKAPIKEY:" + apiKey + "\n");
103 cliente.print("Content-Type: application/x-www-form-urlencoded\n");
104 cliente.print("Content-Length:");
105 cliente.print(postStr.length());
106 cliente.print("\n\n");
107 cliente.print(postStr);
108 }
109 cliente.stop();
110 Serial.println("Aguardando...");
111 delay(20000);
112}