Hi I'm new user. I want to make an automate refilling water tank using ultrasonic sensor HC SR04 to defined the distance and using solenoid valve as an actuator. I want to use millis but i still confused how to used it. Here's I attached the code
'
const int trigPin = 4;
const int echoPin = 5;
const int waterRelayPin = 8;
unsigned long duration, distance;
unsigned long currentMillis = millis();
unsigned long distanceMillis;
bool Flag = false;
void setup()
{
pinMode(trigPin, OUTPUT);
digitalWrite(trigPin, LOW);
pinMode(waterRelayPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop()
{
if (millis() - distanceMillis > 500)
{
distanceMillis = millis();
Distance();
}
if(Flag == false && distance <= 30)
{
Flag = true;
Serial.println("Water Pump : ON");
digitalWrite(waterRelayPin, LOW);
previousMillis = millis();
}
else
{
Flag = false;
Serial.println("Water Pump : OFF");
digitalWrite(waterRelayPin, HIGH);
}
}
void Distance()
{
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration * 0.034 / 2;
int percentage = map(distance, 24, 6, 0, 100);
if(percentage < 0){
percentage = 0;
}
else if(percentage > 100){
percentage = 100;
}
Serial.print("Water Level: ");
Serial.println(percentage);
}'