#include "SevSeg.h"
SevSeg sevseg; //Initiate a seven segment controller object

const int TrigPin = A1;    // the number of the LED pin
const int EchoPin = A0;
int flagPrep = 1;
int flagMeasure = 0;
int flagStopM = 0;
long long lastMilli = 0;
double d = 0;
double distance;
double duration;
double lastValue;
int counter  = 0;
double pipeArea = 8.29*4;
double funnelArea = 8.29*4;

void setup() {
  Serial.begin(9600);
    byte numDigits = 4;  
    byte digitPins[] = {13,12,3,2};
    byte segmentPins[] = {4,5,6,7,8,9,10,11};
    bool resistorsOnSegments = 0; 
    // variable above indicates that 4 resistors were placed on the digit pins.
    // set variable to 1 if you want to use 8 resistors on the segment pins.
    sevseg.begin(COMMON_CATHODE, numDigits, digitPins, segmentPins, resistorsOnSegments);
    sevseg.setBrightness(90);
 pinMode(TrigPin, OUTPUT);
    pinMode(EchoPin, INPUT);
}
void loop() {
  long long currentTime = millis();
  if(flagPrep && lastMilli == 0 || currentTime >= lastMilli + 500)
    {
      digitalWrite(TrigPin, LOW); 
      flagPrep = 0; 
      flagMeasure = 1; 
      lastMilli = currentTime;
    }
  if(flagMeasure && currentTime >= lastMilli + 2){
    digitalWrite(TrigPin, HIGH);
    flagMeasure = 0;
    flagStopM = 1;
    lastMilli = currentTime;
    }
  if(flagStopM && currentTime >= lastMilli + 10){
    digitalWrite(TrigPin, LOW);
    duration =  pulseIn(EchoPin, HIGH,8000);
    distance = (duration*0.0343)/2;
    Serial.println(distance);
    distance = 60.95-distance;
    double rainml = funnelArea / pipeArea * distance   ;

    int decimals;
    Serial.println(rainml);
    if(rainml>=1000) decimals = 0;
    else if( rainml >=100) {rainml = rainml*10; decimals = 1;}
    else if(rainml >= 10) {rainml = rainml*100;decimals = 2;}
    else if(rainml >= 1) { rainml = rainml*1000; decimals = 3;}
    else {decimals = 3; rainml = rainml*1000; }
    sevseg.setNumber(rainml,decimals);
    //Serial.print("hi its beeen ");
    //Serial.println(millis());
    flagStopM = 0;
    flagPrep = 1;
    lastMilli = millis();
    }
    //sevseg.setNumber(lastValue);
    // Must run repeatedly
  
    sevseg.refreshDisplay();
    }