How to Communicate Waterproof Ultrasonic Sensor AJ-SR04M/JSN-SR04T with Arduino/ESP3216 min read

As ultrasonic sensors started being used in cars as reverse parking sensors, manufactures started producing them in bulk which made them easily available in a wide variety of models at cheap prices. We at Probots (www.probots.co.in), sell a wide range of ultrasonic sensors which are easy and simple to interface with microcontrollers.

Probots AJ-SR04M Waterproof Ultrasonic Sensor Module

Why is AJ SR04M the best ultrasonic sensor model?

The most versatile and accurate of all popular ultrasonic sensors in the market is the Waterproof Ultrasonic Sensor AJ-SR04M/JSN-SR04T V2.0. It can detect objects up to 4.5meters, has a very practically useful beam angle of 45 degrees, is accurate up to 0.5cm. Unlike other ultrasonic sensors HC-SR04, JSN-SR04T, and the JSN-SR04T V2, the AJ-SR04M offers a wide range of operating voltage 3-5V(which means it can work on both 5V and 3.3V microcontrollers), has a low power consumption of only 20uA during sleep(which means it can run on batteries for years!).

Other similar sensors HCSR05 and JSN-SR04T have high operating voltage and current consumption( which makes the AJ-SR04M is the best choice for designing consumer products).

Make sure you buy only genuine sensors which come fully functionally tested. Many fakes, clones, and low-cost modules may not give you these options and you may be unable to get them working following this guide.

Any known issues with the AJ-SR04M? Why is this model so unpopular?

There are many articles and YouTube videos showing that JSN-SR04T V2 and AJ-SR04M are not working and they recommend using SN-SR04T. But they didn’t put in an effort to get them working but just concluded that an older sensor JSN-SR04T with fewer features is better.

We recently delivered a custom electronics product using the AJ-SR04M and were able to get it working with no issues. The product has already reached the market and has been received with high satisfaction from both our customers and their users. 

If you are trying to use this ultrasonic sensor in your product or project, then this article will help you get it working immediately.


Check out our online store – www.probots.co.in to find all the parts for your projects! We have 2000+ Electronic Modules, Sensors, and Components for all your electronics projects.
You can purchase this AJ SR04M Waterproof Ultrasonic Sensor here – Buy Now


Before getting started – What are the operating modes of this sensor?

The sensor has multiple operating modes –

  1. Traditional Trigger and Echo Mode – Most popular mode which usese Digital GPIOs
  2. Low Power Traditional Trigger and Echo Mode – Special Lower Power Mode which uses Digital GPIOs. Suited for battery powered applications
  3. Automatic Serial Port Mode – Uses UART Communication for simple and easy communication, requires just 1 UART pin
  4. Low Power Serial Mode – Uses UART Communication for simple and easy communication, low power consumption, requires 2 UART Pins
  5. Computer Printing Mode – Uses UART Communication, outputs distance data in mm, in ASCII readable format

Modes Selection: How to operate the sensor in different Modes?

  • The waterproof ultrasonic sensor can work in any one mode at once.
  • Individual Modes can be selected by changing an onboard resistor (Soldering required).
  • The module checks the values of this resistor during power on and switches the operating mode based on it
  • The module comes with Traditional Trigger and Echo Mode from the factory by default! This is the most popular mode, you will not need to change this unless you want to specifically use the module in a different mode.
An onboard resistor selects the mode of the module

Specifications of the Ultrasonic Sensor AJ SR04M

Before getting started with using the ultrasonic sensor, its good to get familiarised with the sensors’ specifications. More details will be available in the manufacturers datasheet(tough to get an accurate datasheet, as there are lot of variations between manufacturers and lots. But the overall specifications remain the same)

  • Operating Voltage: DC 5V
  • The Module is has an operating range of 20cm to 450cm.
  • Total Current Draw: 30mA
  • Frequency: 40KHZ
  • Resolution: about 0.5cm
  • Beam Angle: less than 50 degrees
  • Working Temperature:-10~70° C
  • Storage temperature:-20~80° C

Board Overview – Overview of the 2 Major Parts in the Sensor

The sensor module consists of two parts –

  • An ultrasonic transducer – transmitter and receiver with a long cable
  • Controller board with a PIC microcontroller (or a cheap clone) to process the raw data from the transducer, and transmit the data as per the selected operating mode
AJ SR04M Waterproof Ultrasonic Sensor - Parts

The 5 working modes of the AJ SR04M – Details with Sample Codes

Traditional Trigger and Echo Mode (same as the popular HCSR04)

This mode uses Trigger and Echo pins. You will have to allocate two digital pins on your microcontroller, and a software timer to calculate the distance.

Trigger pin is an input and Echo an output for the sensor.

The sensor looks for a digital high pulse on the trigger line and transmitts a 40Khz ultrasonic wave. The echo pin changes from low to highon receiving this signal. The time difference between tramitting and receiving will be used to calculated the distance the wave travelled and from the the obstacle distance!

Note that the communication sequence is the same as per HC SR04, but make sure your high signal on the Trigger pin is at least 10us wide. Some users have reported getting good reading only after increasing the trigger width to 20us.

This mode works with the popular Arduino Newping Library. to use this sensor with NewPing Library, (you can also get the sensor working with a few lines of code. Library makes it simple though)

Timing Diagram showing the different steps in operating the sensor in Echo Trigger mode. A High signal on trigger pin starts transmission. By measuring the time takes for the sensor to measure the reflected signal, we can calculate the object distance

Sample Code to test Echo Trigger Mode –

#define echoPin 11 // attach pin D2 Arduino to pin Echo of JSN-SR04T
#define trigPin 12 //attach pin D3 Arduino to pin Trig of JSN-SR04T

// defines variables
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement

void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
  pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
  Serial.begin(9600); // // Serial Communication is starting with 9600 of baud rate speed
  Serial.println("Ultrasonic Sensor HC-SR04 Test"); // print some text in Serial Monitor
  Serial.println("with Arduino UNO R3");
}
void loop() {
  // Clears the trigPin condition
  digitalWrite(trigPin, LOW);  //
  delayMicroseconds(2);
  // Sets the trigPin HIGH (ACTIVE) for 10 microseconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance = duration * 0.034 / 2; // Speed of sound wave divided by 2 (go and back)
  // Displays the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");// working  code for aj-sr04m
}
Measuring the obstacle distance using Waterproof Ultrasonic Sensor module in Traditional mode, output distance obtained at serial monitor and distance of obstacle in mm

This mode is useful if you want to replace a traditional trigger/echo sensor with this module. Numerous libraries are available so programming is easy. But it requires 2 IO Pins and gets complicated as the number of sensors increase.

Low Power Traditional Trigger and Echo Mode

This Mode of working is similar to the previous mode, but it offers extreme low power consumption. This mode consumes only around 40uA of current during sleep. Perfect if you are powering the sensor from a battery. To enter this mode replace resistor R19 by 300KΩ resistor onboard.

In this mode, the module is in sleep mode, when a high signal with a pulse width of more than 1ms TTL trigger is supplied, the module wakes up, starts transmitting and receiving the ultrasonic signal.

Timing Diagram: Module is in Low Power Sleep Mode. A High signal of 1ms on trigger pin starts transmission. By measuring the time takes for the sensor to measure the reflected signal, we can calculate the object distance

The working code for his mode is the same as mode 1. Modify the trigger pulse to a pulse width greater than 1ms to trigger the sensor from sleep mode.

This Mode is very useful if you use the sensor in low-power battery-driven applications. It offers low power consumption, zero interference with other sensors, and is simple to use.

Automatic Serial Mode

Use Resistance value 120KΩ, to enter the Automatic Serial port mode. The trigger signal is not used in this mode. In this mode, the distance calculation happen on the sensor and it outputs the distance directly over the Echo line every 120ms.

AJ-SR04m transmits bytes per measurement, which is shown below.

Byte1Byte2Byte3Byte4
Start ByteDistance in mm (Upper Byte)Distance in mm (Lower Byte)Checksum

The distance is output in binary. Combine Byte 2(MSB) and Byte 3(LSB) to a single 16bit Integer. This is the distance in mm.

40KHZ pulse generated internally for every 120ms and gives the output distance in echo line. distance in (mm). The checksum is the output,  and it is the sum of the Upperbyte and LowerByte. Checksum is used to verify the packet integrity during transmission.

Timing Diagram: Module continuously outputs the distance data in the Echo line using Serial protocol

Sample Code to test Automatic Serial Mode –

#include <SoftwareSerial.h>
#define rxPin 10
#define txPin 11
 
SoftwareSerial jsnSerial(rxPin, txPin);
 
void setup() {
  jsnSerial.begin(9600);
  Serial.begin(9600);
}
 
void loop() {
  if(jsnSerial.available()){
    getDistance();
  }
}
void getDistance(){
  unsigned int distance;
  byte startByte, h_data, l_data, sum = 0;
  byte buf[3];
  
  startByte = (byte)jsnSerial.read();
  if(startByte ==255){
    jsnSerial.readBytes(buf, 3);
    h_data = buf[0];
    l_data = buf[1];
    sum = buf[2];
    distance = (h_data<<8) + l_data;
    if((( h_data + l_data)) != sum){
      Serial.println("Invalid result");
    }
    else{
      Serial.print("Distance [mm]: "); 
      Serial.println(distance);
    } 
  } 
  
  else return;
  delay(100);
}

Use this mode if you do not want to do the distance calculations on your host microcontroller. Also requires just 1 UART line for communications (vs 2 GPIOs for previous modes!)

Low Power Serial Mode: 

Use 47KΩ at R19 to enter the Low power Serial Mode. In this mode the sensor is in low power sleep mode and consumes 20uA. When the trigger command(0x01) is received on the trigger pin, the sensor wakes up, performs distance calculation and outputs the distance over the echo line. The sensor goes back to sleep after transmitting data. This mode has a low power consumption compared to the previous mode 3.

Timing Diagram: Module is in sleep. A 0x01 data on trigger pin starts distance calucation. After the calculation, the distance is output on the Echo line. The module goes back to sleep

Sample Code to test Low Power Serial Mode –

#include <SoftwareSerial.h>
#define rxPin 10
#define txPin 11
 
SoftwareSerial jsnSerial(rxPin, txPin);
 
void setup() {
  jsnSerial.begin(9600);
  Serial.begin(9600);
}
 
void loop() {
    jsnSerial.write(0x01);
    delay(50);
  if(jsnSerial.available()){
    getDistance();
  }
}
void getDistance(){
  unsigned int distance;
  byte startByte, h_data, l_data, sum = 0;
  byte buf[3];
  
  startByte = (byte)jsnSerial.read();
  if(startByte == 255){
    jsnSerial.readBytes(buf, 3);
    h_data = buf[0];
    l_data = buf[1];
    sum = buf[2];
    distance = (h_data<<8) + l_data;
    if((( h_data + l_data)&0xFF) != sum){
      Serial.println("Invalid result");
    }
    else{
      Serial.print("Distance [mm]: "); 
      Serial.println(distance);
    } 
  } 
  else return;
}
Measuring the obstacle distance using Waterproof Ultrasonic Senor module in Lowe power serial mode, output distance obtained at serial monitor and distance of obstacle in mm

Use this mode if you do not want to do distance calculations on your host and if you want low power applications.

Computer Printing Mode:

Simply short the resistor R19(0 Ohm) to enter to this mode. This is the easiest mode compare to other modes – the distance calculation happens onboard and the output data is directly readable on any serial terminal software(including the Serial Monitor on Arduino IDE).

Sample Code to test Computer Printing Mode –

#include <SoftwareSerial.h>
#define rxPin 10
#define txPin 11
 
SoftwareSerial jsnSerial(rxPin, txPin);
 
void setup() {
  
  jsnSerial.begin(9600);
  Serial.begin(9600);
}
 
void loop() {
    jsnSerial.write(0x01);
    delay(10);
    if(jsnSerial.available()){
    Serial.println(jsnSerial.readString());
  }
}
Measuring the obstacle distance using Waterproof Ultrasonic Senor module in Computer printing mode, output distance obtained at serial monitor and distance of obstacle in mm

Use this mode if you want a quick and easy way to read the sensor data. Without any host processing.

Just connect a USB to Serial converter and you can start getting ultrasonic sensor readings to your computer!

FAQ – Common Questions that Users have when using the AJ-SR04M and the JSN-SR04T

Are the AJ-SR04M / JSN-SR04T / JSN-SR04T V2.0 ultrasonic waterproof sensors compatible with ESP32?

Lack of datasheet from the manufacturer and too many varaiants with the same model, it is difficult to answer this! But I have worked with numerous ultrasonic sensor and used them successfully in multiple projects and based on my experience –

  • JSN-SR04 is not compatible with any 3.3V Device including the ESP32!
  • JSN-SR04T is compatible with 3.3V Devices including the ESP32, but requires a long trigger pulse (~10ms) to work reliably
  • AJ-SR04M is compatible with 3.3V Devices including the ESP32

Note: There are numerous varaiants within these modesl, they vary from lot to lot too! But you can get them working, if you understand the basic operation, and are put in effort to debug the outputs when you face a problem! The sensors are actually quite accurate, reliable and consistant, just that documentation is poor and they are subtle variants in every lot!

How to get reliable readings from the AJ-SR04M / JSN-SR04T / JSN-SR04T V2.0 ultrasonic waterproof sensors?

Common issue with these sensors is that the output is zero, echo pin doesnt change state, or readings are inconsistant and frequently output incorrect distance values! I have faced this issue too, you can solve this by –

  • Reading about the sensor, understanding its operations, developing good fundamental knowledge about these sensor. This will help you debug an issue when you face them. This article explains all these concepts and will be an excellent foundation for you to get started! Make sure you read it from the beginning!
  • Increase the length of the Trigger pulse (I found 10ms works well) if you are getting random fluctuations in the reading! When everything else is right, this is the single biggest factor, that should get majority of your issues fixed!
  • Use a noise free power supply that is rated for your sensor model – 3 to 5V or 5V
  • Do not try tuning the onboard inductor, it is already tuned in the factory for 40Khz. It is difficult to restore this setting again when you are not sure your hardware is working~
  • Contact your supplier/manufacture for help. Include the connections, code and detailed problems you are facing

AJ-SR04M vs JSN SR04T vs JSN SR04T V2 What are the differences between these ultrasonic distance sensors?

****Need to update****

Arduino Libraries & Code for the AJ-SR04M / JSN SR04T / JSN SR04T V2 What are the best Arduino Libraries for these ultrasonic distance sensors?

****Need to update****

Debugging a AJ-SR04M / JSN SR04T / JSN SR04T V2. How to get these ultrasonic distance sensors working?

****Need to update****

Fluctutating / Inconsistant / Noise readings with AJ-SR04M / JSN SR04T / JSN SR04T V2. How to get these ultrasonic distance sensors working reliably?

****Need to update****

Better alternative to the AJ-SR04M / JSN SR04T / JSN SR04T V2. What are some better alternatives to these ultrasonic sensors?

****Need to update****

You can purchase all products that were used in this article here –

  • Ultrasonic sensor,
  • Arduino Uno
  • Breadboard
  • Jumper Cables

Many such modules are available for sale on our website. You can check them out here – www.probots.co.in

Chidananda

32 thoughts on “How to Communicate Waterproof Ultrasonic Sensor AJ-SR04M/JSN-SR04T with Arduino/ESP32”

    1. You are right. These are generic modules and keep changing. Unfortunately we dont have any any fixed reliable version/identification yet.

      We rely on the model number that is printed on the PCB. The latest one are marked AJ-SR04M V2.

  1. Sanjeev Garkhail

    Hi,
    I have the previous version of the sensor SR04M-2. Can I connect the sensor to NodeMCU? If yes, how, and if not why? I highly appreciate your answer.

    Thanks!

    Kind regards,

    Sanjeev

    1. You can use it with NodeMCU. Don’t see why you cannot it is a very simple digital interface.

      Make sure you connect VCC of the sensor to 5V on the NodeMCU.

  2. Does anyone knows what’s the purpose of that adjustable component top of the r19 resistor?
    seems like you can use a flat screwdriver just to adjust something…

  3. Antonio Maza Bandres

    const int trigPin = 13; //D13
    const int echoPin = 12; //D12
    ………………..
    void setup() {
    ………..
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    …………..
    }

    void loop() {
    …………………….
    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;
    ………………
    }

  4. Note that you mention 10 milliseconds and some units needing 20 milliseconds in Mode 1 for the trigger pulse, but the actual trigger is 10 microseconds.

    FWIW, the AJ-SR04M I have is reliable with a 10 uSec trigger pulse.

  5. Hello, good information, thank you, I want to know if it incorporates any mode of “cross of an object”, where a change occurs in the environment and this triggers the signal through the echo door, without the distance at which it is located being so relevant .

  6. if I use 5v to supply the board (SR04M) – can I use TX/RX pins to connect to esp32 pins which are using 3.3v ?
    is it safe ?

  7. I’m having problems with the Lilygo Lora32 T3_v1.6.1 (it’s ESP32)
    on the TXD and RXD pins I get “0cm” outputs on most others (34,35,36,39 etc), i get – gpio_set_level(227): GPIO output gpio_num error. any advice would be appreciated

  8. Hello, I’m trying to run two of these sensors together. Initially, I was getting accurate results, but later on, one of them started returning only 28 values. I suspect the sensor is faulty. What steps should I take to make them work together without any malfunctions? How can they work together stably without any issues? Thank you in advance for the information.

  9. Hi,
    Excellent project and well done explaining the differences between sensors, I found out my sensor is the AJ version, which is excellent for my application, battery operated water tank level sensor. Had I not found your site, I would still be working in simple MODE 1.

    My question is, in MODE 4, you don’t state the operating current, rather it is the Standby current of 2mA, with 20uA sleep. Is the operating current still 30mA in MODE 4? I can’t find any reference on the web.

    Thank you.

  10. Hi,

    Excellent project and well done explaining the differences between sensors, I found out my sensor is the AJ version, which is excellent for my application, battery operated water tank level sensor. Had I not found your site, I would still be working in simple MODE 1.

    My question is, in MODE 4, you don’t state the operating current, rather it is the Standby current of 2mA, with 20uA sleep. Is the operating current still 30mA in MODE 4? I can’t find any reference on the web.

    Thank you.

    1. The current consumption in Mode 4 depends on how frequently the sensor is triggered. If it remains in sleeps for most of the time, the current consumed should be in uAs

  11. sensor is placed 150 cm from wall.
    this is the code- and serial monitor

    #include
    #include
    #include

    // Define the OLED display dimensions
    #define SCREEN_WIDTH 128
    #define SCREEN_HEIGHT 64

    // Create an instance of the display
    #define OLED_RESET -1
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

    // Define the SR04 ultrasonic sensor pins
    const int trigPin = 9; // Trigger pin
    const int echoPin = 10; // Echo pin

    // Parameters for moving average filter
    const int numReadings = 10;
    int readings[numReadings]; // Array to store distance readings
    int index = 0; // Current index in the readings array
    long total = 0; // Sum of distances for moving average
    int averageDistance = 0; // The average distance value

    void setup() {
    Serial.begin(9600); // Start serial communication for debugging

    // Initialize the display with the I2C address
    if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Use 0x3C or 0x3D based on your display
    Serial.println(F(“SSD1306 allocation failed”));
    for(;;); // Infinite loop
    }

    display.display(); // Show initial text
    delay(2000); // Pause for 2 seconds
    display.clearDisplay();

    // Initialize SR04 sensor pins
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);

    // Initialize readings array
    for (int i = 0; i < numReadings; i++) {
    readings[i] = 0;
    }
    }

    void loop() {
    long duration;
    int distance;

    // Send a pulse to trigger the measurement
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    // Read the echo pulse duration
    duration = pulseIn(echoPin, HIGH);

    // Calculate distance in cm
    if (duration == 0) {
    distance = 0;
    } else {
    distance = duration * 0.0344 / 2;
    // Ensure the distance is within a reasonable range
    if (distance 400) {
    distance = 0;
    }
    }

    // Update the moving average filter
    total -= readings[index];
    readings[index] = distance;
    total += readings[index];
    index = (index + 1) % numReadings;
    averageDistance = total / numReadings;

    // Display the average distance on the OLED
    display.clearDisplay();
    display.setTextSize(5); // Normal 1:1 pixel scale
    display.setTextColor(SSD1306_WHITE); // Draw white text
    display.setCursor(0,0); // Start at top-left corner
    // display.print(F(“Distance:”));
    display.setCursor(10,20); // Adjust the vertical position as needed
    display.print(averageDistance);
    //display.print(F(“cm”));
    display.display();

    // Debugging info
    Serial.print(“Distance: “);
    Serial.print(distance);
    Serial.print(” cm, Average Distance: “);
    Serial.print(averageDistance);
    Serial.println(” cm”);

    delay(500); // Delay between measurements
    }
    Distance: 153 cm, Average Distance: 153 cm
    Distance: 153 cm, Average Distance: 152 cm
    Distance: 153 cm, Average Distance: 152 cm
    Distance: 213 cm, Average Distance: 158 cm
    Distance: 153 cm, Average Distance: 158 cm
    Distance: 151 cm, Average Distance: 158 cm
    Distance: 238 cm, Average Distance: 167 cm
    Distance: 153 cm, Average Distance: 167 cm
    Distance: 153 cm, Average Distance: 167 cm
    Distance: 153 cm, Average Distance: 167 cm
    Distance: 153 cm, Average Distance: 167 cm
    Distance: 154 cm, Average Distance: 167 cm
    Distance: 158 cm, Average Distance: 167 cm
    Distance: 157 cm, Average Distance: 162 cm
    Distance: 153 cm, Average Distance: 162 cm
    Distance: 152 cm, Average Distance: 162 cm
    Distance: 155 cm, Average Distance: 154 cm
    Distance: 153 cm, Average Distance: 154 cm
    Distance: 154 cm, Average Distance: 154 cm

  12. If I’m using USB Serial port TTL HW597 and have it connected like this TX -> RXD and RX -> TXD. I have mode 5 enabled but what’s the code in python to make it read distance

Leave a Comment

Your email address will not be published. Required fields are marked *

Contents
Scroll to Top