|
| 1 | +// SPDX-FileCopyrightText: 2022 Limor Fried for Adafruit Industries |
| 2 | +// |
| 3 | +// SPDX-License-Identifier: MIT |
| 4 | + |
| 5 | +#include <Adafruit_I2CDevice.h> // requires https://github.com/adafruit/Adafruit_BusIO |
| 6 | +#include <Adafruit_SSD1306.h> |
| 7 | +#include <Fonts/FreeSans9pt7b.h> |
| 8 | + |
| 9 | +#define SR04_I2CADDR 0x57 |
| 10 | +Adafruit_I2CDevice sonar_dev = Adafruit_I2CDevice(SR04_I2CADDR); |
| 11 | +// dont have a i2c device on bus faster than 100KHz, doesnt like it! |
| 12 | +Adafruit_SSD1306 display = Adafruit_SSD1306(128, 64, &Wire1); // connect to stemma qt - Wire1! |
| 13 | + |
| 14 | + |
| 15 | +void setup() { |
| 16 | + Serial.begin(115200); |
| 17 | + |
| 18 | + // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally |
| 19 | + if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3D)) { |
| 20 | + Serial.println(F("SSD1306 allocation failed")); |
| 21 | + for(;;); // Don't proceed, loop forever |
| 22 | + } |
| 23 | + |
| 24 | + display.display(); |
| 25 | + delay(1000); |
| 26 | + |
| 27 | + //while (!Serial); |
| 28 | + |
| 29 | + // Clear the buffer. |
| 30 | + display.clearDisplay(); |
| 31 | + display.display(); |
| 32 | + display.setFont(&FreeSans9pt7b); |
| 33 | + display.setTextSize(1); |
| 34 | + display.setTextColor(SSD1306_WHITE); |
| 35 | + |
| 36 | + if (! sonar_dev.begin(&Wire)) { |
| 37 | + Serial.println("Could not find I2C sonar!"); |
| 38 | + while (1); |
| 39 | + } |
| 40 | + Serial.println("Found RCWL I2C sonar!"); |
| 41 | +} |
| 42 | + |
| 43 | +void loop() { |
| 44 | + uint32_t distance = ping_mm(); |
| 45 | + |
| 46 | + display.clearDisplay(); |
| 47 | + display.setCursor(0, 30); |
| 48 | + display.print("I2C Sonar"); |
| 49 | + display.setCursor(0, 50); |
| 50 | + |
| 51 | + display.print("Ping: "); |
| 52 | + if (distance > 2) { |
| 53 | + display.print(distance, DEC); display.println(" mm"); |
| 54 | + } |
| 55 | + |
| 56 | + Serial.print("Ping mm: "); Serial.println(distance); |
| 57 | + |
| 58 | + yield(); |
| 59 | + display.display(); |
| 60 | + delay(50); |
| 61 | +} |
| 62 | + |
| 63 | +uint32_t ping_mm() |
| 64 | +{ |
| 65 | + uint32_t distance = 0; |
| 66 | + byte buffer[3]; |
| 67 | + buffer[0] = 1; |
| 68 | + // write one byte then read 3 bytes |
| 69 | + if (! sonar_dev.write(buffer, 1)) { |
| 70 | + return 0; |
| 71 | + } |
| 72 | + delay(10); // wait for the ping echo |
| 73 | + if (! sonar_dev.read(buffer, 3)) { |
| 74 | + return 0; |
| 75 | + } |
| 76 | + |
| 77 | + distance = ((uint32_t)buffer[0] << 16) | ((uint32_t)buffer[1] << 8) | buffer[2]; |
| 78 | + distance /= 1000; |
| 79 | + |
| 80 | + if ((distance <= 1) || (distance >= 4500)) { // reject readings too low and too high |
| 81 | + return 0; |
| 82 | + } |
| 83 | + |
| 84 | + return distance; |
| 85 | +} |
0 commit comments