//智能蛇卵觀測器
/*功能說明
1.調整兩感光元件可調整servo馬達旋轉角度
2.記錄溫濕度
3.調整六軸加速度感測器的acceleration以模擬紀錄傾斜角度以偵測是否受外力擾動
4.連間thing speak用以紀錄,由於配合thing speak上傳速度限制,因此反應可能有延遲。
*/
#include <WiFi.h>
#include <HTTPClient.h>
#include <DHT.h>
#include <Wire.h>
#include <MPU6050.h>
#include <ESP32Servo.h>
const char* ssid = "Your wifi ssid"; // ESP32
const char* password = "Your password"; // 12345678
String apiKey = "NL4YM7L4SKL6XIJK";
const char* server = "http://api.thingspeak.com/update";
// 感測器腳位
#define DHTPIN 4
#define DHTTYPE DHT22
const int LDR1_PIN = 34;
const int LDR2_PIN = 35;
const int SERVO_PIN = 18;
// 模組初始化
DHT dht(DHTPIN, DHTTYPE);
MPU6050 mpu;
Servo tiltServo;
void setup() {
Serial.begin(115200);
Serial.print("Connecting to ");
Serial.println(ssid);
//WiFi.begin(ssid, password); // 以STA(網路終端)模式連接到WiFi基地台
WiFi.begin("Wokwi-GUEST", "", 6); //wokwi提供的虛擬 WiFi 接入點
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected.");
Serial.print("IP位址: ");
Serial.println(WiFi.localIP()); // 回傳分配到的IP位址
Serial.print("WiFi RSSI: ");
Serial.println(WiFi.RSSI()); // 回傳接收訊號強度(以 dBm 為單位)
dht.begin();
Wire.begin();
mpu.initialize();
tiltServo.attach(SERVO_PIN);
tiltServo.write(90);
}
void loop() {
// 感測器讀值
float temp = dht.readTemperature();
float humi = dht.readHumidity();
int light1 = analogRead(LDR1_PIN);
int light2 = analogRead(LDR2_PIN);
// MPU6050 傾斜角讀取(pitch)
int16_t ax, ay, az;
mpu.getAcceleration(&ax, &ay, &az);
float pitch = atan2(ax, sqrt(ay * ay + az * az)) * 180 / PI;
// 馬達根據光線自動轉向
int total = light1 + light2;
if (total == 0) total = 1;
int angle = map(light2 * 180 / total, 0, 180, 0, 180);
angle = constrain(angle, 0, 180);
tiltServo.write(angle);
Serial.printf("溫度: %.2f°C, 濕度: %.2f%%, 光1: %d, 光2: %d, 傾斜角: %.2f\n", temp, humi, light1, light2, pitch);
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = String(server) + "?api_key=" + apiKey +
"&field1=" + String(temp) +
"&field2=" + String(humi) +
"&field3=" + String(pitch, 2) +
"&field4=" + String(light1) +
"&field5=" + String(light2);
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
Serial.println("資料已上傳");
} else {
Serial.printf("上傳失敗, 錯誤碼: %d\n", httpCode);
}
http.end();
}
delay(15000); // 20秒上傳一次
}