// TYL (Thrifty Yeti Locator)  TYL_GPS_Test.ino
//
// Display GPS Location on TFT Display for HackerBox 0119: 
// https://hackerboxes.com/products/hackerbox-0119-geopositioning
//
// Use Library Manager to Search for and Install:
//   Adafruit ILI9341 Library (with dependancies)
//   EspSoftwareSerial by Dirk Kaar
//   TinyGPSPlus-ESP32 by Mikal Hart

#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
#include <SoftwareSerial.h>
#include <TinyGPSPlus.h>

#define TFT_CS      15
#define TFT_DC       2
#define TFT_MOSI    13
#define TFT_CLK     14
#define TFT_RST     -1
#define TFT_MISO    12
#define TFT_BL      21
#define GPS_RX       1 
#define GPS_TX       3 

EspSoftwareSerial::UART gpsSerial;
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_MOSI, TFT_CLK, TFT_RST, TFT_MISO);
TinyGPSPlus gps;

void setup() {
  pinMode(TFT_BL, OUTPUT); 
  digitalWrite(TFT_BL, HIGH); //TFT Backlight ON
  gpsSerial.begin(9600, EspSoftwareSerial::SWSERIAL_8N1, GPS_RX, GPS_TX);
  tft.begin();
  tft.setRotation(3);
  tft.fillScreen(ILI9341_BLACK);
  tft.setCursor(0, 0);
  tft.setTextColor(ILI9341_YELLOW, ILI9341_BLACK); 
  tft.setTextSize(2);
  tft.println(F("Setup Complete")); 
  delay(1500);
  tft.fillScreen(ILI9341_BLACK);
}

void loop()
{
  while (gpsSerial.available() > 0){
    if (gps.encode(gpsSerial.read())) {
      DisplayLocation();
      delay(1000);
    }
  }
}

void DisplayLocation()
{
  if (gps.location.isValid())
  {
    tft.setCursor(0, 60);
    tft.println(F("Location: "));
    tft.print(gps.location.lat(), 6);
    tft.print(F(" , "));
    tft.print(gps.location.lng(), 6);
  }
  else
  {
    // Invalid GPS Location
    tft.setCursor(0, 0);
    tft.print(F("Acquiring Satellites..."));
  }
}