user45265: I'm doing my project regarding 40khz ultrasonic sensor which will be used to get accurate distance measurements. I have a separate transmitter and receiver. I want to get the time between the moment my transmitter transmitted the waves and the time my receiver received it. However, I couldn't actually make it work. Does any of you give me a code that would help me transmit and receive the 40khz waves and get the time in between so I could use it to compute for the distance?Thank you in advance. I would greatly appreciate it!

user36955: This is the most basic ultrasound pulse and receive code. I wrote it to work with the HC-SR04 modules; so hopefully it will work fro you too as those also sound at 40khz.
The main functionality comes from the pulseIn() funciton.
#define TRIGPIN 9
#define ECHOPIN 10

void setup() {
  Serial.begin(9600);
  pinMode(TRIGPIN, OUTPUT);
  pinMode(ECHOPIN, INPUT);
}

void loop() {
  digitalWrite(TRIGPIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGPIN, LOW);

  uint16_t duration = pulseIn(ECHOPIN, HIGH, 4000);
  int distance = (duration*.0343)/2;
  Serial.println(distance);
}


Note that you will need to adjust the 4000 (μs) to whatever timeout in you want (or emit entirely if you don't want it).

45265: <p>I'm doing my project regarding 40khz ultrasonic sensor which will be used to get accurate distance measurements. I have a separate transmitter and receiver. I want to get the time between the moment my transmitter transmitted the waves and the time my receiver received it. However, I couldn't actually make it work. Does any of you give me a code that would help me transmit and receive the 40khz waves and get the time in between so I could use it to compute for the distance?Thank you in advance. I would greatly appreciate it!</p>
 36955: <p>This is the most basic ultrasound pulse and receive code. I wrote it to work with the <code>HC-SR04</code> modules; so hopefully it will work fro you too as those also sound at <code>40khz</code>.</p>

<p>The main functionality comes from the <a href="https://www.arduino.cc/reference/en/language/functions/advanced-io/pulsein/" rel="nofollow noreferrer"><code>pulseIn()</code></a> funciton.</p>

<pre><code>#define TRIGPIN 9
#define ECHOPIN 10

void setup() {
  Serial.begin(9600);
  pinMode(TRIGPIN, OUTPUT);
  pinMode(ECHOPIN, INPUT);
}

void loop() {
  digitalWrite(TRIGPIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGPIN, LOW);

  uint16_t duration = pulseIn(ECHOPIN, HIGH, 4000);
  int distance = (duration*.0343)/2;
  Serial.println(distance);
}
</code></pre>

<hr>

<p>Note that you will need to adjust the <code>4000</code> (<code>μs</code>) to whatever timeout in you want (or emit entirely if you don't want it).</p>
