Photon PulseIn Function

@tcb2 Yep, confirmed working :smile:

SUCCESS! Thanks for posting the sensor model. I am using the Parallax 28015, which does not have distinct trigger and echo pins, but rather a single SIG pin. When you connect the echo and trigger pins to the SIG pin simultaneously, the PulseIn times out, perhaps because the photon-to-sensor pulse or sensor-to-photon data is absorbed by the trigger pin. Whatever the case, the solution is to use a single pin for trigger and echo, similar to the Arduino code, by defining the pin as output for trigger and then input for PulseIn.

#define pingPin D0

void setup() {
    pinMode(pingPin, OUTPUT);
    digitalWriteFast(pingPin, LOW);
    delay(50);
    Serial.begin(115200);
}

void loop() {
    uint32_t duration, inches, cm;
    
    pinMode(pingPin, OUTPUT);
    digitalWriteFast(pingPin, HIGH);
    delayMicroseconds(10);
    digitalWriteFast(pingPin, LOW);
  
    pinMode(pingPin, INPUT);
    duration = pulseIn(pingPin, HIGH);
    
    inches = microsecondsToInches(duration);
    cm = microsecondsToCentimeters(duration);
      
    Serial.print(inches);
    Serial.print("in, ");
    // Serial.print(cm);
    // Serial.print("cm");
    // Serial.println();
    Serial.print(duration);
    Serial.println("us");
    
    delay (500);
}

uint32_t microsecondsToInches(uint32_t microseconds)
{
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second).  This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

uint32_t microsecondsToCentimeters(uint32_t microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
}
2 Likes

I can confirm that the above code also works with the MaxBotix LV-Maxsonar-EZ when connected to the PW pin. Kudos to BDub for getting PulseIn up and running!