#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <Wire.h>
#define lebar 128
#define tinggi 64
#define reset -1
#define addr 0x3C
#define TRIG_PIN 9 // 9
#define ECHO_PIN 10 // 10
Adafruit_SSD1306 oled(lebar, tinggi, &Wire, reset);
void printCenter(String text,String mode,int tinggiTeks = 0,int ukuranText = 1,String warna = "putih") {
int16_t x1, y1;
uint16_t w, h;
uint16_t textColor;
if (warna == "putih") {
textColor = SSD1306_WHITE;
} else if (warna == "hitam") {
textColor = SSD1306_BLACK;
} else if (warna == "invert") {
textColor = SSD1306_INVERSE;
}
if (mode == "normal") {
oled.getTextBounds(text, 0, tinggiTeks, &x1, &y1, &w, &h);
while (w > lebar && text.length() > 0) {
text.remove(text.length() - 1);
text.trim();
text += "...";
oled.getTextBounds(text, 0, tinggiTeks, &x1, &y1, &w, &h);
}
int x = (lebar - w) / 2;
oled.setTextSize(ukuranText);
oled.setTextColor(textColor);
oled.setCursor(x, tinggiTeks);
oled.println(text);
} else if (mode == "full") {
oled.getTextBounds(text, 0, 0, &x1, &y1, &w, &h);
while (w > lebar && text.length() > 0) {
text.remove(text.length() - 1);
text.trim();
text += "...";
oled.getTextBounds(text, 0, 0, &x1, &y1, &w, &h);
}
int x = (lebar - w) / 2;
int y = (tinggi - h) / 2;
oled.setTextSize(ukuranText);
oled.setTextColor(textColor);
oled.setCursor(x, y);
oled.println(text);
}
}
void setup() {
Serial.begin(9600);
Wire.begin();
Serial.begin(9600);
if (!oled.begin(SSD1306_SWITCHCAPVCC, addr)) {
Serial.println(F("eror"));
while (true);
}
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
oled.clearDisplay();
printCenter("Penggaris Digital", "full", 0, 1, "putih");
oled.display();
delay(2000);
}
void loop() {
long duration;
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
float senti = (duration * 0.034) / 2;
float meter = senti / 100.0;
oled.clearDisplay();
printCenter("Jarak: " + String(senti) + " CM", "normal", 23, 1, "putih");
printCenter("Jarak: " + String(meter) + " M", "normal", 41, 1, "putih");
oled.display();
delay(200);
}