/********* Pleasedontcode.com **********

	Pleasedontcode thanks you for automatic code generation! Enjoy your code!

	- Terms and Conditions:
	You have a non-exclusive, revocable, worldwide, royalty-free license
	for personal and commercial use. Attribution is optional; modifications
	are allowed, but you're responsible for code maintenance. We're not
	liable for any loss or damage. For full terms,
	please visit pleasedontcode.com/termsandconditions.

	- Project: "Distance Display"
	- Source Code compiled for: Arduino Uno
	- Source Code created on: 2024-01-14 14:50:45

********* Pleasedontcode.com **********/

/****** SYSTEM REQUIREMENTS *****/
/****** SYSTEM REQUIREMENT 1 *****/
	/* find the distance the distance between the device */
	/* and opaque object */
/****** END SYSTEM REQUIREMENTS *****/

/****** DEFINITION OF LIBRARIES *****/
#include <Arduino.h>
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#include <U8g2_for_Adafruit_GFX.h>

/****** FUNCTION PROTOTYPES *****/
void setup(void);
void loop(void);

/***** DEFINITION OF DIGITAL INPUT PINS *****/
const uint8_t sensor_HC_SR04_Echo_PIN_D3 = 3;

/***** DEFINITION OF DIGITAL OUTPUT PINS *****/
const uint8_t sensor_HC_SR04_Trigger_PIN_D2 = 2;

/***** DEFINITION OF I2C PINS *****/
const uint8_t oled_SSD1306OledDisplay_I2C_PIN_SDA_A4 = A4;
const uint8_t oled_SSD1306OledDisplay_I2C_PIN_SCL_A5 = A5;
const uint8_t oled_SSD1306OledDisplay_I2C_SLAVE_ADDRESS = 0x3C;

/****** DEFINITION OF LIBRARIES CLASS INSTANCES*****/
Adafruit_SSD1306 display(oled_SSD1306OledDisplay_I2C_SLAVE_ADDRESS, oled_SSD1306OledDisplay_I2C_PIN_SDA_A4, oled_SSD1306OledDisplay_I2C_PIN_SCL_A5);
U8G2_FOR_ADAFRUIT_GFX u8g2_for_adafruit_gfx;

void setup(void)
{
  // put your setup code here, to run once:
  pinMode(sensor_HC_SR04_Echo_PIN_D3, INPUT);
  pinMode(sensor_HC_SR04_Trigger_PIN_D2, OUTPUT);

  display.begin(SSD1306_SWITCHCAPVCC);
  u8g2_for_adafruit_gfx.begin(display);
}

void loop(void)
{
  // put your main code here, to run repeatedly:
  
  // Measure distance using HC-SR04 sensor
  digitalWrite(sensor_HC_SR04_Trigger_PIN_D2, LOW);
  delayMicroseconds(2);
  digitalWrite(sensor_HC_SR04_Trigger_PIN_D2, HIGH);
  delayMicroseconds(10);
  digitalWrite(sensor_HC_SR04_Trigger_PIN_D2, LOW);
  
  unsigned long duration = pulseIn(sensor_HC_SR04_Echo_PIN_D3, HIGH);
  float distance = duration * 0.034 / 2;
  
  // Display distance on OLED display
  display.clearDisplay();
  u8g2_for_adafruit_gfx.setFont(u8g2_font_helvR14_tf);
  u8g2_for_adafruit_gfx.setCursor(0,20);
  u8g2_for_adafruit_gfx.print("Distance: ");
  u8g2_for_adafruit_gfx.print(distance);
  u8g2_for_adafruit_gfx.print(" cm");
  display.display();
  
  delay(1000); // Wait for 1 second before measuring distance again
}
