-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathesp32.ino
91 lines (74 loc) · 2.42 KB
/
esp32.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
const char *ssid = "**";
const char *password = "**";
const char *serverName = "https://linux.plant-watch.com/data";
const int moistureSensorPin = 36;
const char *apiKey = "**";
// Timer variables
unsigned long previousMillis = 0; // Stores the last time the action was performed
const unsigned long interval = 6 * 60 * 60 * 1000; // 6 hours in milliseconds
void setup()
{
Serial.begin(115200);
// connect to wifi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop()
{
unsigned long currentMillis = millis();
// Check if 6 hours have passed
if (currentMillis - previousMillis >= interval)
{
previousMillis = currentMillis; // Update the last run time
if (WiFi.status() == WL_CONNECTED)
{
// Read the sensor value
int sensorValue = analogRead(moistureSensorPin);
Serial.printf("Moisture Level: %d\n", sensorValue);
// Create the JSON object with the sensor value
DynamicJsonDocument doc(64);
doc["plant"] = "Calethea";
doc["moisture"] = sensorValue;
String jsonString;
serializeJson(doc, jsonString);
// Send the data to the server
HTTPClient http;
http.begin(serverName);
http.addHeader("Content-Type", "application/json");
http.addHeader("x-api-key", apiKey);
int httpResponseCode = http.POST(jsonString);
if (httpResponseCode > 0)
{
Serial.printf("HTTP Response code: %d\n", httpResponseCode);
}
else
{
Serial.printf("Error code: %d\n", httpResponseCode);
}
http.end();
}
else
{
Serial.println("WiFi Disconnected. Reconnecting...");
// Attempt to reconnect WiFi
WiFi.disconnect();
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Reconnecting to WiFi...");
}
Serial.println("Reconnected to WiFi");
}
}
// Small delay to prevent busy looping
delay(100);
}