title: How to measure the time difference between two sensors down to the nanosecond?
body: <p>Similar to laser gates, I am trying to find the time difference between two different trigger sensors.  As of now, I am using Arduino UNO, but if there is a different language or processor that could get this precision, I am open to ideas.  With the Arduino, so far, I have been using the micro() function to get precision at the 4microsecond mark and have seen codes for running a high precision timer such as this one:</p>
  
  <pre><code>void setup()
  {
   pinMode(2, OUTPUT);
   TCCR1A = 0;
   TCCR1B = 0;          // input capture noise canceller disabled, capture on falling edge (may adjust this later), stop timer
   TIMSK1 = 0;          // timer 1 interrupts disabled
   ACSR = 0;             // input capture NOT from analog comparator
   Serial.begin(19200);
  }
  
  void loop()
  {
   static int numDisplayed = 20;
   static bool posEdge = true;
  
   TCCR1B = (posEdge) ? (1 &lt;&lt; ICES1) : 0;        // set up timer 1 to capture on whichever edge we want and stop timer
   TCNT1H = 0;
   TCNT1L = 0;          // clear timer 1
   unsigned long start = micros();  // get the time
  
   cli();
   TIFR1 = 1 &lt;&lt; ICF1;            // clear input capture bit
   TCCR1B |= (1 &lt;&lt; CS10);     // start timer, prescaler = 1
   PORTD |= (1 &lt;&lt; 2);          // set output high
   sei();
  
   unsigned int capture = 0;
   do
   {
     if ((TIFR1 &amp; (1 &lt;&lt; ICF1)) != 0)
     {
       byte temp = ICR1L;
       capture = (ICR1H &lt;&lt; 8) | temp;
     }
   } while (capture == 0 &amp;&amp; micros() - start &lt; 100);     // time out after 100us
  
   PORTD &amp;= ~(1 &lt;&lt; 2);     // set output low
   if (capture != 0)
   {
     if (numDisplayed == 20)
     {
       Serial.println();
       numDisplayed = 0;
     }
     else
     {
       Serial.write(' ');
     }
     Serial.print(capture);
     ++numDisplayed;
     delay(100);
   }
   else
   {
     delayMicroseconds(500);
   }
  }
  </code></pre>
  
  <p>Does anyone know how I could use this in my code?  I have tried using a while statement once the first trigger activates to simplify the code to just do a counter while waiting for the second trigger to activate but it is only good for measurements in 4microseconds.  So if anyone knows how to measure in nanoseconds it would be greatly appreciated. (The estimated time difference between the two triggers is 1.67 microseconds, thus the need for high precision.)</p>