Skip to content

Commit b13b53e

Browse files
committed
oled demo with 2 i2c ports!
1 parent 2e2035c commit b13b53e

File tree

2 files changed

+87
-1
lines changed

2 files changed

+87
-1
lines changed
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
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+
delay(50);
45+
uint32_t distance = ping_mm();
46+
delay(50);
47+
48+
display.clearDisplay();
49+
50+
display.setCursor(0, 30);
51+
display.print("I2C Sonar");
52+
display.setCursor(0, 50);
53+
54+
display.print("Ping: ");
55+
if (distance > 2) {
56+
display.print(distance, DEC); display.println(" mm");
57+
}
58+
59+
Serial.print("Ping mm: "); Serial.println(distance);
60+
61+
yield();
62+
display.display();
63+
}
64+
65+
uint32_t ping_mm()
66+
{
67+
uint32_t distance = 0;
68+
byte buffer[3];
69+
buffer[0] = 1;
70+
// write one byte then read 3 bytes
71+
if (! sonar_dev.write(buffer, 1)) {
72+
return 0;
73+
}
74+
delay(10); // wait for the ping echo
75+
if (! sonar_dev.read(buffer, 3)) {
76+
return 0;
77+
}
78+
79+
distance = ((uint32_t)buffer[0] << 16) | ((uint32_t)buffer[1] << 8) | buffer[2];
80+
distance /= 1000;
81+
82+
if ((distance <= 1) || (distance >= 4500)) { // reject readings too low and too high
83+
return 0;
84+
}
85+
86+
return distance;
87+
}

RCWL1601_I2C/arduino_simpletest/arduino_simpletest.ino

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ Adafruit_I2CDevice sonar_dev = Adafruit_I2CDevice(SR04_I2CADDR);
1010

1111

1212
void setup() {
13-
Wire.begin();
1413
Serial.begin(115200);
1514
while (!Serial);
1615

0 commit comments

Comments
 (0)