#include #include #include #include #include // Ultrasonic sensor pins Ultrasonic ultrasonic(0, 1); // Button on pin 9 to GND Button button(9); // OLED Pin setup #define SCREEN_WIDTH 128 #define SCREEN_HEIGHT 64 Adafruit_SSD1306 oled(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1); void setup() { Serial.begin(9600); button.begin(); // OLED init if (!oled.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { Serial.println(F("SSD1306 allocation failed")); while (true); } oled.clearDisplay(); oled.display(); } void loop() { if (button.pressed()) { int distance = ultrasonic.read(); // Convert to string String text = String(distance) + " cm"; // Choose big font oled.setTextSize(2); // Adjust size as needed for "big" oled.setTextColor(SSD1306_WHITE); // Calculate text bounds for centering int16_t x1, y1; uint16_t w, h; oled.getTextBounds(text, 0, 0, &x1, &y1, &w, &h); int x = (SCREEN_WIDTH - w) / 2; int y = (SCREEN_HEIGHT - h) / 2; // Display centered text oled.clearDisplay(); oled.setCursor(x, y); oled.print(text); oled.display(); } }