me007ys.ino
1 // SPDX-FileCopyrightText: 2020 Limor Fried for Adafruit Industries 2 // 3 // SPDX-License-Identifier: MIT 4 5 // Example code for DYP-ME007YS sensor 6 7 #if defined(__AVR__) || defined(ESP8266) 8 // For UNO and others without hardware serial, we must use software serial... 9 // pin #2 is IN from sensor (WHITE wire) 10 // Set up the serial port to use softwareserial.. 11 #include <SoftwareSerial.h> 12 SoftwareSerial mySerial(2, -1); 13 14 #else 15 // On Leonardo/M0/etc, others with hardware serial, use hardware serial! 16 // #0 is white wire, data input 17 #define mySerial Serial1 18 19 #endif 20 21 #define CONTROL_PIN 5 // This is the YELLOW wire, can be any data line 22 23 int16_t distance; // The last measured distance 24 bool newData = false; // Whether new data is available from the sensor 25 uint8_t buffer[4]; // our buffer for storing data 26 uint8_t idx = 0; // our idx into the storage buffer 27 28 void setup() { 29 // Open serial communications and wait for port to open: 30 Serial.begin(115200); 31 while (!Serial) { 32 delay(10); // wait for serial port to connect. Needed for native USB port only 33 } 34 35 Serial.println("Adafruit DYP-ME007YS Test"); 36 37 // set the data rate for the Serial port, 9600 for the sensor 38 mySerial.begin(9600); 39 pinMode(CONTROL_PIN, OUTPUT); 40 digitalWrite(CONTROL_PIN, HIGH); 41 } 42 43 44 void loop() { // run over and over 45 if (mySerial.available()) { 46 uint8_t c = mySerial.read(); 47 Serial.println(c, HEX); 48 49 // See if this is a header byte 50 if (idx == 0 && c == 0xFF) { 51 buffer[idx++] = c; 52 } 53 // Two middle bytes can be anything 54 else if ((idx == 1) || (idx == 2)) { 55 buffer[idx++] = c; 56 } 57 else if (idx == 3) { 58 uint8_t sum = 0; 59 sum = buffer[0] + buffer[1] + buffer[2]; 60 if (sum == c) { 61 distance = ((uint16_t)buffer[1] << 8) | buffer[2]; 62 newData = true; 63 } 64 idx = 0; 65 } 66 } 67 68 if (newData) { 69 Serial.print("Distance: "); 70 Serial.print(distance); 71 Serial.println(" mm"); 72 newData = false; 73 } 74 }