-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
113 lines (90 loc) · 2.85 KB
/
main.cpp
File metadata and controls
113 lines (90 loc) · 2.85 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#include <Wire.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <BH1750.h>
#include <ESP32Servo.h>
#include "DFRobot_GDL.h"
#define TFT_DC D2
#define TFT_CS D6
#define TFT_RST D3
const char* ssid = "iPhone";
const char* password = "12345678";
const char* api_key = "ed94c71e2aa77121a9923c531bc3d7eb";
String api_url = "http://api.openweathermap.org/data/2.5/weather?q=Sydney&appid=" + String(api_key);
BH1750 lightMeter;
Servo myservo;
DFRobot_ST7789_240x320_HW_SPI screen(TFT_DC, TFT_CS, TFT_RST);
unsigned long lastApiCallTime = 0;
unsigned long lastLuxUpdateTime = 0; // 用于lux更新的时间变量
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Wire.begin();
lightMeter.begin();
delay(100);
myservo.attach(13);
screen.begin();
screen.fillScreen(COLOR_RGB565_WHITE);
screen.setTextWrap(false);
screen.setTextColor(COLOR_RGB565_GREEN);
screen.setTextSize(2);
screen.setCursor(16, 16);
screen.print("Light Intensity:");
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis - lastLuxUpdateTime > 1000) { // 1000 milliseconds
lastLuxUpdateTime = currentMillis;
uint16_t lux = lightMeter.readLightLevel();
// 控制舵机角度
if (lux < 50) {
myservo.write(0);
} else if (lux < 200) {
myservo.write(45);
} else if (lux < 1000) {
myservo.write(90);
} else {
myservo.write(135);
}
// 更新光强值
screen.fillRect(16, 51, screen.width() - 32, 35, COLOR_RGB565_WHITE);
screen.setCursor(16, 51);
screen.print(lux);
}
if (currentMillis - lastApiCallTime > 60000) { // One minute
lastApiCallTime = currentMillis;
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(api_url);
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
DynamicJsonDocument doc(1024);
deserializeJson(doc, payload);
const char* weather = doc["weather"][0]["main"];
float temp = doc["main"]["temp"].as<float>() - 273.15;
int humidity = doc["main"]["humidity"];
screen.fillRect(16, 86, screen.width() - 32, 35 * 3, COLOR_RGB565_WHITE);
screen.setCursor(16, 86);
screen.print("Weather: ");
screen.print(weather);
screen.setCursor(16, 121);
screen.print("Temp: ");
screen.print(temp);
screen.print(" C");
screen.setCursor(16, 156);
screen.print("Humidity: ");
screen.print(humidity);
screen.print("%");
screen.setCursor(16, 191);
screen.print("City: Sydney");
}
http.end();
}
}
}