/*
Ultrasonic Sensor HC-SR04 and Arduino Tutorial
by Dejan Nedelkovski,
www.HowToMechatronics.com
*/
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
// defines variables
long duration;
int distance;
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
#define OLED_RESET -1 // Reset pin tidak terhubung
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
// initialize OLED display with address 0x3C for 128x64
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
while (true);
}
delay(2000); // wait for initializing
display.clearDisplay(); // clear display
// display.setTextSize(1); // text size
// display.setTextColor(WHITE); // text color
// display.setCursor(0, 10); // position to display
// display.println("Hello World!"); // text to display
// display.display(); // show on OLED
}
void loop() {
// Clears the trigPin
// digitalWrite(trigPin, LOW);
// delayMicroseconds(2);
// // Sets the trigPin on HIGH state for 10 micro seconds
// digitalWrite(trigPin, HIGH);
// delayMicroseconds(10);
// digitalWrite(trigPin, LOW);
// // Reads the echoPin, returns the sound wave travel time in microseconds
// duration = pulseIn(echoPin, HIGH);
// // Calculating the distance
// distance = duration * 0.034 / 2;
// // Prints the distance on the Serial Monitor
// Serial.print("Distance: ");
// Serial.println(distance);
// Mengukur jarak menggunakan sensor ultrasonik
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) * 0.0343;
// Menampilkan hasil ke layar OLED
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(0, 0);
display.print(F("Jarak: "));
display.print(distance);
display.print(F(" cm"));
display.display();
delay(1000); // Delay satu detik antara pengukuran
}