// LCD1602 to Arduino Uno connection example
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
//pin numbers
const int trigger=5,echo=6;
//variables:
float distance,duration;
int percent,prevPercent=0;
unsigned long startTime,currentTime=0;
//parameters:
//fullThreshold is percentage at which bin should be emptied
//delayTime is the delay between each loop in milliseconds
//maxDuration is the maximum time the bin can be left without being emptied
//binHeight is the height of the bin
//emptyThreshold is thepercent at which bin is considered empty
const int fullThreshold=75,delayTime=100,maxDuration=3000,binHeight=300,emptyThreshold=5;
void setup() {
Serial.begin(9600);
pinMode(trigger,OUTPUT);
pinMode(echo,INPUT);
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// start timer to empty bin even if it doesn't exceed fullThreshold
startTime=millis();
Serial.begin(115200);
delay(10);
Serial.println();
}
void loop() {
digitalWrite(trigger,LOW);
delayMicroseconds(5);
digitalWrite(trigger,HIGH);
delayMicroseconds(10);
digitalWrite(trigger,LOW);
duration=pulseIn(echo,HIGH);
//distance in cm = (speed in cm/s) * (duration in seconds divided by 2 for the back and forth trip)
distance = 34300 * (duration*0.000001/2);
percent = ((binHeight-distance)/binHeight)*100;
//for debugging purposes, distance can be displayed on serial monitor
/*
Serial.println (percent);
Serial.print ("Distance = ");
Serial.print (distance);
Serial.println (" cm");
*/
if (percent>100 || percent<0) {
lcd.setCursor(0, 0);
lcd.print("!!!ERROR!!! ");
lcd.setCursor(0, 1);
lcd.print(" ");
startTime=millis();
}
else if (percent>fullThreshold){
empty();
startTime=millis();
}else{
currentTime=millis();
if (currentTime - startTime > maxDuration){
empty();
}else{
display();
}
}
if(prevPercent>emptyThreshold && percent<=emptyThreshold){
startTime=millis();
}
prevPercent=percent;
delay(delayTime);
}
void empty(){
lcd.setCursor(0, 0);
lcd.print(percent);
lcd.print("% FULL!!! ");
lcd.setCursor(0, 1);
lcd.print("Please empty.");
}
void display(){
lcd.setCursor(0, 0);
lcd.print(percent);
lcd.print("% full ");
lcd.setCursor(0, 1);
lcd.print(" ");
}