#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Fonts/Org_01.h>
#include <Fonts/FreeSansBold18pt7b.h>

//Screen
Adafruit_SSD1306 display (128, 64, &Wire, -1);

int Frame = 0;

const int start = 14; 
const int stop = 12;    
const int reset = 15;    
const int trig = 27;
const int echo = 26;

float startTime = 0;
float recordTime = 0;
float seconds = 0;
int accuracy = 0;
int score = 0;
bool startIR = false;
bool stopIR = false;
bool UDS = false;
long duration;
int distance;


void setup() {

  //Screen
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
  pinMode(start, INPUT);
  pinMode(stop, INPUT);
  pinMode(reset, INPUT);
  pinMode(trig, OUTPUT); 
  pinMode(echo, INPUT); 
  Serial.begin(9600);
}

void loop() {
  if (digitalRead(start) == HIGH && startIR == false) {
    startTime = millis();
    Serial.println("startTime:");
    Serial.println(startTime);
    startIR = true;
  }

  if (digitalRead(stop) == HIGH && stopIR == false && startIR == true) {
    recordTime = millis() - startTime;
    Serial.println(recordTime);
    seconds = recordTime / 1000;
    stopIR = true;
  }

  if (stopIR == true){
    // Clears the trigPin
    digitalWrite(trig, LOW);
    delayMicroseconds(2);

    // Sets the trigPin on HIGH state for 10 micro seconds
    digitalWrite(trig, HIGH);
    delayMicroseconds(10);
    digitalWrite(trig, LOW);

    // Reads the echoPin, returns the sound wave travel time in microseconds
    duration = pulseIn(echo, HIGH);

    // Calculating the distance
    distance = duration*0.034/2 - 2;

    Serial.println("Distance:");
    Serial.println(distance);

    if (distance == 0){
      accuracy = 20;
    } else if (distance == 1){
      accuracy = 50;
    } else if (distance == 2){
      accuracy = 100;
    } else if (distance == 3){
      accuracy = 50;
    } else if (distance == 4){
      accuracy = 20;
    }

    if (seconds >= 1){
      score = accuracy / 1;
    } else {
      score = accuracy / seconds;
    }
  }

display.setFont(&Org_01);
  display.clearDisplay();

  display.setTextSize(1);
  display.setTextColor(WHITE);

	display.setCursor(5,10);
  display.println("ACCURACY:");

	display.setCursor(70,10);
  display.println(accuracy);

	display.setCursor(5,20);
  display.println("SPEED/SEC:");

	display.setCursor(70,20);
  display.println(seconds);

	display.setCursor(5,30);
  display.println("SCORE:");

	display.setTextSize(4);
	display.setCursor(45,50);
  display.println(score);

  display.display();

  if (digitalRead(reset) == HIGH){
    startTime = 0;
    recordTime = 0;
    seconds = 0;
    accuracy = 0;
    score = 0;
    startIR = false;
    stopIR = false;
    UDS = false;
  }
}