#include <Wire.h> // I2C 通訊函式庫
#include <Adafruit_MPU6050.h> // MPU6050 感測器函式庫
#include <Adafruit_Sensor.h> // 通用感測器介面函式庫
#include <RTClib.h> // DS1307 RTC 時鐘函式庫
#include <Adafruit_SSD1306.h> // OLED 顯示器函式庫
Adafruit_MPU6050 mpu; // 建立 MPU6050 物件
RTC_DS1307 rtc; // 建立 DS1307 RTC 物件
Adafruit_SSD1306 display(128, 64, &Wire); // 建立 OLED 顯示器物件 (解析度 128x64)
void setup() {
Serial.begin(115200); // 啟動序列埠,設定鮑率為 115200
// 初始化 MPU6050
if (!mpu.begin(0x69)) {
Serial.println("MPU6050 not found at 0x69!");
while (1); // 初始化失敗 → 停止程式
}
mpu.setAccelerometerRange(MPU6050_RANGE_8_G); // 設定加速度量測範圍 ±8G
// 初始化 RTC
if (!rtc.begin()) {
Serial.println("RTC not found at 0x68!");
while (1); // 初始化失敗 → 停止程式
}
// 初始化 OLED
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println("OLED not found!");
while (1); // 初始化失敗 → 停止程式
}
display.clearDisplay(); // 清空 OLED 畫面
}
// 依據中央氣象局震度分級表,將 PGA (cm/s^2) 對應到 0–7 級
int getQuakeLevel(float pga_cm) {
if (pga_cm < 0.8) return 0;
else if (pga_cm < 2.5) return 1;
else if (pga_cm < 8) return 2;
else if (pga_cm < 25) return 3;
else if (pga_cm < 80) return 4;
else if (pga_cm < 250) return 5;
else if (pga_cm < 400) return 6;
else return 7;
}
void loop() {
sensors_event_t a, g, temp; // 宣告感測器事件物件
mpu.getEvent(&a, &g, &temp); // 取得最新感測數據
// 將加速度從 m/s^2 轉換成 cm/s^2
float ax = a.acceleration.x * 100;
float ay = a.acceleration.y * 100;
float az = a.acceleration.z * 100;
// 找出三軸加速度的最大值 (PGA)
float pga = max(max(abs(ax), abs(ay)), abs(az));
// 判斷震度級數
int level = getQuakeLevel(pga);
// 取得 RTC 時間
DateTime now = rtc.now();
// 在 OLED 顯示時間與震度級數
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0,0);
display.printf("Time: %02d:%02d:%02d\n", now.hour(), now.minute(), now.second());
display.printf("Quake Level: %d\n", level);
display.display();
delay(2000); // 每 2 秒更新一次
}
Loading
esp32-devkit-v1
esp32-devkit-v1