   }
 }
 
+void sampleVehicles() {
+  if (previousSignalState != traffic) {
+    if (traffic == NS_GREEN && vehicleNSCounter < 8) {
+      minimumNSGreenLight = minimumGreenLight;
+      previousSignalState = NS_GREEN;
+      Serial.print("NS_GREEN normal green signal time: ");
+      Serial.println(minimumNSGreenLight/1000);
+    }
+
+    if (traffic == NS_GREEN && vehicleNSCounter >= 8) {
+      minimumNSGreenLight = minimumGreenLight * (vehicleNSCounter / 4);
+      previousSignalState = NS_GREEN;
+      Serial.print("NS_GREEN calculated green signal time: ");
+      Serial.println(minimumNSGreenLight/1000);
+    }
+
+    if (traffic == EW_GREEN && vehicleEWCounter < 8) {
+      minimumEWGreenLight = minimumGreenLight;
+      previousSignalState = EW_GREEN;
+      Serial.print("EW_GREEN normal green signal time: ");
+      Serial.println(minimumEWGreenLight/1000);
+    }
+
+    if (traffic == EW_GREEN && vehicleEWCounter >= 8) {
+      minimumEWGreenLight = minimumGreenLight * (vehicleEWCounter / 4);
+      previousSignalState = EW_GREEN;
+      Serial.print("EW_GREEN calculated Green signal time: ");
+      Serial.println(minimumEWGreenLight/1000);
+    }
+  }
+}
+
 //creates a couple timers that will fire repeatedly every x ms
 TimedAction vehiclesNSThread = TimedAction(50, countNSVehicles); // checks for NS vehicle every 50 sec and count the total vehicle
 TimedAction vehiclesEWThread = TimedAction(50, countEWVehicles); // checks for ES vehicle every 50 sec and count the total vehicle
 TimedAction vehicleRemovalThread = TimedAction(1000, passVehicles); //a vehicle take minimum 5 to pass
+TimedAction signalThread = TimedAction(5000, sampleVehicles); //samples vehicle at both end
+
 
 
 // where's our third task? well, it's the loop itself :) the task

  }
}

void changeEWGreenToAmber() {
  if (timeSinceStart - previousTimeSinceStart > minimumGreenLight) {
    Serial.println("Vehicle EAST-WEST direction. Changing signal EAST-WEST to green");

    //change NS to amber

    traffic = EW_AMBER;
    previousTimeSinceStart = timeSinceStart;
  } else {
    //limit printing
    long remainingTime =  (minimumEWGreenLight - (timeSinceStart - previousTimeSinceStart)) / long(1000);
    if (remainingTime % 3 == 0) {      //if waiting for green light
      Serial.print("Time left for changing NORTH SOUTH to green in : ");
      Serial.print(remainingTime);
      Serial.println("s");
    }
  }
}

