#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>

// Define pins for ILI9341
#define TFT_CS     10
#define TFT_RST    9
#define TFT_DC     8

// Create ILI9341 display object
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC, TFT_RST);

// Constants
const unsigned long PULSES_PER_KM = 4000;  // Pulse per kilometer for VR-4
const int VSS_PIN = 2;  // VSS signal pin

unsigned long pulseCount = 0;  // Count of pulses
unsigned long lastMillis = 0;  // Timer for speed update
float speedKmh = 0.0;  // Speed in km/h

void setup() {
  Serial.begin(9600);

  pinMode(VSS_PIN, INPUT);  // VSS input pin

  // Initialize TFT display
  tft.begin();
  tft.setRotation(3);  // Adjust screen orientation if needed
  tft.fillScreen(ILI9341_BLACK);  // Set background color
  tft.setTextColor(ILI9341_WHITE); // Set text color
  tft.setTextSize(2);
  
  // Display welcome message
  tft.setCursor(10, 10);
  tft.print("Speedometer");
  delay(1000);  // Show welcome message for a second
}

void loop() {
  // Poll the button for VSS pulses
  if (digitalRead(VSS_PIN) == HIGH) {
    pulseCount++;
    delay(50); // debounce delay
  }

  // Calculate speed every second
  if (millis() - lastMillis >= 1000) {
    lastMillis = millis();

    // Calculate speed in km/h
    speedKmh = ((float)pulseCount / PULSES_PER_KM) * 3600.0; // pulses/km to km/h
    pulseCount = 0;  // Reset pulse count after each second

    // Display speed on TFT
    tft.fillScreen(ILI9341_BLACK);  // Clear the screen
    tft.setCursor(10, 10);
    tft.print("Speed: ");
    tft.print(speedKmh);
    tft.print(" km/h");

    delay(100);  // Short delay to avoid flickering
  }
}