/*

ULTRASONIC SENSOR TEST CODE

In this project I have used Arduino Uno r3 to test UltraSonic Sensor
I have also used an 128x32 OLED display (SSD1306)
You don't need to worry about display if you don't have the display right now
You can also see the resul on the serial monitor.
Anyone can use or modify no any permission is required.

GOOD LUCK!

*/


#include <Arduino.h>
#include <Adafruit_SSD1306.h>

// SSD1306 OLED Display
#define OLED_RESET -1
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 32
#define SSD1306_I2C_ADDRESS 0x3C
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

// PIN CONFIGURATIONS
#define ECHO_PIN 10  // Echo pin of the sensor
#define TRIG_PIN 8  // Trigger pin of the sensor

void setup() {
  Serial.begin(9600);    /*ARDUINO*/     // Disable if you are using ESP32 Dev Board 
  // Serial.begin(115200);   /*ESP32*/  // Enable if you are using ESP32 Dev Board

  // Set pin modes for the ultrasonic sensor
  pinMode(TRIG_PIN, OUTPUT); // Trigger is an output
  pinMode(ECHO_PIN, INPUT);  // Echo is an input

  // Initialize the OLED display
  if (!display.begin(SSD1306_SWITCHCAPVCC, SSD1306_I2C_ADDRESS)) {
    Serial.println(F("SSD1306 allocation failed"));
    for (;;); // Don't proceed, loop forever
  }

  display.clearDisplay();
  display.setTextSize(2);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(20, 13);
  display.print("PAKFONES");
  display.display();
  delay(1000);
  display.clearDisplay();
}

// Measure distance using the ultrasonic sensor
float getDistance() {
  // Ensure trigger pin is low
  digitalWrite(TRIG_PIN, LOW);
  delayMicroseconds(2);

  // Send a 10µs pulse to trigger the ultrasonic sensor
  digitalWrite(TRIG_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIG_PIN, LOW);

  // Measure the duration of the pulse on the echo pin
  long duration = pulseIn(ECHO_PIN, HIGH);

  // Calculate distance in cm (speed of sound is 0.034 cm/us)
  float distance_cm = (duration * 0.034) / 2.0;

  return distance_cm;
}

void loop() {
  // Read the distance
  float distance = getDistance();

  // Print the distance on the serial monitor
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");

  // Display the distance on the OLED
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(SSD1306_WHITE);
  display.setCursor(0, 0);
  display.print("Distance:");
  display.setTextSize(2);
  display.setCursor(0, 15);
  display.print(distance, 1);  // Display one decimal point
  display.print(" cm");
  display.display();

  delay(1000); // Update the display every half second
}