SuggestionsArduino

ME007YS and A02YYUW Updated code

userHead ryandetzel 2024-03-17 03:46:06 1322 Views0 Replies

The example code doesn't work that well if you have other things using CPU or delays. I updated the code with no delays and this works better for my use case so figured I would share. I left it basic so it's easier to read

 

 

https://gist.github.com/ryanrdetzel/6105a605caf01a89de18e51ffcbe0de8

 

 

```

#include <SoftwareSerial.h>


 

https://wiki.dfrobot.com/_A02YYUW_Waterproof_Ultrasonic_Sensor_SKU_SEN0311#target_5


 

SoftwareSerial mySerial(17,16); // RX, TX

unsigned char data[4]={};

float distance;


 

void setup()

{

Serial.begin(9600);

mySerial.begin(9600);

}


 

int mode = 0;

int i = 0;


 

void loop()

{

// Find start byte

// Read remaining three bytes

// Rest

if (mySerial.available()) {

unsigned char byteRead = mySerial.read();

if (mode == 0 && byteRead == 0xff) {

data[i] = byteRead;

mode = 1;

i++;

// Serial.println("Found start byte");

} else if (mode == 1 && i <= 3){

// i = 1

data[i] = byteRead;

i++;

} else if (i == 4){

// validate checksum

int sum= (data[0] + data[1] + data[2]) & 0x00FF;

if (sum == data[3]) {

int distance = (data[1]<<8) + data[2];

for (int i=0;i<sizeof(data);i++){

char hexCar[2];

sprintf(hexCar, "%02X", data[i]);

Serial.print(hexCar);

}

Serial.print(" ,");

Serial.print(distance);

}

Serial.println("");

mode = 0;

i = 0;

}

}

```