#include <LiquidCrystal.h>
#define trigger 10
#define echo 11
#define servo 9
LiquidCrystal lcd(7,6,5,4,3,2);
float time=0,distance=0;
int temp=0;
const int servoPin = 9; //Servo Pin
float Kp = 2.5; //Initial Proportional Gain
float Ki = 0; //Initial Integral Gain
float Kd = 1.1; //Intitial Derivative Gain
double Setpoint, Input, Output, ServoOutput
PID myPID(&Input, &Output, &Setpoint, Kp, Ki, Kd, DIRECT); //Initialize PID object, which is in the class PID.
Servo myServo; //Initialize Servo.
void setup()
{
lcd.begin(16,2);
pinMode(trigger,OUTPUT);
pinMode(echo,INPUT);
pinMode(motor, OUTPUT);
lcd.print(" Water Level “);
lcd.setCursor(0,1);
lcd.print(” Indicator ");
delay(2000);
Serial.begin(9600); //Begin Serial
myServo.attach(servoPin); //Attach Servo
Input = readPosition(); //Calls function readPosition() and sets the water level
// position as the input to the PID algorithm
myPID.SetMode(AUTOMATIC); //Set PID object myPID to AUTOMATIC
myPID.SetOutputLimits(0,100); //Set Output limits to 0 and 100.
}
void loop()
{
lcd.clear();
digitalWrite(trigger,LOW);
delayMicroseconds(2);
digitalWrite(trigger,HIGH);
delayMicroseconds(10);
digitalWrite(trigger,LOW);
delayMicroseconds(2);
time=pulseIn(echo,HIGH);
distance=time*340/20000;
lcd.clear();
lcd.print("Water Space In ");
lcd.setCursor(0,1);
lcd.print("Tank is: ");
lcd.print(distance);
lcd.print(“Cm”);
delay(2000);
if(distance<12 && temp==0)
Setpoint = 15;
Input = readPosition();
myPID.Compute(); //computes Output in range of 0 to 100 degrees
ServoOutput=102+Output; // 102 cm
myServo.write(ServoOutput); //Writes value of Output to servo
{
digitalWrite(servo, LOW);
lcd.clear();
lcd.print("Water Tank Full ");
lcd.setCursor(0,1);
lcd.print(“servo Turned OFF”);
delay(2000);
digitalWrite(LOW);
delay(3000);
temp=1;
}
else if(distance<12 && temp==1)
{
digitalWrite(servo, LOW);
lcd.clear();
lcd.print("Water Tank Full ");
lcd.setCursor(0,1);
lcd.print(“servo Turned OFF”);
delay(5000);
}
else if(distance>30)
{
digitalWrite(servo, HIGH);
lcd.clear();
lcd.print(“LOW Water Level”);
lcd.setCursor(0,1);
lcd.print(“servo Turned ON”);
delay(5000);
temp=0;
}
}
loat readPosition() {
delay(10); //Don’t set too low or echos will run into eachother.
const int pingPin = 7; //Trig Pin Arduino 7
const int pingPin2 = 6; //Echo Pin Arduino 6
long duration, cm;
unsigned long now = millis();
pinMode(pingPin, OUTPUT);
digitalWrite(pingPin, LOW);
delayMicroseconds(2);
digitalWrite(pingPin, HIGH);
delayMicroseconds(5);
digitalWrite(pingPin, LOW);
pinMode(pingPin, INPUT);
duration = pulseIn(pingPin2, HIGH);
cm = duration/(29*2);
if(cm > 30) // 30 cm is the maximum position for the ball // make 35
{cm=25;} // make 30
Serial.println(cm);
return cm; //Returns distance value.
}