ESP32 using A02YYUW
This works fine for interfacing an ESP32 to the A02YYUW Ultrasonic Sensor…
//The ESP32 knows that Serial2 pins are RX=16 and TX=17
unsigned char data[4]={};
float distance;
void setup()
{
Serial.begin(115200);
Serial2.begin(9600);
delay(3000);
Serial.println("Starting");
}
void loop()
{
if(Serial2.read()==0xff)
{
data[0] = 0xff;
for(int i=1;i<4;i++)
{
data[i]=Serial2.read();
}
int sum;
sum=(data[0]+data[1]+data[2])&0x00FF;
if(sum==data[3])
{
distance=(data[1]<<8)+data[2];
Serial.print("distance=");
Serial.print(distance/10);
Serial.println("cm");
}
}
data[0] = 0x00;
Serial2.flush();
delay(100);
}