#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"
#define TFT_DC 4
#define TFT_CS 5
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);

#define xRes 320
#define yRes 240
int xBorder = 10;
int yBorder = 10;

int x1 = 0 + xBorder;
int yLeft = yRes / 2 + yBorder;
int x2 = xRes - xBorder;
int yRight = yRes / 2 - yBorder;
int pitchDeg = 0;
int pitchOffset = 0;
int pitch240 = 0;

void clearDisplay(void) {
  tft.fillScreen(0x0000);
  //tft.fillRect(0, 0, xRes, yRes, 0x0000);
}

void setup() {
  Serial.begin(115200);
  tft.begin();
  tft.setRotation(3);
  tft.fillRect(0, 0, xRes, yRes, 0xFFFF);
  tft.fillRect(0, 0, xRes, yRes, 0x0000);
  tft.drawLine(x1, yLeft, x2, yRight, 0xFFFF);
  tft.fillRect(0, 0, xRes, yRes, 0x0000);

  tft.fillRect(xBorder, yBorder, xRes - xBorder, yRes - yBorder, 0xFFFF);
  tft.fillRect(xBorder, yBorder, xRes - xBorder, yRes - yBorder, 0x0000);
  tft.drawLine(x1 + xBorder, yLeft + yBorder, x2 - xBorder, yRight - yBorder, 0xFFFF);
  tft.fillRect(0, 0, xRes, yRes, 0x0000);
}

void loop() {
  pitchDeg = random(-90, 90);
  pitchOffset = (yRes / 2) * pitchDeg / 90;
  pitch240 = (yRes / 2) - pitchOffset;
  yLeft = pitch240;
  yRight = pitch240;
  //Sky 0080F0
  tft.fillRect(0, 0, xRes, pitch240, 0x041E);
  //Ground 472001
  tft.fillRect(0, pitch240, xRes, 240 - pitch240, 0x4100);
  //Line White
  tft.drawLine(0, yLeft, xRes, yRight, 0xFFFF);
  Serial.printf("Pitch:%i Line:(%i %i),(%i %i)\n", pitchDeg, 0, yLeft, xRes, yRight);
  delay(5000);
  clearDisplay();
}