ESP32 A02YYUW Waterproof Ultrasonic Distance Sensor
Overview
The A02YYUW is a waterproof ultrasonic distance sensor ideal for outdoor and industrial applications. With a measuring range of up to 4.5 meters and a durable build, it is perfect for detecting objects in harsh conditions. It operates using a UART interface and is compatible with microcontrollers like Arduino and ESP32.
About A02YYUW Waterproof Ultrasonic Distance Sensor
The A02YYUW is a waterproof ultrasonic sensor designed for precise distance measurement in harsh environments. With an IP67-rated enclosure, it is dustproof and waterproof, making it ideal for outdoor and industrial applications.
⚡ Key Features
- Wide Measurement Range – Detects distances from 3 cm to 450 cm.
- IP67 Waterproof & Dustproof – Built for moist, outdoor, and industrial environments.
- Reliable UART Communication – Provides stable distance readings via a UART interface.
- Versatile Applications – Used in liquid level detection, obstacle avoidance, and proximity sensing.
The A02YYUW is a great choice for rugged IoT applications, ensuring reliable performance in challenging conditions. 🚀
Where to Buy
Prices are subject to change. We earn from qualifying purchases as an Amazon Associate.
Technical Specifications
Pinout Configuration
The VCC
pin is used to supply power to the sensor, and it typically requires 3.3V or 5V (refer to the datasheet for specific voltage requirements). The GND
pin is the ground connection and must be connected to the ground of your ESP32.
The A02YYUW pinout is as follows:
- VCC: Connect to a 3.3V to 5V power supply.
- GND: Ground connection.
- RX: UART receive pin for communication.
- TX: UART transmit pin for communication.
Wiring with ESP32
VCC
to a 3.3V or 5V power source, GND
to ground, TX
to the microcontroller's RX pin, and RX
to the microcontroller's TX pin. Ensure that the UART communication parameters are set to 9600 baud rate, 8 data bits, 1 stop bit, and no parity.Troubleshooting Guide
Common Issues
🔄 Sensor Returns Constant or Erroneous Readings
Issue: The A02YYUW ultrasonic sensor provides constant or incorrect distance measurements, regardless of the actual distance to the target.
Possible causes include incorrect wiring, insufficient power supply, or improper sensor configuration.
Solution: Ensure that the sensor is connected to a stable 5V power source, as it requires 5V for proper operation. Verify that the sensor's TX (transmit) and RX (receive) lines are correctly connected to the corresponding RX and TX pins on the microcontroller, respectively. Confirm that the baud rate for serial communication is set to 9600 bps, as required by the sensor.
📉 Inconsistent or Fluctuating Distance Measurements
Issue: The sensor outputs distance readings that vary significantly, even when the target distance remains constant.
Possible causes include environmental factors such as temperature variations, soft or angled target surfaces, or electrical noise.
Solution: Position the sensor perpendicular to a hard, flat target surface to ensure accurate reflections. Be aware that temperature changes can affect the speed of sound; consider implementing temperature compensation if precise measurements are required. Implement averaging of multiple readings in your code to mitigate occasional erroneous data.
🚫 Sensor Not Detected or Unresponsive
Issue: The microcontroller fails to detect the A02YYUW sensor, or the sensor does not respond to trigger signals.
Possible causes include incorrect pin assignments in the code, lack of proper initialization, or defective sensor module.
Solution: Double-check the pin assignments in your code to ensure they match the physical connections. Confirm that the sensor is properly initialized in the setup section of your code. If the issue persists, test the sensor with a known working setup or replace it to rule out hardware failure.
🌍 Interference from Environmental Factors
Issue: External factors cause the sensor to produce unreliable readings.
Possible causes include high ambient noise levels, temperature variations, or obstacles in the sensor's field of view.
Solution: Operate the sensor in a controlled environment to minimize acoustic and electrical noise. Be aware that temperature changes can affect the speed of sound; consider implementing temperature compensation if precise measurements are required. Ensure that there are no unintended obstacles within the sensor's detection range that could cause false readings.
Debugging Tips
🔍 Serial Monitor
Use the Serial Monitor to check for error messages and verify the sensor's output. Add debug prints in your code to track the sensor's state.
⚡ Voltage Checks
Use a multimeter to verify voltage levels and check for continuity in your connections. Ensure the power supply is stable and within the sensor's requirements.
Additional Resources
Code Examples
Arduino Example
#include <Arduino.h>
// Define ESP32 hardware serial port for the A02YYUW sensor
#define A02YYUW_TX 18 // ESP32 TX connected to Sensor RX
#define A02YYUW_RX 5 // ESP32 RX connected to Sensor TX
// Initialize hardware serial for A02YYUW
HardwareSerial mySerial(2);
void setup() {
Serial.begin(115200); // Initialize Serial Monitor
mySerial.begin(9600, SERIAL_8N1, A02YYUW_RX, A02YYUW_TX); // Initialize UART2
Serial.println("A02YYUW Distance Sensor Example");
}
void loop() {
if (mySerial.available() >= 4) {
uint8_t data[4];
for (int i = 0; i < 4; i++) {
data[i] = mySerial.read();
}
if (data[0] == 0xFF) { // Check packet start byte
int sum = (data[0] + data[1] + data[2]) & 0xFF;
if (sum == data[3]) { // Validate checksum
int distance = (data[1] << 8) + data[2]; // Calculate distance
if (distance > 30) { // Ensure valid reading
Serial.print("Distance: ");
Serial.print(distance / 10.0);
Serial.println(" cm");
} else {
Serial.println("Below the lower limit");
}
} else {
Serial.println("Checksum error");
}
}
}
delay(100);
}
This Arduino sketch interfaces with the A02YYUW ultrasonic distance sensor using ESP32's hardware serial (UART2) for stable communication.
Hardware Serial on ESP32 #
ESP32 has multiple hardware UART ports, eliminating the need for SoftwareSerial. This sketch uses UART2 (Serial2):
- TX (GPIO18) → Sensor RX
- RX (GPIO5) → Sensor TX
- Baud rate: 9600
Code Breakdown #
- Initialize UART2 with
mySerial.begin(9600, SERIAL_8N1, A02YYUW_RX, A02YYUW_TX);
- Read sensor data (4-byte packets).
- Validate checksum for data integrity.
- Convert distance to cm and print it to the Serial Monitor.
- Error handling for checksum failures and out-of-range readings.
This setup ensures reliable distance measurement without using SoftwareSerial. 🚀
ESP-IDF Example
#include <stdio.h>
#include "driver/uart.h"
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#define RXD_PIN 16
#define TXD_PIN 17
#define UART_NUM UART_NUM_1
#define UART_BUFFER_SIZE (1024 2)
#define UART_TIMEOUT_MS 20
static const char TAG = "UART_SENSOR";
void init_uart(void) {
// Configure UART parameters
const uart_config_t uart_config = {
.baud_rate = 9600,
.data_bits = UART_DATA_8_BITS,
.parity = UART_PARITY_DISABLE,
.stop_bits = UART_STOP_BITS_1,
.flow_ctrl = UART_HW_FLOWCTRL_DISABLE
};
// Apply UART configuration
ESP_ERROR_CHECK(uart_param_config(UART_NUM, &uart_config));
ESP_ERROR_CHECK(uart_set_pin(UART_NUM, TXD_PIN, RXD_PIN, UART_PIN_NO_CHANGE, UART_PIN_NO_CHANGE));
// Install UART driver with RX buffer and a small TX buffer
ESP_ERROR_CHECK(uart_driver_install(UART_NUM, UART_BUFFER_SIZE, 512, 0, NULL, 0));
// Set UART mode explicitly
ESP_ERROR_CHECK(uart_set_mode(UART_NUM, UART_MODE_UART));
}
void uart_task(void *pvParameters) {
uint8_t data[4];
while (1) {
// Read 4 bytes from UART
int len = uart_read_bytes(UART_NUM, data, 4, pdMS_TO_TICKS(UART_TIMEOUT_MS));
if (len == 4 && data[0] == 0xFF) {
// Calculate checksum
int sum = (data[0] + data[1] + data[2]) & 0xFF;
if (sum == data[3]) {
// Convert distance to centimeters
int distance = (data[1] << 8) | data[2];
if (distance > 30) {
ESP_LOGI(TAG, "Distance: %.2f cm", distance / 10.0);
} else {
ESP_LOGW(TAG, "Below the lower limit");
}
} else {
ESP_LOGE(TAG, "Checksum error (Received: 0x%02X, Expected: 0x%02X)", data[3], sum);
}
} else if (len > 0) {
ESP_LOGW(TAG, "Invalid data received");
}
vTaskDelay(pdMS_TO_TICKS(100));
}
}
void app_main(void) {
init_uart();
xTaskCreate(uart_task, "UART Task", 4096, NULL, 5, NULL);
}
This ESP-IDF code interfaces with the A02YYUW ultrasonic distance sensor using UART1 on the ESP32.
UART Configuration #
- TX (GPIO17) → Sensor RX, RX (GPIO16) → Sensor TX
- Baud rate: 9600, 8N1 format
- RX buffer: 2048 bytes
Code Breakdown #
- Initialize UART with
init_uart()
, setting up UART parameters and driver. - Read Sensor Data in
uart_task()
, processing 4-byte packets. - Validate Data by checking the header (0xFF) and checksum.
- Convert Distance from mm to cm and print it to the Serial Monitor.
A 100 ms delay ensures stable readings. 🚀
ESPHome Example
uart:
tx_pin: GPIO5
rx_pin: GPIO18
baud_rate: 9600
sensor:
- platform: a02yyuw
name: "A02YYUW Distance"
update_interval: 100ms
timeout: 2s
uart
platform to interface with the A02YYUW sensor. The tx_pin
and rx_pin
specify the GPIO pins used for UART communication. The baud_rate
is set to 9600 to match the sensor's communication protocol. The sensor
component configures the A02YYUW as the distance sensor, with a user-friendly name 'A02YYUW Distance.' The update_interval
specifies that measurements are taken every 100 ms, and the timeout
ensures reliable communication by preventing prolonged wait times for data.PlatformIO Example
platformio.ini
[env:esp32dev]
platform = espressif32
board = esp32dev
framework = arduino
monitor_speed = 115200
PlatformIO Example Code
#include <SoftwareSerial.h>
SoftwareSerial mySerial(5, 18); // RX, TX
void setup() {
Serial.begin(115200);
mySerial.begin(9600);
Serial.println("A02YYUW Distance Sensor Example");
}
void loop() {
if (mySerial.available() >= 4) {
uint8_t data[4];
for (int i = 0; i < 4; i++) {
data[i] = mySerial.read();
}
if (data[0] == 0xFF) {
int sum = (data[0] + data[1] + data[2]) & 0xFF;
if (sum == data[3]) {
int distance = (data[1] << 8) | data[2];
if (distance > 30) {
Serial.print("Distance: ");
Serial.print(distance / 10.0);
Serial.println(" cm");
} else {
Serial.println("Below the lower limit");
}
} else {
Serial.println("Checksum error");
}
}
}
delay(100);
}
MicroPython Example
from machine import UART
from time import sleep
# Configure UART
uart = UART(2, baudrate=9600, tx=5, rx=18)
def read_distance():
if uart.any() >= 4:
data = uart.read(4)
if data[0] == 0xFF:
checksum = (data[0] + data[1] + data[2]) & 0xFF
if checksum == data[3]:
distance = (data[1] << 8) | data[2]
if distance > 30:
return distance / 10.0
else:
return "Below the lower limit"
else:
return "Checksum error"
return None
print("A02YYUW Distance Sensor Example")
while True:
result = read_distance()
if result:
print(f"Distance: {result} cm")
sleep(0.1)
read_distance()
function reads 4 bytes of data from the UART buffer, validates the header and checksum, and calculates the distance in millimeters. The result is converted to centimeters and returned. The main loop continuously calls this function every 100 ms to print the distance to the console. If the sensor detects an issue, such as a checksum error or a distance below the minimum threshold, appropriate messages are displayed.Conclusion
The ESP32 A02YYUW Waterproof Ultrasonic Distance Sensor is a powerful distance sensor that offers excellent performance and reliability. With support for multiple development platforms including Arduino, ESP-IDF, ESPHome, PlatformIO, and MicroPython, it's a versatile choice for your IoT projects.
For optimal performance, ensure proper wiring and follow the recommended configuration for your chosen development platform.
Always verify power supply requirements and pin connections before powering up your project to avoid potential damage.