//filename:DLD FY1112 W8 ESP step counter and time with WiFi (2023.04.10) v3
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <WiFi.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
//Add real time clock library (RTCLib here)
//#include "RTClib.h"
#include "time.h"
//宣告LCD變數
//LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // 设置LCD引脚连接
LiquidCrystal_I2C lcd(0x27, 16, 2); // 设置LCD I2C地址和列数行数
// 定義RTC時間變數
struct tm timeinfo;
// 宣告MPU6050變數
Adafruit_MPU6050 mpu;
// 宣告角度等變數
float angle = 0; // 角度
float last_angle = 0; // 上一次的角度
float step_length = 0.65; // 步長
int steps = 0; // 步數
// 宣告角度等變數
int stepCount = 0; //計步器計數器
//初始化
void setup() {
// 初始化I2C和顯示屏
Wire.begin();
Serial.begin(115200);
Serial.println("Hello, ESP 32");
lcd.init();
lcd.backlight();
// 連接WiFi並獲取時間
WiFi.begin("Wokwi-GUEST", "");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(1000);
}
Serial.println("Connected");
Serial.println(WiFi.localIP());
configTime(8 * 3600, 0, "pool.ntp.org");
// 等待時間同步完成
while (!time(nullptr)) {
delay(1000);
}
// 初始化 MPU6050
if (!mpu.begin()) {
Serial.println("Failed to find MPU6050 chip");
while (1) {
delay(10);
}
}
}
void loop() {
// 獲取RTC時間
if (!getLocalTime(&timeinfo)) {
lcd.setCursor(0, 0);
lcd.print("Failed to get time");
return;
}
// 顯示時間
lcd.clear();
lcd.setCursor(0, 0); //first line
lcd.print("Time: ");
lcd.print(String(timeinfo.tm_hour) + ":" + String(timeinfo.tm_min) + ":" + String(timeinfo.tm_sec));
// 進入睡眠模式,每0.1分鐘喚醒一次以更新時間
esp_sleep_enable_timer_wakeup(6000000);
esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON);
esp_deep_sleep_start();
//read ESP32 step counter (inside ESP32)
//lcd.setCursor(0, 1);
//lcd.print("Step count: ");
//lcd.print(stepCount);
//or read MPU6050 (outside ESP32)
sensors_event_t event, event2, event3;
mpu.getEvent(&event, &event2, &event3);
// 計算角度
float raw_angle = atan2(event.acceleration.y, event.acceleration.z);
angle = raw_angle * 0.1 / PI;
// 檢查是否發生了一步
if (angle > 0 && last_angle < 0) {
steps++;
lcd.setCursor(0, 1); //second line
lcd.print("Steps: ");
lcd.print(steps);
}
// 更新上一次的角度
last_angle = angle;
// 延遲一段時間,避免過於頻繁的計算
delay(100);
}