Coding issue; Trying to calculate velocity using ultrasonic sensor

I am a 6th grader having issues with my science project. I am trying to write the correct code to determine velocity using waterproof ultrasonic sensor . I am trying to determine the velocity of sound thru various liquid mediums (Rubbing Alcohol, cooking oil, molasses, etc). I have 1 meter tubing filled with the liquids, sensor goes in and gives reading in ms, then I can calculate meters/second.....if I could get code right. Can anyone provide some guidance. Thank you in advance

Which sensor? Post a link to the data sheet or product page.

Ultrasonic transducers intended for air won't work in solids or liquids, because sound energy is not efficiently transmitted to the medium.

Even if it did work, it is a good exercise to calculate the round trip travel time of a sound pulse in a 1 meter container. The speed of sound in water is about 1500 m/s.

Kind'a hard to critique your code by telepathy. Read the stickey on how to use the forum and then post your code in tags.

Any code written? You can use milis() or You can use micros() given 1000 times better resolution.

https://www.elecrow.com/water-proof-integrated-ultrasonic-ranging-module-jsnsr04t-p-1151.html

The sensor I have is a waterproof ultrasonic sensor. I am using 1 meter tubes and trying to do exactly that. Once I get the reading I can divide in half then calculate meters per second. I am hypothesizing sound travels faster thru denser liquids, so I have to show my work. I am first testing at 75 degrees then 30 degrees to see how temp changes velocity.

123Splat 1st time trying to code and using a message board. You enjoy giving 12yr olds crap? Here is the coding I am using. Thx

#include <NewPing.h>

#define ITERATIONS 5 // Number of iterations.
#define TRIGGER_PIN 12 // Arduino pin tied to trigger pin on ping sensor.
#define ECHO_PIN 13 // Arduino pin tied to echo pin on ping sensor.
#define MAX_DISTANCE 100 // Maximum distance (in cm) to ping.
#define PING_INTERVAL 33 // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo).

unsigned long pingTimer[ITERATIONS]; // Holds the times when the next ping should happen for each iteration.
unsigned int ms[ITERATIONS]; // Where the ping distances are stored.
uint8_t currentIteration = 0; // Keeps track of iteration step.

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance.

void setup() {
Serial.begin(115200);
pingTimer[0] = millis() + 75; // First ping starts at 75ms, gives time for the Arduino to chill before starting.
for (uint8_t i = 1; i < ITERATIONS; i++) // Set the starting time for each iteration.
pingTimer = pingTimer[i - 1] + PING_INTERVAL;
}
void loop() {

  • for (uint8_t i = 0; i < ITERATIONS; i++) { // Loop through all the iterations.*
    _ if (millis() >= pingTimer*) { // Is it this iteration’s time to ping?_
    pingTimer += PING_INTERVAL * ITERATIONS; // Set next time this sensor will be pinged.
    _ if (i == 0 && currentIteration == ITERATIONS - 1) oneSensorCycle(); // Sensor ping cycle complete, do something with the results._
    sonar.timer_stop(); // Make sure previous timer is canceled before starting a new ping (insurance).
    _ currentIteration = i; // Sensor being accessed.
    ms[currentIteration] = 0; // Make distance zero in case there’s no ping echo for this iteration._
    sonar.ping_timer(echoCheck); // Do the ping (processing continues, interrupt will call echoCheck to look for echo).
    _ }
    }
    // Other code that DOESN’T analyze ping results can go here.
    }
    void echoCheck() { // If ping received, set the sensor distance to array._

    if (sonar.check_timer())
    ms[currentIteration] = sonar.ping_result / US_ROUNDTRIP_CM;
    _}
    void oneSensorCycle() { // All iterations complete, calculate the median.
    unsigned int uS[ITERATIONS];_
    uint8_t j, it = ITERATIONS;
    uS[0] = NO_ECHO;
    for (uint8_t i = 0; i < it; i++) { // Loop through iteration results.
    if (ms != NO_ECHO) { // Ping in range, include as part of median.
    _ if (i > 0) { // Don’t start sort till second ping.
    for (j = i; j > 0 && uS[j - 1] < ms; j–) // Insertion sort loop.
    uS[j] = uS[j - 1]; // Shift ping array to correct position for sort insertion.
    } else j = 0; // First ping is sort starting point.
    uS[j] = ms; // Add last ping to array in sorted position.
    } else it–; // Ping out of range, skip and don’t include as part of median.
    }
    Serial.print(uS[it >> 1]);
    Serial.println(“ms”);
    }*_

Yeah, I’d have the same concerns when immersing it in liquid.

So… What’s happening when you run that code? Are you getting anything at all? I’m sure you copied it from somewhere, so are you using the same wiring as the example?

I’m not familiar with the NewPing library so I have no idea about your code.

To get the code tags click the </> button at the to-left of the edit window. I can’t show you because the tags don’t show up but it should look like this:

#include <NewPing.h>

#define ITERATIONS     5 // Number of iterations.
#define TRIGGER_PIN   12 // Arduino pin tied to trigger pin on ping sensor.
#define ECHO_PIN      13 // Arduino pin tied to echo pin on ping sensor.
#define MAX_DISTANCE 100 // Maximum distance (in cm) to ping.
#define PING_INTERVAL 33 // Milliseconds between sensor pings (29ms is about the min to avoid cross-sensor echo).

I am a 6th grader

You write very well for a 6th grader!

Thanks. Yeah I copied it to figure out what to do. I'm still getting a distance reading instead of time. It shows ms but it is still givng the distance reading. I checked it with a 1 meter ruler to be sure it was wrong result.

You are using a much too complicated version of the NewPing code. Just use the basic example:

    #include <NewPing.h>
     
    #define TRIGGER_PIN  12
    #define ECHO_PIN     11
    #define MAX_DISTANCE 200
     
    NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);
     
    void setup() {
      Serial.begin(115200);
    }
     
    void loop() {
      delay(50);
      Serial.print("Ping: ");
      Serial.print(sonar.ping_cm());
      Serial.println("cm");
    }

The reported distance is for air and needs to be scaled for other media (assuming the sensor works with other media such as water…count me skeptical…see response #1…please let us know and show your results if you get it to work). Or use the sonar.ping() method to report the time in us (microseconds) instead of distance in cm.

DaveEvans,

I removed _cm to get sonar ping and changed “cm” to “ms” and getting about 1270ms in tap water now. Thanks
I dont know if I can figure out meters per second but I can see which is faster.

#include <NewPing.h>

#define TRIGGER_PIN 12
#define ECHO_PIN 11
#define MAX_DISTANCE 200

NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE);

void setup() {
Serial.begin(115200);
}

void loop() {
delay(50);
Serial.print("Ping: ");
Serial.print(sonar.ping_cm());
Serial.println(“cm”);
}

You should have changed "cm" to "us"...microseconds...not "ms"...milliseconds. So you're consistently getting about 1270 us in about a meter of tap water with your jsnsr04t?

Hi,
Welcome to the forum.

Please read the first post in any forum entitled how to use this forum.
http://forum.arduino.cc/index.php/topic,148850.0.html then look down to item #7 about how to post your code.
It will be formatted in a scrolling window that makes it easier to read.

Look in the NewPing examples for a code called EventTimer.

And use;

 Serial.print(sonar.ping_result);

This returns the ping time.

You might be worth changing this to 150cm to make sure you cover the distance, as the sensor is assuming the medium is air.

#define MAX_DISTANCE 100 // Maximum distance (in cm) to ping.

Tom… :slight_smile:

TomGeorge: Look in the NewPing examples for a code called EventTimer.

The OP doesn't need the EventTimer example. The simple NewPing code in response #8 is sufficient (and appears to be working).

DaveEvans

I switched from "ms" to "us" now. I am not getting 1270 consistently. it is jumping from around 1220 to 1297 but I am seeing a lot of 1270 so I am using that number. I don't know if I can get better readings

Numbers in that ballpark are consistent with the speed of sound traveling through two meters of water.

t = d / v = (2 m) / (1500 m/s) = 1333 microseconds.

It would be interesting to see your tube and sensor - please post a picture!

edit to correct the formula!

Hi, You will have some reflections, so some variation will occur. If you can get 1270 as your most consistent, and you are comparing results from test to test, then using your most consistent readings should give you the test data you need.

I neat project, it will be interesting to see the results you get with other media and temperatures.

Have you got a reading with just air?

Tom... :)

As mentioned in post #14, your numbers are in the ballpark. But since the variation of the speed of sound in water at 30 deg C and 75 deg C is only a few percent, and your range of speeds for water at a constant temperature is also a few percent, it is unlikely you will be able to tease out the difference in velocity vs temperature with your test. You probably need a more sensitive/accurate sensor.

The best you can do with what you have is try averaging a number of readings (after you first reject the occasional outlier, such as echo times that are much smaller or larger than the expected time.)

Also, please post a photo of your tube and sensor. And what diameter is your tube?

DaveEvans, I will have my mom or dad take a picture. I am using 1 inch pvc tubing cut 1 meter. I am getting lot of 0 readings mixed in too. Talking to my dad, he thinks the time between pings is too close (50ms). He says if it takes 1279ms to get a reading, I need to switch my delay between pings to longer than the 1279ms because there are too many pings firing through the reflected ping. Yes, I was figuring I would need to half the results because the ping is one meter and reflecting back 1 meter

TomGeorge, I did get some readings in air but didnt pay attention. When we work on it today, I will see if I can get some readings

You need to pay attention to the difference between ms (milliseconds) and microseconds.

sorry JRemington. I forgot micro is "us" I have input as "us"