JSN-SR04T

Waterproof JSN-SR04T Ultrasonic Distance Sensor with Arduino Tutorial

The JSN-SR04T is an easy to use waterproof ultrasonic distance sensor with a range of 25 to 450 cm. If you are planning to build a water level measuring system or if you need to take other distance measurements outside, then this is the sensor you need!

In this article, I have included a wiring diagram and example codes so you can start experimenting with your sensor. After each example, I break down and explain how the code works, so you should have no problems modifying it to suit your needs.

PCBWay

First, we will look at an example that doesn’t use an Arduino library. Next, I will cover the easy to use NewPing library that has some nice built-in features.

If you would like to learn more about other distance sensors, then the articles below might be useful:


Supplies

Hardware components

JSN-SR04T sensor× 1Amazon
Arduino Uno Rev 3Arduino Uno Rev3× 1Amazon
Breadboard× 1Amazon
Jumper wires~ 6Amazon
USB cable type A/B× 1Amazon

Software

Arduino IDEArduino IDE

Makerguides.com is a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for sites to earn advertising fees by advertising and linking to products on Amazon.com.

When shopping for this sensor, you might come across the updated version, the JSN-SR04T-2.0. This newer version works exactly the same but is rated for 3-5 V instead of 5 V. However, some users have found issues while using the sensors at a lower voltage. Using a longer trigger puls of at least 20 µs instead of 10 µs seems to help if you are having faulty readings.


About the sensor

The sensor comes with a 2.5 m long cable that connects to a breakout board which controls the sensor and does all the processing of the signal. Note that only the sensor and the cable itself are waterproof, if you get water onto the breakout board, the sensor might stop working.

An ultrasonic distance sensor works by sending out ultrasound waves. These ultrasound waves get reflected back by an object and the ultrasonic sensor detects them. By timing how much time passed between sending and receiving the sound waves, you can calculate the distance between the sensor and an object.

Distance (cm) = Speed of sound (cm/µs) × Time (µs) / 2

Where Time is the time between sending and receiving the sound waves in microseconds.

So what are the differences between this sensor and the HC-SR04? The main difference, besides it being waterproof, is that this sensor uses only one ultrasonic transducer instead of two. This transducer serves as both the transmitter and the receiver of the ultrasound waves.

For more info on how ultrasonic sensors work, you can check out my article on the HC-SR04. In this article the working principles of an ultrasonic distance sensor are explained in much greater detail.

JSN-SR04T Specifications

Operating voltage5 V
Operating current30 mA
Quiescent current5 mA
Frequency40 kHz
Measuring range25-450 cm
Resolution2 mm
Measuring angle45-75 degrees
Sensor dimensions23.5 x 20 mm, 2.5 m long cable
PCB dimensions41 x 28.5 mm
Mounting hole18 mm
CostCheck price

For more information you can check out the datasheet here.


Wiring – Connecting JSN-SR04T to Arduino UNO

The wiring diagram/schematic below shows you how to connect the JSN-SR04T sensor to the Arduino. The breakout board of the JSN-SR04T has the exact same pinout as the HC-SR04, so it can be used as a drop-in replacement. The cable of the sensor itself can be plugged into the connector on the back of the breakout board.

JSN-SR04T with Arduino Wiring Diagram Circuit
Wiring diagram/schamatic for the JSN-SR04T ultrasonic distance sensor with Arduino.

The code examples below use digital pin 2 and 3 for the trigger and echo pin, but of course you can change this to any digital pin you want.

JSN-SR04T Connections

JSN-SR04TArduino
5 V5 V
TrigPin 2
EchoPin 3
GNDGND

Example code for JSN-SR04T sensor with Arduino

Now that you have wired up the sensor it is time to connect the Arduino to the computer and upload some code. The sensor can be used without an Arduino library. Later I will show you an example with the NewPing library, which makes the code a lot shorter.

You can upload the following example code to your Arduino using the Arduino IDE. Next, I will explain to you how the code works. This code works for the JSN-SR04T-2.0 too.

You can copy the code by clicking the button in the top right corner of the code field.

/* Arduino example sketch to control a JSN-SR04T ultrasonic distance sensor with Arduino. No library needed. More info: https://www.makerguides.com */

// Define Trig and Echo pin:
#define trigPin 2
#define echoPin 3

// Define variables:
long duration;
int distance;

void setup() {
  // Define inputs and outputs
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  
  // Begin Serial communication at a baudrate of 9600:
  Serial.begin(9600);
}

void loop() {
  // Clear the trigPin by setting it LOW:
  digitalWrite(trigPin, LOW);
  
  delayMicroseconds(5);

 // Trigger the sensor by setting the trigPin high for 10 microseconds:
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  
  // Read the echoPin. pulseIn() returns the duration (length of the pulse) in microseconds:
  duration = pulseIn(echoPin, HIGH);
  
  // Calculate the distance:
  distance = duration*0.034/2;
  
  // Print the distance on the Serial Monitor (Ctrl+Shift+M):
  Serial.print("Distance = ");
  Serial.print(distance);
  Serial.println(" cm");
  
  delay(100);
}

You should see the following output in the serial monitor:

JSN-SR04T Serial monitor output

How the code works

First, the trigger pin and the echo pin are defined. I call them trigPin and EchoPin. The trigger pin is connected to digital pin 2 and the echo pin to digital pin 3 on the Arduino.

The statement #define is used to give a name to a constant value. The compiler will replace any references to this constant with the defined value when the program is compiled. So everywhere you mention trigPin, the compiler will replace it with the value 2 when the program is compiled.

// Define Trig and Echo pin:
#define trigPin 2
#define echoPin 3

Next, I defined two variables: duration and distance. Duration stores the time between sending and receiving the sound waves. The distance variable is used to store the calculated distance.

//Define variables
long duration;
int distance;

In the setup(), you start by setting the trigPin as an output and the echoPin as an input. Next, you initialize serial communication at a baud rate of 9600. Later you will display the measured distance in the serial monitor, which can be accessed with Ctrl+Shift+M or Tools > Serial Monitor. Make sure the baud rate is also set to 9600 in the serial monitor.

void setup() {
  // Define inputs and outputs
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  
  // Begin Serial communication at a baudrate of 9600:
  Serial.begin(9600);
}

In the loop(), you trigger the sensor by setting the trigPin HIGH for 20 µs. Note that to get a clean signal you start by clearing the trigPin by setting it LOW for 5 microseconds.

void loop() {
  // Clear the trigPin by setting it LOW:
  digitalWrite(trigPin, LOW);
  
  delayMicroseconds(5);

 // Trigger the sensor by setting the trigPin high for 10 microseconds:
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

Next, you need to read the length of the pulse sent by the echoPin. I use the function pulseIn() for this. This function waits for the pin to go from LOW to HIGH, starts timing, then waits for the pin to go LOW and stops timing.

After that, you can calculate the distance by using the formula mentioned in the introduction of this tutorial.

  // Read the echoPin. pulseIn() returns the duration (length of the pulse) in microseconds:
  duration = pulseIn(echoPin, HIGH);
  
  // Calculate the distance:
  distance = duration*0.034/2;

Finally, print the calculated distance in the serial monitor.

  // Print the distance on the Serial Monitor (Ctrl+Shift+M):
  Serial.print("Distance = ");
  Serial.print(distance);
  Serial.println(" cm");
  
  delay(100);
}

Example code JSN-SR04T with Arduino and NewPing library

The NewPing library written by Tim Eckel can be used with many ultrasonic distance sensors. The latest version of this library can be downloaded here on bitbucket.org. You might notice that the code below, which uses the NewPing library, is a lot shorter than the code we used before.

You can install the library by going to Sketch > Include Library > Add .ZIP Library in the Arduino IDE.

The library does include some examples that you can use, but you will have to modify them to match your hardware setup. I have included a modified example code below that can be used with the same wiring setup as before.

/*Arduino example sketch to control a JSN-SR04T ultrasonic distance sensor with NewPing libary and Arduino. More info: https://www.makerguides.com */

// Include the library:
#include <NewPing.h>

// Define Trig and Echo pin:
#define trigPin 2
#define echoPin 3

// Define maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500 cm:
#define MAX_DISTANCE 400

// NewPing setup of pins and maximum distance.
NewPing sonar = NewPing(trigPin, echoPin, MAX_DISTANCE);

void setup() {
  // Open the Serial Monitor at 9600 baudrate to see ping results:
  Serial.begin(9600);
}

void loop() {
  // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings:
  delay(50); 
  
  // Measure distance and print to the Serial Monitor:
  Serial.print("Distance = ");
  // Send ping, get distance in cm and print result (0 = outside set distance range):
  Serial.print(sonar.ping_cm()); 
  Serial.println(" cm");
}

Conclusion

In this article, I have shown you how the JSN-SR04T ultrasonic distance sensor works and how you can use it with Arduino. I hope you found it useful and informative. If you did, please share it with a friend that also likes electronics!

I would love to know what projects you plan on building (or have already built) with this sensor. If you have any questions, suggestions, or if you think that things are missing in this tutorial, please leave a comment down below.

Note that comments are held for moderation in order to prevent spam.

Creative Commons License

41 thoughts on “Waterproof JSN-SR04T Ultrasonic Distance Sensor with Arduino Tutorial”

  1. Bhaaskar Rajarajan

    Hi

    Very good explanation.

    1) I like to know how to use this sensor with three wire system
    echo and trigger pin in same I/O
    Is any component needs to connected. I read somewhere in web. 2K2 resistor to be connected between Echo and Trigger pin. If so in which pin I/O to be connected

    2) As you told, the sensor to be used in Narrow tube for measuring in water tank, what is the size of the tube (inches)

    kindly looking for your reply

    Thanks and Regards

    Bhaaskar R

  2. Hi
    Thanks for the amazing set of tutorials. I wonder if you could answer a question with regards to a proposed project I’m undertaking?

    I wish to make a sensor fit for a watercraft to check the depth under and in front of the Hull. This craft can go up to 40mph. Do you think this sensor would be appropriate to use in this project?

  3. I wired the v2-edition of this sensor to my RPI. I instantly worked fine with 3.3V.
    Unfortunatly the datasheet is really correct: measering <20 cm is not possible.
    So I have to change back to the water-unresistant HC-SR04: with this 5V-sensor I was able to measure a minimum of 5 cm. The reason for this is probably that HC-SR04 uses one sender and an extra receiver.

    1. Hi Alex
      Did you get a reply?
      I wound these screws right out and believe they are just covers but, now my sensors don’t report any more than the minimum 20 cm or 0 cm when I cover them. They had been working so until we find out what they actually are I wouldn’t do what I have just done
      Thanks
      Darryl

  4. I have a question about effective range. I have an outdoor application that needs to measure the height of a vertically movable object above a fixed base – but the range could be as much as 13 meters above the base. I note that most ultrasonic devices (in my price range…cheap!) top out at around 5m. Do you think that adding a reflector (three perpendicular faces) to the movable object could extend the range of the JSN-RS04T by 2.6x??

    Optical solutions would be problematic, as optical barriers may be present (e.g. fog, fabric, other light sources). I’m trying to keep my cost low, and can sacrifice accuracy (+/- 2% is acceptable), but not range. Alternatively, would boosting the output signal help?

  5. I got this working with a WEMOS D1 WIFI board!
    The trouble was with the different pins between arduino and WEMOS (or ESP8266, I don’t know the cause). Anyway, I did the following:

    I connected the +5v and Ground to the JSN-SR04 as described, and I connected the ‘ ‘trig’ to the D14/SDA pin on the board, and the ‘echo’ to the D15/SCL on the board.
    Then I changed the code to #define trigPin 4 end #define echoPin 5.
    Plus I changed the baud rate to 112500 to be able to read the serial monitor.
    And it works fine 🙂
    Thanks for this tutorial!

    1. Benne de Bakker

      Hi Frank,

      Thanks for the extra info, I’m glad you got it working with the WEMOS board.

      Benne

  6. Good tuto, I wonder whether it’s possible to established a communication between 2 sensor JSN-SR04T, can you help me ?

    1. Benne de Bakker

      Hi Pierre,

      Yes, this is possible. The easiest way is probably by using the NewPing library. You just need to create two objects of the NewPing class:

      NewPing sonar_1 = NewPing(trigPin_1, echoPin_1, MAX_DISTANCE);
      NewPing sonar_2 = NewPing(trigPin_2, echoPin_2, MAX_DISTANCE);

      Make sure that you define a different set of trig and echo pins for the second sensor.

      When you want to get the distance from the first sensor you can use sonar_1.ping_cm() and for the second sensor sonar_2.ping_cm().

      Benne

  7. Fantastic guide Benne. Got it working within a minute once I had the piece parts in hand. Now all I need to do figure out is how to get the data to a Particle Photon or Electron via I2C. That is probably not going to be easy. Any thoughts that you can offer on that?

  8. hi
    do u know any way to reduce Measuring angle to about 6 degrees.
    totally any idea to have ultrasonic detector with 6 degree or less ?

    1. Benne de Bakker

      Check out the link the Hackaday in the conclusion part of the article. We attached a cone with sound-absorbing material to the end of the sensor to narrow the measuring angle.

  9. I love fast cars so I intend to use this sensor along with an Arduino TTGO T-Call V1.3 ESP32 to measure a car’s speed over a 1/4 mile. My car is a TTRS and develops over 1000 bhp so it should be fun.

  10. edgardo u. villacorte

    Your article provided very useful information for a planned disaster mitigation project in my country. We have a lot of mining companies who have the so called mine tailings dam whose water levels can rise to dangerously high levels during the rainy season.. Several environmental catastrophes have occurred when the dammed water breached the dikes. A simple water level monitoring instrument employing the jsn-sr04t sensor with arduino and gsm modem will likely prevent such a disaster by alerting the mining company’s personnel to open the sluice valves to relieve the water pressure. We are currently in a discussion on how best to implement the project.

    1. Podrias hacer que esas valvulas se accionen automaticamente tambien en base a la medición de nivel que hagas.
      You might as well have thise valves open automatically based on the measurements you make.

  11. In the Conclusion (above) you say “We used one of these sensors and modified it so it could be used in a narrow tube.” In the link to Hackaday you provide I didn’t find that information.

    Am doing a similar thing in Mexico trying to monitor flood levels in streets, and water levels in holding tanks. That pesky 45-70 degree “beam” of the ultrasonic sensor creates problems. The modification to the sensor you mentioned to use a narrow tube would be extremely beneficial. Thanks!

    1. Benne de Bakker

      Hi Scott,

      Thanks for the comment. The answer to your question is buried somewhere in the project logs on Hackaday. What we did is create a 3d printed funnel/cone that we mounted in front of the sensor. On the inside of the funnel we placed some sound absorbing material (in this case we used felt). The funnel has roughly 4 degree walls and combined with the sound absorbing material, we could reduce the effective beam angle quite a bit. Basically, just part of the ‘beam’ is absorbed and only a small narrow part of it can exit the funnel.

      I think there are some SolidWorks files on Hackaday, but you can quite easily DIY something together. Hope this helps a bit.

      Benne

      1. Hi Benne! Thanks for the info. I do see a funnel thing in one of the Solidworks files. Looks like its about 60mm long and shaped roughly 4 degrees. That must be it. I will do up something like it in Sketchup and 3D print it to experiment. Thanks so much!

      2. Has anyone attempted to communicate with the SR04T-2.0 via serial? With the ECHO and TRIG pins also labeled RX and TX, I got to wondering. A piece of info I’ve found is R27 changes the “operating mode”? From what to what? My US-100 Ultrasonic Range Finder operates as an I2C device where it works like all of these devices, Install the jumper though abt it communicates serially, in going so it also computes the distance for you along with the temperature offset, you can even query for the temperature alone and it responds in degrees C. FYI send it 0x50 for the temp and 0x55 for range.

        1. I found several “manuals”, some better, some worse, some Chinese, some bad translations, none really good. It seems also that there are different SW versions. It seems that in the latest it is possible to put several of those boards on a bus and communicate via a serial interface.
          To your question: Mine seems to have three “modes” – but there seem to be versions with up to five different “modes”. To select four modes one would need two digital input ports, or one analog. They use the latter approach. By soldering different resistors at a special location (or open, or shortcut), you can select the mode. For the “continuously serial” mode, they specify a 120 kOhm resistor, but the 100 kOhm that I had available works, too.
          In “continuously serial” mode, the board does every 100 or 120 ms a measurement and sends the result via the serial interface. I can read the bytes. But now comes my problem: Per documentation the record for each measurement should be 4 bytes: Start Flag (xFF), High Byte, Low Byte, CheckSum. It seems that my records consist only of 3 bytes. I am still trying to find more documentation.

          The other modes are “traditional” (like with sending a pulse and waiting for the echo – like described here), “serial on demand” (wait for a command on the serial interface and send the result like in “continuously serial”), and two others.

  12. Hi,
    Great tuto it’s very clear thank you! But did you manage to make the function ping_median of new ping work? I had HCSRO4 and this functions worked perfectly but now it does not… My issue is that I have to get really precise measurements (with millimeters) so with the HCRO4 I used 5 captors and I filtered the values but now I can’t manage to get precise measurements without instability with the JSN SRO4T V2.
    Could you please help me? I feel like I tried everything…

    1. Benne de Bakker

      Hi Marc,

      I haven’t extensively tested the NewPing library with the V2 sensor board myself, but I have read about similar problems before. It mostly has to do with the length of the trigger pulse. For the HC-SR04 this can be slightly below 10us but for the JSN-SR04T V2 it needs to be a bit longer. You can change this in the library source code (sadly there is no other way). You have to change the file NewPing.cpp around line 134. Change the delay time from 10us to around 13 or more microseconds. Tim mentions in this post that you should also add ” #define ONE_PIN_ENABLED false ” to your sketch. See this post: https://bitbucket.org/teckel12/arduino-new-ping/issues/41/jsn-sr04t-20-needs-to-have-longer-high

      I am not 100% sure whether or not this solution always works, but I hope it fixes your problem.

      Benne

  13. Thank you for the well presented tutorial. It is very helpful. Once I get my project working, I will let you know what it is.

  14. Hi Benne
    Thanks for this tutorial, its very well explained for beginners like me!
    I have a project where I want to keep the USsensor at a certain distance from the ground, achieved through activating a 12v solinoid valve. Basicly 2 output pins on the Arduino whould need to go high, one for sensor to low and the other for sensor to high( which will activate relay switches for the higher current to solinoid). I have not come across a tutorial or example coding for something of the kind. Any idea where I can look?

    And would it be possible to write code so the desired distance for the sensor is say, within 10cm, to try and eliminate oscillation?
    Regards
    Andre

    1. Benne de Bakker

      Hi Andre,

      You can probably just use an if else statement.
      if (10 < sonar.ping_cm() < 20){ digitalWrite(solenoidPin1, HIGH): } else if (100 < sonar.ping_cm() < 110){ digitalWrite(solenoidPin2, HIGH); } else { digitalWrite(solenoidPin1, LOW); digitalWrite(solenoidPin2, LOW); } Something like this maybe (note that I used a function from the NewPing library). I unfortunately don't have time to write or debug code for you, so I hope this helps a bit. Greetings, Benne

      1. André du Toit

        Now worries , I don’t expect you to write me code. I’m actually excited to figure it out myself (with the help of Google obviously ?). Every bit of information helps me in the right direction, like if else! So thank you

  15. I’m a newb, so forgive me if this is a stupid question.
    Why do you need a breadboard? Can’t you connect the 5V and GND from the JSN-SR04T directly to the Arduino?

    1. Benne de Bakker

      Hi Tommy,

      Good question. A breadboard is definitely not needed, so you can just wire everything directly from the sensor to the Arduino. I just find a breadboard easy to use when prototyping. If you only have male-male jumper wires, a breadboard makes it easier to wire up the sensor without soldering. If you plan to build something more permanent, I wouldn’t use a breadboard.

      Greetings,

      Benne

    1. Benne de Bakker

      This can easily be done with the NewPing library. Just create two instances of the NewPing class and add an additional trigger and echo pin:

      #define trigPin 2
      #define echoPin 3
      #define trigPin2 4
      #define echoPin2 5

      NewPing sonar(trigPin, echoPin, MAX_DISTANCE);
      NewPing sonar2(trigPin2, echoPin2, MAX_DISTANCE);

      Now if you want to read the first sensor you can use sonar.ping_cm() and for the second sensor sonar2.ping_cm().

      Hope this helps.

      Benne

  16. Is it possible to connect a 3 pin oem parking sensor on this board? Or are there an other board to make that?

    1. Benne de Bakker

      Hi,

      The sensor/ultrasonic transducer that connects to the control board only has two wires/pins. If your oem parking sensor comes with it’s own pcb that creates the signal, then you might be able to control it with an Arduino or other microcontroller. I have written a small section about controlling 3 pin sensors with the NewPing library in my tutorial about the HC-SR04 ultrasonic sensor: https://www.makerguides.com/hc-sr04-arduino-tutorial/.

      Benne

Comments are closed.