Parallax's nifty little sonar uses a single signal line to both trigger a measurement and return a result. The result comes back as a variable width pulse from which one can determine the round trip transit time and from that distance to the acoustic reflector.
I used existing Txtzyme tools to study this behavior and then improved Txtzyme to simplify this sort of measurement. I used the Javascope viewer from an earlier project to capture images of the return pulse that looked like this:
I wrote a shell loop that ran this Txtzyme ten times a second to get a nicely animated display in the scope:
The non-numeric output (_ping_) resets Javascope, then the 420 times repeat prints that many zeros and ones back to my laptop. This code produces samples at the rate of one every 40 microseconds or so. The interpreter takes about 5 microseconds per instruction and then I tack on 10 microseconds to get the capture rate that looks good in the display.
This output is from a revised Txtzyme program that uses a new, t command for measuring the pulse width. Here I was pointing the sensor at the ceiling, wiggled it around a little bit, then waved my hand in front of the sensor twice.
I use perl to send 300 t commands to Txtzyme, again sampling at 10 times a second:
The Txtzyme part of this says, on pin D7, output a trigger pulse, measure the response width, and print it back to Javascope.
(This version of Javascope had the origin in the upper left. I've fixed that too but it's too late tonight to retake the screenshots.)
The t command measures time with this programmed i/o loop:
This leaves tcount equal to the number of times the pin was sampled waiting for end of pulse, or zero, if that end doesn't come fast enough. The loop takes a little more than half a microsecond so with 16-bit arithmetic the timeout happens in a 1/15th of a second.
This is my cycle count for the loop as expressed by gcc:
This means that I'm counting at 1/9th the resolution that is easily obtained with the timer-counter but I'm happy to make that sacrifice to leave the resource for Txtzyme applications.
Look to GitHub for these scripts, an improved Javascope and new hex files with the t command for all versions of Teensy.