/*
 ************************************************************** 
 *               Coal Hopper Fill Level Detector              * 
 *            Inspired by wokwi HC-SR04 example at            *
 *   https://wokwi.com/arduino/projects/304444938977804866    *
 *                Layout used as starting point               *
 *                  Copyright 2022 John Clark                 *
 *                       Version 0.10                         *
 **************************************************************
*/

#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);  //define I2C address 0x27, 16 column and 2 rows

#define PIN_TRIG 3
#define PIN_ECHO 2

const int bottomHopper = 175; // distance to bottom of hopper from sensor in cm
const int depthHopper = 120; // total depth of hopper in cm
int depthCoal; // depth of material covering feed slot
int percentCoal; // fill level of hopper
int lbsCoal; // lbs of coal over feed slot


void setup() {
  Serial.begin(115200);
  lcd.init();
  lcd.clear();
  lcd.backlight();
  pinMode(PIN_TRIG, OUTPUT);
  pinMode(PIN_ECHO, INPUT);
}

void loop() {
  // Start a new measurement:
  digitalWrite(PIN_TRIG, HIGH);
  delayMicroseconds(10);
  digitalWrite(PIN_TRIG, LOW);

  // Read the result:
  int duration = pulseIn(PIN_ECHO, HIGH);
  Serial.print("Distance in CM: ");
  Serial.println(duration / 58);
  Serial.print("Distance in inches: ");
  Serial.println(duration / 148);
  depthCoal = bottomHopper - (duration / 58);
  Serial.print("Depth of Coal (cm):");
  Serial.println(depthCoal);
  
  lcd.setCursor(0, 0);
  lcd.print("Depth coal:");
  lcd.print(depthCoal);
  lcd.print("cm ");

  percentCoal = map(depthCoal,0,depthHopper,0,100); // calculate fill percentage
  Serial.print("Fill level: ");
  Serial.println(percentCoal);

  lcd.setCursor(0,1);
  lcd.print("Fill level: ");
  lcd.print(percentCoal);
  lcd.print("% ");

  delay(1000);
}