//filename: ESP32 step counter (2023.03.28) v3
#include <Wire.h>
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
//#include <LiquidCrystal.h>
#include <LiquidCrystal_I2C.h>
// 初始化 LCD
//LiquidCrystal lcd(12, 11, 5, 4, 3, 2); // 设置LCD引脚连接
LiquidCrystal_I2C lcd(0x27, 16, 2); // 设置LCD I2C地址和列数行数
// 初始化 MPU6050
Adafruit_MPU6050 mpu;
// 變量初始化
float angle = 0; // 角度
float last_angle = 0; // 上一次的角度
float step_length = 0.65; // 步長
int steps = 0; // 步數
void setup() {
// 初始化串口,方便調試
Serial.begin(9600);
// 初始化 MPU6050
if (!mpu.begin()) {
Serial.println("Failed to find MPU6050 chip");
while (1) {
delay(10);
}
}
// 初始化 LCD
lcd.init(); // 初始化LCD
lcd.backlight(); // 打开背光
lcd.setCursor(0, 0);
lcd.print("Step Counter");
}
void loop() {
// 讀取 MPU6050 的值
sensors_event_t event, event2, event3;
mpu.getEvent(&event, &event2, &event3);
// 計算角度
float raw_angle = atan2(event.acceleration.y, event.acceleration.z);
angle = raw_angle * 10 / PI;
// 檢查是否發生了一步
if (angle > 0 && last_angle < 0) {
steps++;
lcd.setCursor(0, 1);
lcd.print("Steps: ");
lcd.print(steps);
}
// 更新上一次的角度
last_angle = angle;
// 延遲一段時間,避免過於頻繁的計算
delay(100);
}