#include "SPI.h"
#include <OneWire.h>
#include <DallasTemperature.h>
//#include "Adafruit_ILI9341.h" // Упростим использование только необходимых частей библиотеки
#include "Wire.h"
#include "MPU6050_light.h"

// Pin definitions for the ILI9341
#define TFT_DC 2
#define TFT_CS 3
//Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);

// Define the pins for the sensors and encoder
#define MPU6050_SDA PA4
#define MPU6050_SCL PA5
#define DS18B20_PIN PA2
#define ENCODER_PIN_A PA0
#define ENCODER_PIN_B PA1

int encoderLastState;
volatile int encoderPosition = 0;

OneWire oneWire(DS18B20_PIN);
DallasTemperature sensors(&oneWire);
MPU6050 mpu(Wire);

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

  Wire.begin(MPU6050_SDA, MPU6050_SCL);
  mpu.begin();
  mpu.calcOffsets(); // Call if stable, flat surface at start

  sensors.begin();

  pinMode(ENCODER_PIN_A, INPUT_PULLUP);
  pinMode(ENCODER_PIN_B, INPUT_PULLUP);
  encoderLastState = digitalRead(ENCODER_PIN_A);

  //tft.fillScreen(ILI9341_BLACK);
  //tft.setTextColor(ILI9341_WHITE);
  //tft.setTextSize(2);
}

void loop() {
  static int lastDisplayed = -1;
  int currentDisplay = encoderPosition % 3;
  if (lastDisplayed != currentDisplay) {
    //tft.fillScreen(ILI9341_BLACK);  // Clear screen only if changed
    //switch (currentDisplay) {
      //case 0: displayAccelerometerData(); break;
      //case 1: displayGyroscopeData(); break;
      //case 2: displayTemperatureData(); break;
    //}
    lastDisplayed = currentDisplay;
  }
  delay(100);
}

void readEncoder() {
  static uint8_t prevState = 0b11;
  uint8_t currentState = (digitalRead(ENCODER_PIN_A) << 1) | digitalRead(ENCODER_PIN_B);
  if (currentState != prevState) {
    if (((prevState == 0b11) && (currentState == 0b01)) || ((prevState == 0b00) && (currentState == 0b10))) {
      encoderPosition++;  // CW
    } else if (((prevState == 0b11) && (currentState == 0b10)) || ((prevState == 0b00) && (currentState == 0b01))) {
      encoderPosition--;  // CCW
    }
    prevState = currentState;
  }
}
/*
void displayAccelerometerData() {
  mpu.update();
  char buf[40];
  snprintf(buf, sizeof(buf), "Accel Data:\nX: %.2f\nY: %.2f\nZ: %.2f", mpu.getAccX(), mpu.getAccY(), mpu.getAccZ());
  tft.setCursor(0, 0);
  tft.print(buf);
}

void displayGyroscopeData() {
  mpu.update();
  char buf[40];
  snprintf(buf, sizeof(buf), "Gyro Data:\nX: %.2f\nY: %.2f\nZ: %.2f", mpu.getGyroX(), mpu.getGyroY(), mpu.getGyroZ());
  tft.setCursor(0, 0);
  tft.print(buf);
}

void displayTemperatureData() {
  sensors.requestTemperatures();
  char buf[40];
  snprintf(buf, sizeof(buf), "Temp Data:\n%.2f C", sensors.getTempCByIndex(0));
  tft.setCursor(0, 0);
  tft.print(buf);
}*/