Example Code for Arduino-Get Distance
Last revision 2026/01/21
This project uses the A02YYUW Ultrasonic Sensor with Arduino to get distance measurements for projects like obstacle avoidance robots.
Hardware Preparation
- Arduino UNO
- UNO IO Sensor Expansion Board
- A02YYUW Ultrasonic Sensor (Purchase Link)
- 4P Connector
Software Preparation
Wiring Diagram
Other Preparation Work
Ensure the sensor is properly connected as per the wiring diagram.
Sample Code
#include <SoftwareSerial.h>
SoftwareSerial mySerial(11, 10); // RX, TX
const uint8_t HEADER_BYTE = 0xFF;
const uint16_t READ_TIMEOUT_MS = 200;
const int ERROR_DISTANCE = -1; // Error return value
void setup() {
Serial.begin(115200);
mySerial.begin(9600);
}
void loop() {
Serial.print("distance=");
Serial.print(getDistance());
Serial.println("mm");
}
uint8_t readN(uint8_t *buf, size_t len) {
size_t offset = 0, left = len;
uint8_t *buffer = buf;
long curr = millis();
while (left) {
if (mySerial.available()) {
buffer[offset] = mySerial.read();
offset++;
left--;
}
if (millis() - curr > READ_TIMEOUT_MS) {
break;
}
}
return offset;
}
/**
* Get distance data from the sensor
* @return Returns the distance value (non-negative) on success, -1 on failure
*/
int getDistance(void) {
uint8_t data[4] = { 0 };
uint8_t receivedByte = 0;
unsigned long startTime = millis();
while (millis() - startTime < READ_TIMEOUT_MS) { // Check if timeout
if (readN(&receivedByte, 1) == 1 && receivedByte == HEADER_BYTE) { // Find the header byte
data[0] = receivedByte;
if (readN(&data[1], 3) == 3) { // Read the remaining 3 bytes
uint8_t checksum = data[0] + data[1] + data[2]; // Checksum
if (checksum == data[3]) {
uint16_t distance = (data[1] << 8) | data[2]; // Calculate and return the distance
return distance;
}
}
}
Serial.println("Error data");
}
Serial.println("Error Reading data timeout");
return ERROR_DISTANCE;
}
Result
Open the Serial Monitor at 115200 baud rate to see the distance measurements in millimeters (e.g., distance=1953mm).
Ensure the sensor is powered with 3.3~5V as per the specifications.
Was this article helpful?
