// Install from the Library Manager: // "Adafruit SSD1306" and "Adafruit GFX" #include #include #include // HC-SR04 pins const int TRIG_PIN = 7; const int ECHO_PIN = 8; // Graph ceiling (cm): further sits on top const int MAX_CM = 100; // Graph area: the screen's bottom 40 rows const int GRAPH_TOP = 24; const int GRAPH_H = 40; // Time between readings (ms) const unsigned long MEASURE_EVERY = 100; // 128x64 screen; I2C address mostly 0x3C Adafruit_SSD1306 oled(128, 64, &Wire, -1); // The last 128 readings, one per column byte history[128]; int newest = 0; unsigned long lastMeasure = 0; void setup() { pinMode(TRIG_PIN, OUTPUT); pinMode(ECHO_PIN, INPUT); Serial.begin(9600); if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { Serial.println("OLED not found"); // No screen: stop here while (true) {} } oled.setTextColor(SSD1306_WHITE); } // Distance in cm; -1 when no echo comes int measureCm() { digitalWrite(TRIG_PIN, LOW); delayMicroseconds(2); digitalWrite(TRIG_PIN, HIGH); delayMicroseconds(10); digitalWrite(TRIG_PIN, LOW); unsigned long echo = pulseIn(ECHO_PIN, HIGH, 30000); if (echo == 0) { return -1; } return echo / 58; } // Distance on top, recent readings below void draw(int cm) { oled.clearDisplay(); oled.setTextSize(2); oled.setCursor(0, 0); if (cm < 0) { oled.print("-- cm"); } else { oled.print(cm); oled.print(" cm"); } // Oldest reading left, newest right for (int x = 0; x < 128; x++) { int h = history[(newest + 1 + x) % 128]; int bottom = GRAPH_TOP + GRAPH_H - 1; oled.drawFastVLine(x, bottom - h, h + 1, SSD1306_WHITE); } oled.display(); } void loop() { if (millis() - lastMeasure < MEASURE_EVERY) { return; } lastMeasure = millis(); int cm = measureCm(); // Unmeasured or too far: right on top int shown = (cm < 0 || cm > MAX_CM) ? MAX_CM : cm; newest = (newest + 1) % 128; history[newest] = map(shown, 0, MAX_CM, 0, GRAPH_H - 1); draw(cm); if (cm < 0) { Serial.println("Distance: no reading"); } else { Serial.print("Distance: "); Serial.print(cm); Serial.println(" cm"); } }