That might be interesting to try with an interrupt. Not to steal your thunder, just sharing thoughts.
unsigned long duration;
unsigned long startMicros;
long last;
bool checking;
void setup()
{
pinMode(D7, OUTPUT); // LED on D7
pinMode(D1, OUTPUT); // Other LED connected from D1 through resistor to ground
// ultrasonic range finder Robotshop RB-lte-54
// GND pin goes to ground
pinMode(D6, INPUT); // echo
pinMode(D2, OUTPUT); // Trig
// VCC pin goes to VIN on the photon
attachInterrupt(D6, rangeISR, FALLING); // interrupt on falling edge
}
void loop(){
if ( checking == false && millis() - last > 1000 ){ // once per second if not doing anything
checking = true; // set a flag so it doesn't get confused
duration = 0;
last = millis(); // get time now for timer
digitalWrite(D2, HIGH); // activate trigger
delayMicroseconds(10);
digitalWrite(D2, LOW); // de-activate trigger
startMicros = micros(); // get time now for start
}
if ( duration ) // it's been set by ISR
{
if ( duration > 2000 ){ // raw data from 200 to 16000
// where 2000 raw = ~35cm, 4000 raw = ~80cm
digitalWrite(D7, HIGH); // D7 Blue LED on if far
digitalWrite(D1, LOW); // Other LED off
} else {
digitalWrite(D7, LOW); // D7 Blue LED off
digitalWrite(D1, HIGH); // Other LED on if Close
}
checking = false; // reset the flag to signal a start
duration = 0; // reset this as well
delay(10); // even circuits need a break
}
}
void rangeISR()
{
duration = micros() - startMicros; // sets duration to current time - start time
}