#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
#define ECHO_PIN 10
#define kunci 13
bool stateKunci = false;
String keterangan;
float jarakTerkunci = 0;
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 textColor = SSD1306_INVERSE;
oled.setTextSize(ukuranText);
oled.setTextColor(textColor);
oled.getTextBounds(text, 0, tinggiTeks, &x1, &y1, &w, &h);
int x = (lebar - w) / 2;
int y = (mode == "center") ? (tinggi - h) / 2 : tinggiTeks;
oled.setCursor(x, y);
oled.println(text);
}
void setup() {
Serial.begin(9600);
Wire.begin();
if (!oled.begin(SSD1306_SWITCHCAPVCC, addr)) {
Serial.println(F("eror"));
while (true);
}
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(kunci, INPUT_PULLUP);
oled.clearDisplay();
printCenter("Penggaris Digital", "center", 0, 1, "putih");
oled.display();
delay(2000);
}
void loop() {
float distance;
if (digitalRead(kunci) == LOW) {
stateKunci = !stateKunci;
delay(200);
}
if (!stateKunci) {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long durasi = pulseIn(ECHO_PIN, HIGH);
distance = durasi * 0.0342 / 2;
jarakTerkunci = distance;
if (distance > 10) keterangan = "Masih Bagus";
else keterangan = "Dibuang";
}
oled.clearDisplay();
printCenter("Jarak: " + String(jarakTerkunci, 1) + " cm", "centerX", 16, 1, "putih");
printCenter(keterangan, "centerX", 40, 1, "putih");
if (stateKunci) printCenter("[TERKUNCI]", "centerX", 0, 1, "putih");
oled.display();
delay(200);
}