File tree Expand file tree Collapse file tree 2 files changed +51
-0
lines changed
RCWL1601_I2C/arduino_simpletest Expand file tree Collapse file tree 2 files changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ // SPDX-FileCopyrightText: 2022 Limor Fried for Adafruit Industries
2
+ //
3
+ // SPDX-License-Identifier: MIT
4
+
5
+ #include < Adafruit_I2CDevice.h>
6
+ // requires https://github.com/adafruit/Adafruit_BusIO
7
+
8
+ #define SR04_I2CADDR 0x57
9
+ Adafruit_I2CDevice sonar_dev = Adafruit_I2CDevice(SR04_I2CADDR);
10
+
11
+
12
+ void setup () {
13
+ Wire.begin ();
14
+ Serial.begin (115200 );
15
+ while (!Serial);
16
+
17
+ if (! sonar_dev.begin (&Wire)) {
18
+ Serial.println (" Could not find I2C sonar!" );
19
+ while (1 );
20
+ }
21
+ Serial.println (" Found RCWL I2C sonar!" );
22
+ }
23
+
24
+ void loop () {
25
+ Serial.print (" Ping mm: " ); Serial.println (ping_mm ());
26
+ delay (100 );
27
+ }
28
+
29
+ uint32_t ping_mm ()
30
+ {
31
+ uint32_t distance = 0 ;
32
+ byte buffer[3 ];
33
+ buffer[0 ] = 1 ;
34
+ // write one byte then read 3 bytes
35
+ if (! sonar_dev.write (buffer, 1 )) {
36
+ return 0 ;
37
+ }
38
+ delay (10 ); // wait for the ping echo
39
+ if (! sonar_dev.read (buffer, 3 )) {
40
+ return 0 ;
41
+ }
42
+
43
+ distance = ((uint32_t )buffer[0 ] << 16 ) | ((uint32_t )buffer[1 ] << 8 ) | buffer[2 ];
44
+ distance /= 1000 ;
45
+
46
+ if ((distance <= 1 ) || (distance >= 4500 )) { // reject readings too low and too high
47
+ return 0 ;
48
+ }
49
+
50
+ return distance;
51
+ }
You can’t perform that action at this time.
0 commit comments