Shop OBEX P1 Docs P2 Docs Learn Events
SRF04 Ultrasonic Range Finder — Parallax Forums

SRF04 Ultrasonic Range Finder

ArchiverArchiver Posts: 46,084
edited 2003-10-17 16:38 in General Discussion
Help! Help!

I thought I would not have any trouble with the SRF04, but I
seem to be unable to get consistent readings.
It seems to bounce over and over, and the readings are not
accurate.

Specifically, part of the code that I run ( from Nuts & Bolts)
is the following:
(All the initializations and parameter settings have been done
earlier)

Main:
GOSUB Get_Sonar ' take sonar reading
DEBUG MoveTo, 15, 3
temp = rawDist
GOSUB RJ_Print ' display raw value

DEBUG MoveTo, 15, 4
distance = rawDist ** 8886 ' divide by 7.3746
temp = distance / 10
GOSUB RJ_Print ' display inches
DEBUG ".", DEC1 distance

DEBUG MoveTo, 15, 5
distance = rawDist ** 22572 ' divide by 2.9033
temp = distance / 10
GOSUB RJ_Print ' display centimeters
DEBUG ".", DEC1 distance

PAUSE 200 ' delay between readings
GOTO main

If I replace "GOTO main" with END, and run the code over
and over,
I get totally inconsistent and erroneour readings. I thought
there was something wrong with the
SRF04 itself, and I send back to Parallax, but, it was
returned with the message that there is
nothing wrong with it.

What am I doing wrong? Please help!!!!!

Comments

  • ArchiverArchiver Posts: 46,084
    edited 2003-10-07 17:56
    We've got new code on our web site. The problem is that a firmware
    change in the SRF04 (which you cannot identify just by looking at it)
    seemed to cause our original code to have problems. I spent a day last
    week rewriting the code so that it will work with old or new SRF04 units
    and on any of our BS2 micros.

    Here's the link:

    http://www.parallax.com/detail.asp?product_id=28015

    -- Jon Williams
    -- Applications Engineer, Parallax
    -- Dallas Office




    Original Message
    From: John Colonias [noparse]/noparse]mailto:[url=http://forums.parallaxinc.com/group/basicstamps/post?postID=Ajl8VdsMbxFAjQV6op1Ko0PzWNyUXaHDRUKGRBQvILeZhti3QOTyDcXPu-4TqbYYuJ9ekcPYNGFTUvA73a0I-TAm]jcolonias@i...[/url
    Sent: Tuesday, October 07, 2003 11:34 AM
    To: basicstamps@yahoogroups.com
    Subject: [noparse][[/noparse]basicstamps] SRF04 Ultrasonic Range Finder


    Help! Help!

    I thought I would not have any trouble with the SRF04, but I
    seem to be unable to get consistent readings.
    It seems to bounce over and over, and the readings are not
    accurate.

    Specifically, part of the code that I run ( from Nuts & Bolts)
    is the following:
    (All the initializations and parameter settings have been done
    earlier)

    Main:
    GOSUB Get_Sonar ' take sonar reading
    DEBUG MoveTo, 15, 3
    temp = rawDist
    GOSUB RJ_Print ' display raw value

    DEBUG MoveTo, 15, 4
    distance = rawDist ** 8886 ' divide by 7.3746
    temp = distance / 10
    GOSUB RJ_Print ' display inches
    DEBUG ".", DEC1 distance

    DEBUG MoveTo, 15, 5
    distance = rawDist ** 22572 ' divide by 2.9033
    temp = distance / 10
    GOSUB RJ_Print ' display centimeters
    DEBUG ".", DEC1 distance

    PAUSE 200 ' delay between readings
    GOTO main

    If I replace "GOTO main" with END, and run the code over
    and over,
    I get totally inconsistent and erroneour readings. I thought
    there was something wrong with the
    SRF04 itself, and I send back to Parallax, but, it was
    returned with the message that there is
    nothing wrong with it.

    What am I doing wrong? Please help!!!!!


    To UNSUBSCRIBE, just send mail to:
    basicstamps-unsubscribe@yahoogroups.com
    from the same email address that you subscribed. Text in the Subject
    and Body of the message will be ignored.


    Your use of Yahoo! Groups is subject to
    http://docs.yahoo.com/info/terms/




    This message has been scanned by WebShield. Please report SPAM to
    abuse@p....
  • ArchiverArchiver Posts: 46,084
    edited 2003-10-07 18:46
    Jon

    Thank you very much. I will try it tonight when I get home, and let you know
    tomorrow.

    John

    On 7 Oct 2003 at 9:56, Jon Williams wrote:

    We've got new code on our web site. The problem is that a firmware
    change in the SRF04 (which you cannot identify just by looking at it)
    seemed to cause our original code to have problems. I spent a day last
    week rewriting the code so that it will work with old or new SRF04 units
    and on any of our BS2 micros.

    Here's the link:

    http://www.parallax.com/detail.asp?product_id=28015

    -- Jon Williams
    -- Applications Engineer, Parallax
    -- Dallas Office




    Original Message
    From: John Colonias [noparse]/noparse]mailto:[url=http://forums.parallaxinc.com/group/basicstamps/post?postID=XnOqlo5q880uNkALjA8m4GTTAsz5ZdYpAR7XKdi753oyS2IHakCCbhFLrQDjF3WZgeCHZ_neCFtqL5evXw19rxEw]jcolonias@i...[/url
    Sent: Tuesday, October 07, 2003 11:34 AM
    To: basicstamps@yahoogroups.com
    Subject: [noparse][[/noparse]basicstamps] SRF04 Ultrasonic Range Finder


    Help! Help!

    I thought I would not have any trouble with the SRF04, but I
    seem to be unable to get consistent readings.
    It seems to bounce over and over, and the readings are not
    accurate.

    Specifically, part of the code that I run ( from Nuts & Bolts)
    is the following:
    (All the initializations and parameter settings have been done
    earlier)

    Main:
    GOSUB Get_Sonar ' take sonar reading
    DEBUG MoveTo, 15, 3
    temp = rawDist
    GOSUB RJ_Print ' display raw value

    DEBUG MoveTo, 15, 4
    distance = rawDist ** 8886 ' divide by 7.3746
    temp = distance / 10
    GOSUB RJ_Print ' display inches
    DEBUG ".", DEC1 distance

    DEBUG MoveTo, 15, 5
    distance = rawDist ** 22572 ' divide by 2.9033
    temp = distance / 10
    GOSUB RJ_Print ' display centimeters
    DEBUG ".", DEC1 distance

    PAUSE 200 ' delay between readings
    GOTO main

    If I replace "GOTO main" with END, and run the code over
    and over,
    I get totally inconsistent and erroneour readings. I thought
    there was something wrong with the
    SRF04 itself, and I send back to Parallax, but, it was
    returned with the message that there is
    nothing wrong with it.

    What am I doing wrong? Please help!!!!!


    To UNSUBSCRIBE, just send mail to:
    basicstamps-unsubscribe@yahoogroups.com
    from the same email address that you subscribed. Text in the Subject
    and Body of the message will be ignored.


    Your use of Yahoo! Groups is subject to
    http://docs.yahoo.com/info/terms/




    This message has been scanned by WebShield. Please report SPAM to
    abuse@p....


    To UNSUBSCRIBE, just send mail to:
    basicstamps-unsubscribe@yahoogroups.com
    from the same email address that you subscribed. Text in the Subject and Body
    of the message will be ignored.


    Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
  • ArchiverArchiver Posts: 46,084
    edited 2003-10-13 19:20
    Jon,

    Tried new code and it is consideably better than the previous ones. However,
    it
    still, occassionally, registers erroneous reading. I also noticed that I get
    consistendly
    lower readings that what actually the distance should be, therefore, I thought
    of
    writing code to pick the highest of three readings. Any better way ?

    Thanks, John


    On 7 Oct 2003 at 9:56, Jon Williams wrote:

    We've got new code on our web site. The problem is that a firmware
    change in the SRF04 (which you cannot identify just by looking at it)
    seemed to cause our original code to have problems. I spent a day last
    week rewriting the code so that it will work with old or new SRF04 units
    and on any of our BS2 micros.

    Here's the link:

    http://www.parallax.com/detail.asp?product_id=28015

    -- Jon Williams
    -- Applications Engineer, Parallax
    -- Dallas Office




    Original Message
    From: John Colonias [noparse]/noparse]mailto:[url=http://forums.parallaxinc.com/group/basicstamps/post?postID=7E-sKFH2Czgk0Hjx5ZVH829DAA8hvtqfRdBmZcTIdp9WuO9An5AoXdBgiIBR9OYr4oGVixdFMAdE7bcxLbsn3h-0OwU]jcolonias@i...[/url
    Sent: Tuesday, October 07, 2003 11:34 AM
    To: basicstamps@yahoogroups.com
    Subject: [noparse][[/noparse]basicstamps] SRF04 Ultrasonic Range Finder


    Help! Help!

    I thought I would not have any trouble with the SRF04, but I
    seem to be unable to get consistent readings.
    It seems to bounce over and over, and the readings are not
    accurate.

    Specifically, part of the code that I run ( from Nuts & Bolts)
    is the following:
    (All the initializations and parameter settings have been done
    earlier)

    Main:
    GOSUB Get_Sonar ' take sonar reading
    DEBUG MoveTo, 15, 3
    temp = rawDist
    GOSUB RJ_Print ' display raw value

    DEBUG MoveTo, 15, 4
    distance = rawDist ** 8886 ' divide by 7.3746
    temp = distance / 10
    GOSUB RJ_Print ' display inches
    DEBUG ".", DEC1 distance

    DEBUG MoveTo, 15, 5
    distance = rawDist ** 22572 ' divide by 2.9033
    temp = distance / 10
    GOSUB RJ_Print ' display centimeters
    DEBUG ".", DEC1 distance

    PAUSE 200 ' delay between readings
    GOTO main

    If I replace "GOTO main" with END, and run the code over
    and over,
    I get totally inconsistent and erroneour readings. I thought
    there was something wrong with the
    SRF04 itself, and I send back to Parallax, but, it was
    returned with the message that there is
    nothing wrong with it.

    What am I doing wrong? Please help!!!!!


    To UNSUBSCRIBE, just send mail to:
    basicstamps-unsubscribe@yahoogroups.com
    from the same email address that you subscribed. Text in the Subject
    and Body of the message will be ignored.


    Your use of Yahoo! Groups is subject to
    http://docs.yahoo.com/info/terms/




    This message has been scanned by WebShield. Please report SPAM to
    abuse@p....


    To UNSUBSCRIBE, just send mail to:
    basicstamps-unsubscribe@yahoogroups.com
    from the same email address that you subscribed. Text in the Subject and Body
    of the message will be ignored.


    Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
  • ArchiverArchiver Posts: 46,084
    edited 2003-10-13 19:32
    Depends....

    Here's the thing. If you have a *new* unit (built May 2003 or later)
    there is a hidden function. The problem is that there is no way to
    physically tell one unit from the next because they aren't marked.
    Anyway, if you ground the "Do Not Connect" pin on the new units it
    extends the time before the sonic burst out to about 300 uS -- this
    gives the BS2 plenty of time to get ready with PULSIN. PULSIN will be
    more accurate because it sees the whole return pulse which is
    proportional to the object distance -- RCTIME misses a bit of the front
    edge. That said, the SRF04 is not a lab grade instrument and getting 1
    cm resolution is all that can be expected -- if that.

    Another thing. The setup time for PULSIN can be affected by the pins
    you choose. I always used 0 (trigger) and 1 (echo) and NEVER had any
    problems with my original program running on a stock BS2.

    -- Jon


    Original Message
    From: John Colonias [noparse]/noparse]mailto:[url=http://forums.parallaxinc.com/group/basicstamps/post?postID=ZirzW_5yEQ0ayx6qJ93Y9NvtnZP4YimqjZWshe9cqMjtlM0I8XzFsXsuZTenEPD7GyiwN-figZcYcyCTPNX97bolEA]jcolonias@i...[/url
    Sent: Monday, October 13, 2003 1:21 PM
    To: basicstamps@yahoogroups.com
    Subject: RE: [noparse][[/noparse]basicstamps] SRF04 Ultrasonic Range Finder


    Jon,

    Tried new code and it is consideably better than the previous ones.
    However, it
    still, occassionally, registers erroneous reading. I also noticed that I
    get consistendly
    lower readings that what actually the distance should be, therefore, I
    thought of
    writing code to pick the highest of three readings. Any better way ?

    Thanks, John


    On 7 Oct 2003 at 9:56, Jon Williams wrote:

    We've got new code on our web site. The problem is that a firmware
    change in the SRF04 (which you cannot identify just by looking at it)
    seemed to cause our original code to have problems. I spent a day last
    week rewriting the code so that it will work with old or new SRF04 units
    and on any of our BS2 micros.

    Here's the link:

    http://www.parallax.com/detail.asp?product_id=28015

    -- Jon Williams
    -- Applications Engineer, Parallax
    -- Dallas Office




    Original Message
    From: John Colonias [noparse]/noparse]mailto:[url=http://forums.parallaxinc.com/group/basicstamps/post?postID=ZirzW_5yEQ0ayx6qJ93Y9NvtnZP4YimqjZWshe9cqMjtlM0I8XzFsXsuZTenEPD7GyiwN-figZcYcyCTPNX97bolEA]jcolonias@i...[/url
    Sent: Tuesday, October 07, 2003 11:34 AM
    To: basicstamps@yahoogroups.com
    Subject: [noparse][[/noparse]basicstamps] SRF04 Ultrasonic Range Finder


    Help! Help!

    I thought I would not have any trouble with the SRF04, but I
    seem to be unable to get consistent readings.
    It seems to bounce over and over, and the readings are not
    accurate.

    Specifically, part of the code that I run ( from Nuts & Bolts)
    is the following:
    (All the initializations and parameter settings have been done
    earlier)

    Main:
    GOSUB Get_Sonar ' take sonar reading
    DEBUG MoveTo, 15, 3
    temp = rawDist
    GOSUB RJ_Print ' display raw value

    DEBUG MoveTo, 15, 4
    distance = rawDist ** 8886 ' divide by 7.3746
    temp = distance / 10
    GOSUB RJ_Print ' display inches
    DEBUG ".", DEC1 distance

    DEBUG MoveTo, 15, 5
    distance = rawDist ** 22572 ' divide by 2.9033
    temp = distance / 10
    GOSUB RJ_Print ' display centimeters
    DEBUG ".", DEC1 distance

    PAUSE 200 ' delay between readings
    GOTO main

    If I replace "GOTO main" with END, and run the code over
    and over,
    I get totally inconsistent and erroneour readings. I thought
    there was something wrong with the
    SRF04 itself, and I send back to Parallax, but, it was
    returned with the message that there is
    nothing wrong with it.

    What am I doing wrong? Please help!!!!!


    To UNSUBSCRIBE, just send mail to:
    basicstamps-unsubscribe@yahoogroups.com
    from the same email address that you subscribed. Text in the Subject
    and Body of the message will be ignored.


    Your use of Yahoo! Groups is subject to
    http://docs.yahoo.com/info/terms/




    This message has been scanned by WebShield. Please report SPAM to
    abuse@p....


    To UNSUBSCRIBE, just send mail to:
    basicstamps-unsubscribe@yahoogroups.com
    from the same email address that you subscribed. Text in the Subject
    and Body of the message will be ignored.


    Your use of Yahoo! Groups is subject to
    http://docs.yahoo.com/info/terms/



    To UNSUBSCRIBE, just send mail to:
    basicstamps-unsubscribe@yahoogroups.com
    from the same email address that you subscribed. Text in the Subject
    and Body of the message will be ignored.


    Your use of Yahoo! Groups is subject to
    http://docs.yahoo.com/info/terms/




    This message has been scanned by WebShield. Please report SPAM to
    abuse@p....
  • ArchiverArchiver Posts: 46,084
    edited 2003-10-14 01:32
    From: "John Colonias" <jcolonias@i...>


    > [noparse][[/noparse]...] still, occassionally, registers erroneous reading. I also noticed
    that I
    > get consistendly lower readings that what actually the distance should be,
    > therefore, I thought of writing code to pick the highest of three
    readings.
    > Any better way ?

    The first thing you mention is easy to explain: the consistently low
    readings. The measurement of pulse width begins a noticeable time period
    after the leading edge of the acoustic pulse train leaves the emitter can.
    At least 300 microseconds if you're using a fast Stamp and the PULSIN
    command. A little bit longer if you're using a BS2 and the RCTIME command.
    You need to calibrate this delay as an offset in the raw pulse measurement.
    Don't worry about theory. Just take repeated measurements at a near distance
    like 18" and determine how much to add the raw reading. It is a fixed offset
    and not a percentage of the total range.

    As to the erroneous readings, I've been testing two examples of the SRF04
    for a few weeks, John. Before playing with your code too much, consider what
    you might expect from "perfect" code. If we're not careful, it's easy to
    create a clean fiction in software that doesn't reflect the messy real
    world. And from a sensor, we want data not fiction.

    Recognize that this is not a narrow-beam, high-frequency sensor. For
    contrast, it specifically is NOT a laser rangefinder. Devantech's published
    chart in the manual is interpreted by them as indicating a 30° beam width.
    It looks more like 45° at least, and 60° for practical purposes. We're
    talking about a couple of very small acoustic cans here. My point is that
    for testing its performance, don't set the equipment on a cluttered tabletop
    and expect consistent readings. Use a flat surface; a flat target plate to
    provide a return; and nothing else above, below, left, or right of the beam
    path to the target. This will avoid "erroneous" readings that actually are
    giving you the valid distance to an intermediate object you didn't realize
    was within that broad beam width.

    I'm not an acoustic engineer, so I wasn't sure if it would be a problem, but
    I also turned off my in-computer stereo sound system while running tests. I
    figured it couldn't hurt to be careful, and a lot of the music was creating
    high energy levels at sub-harmonics of that 40 kHz frequency of the sonar.
    For all I knew, that might lead to spurious lock-ups. If nothing else, the
    music would add to the background noise level and thereby reduce the
    signal-to-noise ratio the receiver will enjoy.

    Even with those precautions, don't expect the same raw reading each time.
    Even with an artificially empty test environment, the real world is not that
    smooth. Let me run down some of the causes I've seen for readings that seem
    erratic to us.

    First, the Stamp is not an oscilloscope. It is counting discrete "ticks" of
    it's own clock to measure the pulse duration on that echo line. The actual
    duration necessarily falls on one side of the other of a "tick" boundary.
    That means a raw reading of 1000 this time might be followed by 1001 and
    then by 999 -- and they all would be right, with no way to choose a "best"
    one. This is discretization error and it's inherent in assigning an integer
    value to a real number.

    Second, this is a 40 kHz acoustic wave train at a pretty low energy level.
    The receiver has to lock up on the reflected energy of that pulse in the
    presence of acoustic energy of all sorts reaching that can. Without getting
    into the theory of doing such, I seem to remember that the absolute
    theoretical best for a phase-locked loop to detect the beginning of a wave
    form is three cycles. It's been several decades since a true expert on this
    subject told me that, so there's a ten percent chance I'm misremembering and
    he said two cycles -- but I don't think so. The reason is I'm a stubborn guy
    and I seem to remember him having to work hard to convince me it couldn't be
    done one cycle sooner. Catching a waveform on the first cycle is just plain
    silly so we surely were arguing about doing by the second, with him
    insisting a third cycle was necessary.

    For the sake of argument, let's assume it takes three cycles in a best case.
    Even in a cleaned-up test situation, you don't have a perfect signal and a
    perfect sensor. So it's usually going to take much longer -- say five or six
    cycles -- to "recognize" the returning waveform. That is, to lock up by
    synchronizing with it. That "lock up" is what will drop the echo line and
    terminate the pulse from the point of view of the Stamp. The sensor doesn't
    know how many cycles it took to achieve lock-up, so it can't tell us even if
    the interface gave us a way to ask.

    There actually are some tricky ways to approximate that, but this isn't a
    billion dollar sonar suite on a submarine we're talking about. So the sensor
    cannot tell us, because it does not "know" when the real leading edge
    arrived for that returning echo.

    Lock up, schmock up. All we know is the echo line went low. What we can
    observe is that it even after we take out the little variations of one Stamp
    tick more or less, we still get "big" jumps of 12 to 13 clocks regularly. At
    least I do with a BS2 conducting the tests. Your mileage with vary with a
    Stamp that has a different clock rate. Because a little arithmetic explains
    those jumps. This is 40 kHz signal. That's 40,000 times per second that it
    goes from one peak of acoustic pressure to the next peak. Take the inverse
    of 40,000 and you have 25 millionths, or 25 microseconds, from peak to peak.
    We can't measure 25 microseconds from a BS2 -- only 24 microseconds or 26
    microseconds. That's 12 clocks or 13 clocks.

    So every time the receiver takes one cycle more or less to lock up, we see a
    jump of 12 or 13 clocks up or down. Or sometimes 25 clocks between one
    "ping" and the next. Or even 36 to 40 clocks, because each reading must vary
    up and down by a clock or two because of measurement resolution in the
    stamp, and the sensor itself is varying by some multiple of 25 microseconds
    up or down because of the frequency of the waveform.

    6. Don't average all this. I disagree with the Parallax app note on this
    point. It was a good chance to teach people how to average values with a
    limited number of bits available in the accumulator, but the average is not
    appropriate to this raw data. (Technically, we say that this is not a
    Gaussian source of noise, so the mean is not an appropriate metric.)
    Instead, pick one answer and use that. The average will be some in-between
    number whose only sure trait is being wrong. (It might land on the right
    value like a stopped clock, but that's another joke for another day.) If you
    feel compelled to use multiple pings when you've already got a valid
    measurement, just put the results in "buckets" and pick the bucket that gets
    the most hits. This still won't be any more "right" than the next bucket
    over, because we have no idea how many cycles into the returning echo that
    lock-up occurred. But it might be fun to try, and do it if it makes you feel
    better about the answer your subroutine returns.

    7. Don't use a rope as a micrometer. The acoustic wave train from this
    sensor is two inches long for a reason. Well, probably. Maybe they did it
    because they saw somebody else use that pulse width, but for the sake of
    argument we'll assume that Devantech or that somebody else did the work to
    know how likely it is to pick up the returning waveform in a particular
    length of time -- that is, a particular pulse width. At short range in good
    conditions, half that pulse duration might work 90% of the time. But we
    can't pick our conditions when the sensor actually goes to work. Across the
    usable range of the sensor, we're talking about multi-path returns
    interfering with the waveform, noise spikes reducing some parts to a
    signal-to-noise ratio too low for lock-up, phase distortions from umpteen
    causes, and so forth and so on. I'm surprised a low cost receiver can lock
    up in eight cycles as reliably as this one does. But those eight cycles are
    needed sometimes, and we can't assume lock-up occurred at any particular
    point in that returning waveform. The receiver may have locked up by the
    third cycle, or it may not have locked until the eighth cycle.

    A precision of about two cycles is achieved under optimum conditions. In
    other words, if I take that raw reading and divide by 25 clocks (or 50
    microseconds), I start to get consistent reports from my subroutine. This is
    optimum conditions remember. That flat plate target business with my robot
    unmoving on a steady surface looking at a wall less than six inches away.
    That precision is 0.45 inches or 1.1 cm in the raw counts. For convenience,
    I multiplied by the range factor and report my result to the calling routine
    in multiples of half an inch. After multiplying, I apply that offset I
    mentioned at the beginning. Calibrated in half inches, because nothing
    closer is meaningful.

    This half inch is the precision of course, NOT the accuracy unless
    conditions are ideal. The accuracy of any particular return over the full
    range cannot be assumed to be better than plus or minus four clocks unless
    you are willing to take into account a lot other factors. You could, for
    example, de-rate the expected accuracy in accordance with the reported
    range. Personally, I don't expect an accurate resolution of less than one
    inch even when looking straight down at a flat surface: a distance of 8.5"
    for my robot. Not unless I know the surface is flat and no objects are down
    there -- in which case I didn't need the sensor...

    8. Finally, don't expect a reading every time. For two reasons. You didn't
    specify what kind of erroneous results you were getting, so I can't guess
    which applies. First, the echoes may return in such a gnarly garbled state
    that the receiver never sees a clean enough sine wave to lock up. This
    results in the echo line remaining high for 36 ms. On a BS2 your raw reading
    will be about 18,000. The second possibility is a problem at the interface.
    We have two devices here designed thousands of miles apart. Like men and
    women, their timing will not always agree when they try to interface.

    That conditional compilation code deals with this by using one instruction
    for the fast Stamps and another for the slow Stamps, but the Devantech unit
    appears to be an analog interface design. That is, it is not controlled by a
    crystal oscillator. (I can't imagine bothering. This is not a criticism,
    just an explanation.) That means timing on its side of the interface will
    vary with temperature of the components, which in turn varies with the duty
    cycle of the emitter as well as the ambient. Sometimes a particular unit
    could be a little too slow to raise the echo line for RCTIME to work, even
    on the slower Stamps like my BS2. One of my examples was like that. I doubt
    any unit would be fast enough to beat one of the faster Stamps using PULSIN,
    but using PULSIN with the slower Stamps rarely works. Only occasionally will
    the Devantech be slow enough for PULSIN to catch the leading edge of the
    echo line.

    If your unit slows down just enough for the RCTIME command to be set up and
    looking at the pin before the echo line is raised, then RCTIME will return a
    value of one. This means "I looked for the signal condition you told me to
    measure and it went away in one clock or less." Really, RCTIME was not
    patient enough for the signal to appear in the first place, but we have to
    supply the patience. Computers just do what we literally ask.

    So, the nasty messy reality of echoes and their detectors in the physical
    world mean you should expect all sorts of differences from one call to the
    next of the SRF04:

    1. A simple 1. The sonar raised the echo line a little late for RCTIME to
    work. Natural variation in analog components. Just include a loop to send
    out pings until a result other than one is achieved.

    2. A simple 0. The sonar raised the echo line a little early while you were
    using a PULSIN to measure the result. Jon's new sample code does not do this
    with the slower Stamps, but the old sample code did. Use RCTIME as Jon does.
    Or if you insist, accept this also as a natural variation in analog
    components and include a loop to send out pings until a result other than
    zero is achieved. Expect to require a lot of pings sometimes to get a signal
    valid range. I don't recommend this, understand. I'm just reporting my
    results with this technique.

    3. An equally simple 18000 (or so). No echo was detected. This is a valid
    answer that means the nearest target is out of range.

    4. Variation of one or two clocks up or down. Sometimes called "jitter", but
    most of this is just the natural effect of examining data from an analog
    event measured to a spurious digital precision. Nothing happening out there
    is known to a resolution of two microseconds. Don't even bother looking at
    the data until it's been reduced to the practical precision of half an inch
    or so. Or centimeters if you prefer metric.

    5. Variation of some multiple of 12 to 13 clocks up or down. Caused by
    lock-up with the acoustic waveform occurring one or two cycles either way.
    Or three or four. Not only natural, but inherent in any "interesting"
    environment. That is, one where we're measuring an unknown reality and
    attempting to learn about it from the sensor data. We can avoid these
    cycle-to-cycle variations only in artificially ideal lab situations.

    6. Big shifts in distance from one reading to the next. Ten inches, three
    feet, what have you. The effect of a very wide beam angle on this sensor. If
    the echo from a near field object at the fringe of the beam is marginal, we
    might lock up on its echo one time in three or even less. When we do, it's
    distance will be reported. When we don't, the stronger echo from the more
    distant object will be reported. Both are valid distances, and your software
    must recognize this as indicating multiple objects in the beam pattern, not
    a sensor "error." This is characteristic of active sensors emitting a beam.
    It's just more evident when the beam cone is as wide as this one.

    Finally, if you're seriously bothered by the occasional missed reading
    because of timing at the interface, you can add a pulse delay to the trigger
    pulse using a 555 in monostable mode. This can be adjusted to push the
    actual trigger pulse far enough after the PULSOUT command that even a slow
    Stamp will always get to the next command before the Devantech can raise the
    echo line. Then you can use the PULSIN command to measure the result. Not
    all examples of the SRF04 will be subject to this problem. Production
    variation of components, supplier changes, and all these things affect
    analog circuits as well the environmental effects on a specific example once
    you have it in hand. So if your example does seem to have occasional timing
    problems at the interface, you can either ignore it or wire up a quick
    solution. Gotta be an app note around on that somewhere. If not, I'll post a
    circuit.

    In this situation, you're still missing the first part of the travel time
    for the acoustic pulse, because Devantech does not raise the echo line until
    they turn on the receiver, and they have to wait to do that until the tail
    end of the acoustic waveform passes the receiver. Plus a little bit to let
    ringing die down I suppose. Basically, you'll still need to calibrate that
    offset value I mentioned.

    Good luck, and don't expect too much of a $35 sensor<g>.

    Gary

    P.S. Has anyone seen a $35 LASER rangefinder we can fool around with? I'd
    even go to $40 or $41... Oh well<sigh>.
  • ArchiverArchiver Posts: 46,084
    edited 2003-10-14 07:57
    Gary W. Sims,
    Bravo, bravissimo!
    Dov Yassky
    Original Message
    From: "Gary W. Sims" <simsgw@c...>
    To: <basicstamps@yahoogroups.com>
    Sent: Tuesday, October 14, 2003 03:32
    Subject: Re: [noparse][[/noparse]basicstamps] SRF04 Ultrasonic Range Finder


    > From: "John Colonias" <jcolonias@i...>
    >
    >
    > > [noparse][[/noparse]...] still, occassionally, registers erroneous reading. I also noticed
    > that I
    > > get consistendly lower readings that what actually the distance should
    be,
    > > therefore, I thought of writing code to pick the highest of three
    > readings.
    > > Any better way ?
    >
    > The first thing you mention is easy to explain: the consistently low
    > readings. The measurement of pulse width begins a noticeable time period
    > after the leading edge of the acoustic pulse train leaves the emitter can.
    > At least 300 microseconds if you're using a fast Stamp and the PULSIN
    > command. A little bit longer if you're using a BS2 and the RCTIME command.
    > You need to calibrate this delay as an offset in the raw pulse
    measurement.
    > Don't worry about theory. Just take repeated measurements at a near
    distance
    > like 18" and determine how much to add the raw reading. It is a fixed
    offset
    > and not a percentage of the total range.
    >
    > As to the erroneous readings, I've been testing two examples of the SRF04
    > for a few weeks, John. Before playing with your code too much, consider
    what
    > you might expect from "perfect" code. If we're not careful, it's easy to
    > create a clean fiction in software that doesn't reflect the messy real
    > world. And from a sensor, we want data not fiction.
    >
    > Recognize that this is not a narrow-beam, high-frequency sensor. For
    > contrast, it specifically is NOT a laser rangefinder. Devantech's
    published
    > chart in the manual is interpreted by them as indicating a 30° beam width.
    > It looks more like 45° at least, and 60° for practical purposes. We're
    > talking about a couple of very small acoustic cans here. My point is that
    > for testing its performance, don't set the equipment on a cluttered
    tabletop
    > and expect consistent readings. Use a flat surface; a flat target plate to
    > provide a return; and nothing else above, below, left, or right of the
    beam
    > path to the target. This will avoid "erroneous" readings that actually are
    > giving you the valid distance to an intermediate object you didn't realize
    > was within that broad beam width.
    >
    > I'm not an acoustic engineer, so I wasn't sure if it would be a problem,
    but
    > I also turned off my in-computer stereo sound system while running tests.
    I
    > figured it couldn't hurt to be careful, and a lot of the music was
    creating
    > high energy levels at sub-harmonics of that 40 kHz frequency of the sonar.
    > For all I knew, that might lead to spurious lock-ups. If nothing else, the
    > music would add to the background noise level and thereby reduce the
    > signal-to-noise ratio the receiver will enjoy.
    >
    > Even with those precautions, don't expect the same raw reading each time.
    > Even with an artificially empty test environment, the real world is not
    that
    > smooth. Let me run down some of the causes I've seen for readings that
    seem
    > erratic to us.
    >
    > First, the Stamp is not an oscilloscope. It is counting discrete "ticks"
    of
    > it's own clock to measure the pulse duration on that echo line. The actual
    > duration necessarily falls on one side of the other of a "tick" boundary.
    > That means a raw reading of 1000 this time might be followed by 1001 and
    > then by 999 -- and they all would be right, with no way to choose a "best"
    > one. This is discretization error and it's inherent in assigning an
    integer
    > value to a real number.
    >
    > Second, this is a 40 kHz acoustic wave train at a pretty low energy level.
    > The receiver has to lock up on the reflected energy of that pulse in the
    > presence of acoustic energy of all sorts reaching that can. Without
    getting
    > into the theory of doing such, I seem to remember that the absolute
    > theoretical best for a phase-locked loop to detect the beginning of a wave
    > form is three cycles. It's been several decades since a true expert on
    this
    > subject told me that, so there's a ten percent chance I'm misremembering
    and
    > he said two cycles -- but I don't think so. The reason is I'm a stubborn
    guy
    > and I seem to remember him having to work hard to convince me it couldn't
    be
    > done one cycle sooner. Catching a waveform on the first cycle is just
    plain
    > silly so we surely were arguing about doing by the second, with him
    > insisting a third cycle was necessary.
    >
    > For the sake of argument, let's assume it takes three cycles in a best
    case.
    > Even in a cleaned-up test situation, you don't have a perfect signal and a
    > perfect sensor. So it's usually going to take much longer -- say five or
    six
    > cycles -- to "recognize" the returning waveform. That is, to lock up by
    > synchronizing with it. That "lock up" is what will drop the echo line and
    > terminate the pulse from the point of view of the Stamp. The sensor
    doesn't
    > know how many cycles it took to achieve lock-up, so it can't tell us even
    if
    > the interface gave us a way to ask.
    >
    > There actually are some tricky ways to approximate that, but this isn't a
    > billion dollar sonar suite on a submarine we're talking about. So the
    sensor
    > cannot tell us, because it does not "know" when the real leading edge
    > arrived for that returning echo.
    >
    > Lock up, schmock up. All we know is the echo line went low. What we can
    > observe is that it even after we take out the little variations of one
    Stamp
    > tick more or less, we still get "big" jumps of 12 to 13 clocks regularly.
    At
    > least I do with a BS2 conducting the tests. Your mileage with vary with a
    > Stamp that has a different clock rate. Because a little arithmetic
    explains
    > those jumps. This is 40 kHz signal. That's 40,000 times per second that it
    > goes from one peak of acoustic pressure to the next peak. Take the inverse
    > of 40,000 and you have 25 millionths, or 25 microseconds, from peak to
    peak.
    > We can't measure 25 microseconds from a BS2 -- only 24 microseconds or 26
    > microseconds. That's 12 clocks or 13 clocks.
    >
    > So every time the receiver takes one cycle more or less to lock up, we see
    a
    > jump of 12 or 13 clocks up or down. Or sometimes 25 clocks between one
    > "ping" and the next. Or even 36 to 40 clocks, because each reading must
    vary
    > up and down by a clock or two because of measurement resolution in the
    > stamp, and the sensor itself is varying by some multiple of 25
    microseconds
    > up or down because of the frequency of the waveform.
    >
    > 6. Don't average all this. I disagree with the Parallax app note on this
    > point. It was a good chance to teach people how to average values with a
    > limited number of bits available in the accumulator, but the average is
    not
    > appropriate to this raw data. (Technically, we say that this is not a
    > Gaussian source of noise, so the mean is not an appropriate metric.)
    > Instead, pick one answer and use that. The average will be some in-between
    > number whose only sure trait is being wrong. (It might land on the right
    > value like a stopped clock, but that's another joke for another day.) If
    you
    > feel compelled to use multiple pings when you've already got a valid
    > measurement, just put the results in "buckets" and pick the bucket that
    gets
    > the most hits. This still won't be any more "right" than the next bucket
    > over, because we have no idea how many cycles into the returning echo that
    > lock-up occurred. But it might be fun to try, and do it if it makes you
    feel
    > better about the answer your subroutine returns.
    >
    > 7. Don't use a rope as a micrometer. The acoustic wave train from this
    > sensor is two inches long for a reason. Well, probably. Maybe they did it
    > because they saw somebody else use that pulse width, but for the sake of
    > argument we'll assume that Devantech or that somebody else did the work to
    > know how likely it is to pick up the returning waveform in a particular
    > length of time -- that is, a particular pulse width. At short range in
    good
    > conditions, half that pulse duration might work 90% of the time. But we
    > can't pick our conditions when the sensor actually goes to work. Across
    the
    > usable range of the sensor, we're talking about multi-path returns
    > interfering with the waveform, noise spikes reducing some parts to a
    > signal-to-noise ratio too low for lock-up, phase distortions from umpteen
    > causes, and so forth and so on. I'm surprised a low cost receiver can lock
    > up in eight cycles as reliably as this one does. But those eight cycles
    are
    > needed sometimes, and we can't assume lock-up occurred at any particular
    > point in that returning waveform. The receiver may have locked up by the
    > third cycle, or it may not have locked until the eighth cycle.
    >
    > A precision of about two cycles is achieved under optimum conditions. In
    > other words, if I take that raw reading and divide by 25 clocks (or 50
    > microseconds), I start to get consistent reports from my subroutine. This
    is
    > optimum conditions remember. That flat plate target business with my robot
    > unmoving on a steady surface looking at a wall less than six inches away.
    > That precision is 0.45 inches or 1.1 cm in the raw counts. For
    convenience,
    > I multiplied by the range factor and report my result to the calling
    routine
    > in multiples of half an inch. After multiplying, I apply that offset I
    > mentioned at the beginning. Calibrated in half inches, because nothing
    > closer is meaningful.
    >
    > This half inch is the precision of course, NOT the accuracy unless
    > conditions are ideal. The accuracy of any particular return over the full
    > range cannot be assumed to be better than plus or minus four clocks unless
    > you are willing to take into account a lot other factors. You could, for
    > example, de-rate the expected accuracy in accordance with the reported
    > range. Personally, I don't expect an accurate resolution of less than one
    > inch even when looking straight down at a flat surface: a distance of 8.5"
    > for my robot. Not unless I know the surface is flat and no objects are
    down
    > there -- in which case I didn't need the sensor...
    >
    > 8. Finally, don't expect a reading every time. For two reasons. You didn't
    > specify what kind of erroneous results you were getting, so I can't guess
    > which applies. First, the echoes may return in such a gnarly garbled state
    > that the receiver never sees a clean enough sine wave to lock up. This
    > results in the echo line remaining high for 36 ms. On a BS2 your raw
    reading
    > will be about 18,000. The second possibility is a problem at the
    interface.
    > We have two devices here designed thousands of miles apart. Like men and
    > women, their timing will not always agree when they try to interface.
    >
    > That conditional compilation code deals with this by using one instruction
    > for the fast Stamps and another for the slow Stamps, but the Devantech
    unit
    > appears to be an analog interface design. That is, it is not controlled by
    a
    > crystal oscillator. (I can't imagine bothering. This is not a criticism,
    > just an explanation.) That means timing on its side of the interface will
    > vary with temperature of the components, which in turn varies with the
    duty
    > cycle of the emitter as well as the ambient. Sometimes a particular unit
    > could be a little too slow to raise the echo line for RCTIME to work, even
    > on the slower Stamps like my BS2. One of my examples was like that. I
    doubt
    > any unit would be fast enough to beat one of the faster Stamps using
    PULSIN,
    > but using PULSIN with the slower Stamps rarely works. Only occasionally
    will
    > the Devantech be slow enough for PULSIN to catch the leading edge of the
    > echo line.
    >
    > If your unit slows down just enough for the RCTIME command to be set up
    and
    > looking at the pin before the echo line is raised, then RCTIME will return
    a
    > value of one. This means "I looked for the signal condition you told me to
    > measure and it went away in one clock or less." Really, RCTIME was not
    > patient enough for the signal to appear in the first place, but we have to
    > supply the patience. Computers just do what we literally ask.
    >
    > So, the nasty messy reality of echoes and their detectors in the physical
    > world mean you should expect all sorts of differences from one call to the
    > next of the SRF04:
    >
    > 1. A simple 1. The sonar raised the echo line a little late for RCTIME to
    > work. Natural variation in analog components. Just include a loop to send
    > out pings until a result other than one is achieved.
    >
    > 2. A simple 0. The sonar raised the echo line a little early while you
    were
    > using a PULSIN to measure the result. Jon's new sample code does not do
    this
    > with the slower Stamps, but the old sample code did. Use RCTIME as Jon
    does.
    > Or if you insist, accept this also as a natural variation in analog
    > components and include a loop to send out pings until a result other than
    > zero is achieved. Expect to require a lot of pings sometimes to get a
    signal
    > valid range. I don't recommend this, understand. I'm just reporting my
    > results with this technique.
    >
    > 3. An equally simple 18000 (or so). No echo was detected. This is a valid
    > answer that means the nearest target is out of range.
    >
    > 4. Variation of one or two clocks up or down. Sometimes called "jitter",
    but
    > most of this is just the natural effect of examining data from an analog
    > event measured to a spurious digital precision. Nothing happening out
    there
    > is known to a resolution of two microseconds. Don't even bother looking at
    > the data until it's been reduced to the practical precision of half an
    inch
    > or so. Or centimeters if you prefer metric.
    >
    > 5. Variation of some multiple of 12 to 13 clocks up or down. Caused by
    > lock-up with the acoustic waveform occurring one or two cycles either way.
    > Or three or four. Not only natural, but inherent in any "interesting"
    > environment. That is, one where we're measuring an unknown reality and
    > attempting to learn about it from the sensor data. We can avoid these
    > cycle-to-cycle variations only in artificially ideal lab situations.
    >
    > 6. Big shifts in distance from one reading to the next. Ten inches, three
    > feet, what have you. The effect of a very wide beam angle on this sensor.
    If
    > the echo from a near field object at the fringe of the beam is marginal,
    we
    > might lock up on its echo one time in three or even less. When we do, it's
    > distance will be reported. When we don't, the stronger echo from the more
    > distant object will be reported. Both are valid distances, and your
    software
    > must recognize this as indicating multiple objects in the beam pattern,
    not
    > a sensor "error." This is characteristic of active sensors emitting a
    beam.
    > It's just more evident when the beam cone is as wide as this one.
    >
    > Finally, if you're seriously bothered by the occasional missed reading
    > because of timing at the interface, you can add a pulse delay to the
    trigger
    > pulse using a 555 in monostable mode. This can be adjusted to push the
    > actual trigger pulse far enough after the PULSOUT command that even a slow
    > Stamp will always get to the next command before the Devantech can raise
    the
    > echo line. Then you can use the PULSIN command to measure the result. Not
    > all examples of the SRF04 will be subject to this problem. Production
    > variation of components, supplier changes, and all these things affect
    > analog circuits as well the environmental effects on a specific example
    once
    > you have it in hand. So if your example does seem to have occasional
    timing
    > problems at the interface, you can either ignore it or wire up a quick
    > solution. Gotta be an app note around on that somewhere. If not, I'll post
    a
    > circuit.
    >
    > In this situation, you're still missing the first part of the travel time
    > for the acoustic pulse, because Devantech does not raise the echo line
    until
    > they turn on the receiver, and they have to wait to do that until the tail
    > end of the acoustic waveform passes the receiver. Plus a little bit to let
    > ringing die down I suppose. Basically, you'll still need to calibrate that
    > offset value I mentioned.
    >
    > Good luck, and don't expect too much of a $35 sensor<g>.
    >
    > Gary
    >
    > P.S. Has anyone seen a $35 LASER rangefinder we can fool around with? I'd
    > even go to $40 or $41... Oh well<sigh>.
    >
    >
    >
    > To UNSUBSCRIBE, just send mail to:
    > basicstamps-unsubscribe@yahoogroups.com
    > from the same email address that you subscribed. Text in the Subject and
    Body of the message will be ignored.
    >
    >
    > Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
    >
    >
  • ArchiverArchiver Posts: 46,084
    edited 2003-10-14 14:16
    Gary,

    Thanks for taking the time to reply in such a detailed manner. I agree with you
    that
    averaging in not the right way. Actually, I did disect the code and wrote a
    better
    averaging algorithm , but it was useless. The erroneous answers I was referring
    to
    were that they jumped around. One reading would be preety close to the actujal
    distance, the next almost 200% of, then the next pretty close to the previous,
    etc.
    That lead to believe that it would be better to selectively ignore those
    readings that
    deviate so much from a norm.
    I really dont expect great accuracy from a $35 device, but I will take your
    advices
    and play with it a little more.

    Thanks again,

    John

    On 13 Oct 2003 at 17:32, Gary W. Sims wrote:

    From: "John Colonias" <jcolonias@i...>


    > [noparse][[/noparse]...] still, occassionally, registers erroneous reading. I also noticed
    that I
    > get consistendly lower readings that what actually the distance should be,
    > therefore, I thought of writing code to pick the highest of three
    readings.
    > Any better way ?

    The first thing you mention is easy to explain: the consistently low
    readings. The measurement of pulse width begins a noticeable time period
    after the leading edge of the acoustic pulse train leaves the emitter can.
    At least 300 microseconds if you're using a fast Stamp and the PULSIN
    command. A little bit longer if you're using a BS2 and the RCTIME command.
    You need to calibrate this delay as an offset in the raw pulse measurement.
    Don't worry about theory. Just take repeated measurements at a near distance
    like 18" and determine how much to add the raw reading. It is a fixed offset
    and not a percentage of the total range.

    As to the erroneous readings, I've been testing two examples of the SRF04
    for a few weeks, John. Before playing with your code too much, consider what
    you might expect from "perfect" code. If we're not careful, it's easy to
    create a clean fiction in software that doesn't reflect the messy real
    world. And from a sensor, we want data not fiction.

    Recognize that this is not a narrow-beam, high-frequency sensor. For
    contrast, it specifically is NOT a laser rangefinder. Devantech's published
    chart in the manual is interpreted by them as indicating a 30° beam width.
    It looks more like 45° at least, and 60° for practical purposes. We're
    talking about a couple of very small acoustic cans here. My point is that
    for testing its performance, don't set the equipment on a cluttered tabletop
    and expect consistent readings. Use a flat surface; a flat target plate to
    provide a return; and nothing else above, below, left, or right of the beam
    path to the target. This will avoid "erroneous" readings that actually are
    giving you the valid distance to an intermediate object you didn't realize
    was within that broad beam width.

    I'm not an acoustic engineer, so I wasn't sure if it would be a problem, but
    I also turned off my in-computer stereo sound system while running tests. I
    figured it couldn't hurt to be careful, and a lot of the music was creating
    high energy levels at sub-harmonics of that 40 kHz frequency of the sonar.
    For all I knew, that might lead to spurious lock-ups. If nothing else, the
    music would add to the background noise level and thereby reduce the
    signal-to-noise ratio the receiver will enjoy.

    Even with those precautions, don't expect the same raw reading each time.
    Even with an artificially empty test environment, the real world is not that
    smooth. Let me run down some of the causes I've seen for readings that seem
    erratic to us.

    First, the Stamp is not an oscilloscope. It is counting discrete "ticks" of
    it's own clock to measure the pulse duration on that echo line. The actual
    duration necessarily falls on one side of the other of a "tick" boundary.
    That means a raw reading of 1000 this time might be followed by 1001 and
    then by 999 -- and they all would be right, with no way to choose a "best"
    one. This is discretization error and it's inherent in assigning an integer
    value to a real number.

    Second, this is a 40 kHz acoustic wave train at a pretty low energy level.
    The receiver has to lock up on the reflected energy of that pulse in the
    presence of acoustic energy of all sorts reaching that can. Without getting
    into the theory of doing such, I seem to remember that the absolute
    theoretical best for a phase-locked loop to detect the beginning of a wave
    form is three cycles. It's been several decades since a true expert on this
    subject told me that, so there's a ten percent chance I'm misremembering and
    he said two cycles -- but I don't think so. The reason is I'm a stubborn guy
    and I seem to remember him having to work hard to convince me it couldn't be
    done one cycle sooner. Catching a waveform on the first cycle is just plain
    silly so we surely were arguing about doing by the second, with him
    insisting a third cycle was necessary.

    For the sake of argument, let's assume it takes three cycles in a best case.
    Even in a cleaned-up test situation, you don't have a perfect signal and a
    perfect sensor. So it's usually going to take much longer -- say five or six
    cycles -- to "recognize" the returning waveform. That is, to lock up by
    synchronizing with it. That "lock up" is what will drop the echo line and
    terminate the pulse from the point of view of the Stamp. The sensor doesn't
    know how many cycles it took to achieve lock-up, so it can't tell us even if
    the interface gave us a way to ask.

    There actually are some tricky ways to approximate that, but this isn't a
    billion dollar sonar suite on a submarine we're talking about. So the sensor
    cannot tell us, because it does not "know" when the real leading edge
    arrived for that returning echo.

    Lock up, schmock up. All we know is the echo line went low. What we can
    observe is that it even after we take out the little variations of one Stamp
    tick more or less, we still get "big" jumps of 12 to 13 clocks regularly. At
    least I do with a BS2 conducting the tests. Your mileage with vary with a
    Stamp that has a different clock rate. Because a little arithmetic explains
    those jumps. This is 40 kHz signal. That's 40,000 times per second that it
    goes from one peak of acoustic pressure to the next peak. Take the inverse
    of 40,000 and you have 25 millionths, or 25 microseconds, from peak to peak.
    We can't measure 25 microseconds from a BS2 -- only 24 microseconds or 26
    microseconds. That's 12 clocks or 13 clocks.

    So every time the receiver takes one cycle more or less to lock up, we see a
    jump of 12 or 13 clocks up or down. Or sometimes 25 clocks between one
    "ping" and the next. Or even 36 to 40 clocks, because each reading must vary
    up and down by a clock or two because of measurement resolution in the
    stamp, and the sensor itself is varying by some multiple of 25 microseconds
    up or down because of the frequency of the waveform.

    6. Don't average all this. I disagree with the Parallax app note on this
    point. It was a good chance to teach people how to average values with a
    limited number of bits available in the accumulator, but the average is not
    appropriate to this raw data. (Technically, we say that this is not a
    Gaussian source of noise, so the mean is not an appropriate metric.)
    Instead, pick one answer and use that. The average will be some in-between
    number whose only sure trait is being wrong. (It might land on the right
    value like a stopped clock, but that's another joke for another day.) If you
    feel compelled to use multiple pings when you've already got a valid
    measurement, just put the results in "buckets" and pick the bucket that gets
    the most hits. This still won't be any more "right" than the next bucket
    over, because we have no idea how many cycles into the returning echo that
    lock-up occurred. But it might be fun to try, and do it if it makes you feel
    better about the answer your subroutine returns.

    7. Don't use a rope as a micrometer. The acoustic wave train from this
    sensor is two inches long for a reason. Well, probably. Maybe they did it
    because they saw somebody else use that pulse width, but for the sake of
    argument we'll assume that Devantech or that somebody else did the work to
    know how likely it is to pick up the returning waveform in a particular
    length of time -- that is, a particular pulse width. At short range in good
    conditions, half that pulse duration might work 90% of the time. But we
    can't pick our conditions when the sensor actually goes to work. Across the
    usable range of the sensor, we're talking about multi-path returns
    interfering with the waveform, noise spikes reducing some parts to a
    signal-to-noise ratio too low for lock-up, phase distortions from umpteen
    causes, and so forth and so on. I'm surprised a low cost receiver can lock
    up in eight cycles as reliably as this one does. But those eight cycles are
    needed sometimes, and we can't assume lock-up occurred at any particular
    point in that returning waveform. The receiver may have locked up by the
    third cycle, or it may not have locked until the eighth cycle.

    A precision of about two cycles is achieved under optimum conditions. In
    other words, if I take that raw reading and divide by 25 clocks (or 50
    microseconds), I start to get consistent reports from my subroutine. This is
    optimum conditions remember. That flat plate target business with my robot
    unmoving on a steady surface looking at a wall less than six inches away.
    That precision is 0.45 inches or 1.1 cm in the raw counts. For convenience,
    I multiplied by the range factor and report my result to the calling routine
    in multiples of half an inch. After multiplying, I apply that offset I
    mentioned at the beginning. Calibrated in half inches, because nothing
    closer is meaningful.

    This half inch is the precision of course, NOT the accuracy unless
    conditions are ideal. The accuracy of any particular return over the full
    range cannot be assumed to be better than plus or minus four clocks unless
    you are willing to take into account a lot other factors. You could, for
    example, de-rate the expected accuracy in accordance with the reported
    range. Personally, I don't expect an accurate resolution of less than one
    inch even when looking straight down at a flat surface: a distance of 8.5"
    for my robot. Not unless I know the surface is flat and no objects are down
    there -- in which case I didn't need the sensor...

    8. Finally, don't expect a reading every time. For two reasons. You didn't
    specify what kind of erroneous results you were getting, so I can't guess
    which applies. First, the echoes may return in such a gnarly garbled state
    that the receiver never sees a clean enough sine wave to lock up. This
    results in the echo line remaining high for 36 ms. On a BS2 your raw reading
    will be about 18,000. The second possibility is a problem at the interface.
    We have two devices here designed thousands of miles apart. Like men and
    women, their timing will not always agree when they try to interface.

    That conditional compilation code deals with this by using one instruction
    for the fast Stamps and another for the slow Stamps, but the Devantech unit
    appears to be an analog interface design. That is, it is not controlled by a
    crystal oscillator. (I can't imagine bothering. This is not a criticism,
    just an explanation.) That means timing on its side of the interface will
    vary with temperature of the components, which in turn varies with the duty
    cycle of the emitter as well as the ambient. Sometimes a particular unit
    could be a little too slow to raise the echo line for RCTIME to work, even
    on the slower Stamps like my BS2. One of my examples was like that. I doubt
    any unit would be fast enough to beat one of the faster Stamps using PULSIN,
    but using PULSIN with the slower Stamps rarely works. Only occasionally will
    the Devantech be slow enough for PULSIN to catch the leading edge of the
    echo line.

    If your unit slows down just enough for the RCTIME command to be set up and
    looking at the pin before the echo line is raised, then RCTIME will return a
    value of one. This means "I looked for the signal condition you told me to
    measure and it went away in one clock or less." Really, RCTIME was not
    patient enough for the signal to appear in the first place, but we have to
    supply the patience. Computers just do what we literally ask.

    So, the nasty messy reality of echoes and their detectors in the physical
    world mean you should expect all sorts of differences from one call to the
    next of the SRF04:

    1. A simple 1. The sonar raised the echo line a little late for RCTIME to
    work. Natural variation in analog components. Just include a loop to send
    out pings until a result other than one is achieved.

    2. A simple 0. The sonar raised the echo line a little early while you were
    using a PULSIN to measure the result. Jon's new sample code does not do this
    with the slower Stamps, but the old sample code did. Use RCTIME as Jon does.
    Or if you insist, accept this also as a natural variation in analog
    components and include a loop to send out pings until a result other than
    zero is achieved. Expect to require a lot of pings sometimes to get a signal
    valid range. I don't recommend this, understand. I'm just reporting my
    results with this technique.

    3. An equally simple 18000 (or so). No echo was detected. This is a valid
    answer that means the nearest target is out of range.

    4. Variation of one or two clocks up or down. Sometimes called "jitter", but
    most of this is just the natural effect of examining data from an analog
    event measured to a spurious digital precision. Nothing happening out there
    is known to a resolution of two microseconds. Don't even bother looking at
    the data until it's been reduced to the practical precision of half an inch
    or so. Or centimeters if you prefer metric.

    5. Variation of some multiple of 12 to 13 clocks up or down. Caused by
    lock-up with the acoustic waveform occurring one or two cycles either way.
    Or three or four. Not only natural, but inherent in any "interesting"
    environment. That is, one where we're measuring an unknown reality and
    attempting to learn about it from the sensor data. We can avoid these
    cycle-to-cycle variations only in artificially ideal lab situations.

    6. Big shifts in distance from one reading to the next. Ten inches, three
    feet, what have you. The effect of a very wide beam angle on this sensor. If
    the echo from a near field object at the fringe of the beam is marginal, we
    might lock up on its echo one time in three or even less. When we do, it's
    distance will be reported. When we don't, the stronger echo from the more
    distant object will be reported. Both are valid distances, and your software
    must recognize this as indicating multiple objects in the beam pattern, not
    a sensor "error." This is characteristic of active sensors emitting a beam.
    It's just more evident when the beam cone is as wide as this one.

    Finally, if you're seriously bothered by the occasional missed reading
    because of timing at the interface, you can add a pulse delay to the trigger
    pulse using a 555 in monostable mode. This can be adjusted to push the
    actual trigger pulse far enough after the PULSOUT command that even a slow
    Stamp will always get to the next command before the Devantech can raise the
    echo line. Then you can use the PULSIN command to measure the result. Not
    all examples of the SRF04 will be subject to this problem. Production
    variation of components, supplier changes, and all these things affect
    analog circuits as well the environmental effects on a specific example once
    you have it in hand. So if your example does seem to have occasional timing
    problems at the interface, you can either ignore it or wire up a quick
    solution. Gotta be an app note around on that somewhere. If not, I'll post a
    circuit.

    In this situation, you're still missing the first part of the travel time
    for the acoustic pulse, because Devantech does not raise the echo line until
    they turn on the receiver, and they have to wait to do that until the tail
    end of the acoustic waveform passes the receiver. Plus a little bit to let
    ringing die down I suppose. Basically, you'll still need to calibrate that
    offset value I mentioned.

    Good luck, and don't expect too much of a $35 sensor<g>.

    Gary

    P.S. Has anyone seen a $35 LASER rangefinder we can fool around with? I'd
    even go to $40 or $41... Oh well<sigh>.



    To UNSUBSCRIBE, just send mail to:
    basicstamps-unsubscribe@yahoogroups.com
    from the same email address that you subscribed. Text in the Subject and Body
    of the message will be ignored.


    Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
  • ArchiverArchiver Posts: 46,084
    edited 2003-10-15 21:05
    From: "John Colonias" <jcolonias@i...>

    > The erroneous answers I was referring to were that they jumped
    > around. One reading would be preety close to the actujal distance,
    > the next almost 200% of, then the next pretty close to the
    > previous, etc. That lead to believe that it would be better to
    > selectively ignore those readings that deviate so much from a norm.
    >
    Well, you could ignore the readings in a range that is not of interest.
    (That is, you could deal only with the closer returns for example.) Or you
    could treat them both as targets to evaluate. That's what we do in
    significant sensor applications.

    In your test situation, make sure you have that completely flat test bench I
    mentioned, and that the target is a fairly large flat plate. I'm betting one
    or the other distance reading will stop appearing once that's the case.

    The situation you describe is the result I got when secondary targets in the
    cone of the emitter were returning echos as well. Sometimes the primary
    would return the echo that locked up the PLL in the receiver, and sometimes
    one or the other secondary target would generate the lock-up.

    Gary
  • ArchiverArchiver Posts: 46,084
    edited 2003-10-15 22:36
    --- In basicstamps@yahoogroups.com, "John Colonias" <jcolonias@i...>
    wrote:
    > Help! Help!
    >
    > I thought I would not have any trouble with the SRF04, but I
    > seem to be unable to get consistent readings.
    > It seems to bounce over and over, and the readings are not
    > accurate.
    ...

    John,

    I feel compelled to reply if for nothing else to complete some of the
    comments.

    The SRF04 is not a PLL based unit (not hardware anyway, and most
    certainly not software). So the PLL acquisition time does not apply
    to it (and 3 cycles is certainly the lowest acquisition time - 1
    extra for discrimination). It is actually based on counting
    techniques (open loop in nature). Eight cycles is what was previously
    used in actual PLL-based devices (such as the Polaroid ranger).
    Devantech probably just figure (empirically) this was a good average
    number for the counting technique. If I read their code right, the
    SRF04 is nothing more than a tuned frequency counter.

    The main reason for erroneous readings should be the sample rate if
    nothing else. The BS2 samples from what I gather here at 25usec,
    which is not really that inadequate for something that travels at
    74usec/in (approx). A PIC would give a better resolution at 1-2usec.
    But even with the BS2, if you were at the theoretical limit
    (~3.5cm),that is only 25% variation (and gets better as your distance
    increases).

    Now, I believe the 25usec instruction cycle time is average. The BS2
    is not really good for accurate timing because everything is
    interpreted (i.e., you have no real control of the timing). An MCU is
    ideal for something like this because you can control the timing down
    to the cycle time. Anyway, averaging is simple but as was mentioned
    it is not the proper way to interpret the signal. Mainly, because if
    nothing else you will be averaging the own measurement system error
    as well as the multi-path signal error. God knows what answer you get?

    In a good receiver system (where the measurement system is
    consistent - precise) your main source of error is the signal
    environment. You already know the signal statistics since you're
    generating it, you also can estimate the environment and thus create
    a good detector (discriminator) for the new statistics. In any case,
    a good trick used in such systems is the median. This is nothing else
    than accumulating returns in different 'bins' and selecting the one
    with the most (same as a histogram). On a reliable system (note that
    I would not consider the BS2 timing as reliable - or repeatable I
    should say), this method 'throws' out the outliers and uses the
    strongest return. Not by signal strength, which gives you the closest
    one (most likely a non-primary path), but by statistical strength.
    This is used in almost any pulsed radar detection scheme (for clutter
    reduction and many other things) but it is much more complex than
    this description. The sampling rate must be enough to guarantee
    return at maximum distance (i.e. power), the pulse width gives you
    the best resolution (with no additional signal processing), and all
    this have to be selected so the samples can be considered
    statistically independent to some degree.

    I know this is far more than the original question, but I felt the
    need to complete an other wise very good answer.

    Langue.
  • ArchiverArchiver Posts: 46,084
    edited 2003-10-15 23:04
    Both RCTIME and PULSIN deliver 2 uSec resolution, not 25 uSec as
    suggested below. The unit is "noisy" (readings will bounce around a
    bit) so it is best to take several samples and average.

    -- Jon Williams
    -- Applications Engineer, Parallax
    -- Dallas Office



    Original Message
    From: languer [noparse]/noparse]mailto:[url=http://forums.parallaxinc.com/group/basicstamps/post?postID=B8QgwlnjUd6u8sw-1OATyB9rYO0pVYYS7z5RZnmOdlMUsJ1IGv97QH8sqG0tBlIyI80EaVHiEm78mhYq3tIzB-rDbkw]langue_rodriguez@m...[/url
    Sent: Wednesday, October 15, 2003 4:36 PM
    To: basicstamps@yahoogroups.com
    Subject: [noparse][[/noparse]basicstamps] Re: SRF04 Ultrasonic Range Finder


    --- In basicstamps@yahoogroups.com, "John Colonias" <jcolonias@i...>
    wrote:
    > Help! Help!
    >
    > I thought I would not have any trouble with the SRF04, but I
    > seem to be unable to get consistent readings.
    > It seems to bounce over and over, and the readings are not
    > accurate.
    ...

    John,

    I feel compelled to reply if for nothing else to complete some of the
    comments.

    The SRF04 is not a PLL based unit (not hardware anyway, and most
    certainly not software). So the PLL acquisition time does not apply
    to it (and 3 cycles is certainly the lowest acquisition time - 1
    extra for discrimination). It is actually based on counting
    techniques (open loop in nature). Eight cycles is what was previously
    used in actual PLL-based devices (such as the Polaroid ranger).
    Devantech probably just figure (empirically) this was a good average
    number for the counting technique. If I read their code right, the
    SRF04 is nothing more than a tuned frequency counter.

    The main reason for erroneous readings should be the sample rate if
    nothing else. The BS2 samples from what I gather here at 25usec,
    which is not really that inadequate for something that travels at
    74usec/in (approx). A PIC would give a better resolution at 1-2usec.
    But even with the BS2, if you were at the theoretical limit
    (~3.5cm),that is only 25% variation (and gets better as your distance
    increases).

    Now, I believe the 25usec instruction cycle time is average. The BS2
    is not really good for accurate timing because everything is
    interpreted (i.e., you have no real control of the timing). An MCU is
    ideal for something like this because you can control the timing down
    to the cycle time. Anyway, averaging is simple but as was mentioned
    it is not the proper way to interpret the signal. Mainly, because if
    nothing else you will be averaging the own measurement system error
    as well as the multi-path signal error. God knows what answer you get?

    In a good receiver system (where the measurement system is
    consistent - precise) your main source of error is the signal
    environment. You already know the signal statistics since you're
    generating it, you also can estimate the environment and thus create
    a good detector (discriminator) for the new statistics. In any case,
    a good trick used in such systems is the median. This is nothing else
    than accumulating returns in different 'bins' and selecting the one
    with the most (same as a histogram). On a reliable system (note that
    I would not consider the BS2 timing as reliable - or repeatable I
    should say), this method 'throws' out the outliers and uses the
    strongest return. Not by signal strength, which gives you the closest
    one (most likely a non-primary path), but by statistical strength.
    This is used in almost any pulsed radar detection scheme (for clutter
    reduction and many other things) but it is much more complex than
    this description. The sampling rate must be enough to guarantee
    return at maximum distance (i.e. power), the pulse width gives you
    the best resolution (with no additional signal processing), and all
    this have to be selected so the samples can be considered
    statistically independent to some degree.

    I know this is far more than the original question, but I felt the
    need to complete an other wise very good answer.

    Langue.



    To UNSUBSCRIBE, just send mail to:
    basicstamps-unsubscribe@yahoogroups.com
    from the same email address that you subscribed. Text in the Subject
    and Body of the message will be ignored.


    Your use of Yahoo! Groups is subject to
    http://docs.yahoo.com/info/terms/




    This message has been scanned by WebShield. Please report SPAM to
    abuse@p....
  • ArchiverArchiver Posts: 46,084
    edited 2003-10-16 00:08
    --- In basicstamps@yahoogroups.com, "Jon Williams" <jwilliams@p...>
    wrote:
    > Both RCTIME and PULSIN deliver 2 uSec resolution, not 25 uSec as
    > suggested below. The unit is "noisy" (readings will bounce around a
    > bit) so it is best to take several samples and average.
    >
    > -- Jon Williams
    > -- Applications Engineer, Parallax
    > -- Dallas Office
    ...

    I stand corrected, 2usec resolution is right. In my mind (not really
    knowing how the tokens in the Stamp are structured), what you do not
    have control over is the instruction timing. Once the instruction is
    initiated and the pulse goes out you can discriminate between pulses
    2usec apart, but you can not tell the overall return with such
    accuracy (i.e. the time from the pulse initiation 'PULSOUT' to the
    actual time the measurement starts 'RCTIME'). Or maybe you can?

    langue.
  • ArchiverArchiver Posts: 46,084
    edited 2003-10-16 01:20
    The instruction setups (fetch from EEPROM, unpack, setup) have been
    timed by some Stamp users but are usually not useful nor required. The
    tricky part about the SRF04 is that the setup time for PULSIN on the BS2
    and BS2e can take longer than the delay between the trigger and the
    front-end of the echo input -- so the low-to-high transition is missed.
    Hence the use of RCTIME with the BS2 and BS2e, which is just looking
    (the way we use it in the demo) for a high-to-low transition.

    -- Jon Williams
    -- Applications Engineer, Parallax
    -- Dallas Office


    Original Message
    From: languer [noparse]/noparse]mailto:[url=http://forums.parallaxinc.com/group/basicstamps/post?postID=h3KGNHY4jBzLZUFrlCPFtoXfV1rU2tABj5FaazLq5Xv6p4a5MEDsZSjredi4PEbTnICAnw92AtTpyEZFqLPtAVpyKRPh2Q]langue_rodriguez@m...[/url
    Sent: Wednesday, October 15, 2003 6:08 PM
    To: basicstamps@yahoogroups.com
    Subject: [noparse][[/noparse]basicstamps] Re: SRF04 Ultrasonic Range Finder


    --- In basicstamps@yahoogroups.com, "Jon Williams" <jwilliams@p...>
    wrote:
    > Both RCTIME and PULSIN deliver 2 uSec resolution, not 25 uSec as
    > suggested below. The unit is "noisy" (readings will bounce around a
    > bit) so it is best to take several samples and average.
    >
    > -- Jon Williams
    > -- Applications Engineer, Parallax
    > -- Dallas Office
    ...

    I stand corrected, 2usec resolution is right. In my mind (not really
    knowing how the tokens in the Stamp are structured), what you do not
    have control over is the instruction timing. Once the instruction is
    initiated and the pulse goes out you can discriminate between pulses
    2usec apart, but you can not tell the overall return with such
    accuracy (i.e. the time from the pulse initiation 'PULSOUT' to the
    actual time the measurement starts 'RCTIME'). Or maybe you can?

    langue.



    To UNSUBSCRIBE, just send mail to:
    basicstamps-unsubscribe@yahoogroups.com
    from the same email address that you subscribed. Text in the Subject
    and Body of the message will be ignored.


    Your use of Yahoo! Groups is subject to
    http://docs.yahoo.com/info/terms/




    This message has been scanned by WebShield. Please report SPAM to
    abuse@p....
  • ArchiverArchiver Posts: 46,084
    edited 2003-10-16 01:37
    The time elapsed from the end of a PULSOUT to the point where PULSIN
    is ready to accept an input pulse is close to 240 microseconds. At
    1100 feet per second, sound can travel about 3 inches during that
    dead time.

    The time that the stamp interpreter takes to read the commands is
    quite deterministic. There is only a small dependence on position in
    memory and exact values of pin numbers etc.

    RCtime is a little faster, 220 microseconds. I have timing data I
    collected as well as some that Steve Parkis contributed, posted at
    http://www.emesystems.com/BS2speed.htm
    Input commands like PULSIN and RCtime were a little tricky. I
    measured those latencies by feeding the Stamp pin a high frequency
    signal, so it would trigger ASAP.

    An range finder needs to be calibrated empirically. But it should
    come out pretty close to theory!

    -- Tracy




    >--- In basicstamps@yahoogroups.com, "Jon Williams" <jwilliams@p...>
    >wrote:
    >> Both RCTIME and PULSIN deliver 2 uSec resolution, not 25 uSec as
    >> suggested below. The unit is "noisy" (readings will bounce around a
    >> bit) so it is best to take several samples and average.
    >>
    >> -- Jon Williams
    >> -- Applications Engineer, Parallax
    >> -- Dallas Office
    >...
    >
    >I stand corrected, 2usec resolution is right. In my mind (not really
    >knowing how the tokens in the Stamp are structured), what you do not
    >have control over is the instruction timing. Once the instruction is
    >initiated and the pulse goes out you can discriminate between pulses
    >2usec apart, but you can not tell the overall return with such
    >accuracy (i.e. the time from the pulse initiation 'PULSOUT' to the
    >actual time the measurement starts 'RCTIME'). Or maybe you can?
    >
    >langue.
  • ArchiverArchiver Posts: 46,084
    edited 2003-10-16 07:54
    From: "languer" <langue_rodriguez@m...>
    >
    > The SRF04 is not a PLL based unit (not hardware anyway, and most
    > certainly not software). So the PLL acquisition time does not apply
    > to it [noparse][[/noparse]...] It is actually based on counting techniques [noparse][[/noparse]...]
    >
    Langue's comments made me curious enough to dig up the design material for
    the Devantech unit. The schematic is a curious blend of digital and analog
    circuit techniques. The designer's own comments are available at
    http://makeashorterlink.com/?P4E921A36 and you can link to the PIC code and
    the schematic from that page if you'd like to see it also.

    As Langue says, the designer does not use a PLL IC, which caught me by
    surprise. [noparse][[/noparse]Feel free to delete all after if you don't give a hoot how
    Devantech did their sonar<g>.] He simply amplifies the signal from the
    piezoelectric transducer with a couple of op-amps in series and then runs an
    LM311 comparator on the result. The digital output from that chip is watched
    by the PIC microcontroller. It times the interval between falling edges --
    the high-to-low transitions -- and accepts anything between 22 and 30
    microseconds as being an echo of the eight square-wave pulses he just
    transmitted. If he gets three transitions in a row, spaced appropriately, he
    calls it a valid echo of his pulse. Any missed edge, and he restarts the
    count.

    Looking at the schematic in conjunction with the code, it is not really a
    frequency counter, but I can see how it looked like one from the PIC code
    with no schematic. It wouldn't take much of a change to use it that way, but
    he never really produces a frequency except by inference, because he will
    accept the transitions created by anything from 33 kHz to 45 kHz. Three
    consecutive transitions, or cycles. Just like a PLL.

    Like most designs seen for the first time, this technique puzzled me at
    first. He does "acquire" in the sense a digital designer might use the word,
    but it's nothing like the phase lock that is meant by acquisition in an
    analog context. It's rather like treating the signal as acoustic bits. It's
    reminiscent of our old delay-line memories, where you transmit the bits you
    want to remember and then catch them when they come back and re-transmit
    them. [noparse][[/noparse]See your local Smithsonian...] Makes me wonder if this guy is my age
    or just successfully re-invented a smallish wheel.

    Actually, I'm still puzzled about his reasons after thinking about it. PLL's
    are not priced like resistors, but they're pretty cheap chips, and emitting
    a square wave signal as a sensor does interesting things to your return in
    different conditions. My doctor sometimes uses the word that way for my test
    results: "Ah. This is interesting..."

    But basically, his objective was to make a smaller unit than the Polaroid at
    lower cost, and it works. So he did his job. He takes longer than a PLL to
    lock up in noisy conditions (at least I think so after a quick review), but
    he carefully specifies a lack of interest in ranges where that is likely to
    be the case. (Not that he puts it that way.) In other words, he may have
    used a technique that cost him range, but he decided the grapes were sour
    that far out on the vine anyway.

    The only performance objective was to reduce the minimum range compared to
    the Polaroid Ranger. Minimum. Not maximum range. Polaroid uses a much longer
    blanking interval, I gather. He avoided that necessity by observing that any
    return from short range is a much stronger signal than the ringing from the
    nearby emitter. (In this context, "ringing" actually means the mechanical
    vibrations that continue after the powered pulses have quit.) So instead of
    blanking until that ringing quits, he substituted a period of very reduced
    sensitivity that gradually returns to full sensitivity. Very nice.

    > The main reason for erroneous readings should be the sample rate if
    > nothing else. The BS2 samples from what I gather here at 25usec,

    I'm sure the misunderstanding here arose from that code listing without a
    schematic. Jon Williams already has mentioned the actual speed of the BS2.
    And of course, it's not the BS2 doing any of that stuff the code describes,
    it's the other microcontroller -- the one on the SRF-04 board itself. You're
    right that it does sample though.

    The code mentions a 25 usec cycle, but it's referring to the time between
    transitions from the LM311 while observing a valid signal. While waiting, it
    samples at 2 usec intervals. Hmmm. Actually, this is very interesting... I
    had started to say that his code is vulnerable to higher frequencies being
    misrecognized as valid, because he samples every two usec while waiting for
    a transition, but he goes away for fifteen usec or so every time he catchs a
    transition. A transition during that period will be missed. That would be
    another defect of not using a PLL, but I went back to re-read the code
    before making that assertion...

    When I did, I spotted a comment I missed the first time. Suddenly I'm not
    puzzled any more. The SRF-04 does not do any frequency checks at all. At
    least not in the code. Could, but does not. All that stuff about counting
    three bits -- all that was hypothetical. The code is there, but what he
    used for the production model is a single transition from the comparator. He
    relies on the piezo transducer to keep signals of the wrong frequency from
    reaching the LM311. So as soon as he gets that first transition, he drops
    the echo line. Reporting what would be a phase lock condition in a PLL, but
    since he doesn't wait for any fancy shmancy lock up, he won't be affected by
    all that three-cycle stuff, will he? Free at last of analog nonsense! Well,
    not really. The world is analog. Suck it up.

    This just means all that stuff about phase-locked loops comes back into
    play, but in an interesting way I admit. Such circuits were conceived in the
    early twentieth century as a way to achieve the behavior of a wine glass in
    the presence of a strong acoustic signal, or the waves in a tidal race like
    the Bay of Fundy, or what have you: the ability of some objects to achieve
    phase resonance with an impinging energy source. And this designer is saying
    that he chose (or was given as a precondition) a piezoelectric component
    with a strong notch, a very narrow band of frequencies for which it will
    resonate and produce an output signal. I can't find a spec on that piece, so
    we'll have to take his word for it -- but it's a credible assertion. (And
    the device works sitting here on my desk, so...)

    On the other hand, I can't think of any reason why such a device would
    escape the same limitations and sources of error as a conventional PLL,
    which is derived from those physical phenomena after all. But I had fun
    trying<g>. Sadly, we're back to the original problem of phase lock, and
    which cycle of the echo is going to be "caught" -- it's just an
    electro-mechanical origin instead of a modern PLL circuit.

    >
    > I know this is far more than the original question, but I felt the
    > need to complete an other wise very good answer.
    >
    Me too, Langue. We've gone far off the basic question, which was "why do I
    get funky answers from my SRF-04?" if I remember correctly, but personally
    I'm glad we did. I understand my unit a lot better now after reviewing the
    design material.

    Did you catch all that, John? We said: "Funky answers? Murphy's Law." None
    of the rest matters unless you also wanted to know to how it worked.

    Gary
  • ArchiverArchiver Posts: 46,084
    edited 2003-10-16 16:42
    Gary et All

    I have been reading all the materail that you guys have been writing and I
    have been experimenting at the same time, because it seems like that one has to
    empirically "tune" his device to perform according to specs.

    So my results are the following: The SRF-04 gives bursts of consisted readings
    at
    perhaps two or three levels. For example, I set up the Bot at a distance of
    exactly
    1.0 ft from a wall. The SRF-04 produced 4 readings showing 9.6" and 3 readings
    showing 11.8". Well, encouraged, I changed the distance to 2 ft. and expected a

    reading of 19.2". I did get 2 readings of 19.2 and 3 readings of 23.8.

    I played with a lot of various conditions and all produced similar results. My
    strategy, then is to create stacks of readings, maybe 8-10 and set them up in
    similar
    piles. Then choose the one reading that has the most hits.

    I am very pleased with the device now that I understand better its
    idiosyncrasies.

    Thanks to all those who have contributed to this understanding. Once, I have it
    tuned I will report my results.

    John

    On 15 Oct 2003 at 23:54, Gary W. Sims wrote:

    From: "languer" <langue_rodriguez@m...>
    >
    > The SRF04 is not a PLL based unit (not hardware anyway, and most
    > certainly not software). So the PLL acquisition time does not apply
    > to it [noparse][[/noparse]...] It is actually based on counting techniques [noparse][[/noparse]...]
    >
    Langue's comments made me curious enough to dig up the design material for
    the Devantech unit. The schematic is a curious blend of digital and analog
    circuit techniques. The designer's own comments are available at
    http://makeashorterlink.com/?P4E921A36 and you can link to the PIC code and
    the schematic from that page if you'd like to see it also.

    As Langue says, the designer does not use a PLL IC, which caught me by
    surprise. [noparse][[/noparse]Feel free to delete all after if you don't give a hoot how
    Devantech did their sonar<g>.] He simply amplifies the signal from the
    piezoelectric transducer with a couple of op-amps in series and then runs an
    LM311 comparator on the result. The digital output from that chip is watched
    by the PIC microcontroller. It times the interval between falling edges --
    the high-to-low transitions -- and accepts anything between 22 and 30
    microseconds as being an echo of the eight square-wave pulses he just
    transmitted. If he gets three transitions in a row, spaced appropriately, he
    calls it a valid echo of his pulse. Any missed edge, and he restarts the
    count.

    Looking at the schematic in conjunction with the code, it is not really a
    frequency counter, but I can see how it looked like one from the PIC code
    with no schematic. It wouldn't take much of a change to use it that way, but
    he never really produces a frequency except by inference, because he will
    accept the transitions created by anything from 33 kHz to 45 kHz. Three
    consecutive transitions, or cycles. Just like a PLL.

    Like most designs seen for the first time, this technique puzzled me at
    first. He does "acquire" in the sense a digital designer might use the word,
    but it's nothing like the phase lock that is meant by acquisition in an
    analog context. It's rather like treating the signal as acoustic bits. It's
    reminiscent of our old delay-line memories, where you transmit the bits you
    want to remember and then catch them when they come back and re-transmit
    them. [noparse][[/noparse]See your local Smithsonian...] Makes me wonder if this guy is my age
    or just successfully re-invented a smallish wheel.

    Actually, I'm still puzzled about his reasons after thinking about it. PLL's
    are not priced like resistors, but they're pretty cheap chips, and emitting
    a square wave signal as a sensor does interesting things to your return in
    different conditions. My doctor sometimes uses the word that way for my test
    results: "Ah. This is interesting..."

    But basically, his objective was to make a smaller unit than the Polaroid at
    lower cost, and it works. So he did his job. He takes longer than a PLL to
    lock up in noisy conditions (at least I think so after a quick review), but
    he carefully specifies a lack of interest in ranges where that is likely to
    be the case. (Not that he puts it that way.) In other words, he may have
    used a technique that cost him range, but he decided the grapes were sour
    that far out on the vine anyway.

    The only performance objective was to reduce the minimum range compared to
    the Polaroid Ranger. Minimum. Not maximum range. Polaroid uses a much longer
    blanking interval, I gather. He avoided that necessity by observing that any
    return from short range is a much stronger signal than the ringing from the
    nearby emitter. (In this context, "ringing" actually means the mechanical
    vibrations that continue after the powered pulses have quit.) So instead of
    blanking until that ringing quits, he substituted a period of very reduced
    sensitivity that gradually returns to full sensitivity. Very nice.

    > The main reason for erroneous readings should be the sample rate if
    > nothing else. The BS2 samples from what I gather here at 25usec,

    I'm sure the misunderstanding here arose from that code listing without a
    schematic. Jon Williams already has mentioned the actual speed of the BS2.
    And of course, it's not the BS2 doing any of that stuff the code describes,
    it's the other microcontroller -- the one on the SRF-04 board itself. You're
    right that it does sample though.

    The code mentions a 25 usec cycle, but it's referring to the time between
    transitions from the LM311 while observing a valid signal. While waiting, it
    samples at 2 usec intervals. Hmmm. Actually, this is very interesting... I
    had started to say that his code is vulnerable to higher frequencies being
    misrecognized as valid, because he samples every two usec while waiting for
    a transition, but he goes away for fifteen usec or so every time he catchs a
    transition. A transition during that period will be missed. That would be
    another defect of not using a PLL, but I went back to re-read the code
    before making that assertion...

    When I did, I spotted a comment I missed the first time. Suddenly I'm not
    puzzled any more. The SRF-04 does not do any frequency checks at all. At
    least not in the code. Could, but does not. All that stuff about counting
    three bits -- all that was hypothetical. The code is there, but what he
    used for the production model is a single transition from the comparator. He
    relies on the piezo transducer to keep signals of the wrong frequency from
    reaching the LM311. So as soon as he gets that first transition, he drops
    the echo line. Reporting what would be a phase lock condition in a PLL, but
    since he doesn't wait for any fancy shmancy lock up, he won't be affected by
    all that three-cycle stuff, will he? Free at last of analog nonsense! Well,
    not really. The world is analog. Suck it up.

    This just means all that stuff about phase-locked loops comes back into
    play, but in an interesting way I admit. Such circuits were conceived in the
    early twentieth century as a way to achieve the behavior of a wine glass in
    the presence of a strong acoustic signal, or the waves in a tidal race like
    the Bay of Fundy, or what have you: the ability of some objects to achieve
    phase resonance with an impinging energy source. And this designer is saying
    that he chose (or was given as a precondition) a piezoelectric component
    with a strong notch, a very narrow band of frequencies for which it will
    resonate and produce an output signal. I can't find a spec on that piece, so
    we'll have to take his word for it -- but it's a credible assertion. (And
    the device works sitting here on my desk, so...)

    On the other hand, I can't think of any reason why such a device would
    escape the same limitations and sources of error as a conventional PLL,
    which is derived from those physical phenomena after all. But I had fun
    trying<g>. Sadly, we're back to the original problem of phase lock, and
    which cycle of the echo is going to be "caught" -- it's just an
    electro-mechanical origin instead of a modern PLL circuit.

    >
    > I know this is far more than the original question, but I felt the
    > need to complete an other wise very good answer.
    >
    Me too, Langue. We've gone far off the basic question, which was "why do I
    get funky answers from my SRF-04?" if I remember correctly, but personally
    I'm glad we did. I understand my unit a lot better now after reviewing the
    design material.

    Did you catch all that, John? We said: "Funky answers? Murphy's Law." None
    of the rest matters unless you also wanted to know to how it worked.

    Gary




    To UNSUBSCRIBE, just send mail to:
    basicstamps-unsubscribe@yahoogroups.com
    from the same email address that you subscribed. Text in the Subject and Body
    of the message will be ignored.


    Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
  • ArchiverArchiver Posts: 46,084
    edited 2003-10-16 20:21
    The way that the police radar I have works, is that it looks for 5
    consecutive readings that agree<G>. With a complex target, it is possible
    to get reflections and echos back that are confusing. I built my own
    doppler radar and found that I had seriously bouncing data. I built a
    coincidence counter, where if it found two speeds that agreed, it would
    display the speeds. The 2 coincidence indicator worked "better," but was
    still insufficient. It was at that point I received the police radar and
    found out about the 5 consecutive readings.

    Though my radars were looking for speed instead of range, I would think that
    the problems would be similar.

    Original Message
    From: Gary W. Sims [noparse]/noparse]mailto:[url=http://forums.parallaxinc.com/group/basicstamps/post?postID=S84mL7DUU0D09d_w6d97_WxydiHoODIE8MQhzCPRxlyE63AO2L2d24NicwCjxZDi1ILEfgLudtKkyI9W1fAPNw]simsgw@c...[/url
    Sent: Wednesday, October 15, 2003 4:06 PM
    To: basicstamps@yahoogroups.com
    Subject: Re: [noparse][[/noparse]basicstamps] SRF04 Ultrasonic Range Finder


    From: "John Colonias" <jcolonias@i...>

    > The erroneous answers I was referring to were that they jumped around.
    > One reading would be preety close to the actujal distance, the next
    > almost 200% of, then the next pretty close to the previous, etc. That
    > lead to believe that it would be better to selectively ignore those
    > readings that deviate so much from a norm.
    >
    Well, you could ignore the readings in a range that is not of interest.
    (That is, you could deal only with the closer returns for example.) Or you
    could treat them both as targets to evaluate. That's what we do in
    significant sensor applications.

    In your test situation, make sure you have that completely flat test bench I
    mentioned, and that the target is a fairly large flat plate. I'm betting one
    or the other distance reading will stop appearing once that's the case.

    The situation you describe is the result I got when secondary targets in the
    cone of the emitter were returning echos as well. Sometimes the primary
    would return the echo that locked up the PLL in the receiver, and sometimes
    one or the other secondary target would generate the lock-up.

    Gary




    To UNSUBSCRIBE, just send mail to:
    basicstamps-unsubscribe@yahoogroups.com
    from the same email address that you subscribed. Text in the Subject and
    Body of the message will be ignored.


    Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
  • ArchiverArchiver Posts: 46,084
    edited 2003-10-17 16:38
    On 7 Oct 2003 at 12:46, John Colonias wrote:

    Jon

    Thank you very much. I will try it tonight when I get home, and let you know
    tomorrow.

    John

    On 7 Oct 2003 at 9:56, Jon Williams wrote:

    We've got new code on our web site. The problem is that a firmware
    change in the SRF04 (which you cannot identify just by looking at it)
    seemed to cause our original code to have problems. I spent a day last
    week rewriting the code so that it will work with old or new SRF04 units
    and on any of our BS2 micros.

    Here's the link:

    http://www.parallax.com/detail.asp?product_id=28015

    -- Jon Williams
    -- Applications Engineer, Parallax
    -- Dallas Office




    Original Message
    From: John Colonias [noparse]/noparse]mailto:[url=http://forums.parallaxinc.com/group/basicstamps/post?postID=VfGMzVCMiq4pgKjdqDD1Jw60p-VaIX5TIFeCWB8btuZ75RxKMCYV2Cs5QfAevltW97naqHNOH1hpJNT0ZqxnsLd-]jcolonias@i...[/url
    Sent: Tuesday, October 07, 2003 11:34 AM
    To: basicstamps@yahoogroups.com
    Subject: [noparse][[/noparse]basicstamps] SRF04 Ultrasonic Range Finder


    Help! Help!

    I thought I would not have any trouble with the SRF04, but I
    seem to be unable to get consistent readings.
    It seems to bounce over and over, and the readings are not
    accurate.

    Specifically, part of the code that I run ( from Nuts & Bolts)
    is the following:
    (All the initializations and parameter settings have been done
    earlier)

    Main:
    GOSUB Get_Sonar ' take sonar reading
    DEBUG MoveTo, 15, 3
    temp = rawDist
    GOSUB RJ_Print ' display raw value

    DEBUG MoveTo, 15, 4
    distance = rawDist ** 8886 ' divide by 7.3746
    temp = distance / 10
    GOSUB RJ_Print ' display inches
    DEBUG ".", DEC1 distance

    DEBUG MoveTo, 15, 5
    distance = rawDist ** 22572 ' divide by 2.9033
    temp = distance / 10
    GOSUB RJ_Print ' display centimeters
    DEBUG ".", DEC1 distance

    PAUSE 200 ' delay between readings
    GOTO main

    If I replace "GOTO main" with END, and run the code over
    and over,
    I get totally inconsistent and erroneour readings. I thought
    there was something wrong with the
    SRF04 itself, and I send back to Parallax, but, it was
    returned with the message that there is
    nothing wrong with it.

    What am I doing wrong? Please help!!!!!


    To UNSUBSCRIBE, just send mail to:
    basicstamps-unsubscribe@yahoogroups.com
    from the same email address that you subscribed. Text in the Subject
    and Body of the message will be ignored.


    Your use of Yahoo! Groups is subject to
    http://docs.yahoo.com/info/terms/




    This message has been scanned by WebShield. Please report SPAM to
    abuse@p....


    To UNSUBSCRIBE, just send mail to:
    basicstamps-unsubscribe@yahoogroups.com
    from the same email address that you subscribed. Text in the Subject and Body
    of the message will be ignored.


    Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/



    To UNSUBSCRIBE, just send mail to:
    basicstamps-unsubscribe@yahoogroups.com
    from the same email address that you subscribed. Text in the Subject and Body
    of the message will be ignored.


    Your use of Yahoo! Groups is subject to http://docs.yahoo.com/info/terms/
Sign In or Register to comment.