/*
  Wokwi Custom UART Chip example

  The chip implements a simple ROT13 letter substitution cipher:
  https://en.wikipedia.org/wiki/ROT13

  See https://link.wokwi.com/custom-chips-alpha for more info about custom chips
*/

#include "DHTesp.h"
#include <Adafruit_MPU6050.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

#define DHT_PIN 15
DHTesp dhtSensor;

LiquidCrystal_I2C LCD = LiquidCrystal_I2C(0x27, 16, 2);

#define RXD2 16
#define TXD2 17

String sensorString = "";

Adafruit_MPU6050 mpu;
sensors_event_t event;

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

  sensorString.reserve(30);
  
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);

  Serial2.begin(115200, SERIAL_8N1, RXD2, TXD2);

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

  LCD.init();
  LCD.backlight();
  LCD.setCursor(0, 0);
  LCD.print("Hello there,");
  LCD.setCursor(0, 1);
  LCD.print("General Kenobi");
  delay(2000);
}

void uart_example() {
  // Send String to UART Breakout and print response
  char strToShift[] = "a";
  Serial2.print(strToShift);
  Serial.print("Sending command ");
  Serial.print(strToShift);
  Serial.print(", response: ");
  delay(100);      
  while (Serial2.available()) {
    char inchar = (char)Serial2.read();
    sensorString += inchar;
  }
  Serial.println();
  Serial.print(sensorString);
  Serial.println();

  LCD.setCursor(0,1);
  LCD.print("Ph: ");
  LCD.print(sensorString);

  sensorString = "";
}

void sensor_example() {
  // Read then print Temp and Humidity
  float temperature = dhtSensor.getTemperature();
  float humidity = dhtSensor.getHumidity();

  // Check if any reads failed and exit early (to try again).
  if (isnan(temperature) || isnan(humidity)) {
    Serial.println(F("Failed to read from DHT sensor!"));
    Serial.println();
    return;
  }

  Serial.print(F("Humidity: "));
  Serial.print(humidity);
  Serial.print(F("%  Temperature: "));
  Serial.print(temperature);
  Serial.println(F("°C "));
  Serial.println();

  LCD.setCursor(0, 0);
  LCD.print(F("Tmp "));
  LCD.print(temperature, 1);
  LCD.print(F("Hum "));
  LCD.print(humidity, 0);
  LCD.print(F("% "));
}

void accell_example() {
  mpu.getAccelerometerSensor()->getEvent(&event);
  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");

  LCD.print(" g=");
  LCD.print(event.acceleration.z, 2);

  delay(500);
}


void loop() {
  LCD.clear();  
  sensor_example();
  uart_example();  
  accell_example();

  // Wait a few seconds between measurements.
  delay(2000);
}
UART ExampleBreakout