简体   繁体   中英

How to measure the distance of 3 meter to be exact from 3000 - 0 in ultrasonic?

I'm trying to measure a distance of a 3 meter water tank, with ultrasonic sensor to be exact from 3000 - 0.

When the object (water) get closer to the sensor 3000 when gets far to 3m count it as 0.

Example: We have a water tank with a capacity of 3000 Liter and we want to measure it with ultrasonic sensor, so when it is full it should measure 3000 when it's empty it should measure 0.

How can i do that?

This is what i have done but unfortunately it doesn't measure as it should be, if it's close it measures till 2743 and if it is far it measure just till 1700.

Here is the code:

//------------
//SENSOR
//------------
int readDistance() {
  // Transmitting pulse
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

  long t = 0, h = 0;

  // Waiting for pulse
  t = pulseIn(echoPin, HIGH);

  // Calculating distance
  h = t / 58;
  h = h - 6 ;  // offset correction
  h = 580 - h;  // water height, 0 - 50 cm

  return  5 * h;  // distance in %, 0-100 %;
}

I'm not sure about the logic of your code, but that's more or less how I'd do it, assumung your sensor is linear. If you're using a modern compiler, this function along with its local variables could be constexpr . If you have more than one sensor, may be useful to wrap this in a class .

int raw_read_to_mm(const int raw_read)
{
    // Tuning data (fill by hand with the proper values)
    static const int hmin = 0; // [mm] Minimum water level
    static const int hmax = 3000; // [mm] Maximum water level
    static const int read_hmin = 123456; // Sensor read at hmin
    static const int read_hmax = 12; // Sensor read at hmax
    //static_assert( (read_hmax-read_hmin)!=0 );

    // A little verbose, to show what I'm doing
    // calculation is done using floating point
    // to avoid truncation errors
    static const double delta_h = (hmax-hmin);
    static const double delta_read = (read_hmax-read_hmin);
    static const double k = delta_h / delta_read;

    return static_cast<int>( hmin + k*(raw_read-read_hmin) );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM