me007ys_OLED.ino
1 // SPDX-FileCopyrightText: 2020 Limor Fried for Adafruit Industries 2 // 3 // SPDX-License-Identifier: MIT 4 5 #include <Adafruit_SSD1306.h> 6 #include <Fonts/FreeSans9pt7b.h> 7 8 Adafruit_SSD1306 display = Adafruit_SSD1306(128, 32, &Wire); 9 10 // Example code for DYP-ME007YS sensor 11 12 #if defined(__AVR__) || defined(ESP8266) 13 // For UNO and others without hardware serial, we must use software serial... 14 // pin #2 is IN from sensor (WHITE wire) 15 // Set up the serial port to use softwareserial.. 16 #include <SoftwareSerial.h> 17 SoftwareSerial mySerial(2, -1); 18 19 #else 20 // On Leonardo/M0/etc, others with hardware serial, use hardware serial! 21 // #0 is white wire, data input 22 #define mySerial Serial1 23 24 #endif 25 26 #define CONTROL_PIN 5 // This is the YELLOW wire, can be any data line 27 28 int16_t distance; // The last measured distance 29 bool newData = false; // Whether new data is available from the sensor 30 uint8_t buffer[4]; // our buffer for storing data 31 uint8_t idx = 0; // our idx into the storage buffer 32 33 void setup() { 34 // Open serial communications and wait for port to open: 35 Serial.begin(115200); 36 37 if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32 38 Serial.println(F("SSD1306 allocation failed")); 39 for(;;); // Don't proceed, loop forever 40 } 41 display.display(); 42 delay(500); 43 display.setTextColor(WHITE); 44 display.setFont(&FreeSans9pt7b); 45 display.setTextSize(1); 46 47 Serial.println("Adafruit DYP-ME007YS Test"); 48 49 // set the data rate for the Serial port, 9600 for the sensor 50 mySerial.begin(9600); 51 pinMode(CONTROL_PIN, OUTPUT); 52 digitalWrite(CONTROL_PIN, HIGH); 53 } 54 55 56 void loop() { // run over and over 57 if (mySerial.available()) { 58 uint8_t c = mySerial.read(); 59 Serial.println(c, HEX); 60 61 // See if this is a header byte 62 if (idx == 0 && c == 0xFF) { 63 buffer[idx++] = c; 64 } 65 // Two middle bytes can be anything 66 else if ((idx == 1) || (idx == 2)) { 67 buffer[idx++] = c; 68 } 69 else if (idx == 3) { 70 uint8_t sum = 0; 71 sum = buffer[0] + buffer[1] + buffer[2]; 72 if (sum == c) { 73 distance = ((uint16_t)buffer[1] << 8) | buffer[2]; 74 newData = true; 75 } 76 idx = 0; 77 } 78 } 79 80 if (newData) { 81 Serial.print("Distance: "); 82 Serial.print(distance); 83 Serial.println(" mm"); 84 newData = false; 85 display.clearDisplay(); 86 display.setCursor(0, 13); 87 display.print("UART Sonar"); 88 display.setCursor(0, 30); 89 display.print("Dist.: "); 90 display.print(distance); 91 display.println(" mm"); 92 display.display(); 93 } 94 }