/*
  BME TO ESP32 ST7789 WIFI TFT 21-09-2023
*/
#include <WiFi.h>
#include <WebServer.h>
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>
#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7789.h> // library for ST7789
#include <SPI.h>

//======= For HEHUI Smart Display Lcd Tft Module ==============
// ST7789 TFT module connections
#define TFT_CS  15
#define TFT_DC   2
#define TFT_RST  4
#define TFT_SCL 18
#define TFT_SDA 23
// Initialize Adafruit ST7789 TFT library
Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);
//==============================================================

//===== Redefinition I2C for the BME280.==
#define I2C_SDA 33
#define I2C_SCL 32
TwoWire I2CBME = TwoWire(0);
Adafruit_BME280 bme;
//========================================

#define SEALEVELPRESSURE_HPA (1019.25)// Or your local

float temperature, humidity, pressure, altitude;

/*Put your SSID & Password*/
const char* ssid = "YOUR SSID";  // Enter SSID here
const char* password = "YOUR PASSWORD";  //Enter Password here
WebServer server(80);

void setup() {
 Serial.begin(115200);
 Serial.println ("");
 Serial.println ("BME280 TO ESP32 ST7789 WIFI TFT 21-09-2023");
 Serial.println ("");
 delay(50);
 // if the display has CS pin try with SPI_MODE0// Was spi mode 2
 tft.init(240, 320, SPI_MODE2);    // Init ST7789 display 240x320 pixel

 // if the screen is flipped, remove this command
 tft.fillScreen(ST77XX_BLACK);
 tft.invertDisplay(false);
 tft.setRotation(0);

 //==============Setup part for re-define bme ==========
 I2CBME.begin(I2C_SDA, I2C_SCL, 100000);
 bool status;

 status = bme.begin(0x76, &I2CBME);
 if (!status) {
   tft.fillScreen(ST77XX_BLACK);
   tft.invertDisplay(false);
   tft.setTextColor(ST77XX_WHITE);
   tft.setTextSize(2);
   tft.setCursor(10, 20);
   tft.print( "No BME280 Sensor");
   tft.setCursor(10, 45);
   tft.print( "found.");
   tft.setCursor(10, 70);
   tft.print( "Check the wiring.");
   while (1);
 }
 //==================================================
 tft.fillScreen(ST77XX_BLACK);
 tft.invertDisplay(false);
 tft.setTextColor(ST77XX_WHITE);
 tft.setTextSize(2);
 tft.setCursor(30, 20);
 tft.print("Connecting to ");
 tft.setCursor(10, 45);
 tft.print(ssid);
 delay(4000);

 //connect to your local wi-fi network
 WiFi.begin(ssid, password);
 //check wi-fi is connected to wi-fi network
 while (WiFi.status() != WL_CONNECTED) {
   delay(1000);
   tft.setCursor(10, 70);
   tft.print(".");

   //========================================
   tft.fillScreen(ST77XX_BLACK);
   tft.invertDisplay(false);
   tft.setTextColor(ST77XX_WHITE);
   tft.setTextSize(2);
   tft.setCursor(0, 20);
   tft.println("Searching for Wi-Fi.");
   //========================================
 }