NewPing Library: HC-SR04, SRF05, SRF06, DYP-ME007, Parallax PING))) - v1.7

Hi :slight_smile: I'm a student who is completing an HND in systems engineering, my graded unit project inlvolves and arduino, ultrasonic sensor, relay switch, buzzer and a pump. When the ultrasonic see's my given high and low parameters is switches the relay which activates both my pump and buzzer for the duration of filling the tank.

I have the programme working fine :):slight_smile: however i'm experiencing rapid switching when the sensor reaches around my high and low level. Through some research I have now added hysteresis to help issues, however, i can't seem to get it to work properly.

I have posted the current adapted programme below, can anyone help? Please.....

// defines pins numbers
const int trigPin = 9;
const int echoPin = 10;
const int buzzer = 11;
const int relayPin = 13;

// defines variables
long duration;
int distance;
int lastDistance;
int hysteresis = 2;

void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
pinMode(buzzer, OUTPUT);
pinMode(relayPin, OUTPUT);
Serial.begin(9600); // Starts the serial communication
}

void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(1000);

// Sets the trigPin on HIGH state for 30 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(1000);
digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);

// Calculating the distance
distance= duration*0.034/2;

lastDistance = distance;
if ((lastDistance + hysteresis) <= 12 && (lastDistance - hysteresis) >= 4){
digitalWrite(buzzer, HIGH);
digitalWrite(relayPin, HIGH);
}

else{
digitalWrite(buzzer, LOW);
digitalWrite(relayPin, LOW);
}

// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
}