/* 
--------------------------------------------  
-------- Begin Initialise Variables --------
--------------------------------------------
*/

//**** STAGE 1 ********

//DEFINE VARIABLES HERE....
//pins
int trig_Pin_f = 3; //US sensor forward trigger pin
int echo_Pin_f = 2; //US sensor forward echo pin
int enable_pin = 9;
int direction_pin = 6;
int plat_sensor_pin = A2;
int start_sensor_pin = A0;
int tunnel_sensor_pin = A1;


float distance = 0.0; // variable for the forwards distance measurement
int motor_percent = 0; // percentage power of motor
int motor_PWM = 0;// define PWM output



//Variables to find the threshold LDR values

int LDR_step = 200; //Used to calculate threshold

int start_LDR_background; // Background light level at start LDR
int start_LDR_threshold=0; 
int start_LDR_current;

int tunnel_LDR_current;
int tunnel_LDR_background;
int tunnel_LDR_threshold;

int plat_LDR_current;
int plat_LDR_background;
int plat_LDR_threshold;



/* 
----------------------------------  
-------- Begin Setup Loop --------
----------------------------------
*/

//**** STAGE 2 *******
void setup() {

  //begin serial transmission
  Serial.begin(9600); // Start Serial comms with a baud rate of 9600

  //**** SETUP YOUR PINS HERE
  pinMode(trig_Pin_f, OUTPUT); //US sensor forward trigger pin = output
  pinMode(echo_Pin_f, INPUT); //US sensor forward echo pin = input
  pinMode(enable_pin, OUTPUT);
  pinMode(direction_pin, OUTPUT);
  pinMode(plat_sensor_pin, INPUT);
  pinMode(start_sensor_pin, INPUT);
  pinMode(tunnel_sensor_pin, INPUT);


    //Calculating backgroud LDR Value at start 
  for(int i = 0 ; i <= 500 ; i++){
    start_LDR_current = analogRead(start_sensor_pin);
    if (start_LDR_current < start_LDR_background){
      start_LDR_background = start_LDR_current;
    }
  }

  //Calculate Background LDR reading at the tunnel 
  for(int i = 0 ; i <= 500 ; i++){
    tunnel_LDR_current = analogRead(tunnel_sensor_pin);
    Serial.print(tunnel_LDR_current);
    if (tunnel_LDR_current < tunnel_LDR_background){
      tunnel_LDR_background = tunnel_LDR_current;
    }
  }

//Calculate Background LDR reading at the platform
  for(int i = 0 ; i <= 500 ; i++){
    plat_LDR_current = analogRead(plat_sensor_pin);
    if (plat_LDR_current < plat_LDR_background){
      plat_LDR_background = plat_LDR_current;
    }
  }