int set = 20; //(4-20mA) It can be mapped with tank level
int err, actual, pv;
bool a = LOW;
int valve = 9;
int disp=0;
int step = 5; //(Minimum Step value-low error and slow response)
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
int sensor = analogRead(A0);
actual = map(sensor, 50, 950, 4, 20); //Input current sensor output
err = set - actual;
if (a == LOW) {
if (pv > 0) //empty
{
pv = err * 20 / 4 + 20;
} else //partially filled
{
pv = 20; // Should be equal to 4mA
}
a = HIGH;
}
if (err == 0) { pv = pv; }
if (err > 0) {
pv = pv + step; //(Minimum Step value-low error and slow response)
if (pv > 255) {
pv = 255; //SHould be equal to 20mA
}
}
if (err < 0) {
pv = pv - step; //(Minimum Step value-low error and slow response)
if (pv < 25) { pv = 20; }
}
analogWrite(valve, pv);
disp++;
if (disp > 10) //Display rate disp*delay
{
Serial.println("Sensor value");
Serial.println(sensor);
Serial.println("Actual value");
Serial.println(actual);
Serial.println("Error value");
Serial.println(err);
Serial.println("PV value");
Serial.println(pv);
disp = 0;
}
delay(100); //Response delay
}