1

I have a ultrasonic sensor and in order to get the distance I use the pulseIn() function included in the arduino library, and then change it to distance. As the ultrasounds does not work equally in different materials as i have seen in Performance comparison of Infrared and Ultrasonic sensors for obstacles of different materials in vehicle/ robot navigation applications. My question is if there is a way of changing the pulseIn() to have different materials, function:

unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout)
{
    // cache the port and bit of the pin in order to speed up the
    // pulse width measuring loop and achieve finer resolution.  calling
    // digitalRead() instead yields much coarser resolution.
    uint8_t bit = digitalPinToBitMask(pin);
    uint8_t port = digitalPinToPort(pin);
    uint8_t stateMask = (state ? bit : 0);

    // convert the timeout from microseconds to a number of times through
    // the initial loop; it takes approximately 16 clock cycles per iteration
    unsigned long maxloops = microsecondsToClockCycles(timeout)/16;

    unsigned long width = countPulseASM(portInputRegister(port), bit, stateMask, maxloops);

    // prevent clockCyclesToMicroseconds to return bogus values if countPulseASM timed out
    if (width)
        return clockCyclesToMicroseconds(width * 16 + 16);
    else
        return 0;
}

or the countPulseASM, which I translate from the asembled code, which can have some errors) as:

// wait for any previous pulse to end
while ((*port & bit) == stateMask)
{
        if (--maxloops == 0) 
        {
           return 0;
        }
}

// wait for the pulse to start
 while ((*port & bit) != stateMask)
{
    if (--maxloops == 0)
    {
       return 0;
    }
}

// wait for the pulse to stop
 while ((*port & bit) == stateMask) 
 {
    if (++width == maxloops)
    {
        return 0;
    }
 }
return width;

Another way of doing that is having a correction factor while changing the time into the distance, but for that I shold have the differences of all the materials.

0

pulseIn just returns the length of a pulse on a pin. That has nothing to do with materials and can have no concept of materials. It is just time. You cannot change time just to suit different materials.

Instead if you want to calculate the distance depending on different materials you need the actual time of the pulse to then calculate the distance in different ways.

That is down to your sketch to do that calculation using the time provided by pulseIn and your own adjustment values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.