I tried to run a pump when the distance to the ultrasonic sensor is too high/low. I copied something together from various examples. The sensor works and so does the pump, but when I combine both, the sensor does not measure reliably (sometimes only very small or very high values) and the pump runs irregularly or all the time. Can you take a look at the programming and structure and tell me what could be the problem?
Good advice! I made sure the pump wires and the battery are far away from the Uno and the ultrasonic sensor and now the pump does not turn on when the distance is less than 10cm (like it should) :). However, the serial monitor did not show anything after a few loops (but the pump still turned on/off as it should) and the pump partially ran too short (only a second).
Many people have problems with that pump causing interference with the Arduino and other parts.
To permanently fix the problem, you will need to buy a 0.1uF ceramic capacitor (C1) and a 1N4002 diode (D1).
Connect like shown below.
Don't use a 9V battery, the voltage is too way too high for that pump.
I have just used one of these Power Supply instead of the battery, but the serial monitor shut down again and the loops did not work after a few loops...
I have added a 6V power supply, the 0.1uF ceramic capacitor and a 1N4002 diode and now it works better! Thank you so much! However, sometimes the ultrasonic sensors shows odd values like 802 or 803, but I dont understand why...
If there is nothing in front of the sensor so that it can measure a distance, it will time out and return a large Time value and that will result in a large distance being shown
Thank you for all the help, Jim! I really appreciate it! After adjusting the code it works without problems.
Here is the final code.
int PUMPE = 11;
int ECHO = 6;
int SENDEN = 7;
long Entfernung = 0;
void setup()
{
Serial.begin(9600);
pinMode(SENDEN, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(PUMPE, OUTPUT);
}
void loop()
{
// Sender kurz ausschalten um Störungen des Signal zu vermeiden
digitalWrite(SENDEN, LOW);
delay(5);
// Signal senden
digitalWrite(SENDEN, HIGH);
delayMicroseconds(10);
digitalWrite(SENDEN, LOW);
// pulseIn -> Zeit messen, bis das Signal zurückkommt
long Zeit = pulseIn(ECHO, HIGH);
// Entfernung in cm berechnen
// Zeit/2 -> nur eine Strecke
Entfernung = (Zeit / 2) * 0.03432;
Serial.println(Entfernung);
delay(1000);
if (Entfernung>10 && Entfernung <200) {
digitalWrite(PUMPE, HIGH);
delay (3000); //3000 ist die Zeit in Millisekunden, die die Pumpe laufen soll
digitalWrite(PUMPE, LOW);
}
else if (Entfernung<10 || Entfernung >=200) {
digitalWrite(PUMPE, LOW);
delay (3000); //3000 ist die Zeit in Millisekunden, die die Pumpe laufen soll
}
}