float distance = 0;
int duration = 0;      // collection duration in milliseconds

unsigned long timeRef;    // reference for starting time

int F = 2;                                                   //frequency of the signal
int Fs = 100;                                                //sampling frequency
int n = 100;                                                 //number of samples
float t;                                                     //Time instance

int sampling_interval;
float samples[100];                                          

void setup()
{
  Serial.begin(9600);
  for (int n = 0; n < 100; n++)
  {
    t = (float) n / Fs;                                       //creating time isntance to find the 500 samples
    samples[n] = (float) (1.5 * sin(2 * 3.14 * t) + 1.5);     //calculating the sin value at each time instance
  }
  sampling_interval = 1000000 / (F * n); 
  Serial.println(0.000, 3);
}

void loop()
{
  if (duration > 0)
  {
    int now = (micros() - timeRef)/1000;
    if (now < duration)
    {
      int index = map(now, 0, duration, 0, 100) % 100;
      distance = samples[index];
      Serial.println(distance, 3);
      delay(100);
    }
    else
    {
      duration = 0;
    }
  }

  if (Serial.available() > 0) 
  {
    // read the incoming byte as duration
    String inString = Serial.readString();
    duration = inString.toInt();
    
    // reset timeRef
    timeRef = micros();
  }
}