// --------------------------------------------------------------------------------
/*

18 加速度感應器 MPU6050

[學習重點]

1. 認識加速度感應器 MPU6050
https://docs.wokwi.com/parts/wokwi-mpu6050

2. 認識 event

3. 認識 Serial output

[挑戰]

- 現時只顯示了加速度的數據,試修改程式以顯示 MPU6050 的傾斜度數據


Created by Jason on 18 Aug 2022.

*/
// --------------------------------------------------------------------------------

// LCD
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,20,4);  // set the LCD address to 0x27 for a 16 chars and 2 line display

// MPU6050
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
Adafruit_MPU6050 mpu;

void setup(void) {
  Serial.begin(115200);

  // LCD
  lcd.init();
  lcd.backlight();

  // MPU6050
  while (!mpu.begin()) {
    Serial.println("MPU6050 not connected!");
    delay(1000);
  }
  Serial.println("MPU6050 ready!");
}

// MPU6050
sensors_event_t event; // Event for MPU6050

void loop() {
  // MPU6050
  mpu.getAccelerometerSensor()->getEvent(&event);

  // 顯示訊息到 LCD
  lcd.setCursor(3,0); // 設定遊標位置 (左邊數第幾個字, 行數)
  lcd.print("X: ");
  lcd.print(event.acceleration.x);
  lcd.print(" m/s^2   ");
  lcd.setCursor(3,1);
  lcd.print("Y: ");
  lcd.print(event.acceleration.y);
  lcd.print(" m/s^2   ");
  lcd.setCursor(3,2);
  lcd.print("Z: ");
  lcd.print(event.acceleration.z);
  lcd.print(" m/s^2   ");
  lcd.setCursor(3,3);
  lcd.print("Temperation: ");
  lcd.print(event.temperature);
  lcd.print("   ");

  // 顯示訊息到 Serial
  Serial.print("[");
  Serial.print(millis());
  Serial.print("] X: ");
  Serial.print(event.acceleration.x);
  Serial.print(", Y: ");
  Serial.print(event.acceleration.y);
  Serial.print(", Z: ");
  Serial.print(event.acceleration.z);
  Serial.println(" m/s^2");

  delay(500);
}