The pump does not switch

The stand is needed to regulate the water level.

The HC-SR04 ultrasonic sensor measures the water level, if it reaches the desired level, which is preset in the sketch, the pump should switch, but the pump does not switch and starts working from the moment I just insert the batteries.

Connected everything according to the connection scheme:

схема подключений

The ultrasonic sensor detects the level, this can be understood from the video, when I put my hand to the sensor and a dim light signal lights up on the arduino board, the level is also displayed in the port monitor, in the arduino ide program.

Video with a demonstration of the system: 1 - YouTube

When I connect the VCC from the relay to the batteries, the pump turns off and the lights on the relay light up, but it does not respond to the ultrasonic sensor in any way, video: 2 - YouTube

Link to the sketch: AutoNasos — Яндекс.Диск

The system uses:
relay JQC-3FF-S-Z
pump MINI DC6-12V R385
arduino nano v3 board

What needs to be changed so that when the water reaches the specified range, the pump turns off/on?

Did you test the ultrasonic sensor by itself before putting it near the water? Did it report the distance properly?

Your frizzy picture is not readable. Try drawing a schematic for clarity. Also add links to technical information on the hardware devices. A few observations; maybe you're lucky, that relay will blow your Arduino. Your pump is rated with a 6V minimum, your 3V from the battery will not work. There are other problems as well.

The ultrasonic sensor works correctly and determines the distance to the object, the distance is displayed in the port monitor in the Arduino IDE

Hello polyana1
Post your current sketch, well formated, with comments and in so called code tags "</>" and a schematic, not a Fritzy diagram, to see how we can help.
Have a nice day and enjoy coding in C++.
Дайте миру шанс

The pump works, but does not switch under the right conditions, which are prescribed in the sketch

The system consists of:
HC-SR04 Ultrasonic sensor
Touch button TTP223
Arduino Nano V3
Key switch KCD1-101
Lithium rechargeable battery HG2
Piezo squeaker for signal
MINI DC6-12V R385 Water Pump
Relay for switching on the load JQC-3FF-S-Z
Float switch

//Программа управления насосом по датчику расстояния
#include "Ultrasonic.h"


boolean pereliv = 0; //переменная для хранения значения с датчика перелива
boolean key = 0;    //переменная для хранения значения с кнопки (1 если кнопка нажата, 0 если нет)
boolean trevoga = 0; //переменная сигнализирующая о наличии тревоги
float maxLevel=4.00;  //расстояние в сантиметрах, соответствующее максимальному уровню жидкости в емкости
float minLevel=7.00; //расстояние в сантиметрах, соответствующее минимальному уровню жидкости в емкости

Ultrasonic ultrasonic(3, 4); //подключили датчик расстояния (TRIG к 3 пину. ECHO к 4)



void setup()
{
  Serial.begin(9600); 	 // запускаем серийный порт
  pinMode(8, INPUT_PULLUP);  //ПОДКЛЮЧИЛИ ПИН КНОПКИ (ИСПОЛЬЗУЕТСЯ ДЛЯ ОТКЛЮЧЕНИЯ РЕЖИМА ТРЕВОГИ)
  pinMode(10, INPUT_PULLUP);  //ПОДКЛЮЧИЛИ ПИН ПОПЛАВКОВОГО ВЫКЛЮЧАТЕЛЯ (НА СЛУЧАЙ ПЕРЕЛИВА)
}

void loop()
{
  float rast = ultrasonic.Ranging(CM); 	// получаем расстояние с ультразвукового датчика и сохраняем его в rast
  pereliv = digitalRead(10); // считываем состояние поплавкового выключателя
  key = digitalRead(8); // считываем состояние кнопки

  Serial.print(rast); 					// выводим растояние до воды в монитор порта
  
  if (rast > minLevel) { //если растояние до поверхности воды больше 7 см
    digitalWrite(12, HIGH);  //включаем питание на реле
    digitalWrite(13, HIGH);  //подаем сигнал реле на включение насоса
    Serial.println("    OnNasos");
  }

  if (rast < maxLevel) { //если растояние до поверхности воды меньше maxLevel;
    digitalWrite(13, LOW); //даем сигнал на отключение реле
    digitalWrite(12, LOW); //отключаем питание реле
      Serial.println("    OFFNasos");
  }

  if (pereliv == 1) {//если сработал поплавковый выключатель, то
    trevoga = 1;  //включаем режим тревоги
  }

  if (trevoga == 1) {  //если режим тревоги включен, то
    digitalWrite(13, LOW); //даем сигнал на отключение реле
    digitalWrite(12, LOW); //отключаем питание реле
    tone(7, 2500, 250); //подаем сигнал тревоги с частотой 2500 и длительностью 250мс
  }

  if (key == 1) {  //если нажата кнопка, то
    trevoga = 0;  //отключаем режим тревоги
  }

 if (trevoga == 0) {  //если режим тревоги отключен, то
    noTone(7);  //отключаем пьезопищалку
  }



  delay(500); 								// задержка

  
}

None will read data from external sources !

The stand is designed to maintain the liquid level in the specified ranges.
It should work according to the principle according to which the Arduino Nano microcontroller polls the ultrasonic sensor, determining the distance to the surface of the liquid. The program determines the minimum and maximum distance to it. The Arduino Nano microcontroller must turn the pump off and on, automatically maintaining the liquid level in the specified ranges. Additionally, a float switch is installed to protect against overflow. In case of an emergency, for example, if the ultrasonic distance sensor does not work, the float will work to prevent flooding, and the Arduino Nano microcontroller will turn off the pump and give a signal to the sound emitter, the signal of which will indicate an emergency, to turn off the alarm, you need to press the touch button.

The point of the relay is to isolate the pump electrically from the Arduino. Since you're using one power supply for both, the relay is offering no protection.

My choice would be to use a MOSFET in place of the relay which isolates the arduino port pin from the motor. For testing I would just use the LED on the relay module to determine if it is on or off. I think you may get better results as your are very weak on the power side. The link points to a relay, not a relay module, there is a big difference. Relays have a minimum pull in voltage, if it is not met or exceeded it may not work. It appears you have the batteries connected to Vin, that is asking for problems as there is a voltage drop across the regulator. All of this and more would have been easy to get from a proper schematic.

Hi, @polyana1
Welcome to the forum.
Please draw your circuit and post an image of it.
Take your time and include power supplies, component names and pin labels.

This will provide us with a more informative diagram.
I understand you did not write this code.

Forget the code you have for the moment.

You now need to write some code, JUST to use your Ultrasonic Sensor, nothing else.
The Ultrasonic Library should have some examples for you to use, to check if you are communicating with the sensor.
Code that JUST reads the Ultrasonic sensor.

You are now in troubleshooting mode and you need to take logical steps to find your problem.

Tom.... :smiley: :+1: :coffee: :australia:

Hi,
If this is your library, this example should work.

/*
 * Ultrasonic Simple
 * Prints the distance read by an ultrasonic sensor in
 * centimeters. They are supported to four pins ultrasound
 * sensors (liek HC-SC04) and three pins (like PING)))
 * and Seeed Studio sensors).
 *
 * The circuit:
 * * Module HR-SC04 (four pins) or PING))) (and other with
 *   three pins), attached to digital pins as follows:
 * ---------------------    --------------------
 * | HC-SC04 | Arduino |    | 3 pins | Arduino |
 * ---------------------    --------------------
 * |   Vcc   |   5V    |    |   Vcc  |   5V    |
 * |   Trig  |   12    | OR |   SIG  |   13    |
 * |   Echo  |   13    |    |   Gnd  |   GND   |
 * |   Gnd   |   GND   |    --------------------
 * ---------------------
 * Note: You do not obligatorily need to use the pins defined above
 * 
 * By default, the distance returned by the read()
 * method is in centimeters. To get the distance in inches,
 * pass INC as a parameter.
 * Example: ultrasonic.read(INC)
 *
 * created 3 Apr 2014
 * by Erick Simões (github: @ErickSimoes | twitter: @AloErickSimoes)
 * modified 23 Jan 2017
 * by Erick Simões (github: @ErickSimoes | twitter: @AloErickSimoes)
 * modified 03 Mar 2017
 * by Erick Simões (github: @ErickSimoes | twitter: @AloErickSimoes)
 * modified 11 Jun 2018
 * by Erick Simões (github: @ErickSimoes | twitter: @AloErickSimoes)
 *
 * This example code is released into the MIT License.
 */

#include <Ultrasonic.h>

/*
 * Pass as a parameter the trigger and echo pin, respectively,
 * or only the signal pin (for sensors 3 pins), like:
 * Ultrasonic ultrasonic(13);
 */
Ultrasonic ultrasonic(3, 4);
int distance;

void setup() {
  Serial.begin(9600);
}

void loop() {
  // Pass INC as a parameter to get the distance in inches
  distance = ultrasonic.read();
  
  Serial.print("Distance in CM: ");
  Serial.println(distance);
  delay(1000);
}

Set the IDE serial monitor to 9600 baud.

Tom... :smiley: :+1: :coffee: :australia:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.