/*
  Simple "Hello World" for ILI9341 LCD

  https://wokwi.com/arduino/projects/308024602434470466
  https://english.stackexchange.com/questions/20356/origin-of-i-can-haz

*/

#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"

#define TFT_DC 9
#define TFT_CS 10

#define VERT_PIN A0
#define HORZ_PIN A1
#define SEL_PIN  2

int maxX = 0;
int maxY = 0;
int x = 0;
int y = 0; 

//int x = 25;
//int y = 115; 
//int maxX = tft.height();
//int maxY = tft.width();

Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);

void setup() {

  pinMode(VERT_PIN, INPUT);
  pinMode(HORZ_PIN, INPUT);
  pinMode(SEL_PIN, INPUT_PULLUP);

  tft.begin();

  maxX = tft.height();
  maxY = tft.width();
  x = maxX / 2;
  y = maxY / 2; 

  tft.setRotation(1);

  tft.setCursor(0, 0);
  tft.setTextColor(ILI9341_WHITE);
  tft.setTextSize(0);
  tft.println("Seja bem-vindo ...");
  tft.println();

  tft.setCursor(0, 20);
  tft.setTextColor(ILI9341_GREEN);
  tft.setTextSize(1);
  tft.println("012345678901234567890123456789012345678901234567890");
  tft.println();

  delay(3000);

  tft.fillScreen(ILI9341_BLACK);

  tft.drawRect(0,0,maxX,maxY,ILI9341_GREEN);

}

void loop() { 

  int horz = analogRead(HORZ_PIN);
  int vert = analogRead(VERT_PIN);

  if (vert < 300) {
    y = min(y + 1, maxY);   
  }
  
  if (vert > 700) {    
    y = max(y - 1, 0); 
  }
  
  if (horz > 700) {
    x = max(x - 1, 0);    
  }
  
  if (horz < 300) {
    x = min(x + 1, maxX);
  }
  
  if (digitalRead(SEL_PIN) == LOW) {

  tft.fillScreen(ILI9341_BLACK);
  tft.drawRect(0,0,maxX,maxY,ILI9341_GREEN);
  x = maxX / 2;
  y = maxY / 2;

  }

  tft.drawCircle(x, y, 0.5, ILI9341_YELLOW);
  tft.fillCircle(x, y, 0.5, ILI9341_YELLOW);
 
  delay(100);

}