#include <LiquidCrystal_I2C.h>
// set the LCD number of columns and rows
const int lcdColumns = 16;
const int lcdRows = 2;
// set the trigger and echo pins
const int trigPin = 12;
const int echoPin = 14;
//set the pump trigger pins
const int pump1Pin = 15;
const int pump2Pin = 2;
//ccl4
//define sound velocity in cm/uS
#define SOUND_VELOCITY 0.034
#define CM_TO_INCH 0.393701
long duration;
float distanceCm;
float distanceInch;
// set LCD address, number of columns and rows
// if you don't know your display address, run an I2C scanner sketch
LiquidCrystal_I2C lcd(0x27, lcdColumns, lcdRows);
void setup(){
// initialize LCD
lcd.init();
// turn on LCD backlight
lcd.backlight();
// Starts the serial communication
Serial.begin(115200);
// Sets the trigPin as an Output
pinMode(trigPin, OUTPUT);
// Sets the echoPin as an Input
pinMode(echoPin, INPUT);
pinMode(pump1Pin, OUTPUT);
pinMode(pump2Pin, OUTPUT);
}
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);
// Calculate the distance
distanceCm = duration * SOUND_VELOCITY/2;
// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;
// set cursor to first column, first row
lcd.setCursor(0, 0);
// print message
lcd.print("Dist: ");
lcd.print(distanceCm);
lcd.print("cm");
// set cursor to first column, second row
lcd.setCursor(0, 1);
lcd.print("Dist: ");
lcd.print(distanceInch);
lcd.print("\"");
// pump1 is pump to supply water to water tank
// pump2 is pump out the water from water tank
// Assume Ultrasonic sensor is installed above water level
// Note: In simulation, the smallest value for ultrasonic sensor is 2cm,
// while the biggest value is 400cm.
if(distanceCm > 6.0){
digitalWrite(pump1Pin, HIGH);
digitalWrite(pump2Pin, LOW);
}
else if(distanceCm < 3.0 )
{
digitalWrite(pump2Pin, HIGH);
digitalWrite(pump1Pin, LOW);
}
else
{
digitalWrite(pump1Pin, LOW);
digitalWrite(pump2Pin, LOW);
}
delay(1500);
lcd.clear();
}