Integrated Design and Control of a Sustainable Stormwater Treatment System

: In this work, issues of water separation and puri ﬁ cation are addressed, where, in order to achieve the desired results, it is necessary to use several disciplines such as classical physics, bio-technology, automatic control, automation, and applications of industry 4.0. Further, the need for comprehensive and automated solutions for rainwater treatment in the agricultural sector is addressed. This research focuses on designing and implementing a system adapted to these needs using Siemens technologies. The methodology ranges from the design of the Piping and Instrumentation Diagram (P&ID) to the implementation of the interface, incorporating Siemens technologies for data acquisition, electrical connections, treatment programming, and PID controller design. The results show signi ﬁ cant advances in the development of the system, highlighting the e ﬀ ectiveness of automation and the HMI-PLC human–machine interface in process monitoring and control. These ﬁ ndings support the viability of a comprehensive rainwater treatment system for the agricultural sector, with important implications for water e ﬃ ciency, environmental preservation, and increased productivity in agricultural and livestock activities. The contribution of this work is the relationship between engineering and research focused on industrial processes. The scienti ﬁ c contribution is to obtain the dynamic models and apply two strategies to obtain the gains of the PID controller. The ﬁ rst method is performed through the proposal of a Hurwi tz polynomial, and the second is performed through genetic algorithms (GA), where they are implemented in a controller that is commonly used in the industry. The technological part includes the integration of work (schemes, programming, and communications) so that the result is as close to what was expected.


Introduction
Rainwater harvesting is an ancient practice that was used to combat the risk of floods and droughts; it is currently more important because it helps supply water needs in areas where there is a water shortage [1].
An important part of rainwater collection is the continuous study of the amount of rainfall that occurs annually.Thus, the Internet of Things (IoT) is a device with network connectivity that helps detect and collect data that can then be used, in this case, in rainwater harvesting systems coupled to wireless sensor networks (WSN) that help maintain constant inspection of the infrastructure [2].
In rainwater treatment systems, automation and control are important, leading to better control over the unit operations that make up this system.Each of the unit operations maintains a range in each of its parameters for optimal operation.This set of unitary operations will have the objective of being able to use rainwater until it is purified, for which it is important to comply with current water regulations for each of the countries.In Mexico, the standard in charge of defining the maximum permissible limits of water quality for human use and consumption is NOM-127-SSA1-2021.This standard indicates the physical, chemical, and biological parameters that the treated water must meet [3].
According to CONAGUA, [4] the country is losing its water quality, and in addition to this, water scarcity in Mexico has been increasing.This is causing millions of dollars in losses in livestock and agriculture and thus raising the food costs of the basic basket.Important data on water contamination include the existence of solids in drinking water, such as manganese, iron, feces, nitrates, and mercury.These types of pollutants greatly affect livestock farming, resulting in poor-quality food for human consumption [5].
On the other hand, the amount of drinking water that exists globally is only 0.3% [3].
In addition to all these details, the largest percentage of water goes to livestock and agricultural processes.[6] indicates that Mexico fortunately has 0.1% of all the fresh water on the planet.However, poor water care habits directly harm the citizens of Mexico.On the other hand, the contamination of aquifers represents an additional problem to waste and low availability and is generated when untreated wastewater is discharged regardless of its origin, whether domestic, industrial, agricultural, or mining.In 2010, more than 70% of Mexico's water bodies were polluted, especially those in the Valley of Mexico.
In general, Mexico is losing large amounts of water, and with the growing population growth, food consumption continues to increase.Agriculture and livestock in certain seasons have created water cuts to such an extent that in 2019, Mexico inaugurated the first seawater desalination plant in the American continent.The sole purpose of the plant was to support a region of Baja California, and this was only for agricultural cultivation [7].
Water is extremely important for all living beings on this earth, and certain types of strategies are often proposed to improve its quality or misuse it.One study [8] details a method of water filtration that employs a self-cone design and uses physical-chemical processes to make the water drinkable.
Some publications mention that one of the best ways or alternatives to supply clean water is through rainwater harvesting in households; [9] provides a statistical analysis of rainwater harvesting in 11 homes and in 2 seasons (dry season and wet seasons), where the results showed that the parameters that meet the clean water quality standard are turbidity, iron, manganese, nitrate, and nitrite at both observation times.Meanwhile, color, pH, TDS, and E. coli exceed the clean water quality standard.The highest volume of rainwater runoff was 20.59 m 3 for the first week, and that of the second week was 14.06 m 3 .In conclusion, the rooftop catchment area significantly affects the quantity and quality of rainwater runoff and can potentially be used as a clean water supply through a simple water treatment unit.
In a similar way, in [10], the authors talk about the quality of rainwater on rooftops, where they conclude that the parameters involved are pH, temperature, conductivity, dissolved oxygen (DO), total suspended solids (TSS), ammonia nitrogen (NH3-N), biochemical oxygen demand (BOD), chemical oxygen demand (COD), E. coli, and total coliform bacteria.The results showed that the total WQI values before and after treatment were 86.3 ± 8.963 and 87.6 ± 2.081, respectively.Positive correlations were found for the NH3-N parameter, COD, and pH, while the paired T test showed a significant correlation between COD and the presence of bacteria.Total coliforms are still at a safe level according to NWQS, with an average value and standard deviation for before and after treatment of 38.11 ± 13,960 cfu/mL and 10.33 ± 6.671 cfu/mL, respectively.This results in a safe and hygienic method, where no extensive processes are needed for water filtration and purification.
In [11], mathematical expressions are used to determine the best method to use for water harvesting.
On the other hand, in [12], the authors use a photocatalysis method for rainwater purification, where they develop a decontaminating zinc (Zn) roof covered by ZnO nanostructures (NS) using a one-step seedless hydrothermal growth method in 2 h.
Much has been said about physical and chemical methods; however, few works talk about how to clean water using radiofrequency.An example of such a work is seen in [13], where a radio frequency (RF) treatment system is introduced to purify the water from the source with a small chance of contamination.RF is generated by applying a frequency of 1.5 MHz through a 2 mm diameter glass reactor that is wrapped by a 2 mm copper wire.The results show that the UV260 value and dissolved organic carbon (DOC) are reduced during RF treatment.DOC was reduced by a smaller amount compared to UV260, suggesting a partial transformation of biorefractory DOM.A fluorescence excitation emission matrix showed that humic-type substances in rainwater were reduced faster than proteintype substances, indicating that humic-type substances are susceptible to reduction by radiofrequency treatment.The results provide information on the use of RF treatment in a rainwater purification process for the production of drinking water.
An article that can greatly support the underpinnings of this work is [14], which summarizes the principles and classification of sustained-release technologies, as well as the typical methods of preparation of sustained-release agents.By introducing the progress of applied research of sustained-release technologies in environmental fields such as rainwater purification, wastewater/drinking water treatment, and soil and atmosphere remediation, the application characteristics of these sustained-release technologies and their prospect of application in environmental remediation were evaluated.In water treatment, it was specially planned.
Changing the subject a bit, the industrial demand for automating its processes has been increasing, where these days automation is not only in the scope of the process that is carried out being automatic, but this process can be seen on local screens within the company (industry 3.0).Better yet, this process can be visualized and controlled from remote locations.To accomplish this, it is important to analyze a large number of risks that exist in automation.One work that details this part is [15].It provides information on SCADA systems, security tips, vulnerabilities in networks, industrial protocols, and programming.Therefore, this publication supports the idea of not using CoDeSys software due to its great vulnerabilities and opting for software from Allen Bradley and Siemens.The software of Siemens and its team is chosen for its great benefits when programming and configuration of its protocols, in addition to its costs.
In [16], there is work applied to the Internet of Things (IOT).Using an Arduino card, the interface that contains the communication protocols is developed to upload information to a cloud and download this information so that the output signals are activated.
One of the problems when automating processes that have a large number of variables and interactions between alternate processes is that they fail if any of their variables (sensors) do not send the signal; therefore, it is important to take into account a method when programming the industrial process.In [17], a hybrid method is developed that combines the "control diagram with stages and transitions" (GRAFCET) programming method with the "Study guide for start and stop modes" (GEMMA), which is called a generator.GEMMAGRAFCET.An interesting part of the article is that it leaves the programming of the block with "C" code, which is suitable for any PLC.The programming method used in this work is a hybrid method where heuristic programming, the cascade method, and function blocks are combined.
In [18], a nitrogen protection device is built based on ultraviolet spectrophotometry, complemented with a programmable logic controller (PLC), to form an automatic control system for the direct detection of target substances (SO 4 2−, Pb 2 + and S 2−) in zinc hydrometallurgy.When reading this work, it is observed that the piping and instrumentation diagram is not standardized under a standard.This does not indicate that it is wrong, but this point is used in favor of the work so that the piping and instrumentation diagrams are as close as possible to the ISA standards.A highlight of [18] is the quality of the absorption charts.
In [19], there is a proposal for a technological architecture that allows the supervision and control of the operating parameters of gas injection (flow, temperature, and pressure) in a cluster of a high-pressure gas injection plant.The contribution taken from this work is its architectural system, which is broken down little by little until the solution of the problem is reached.
The process of automating and monitoring processes is not only applied to industrial processes but also to domestic issues and naval processes; an example of this is [20], which carried a PLC-based communication system and established a test bench facility in cooperation with SK Telecom Co., Ltd. and Hyundai Heavy Industries Co., Ltd.
The authors of [21] talk about the importance of implementing the lineless assembly concept focused on the production of industrial systems, which can be known or searched for as digital twin systems.The objective of this work is the development and implementation of a software architecture for the planning and control of a lineless assembly system.The approach of this work is very similar to our own.
An important means for industrial automation and national defense, the degree of application of hydraulic control technology has become an important symbol of measuring the level of industrialization of a country.In [22], the accuracy of hydraulic control systems is often difficult to guarantee due to non-linear factors such as leaks, contaminants, processing errors, and component degradation [23].
Automatic control and industrial processes can be found in different areas; one of them is agriculture.In fact, today, there are several investigations that talk about automated processes in agriculture.An example of this is [24].This work discusses a biomass hot air oven in which its temperature is controlled by means of Diffuse PID control.
This starts from the assumption that the control accuracy of a hydraulic control system (valve control system and pump control system) and its related PID control algorithms must be ensured to reduce the energy consumption of the system [25].
One of the details of the design and development of a PID controller is to find its gains, and there are different methods and strategies used to find these gains.One interesting method is seen in [26], where they use the mapping of the poles and zeros of the inverted pendulum to later see the geometric location of the roots of each PID controller.
There are a wide variety of strategies for the design and development of the PID.An interesting work is [27], where the design and implementation of a PID control for a second-order plant is carried out.Most of the variables measured in an industrial process (pressure, temperature, flow, voltage or current in a motor, and pH, among others) are second-order systems.
PID control began in 1920; however, industrial application began between the 1980s and 1990s.In fact, today, at an industrial level, it is still widely used due to ease of implementation, application, and results.There are many cases where different types of controllers with PID control are compared, such as [28,29].
On the other hand, there are new methods used to find controller gains; these methods are known as intelligent algorithms.One of the best known is the particle swarm optimization (PSO) method.One such study is [30].This work discusses the combination of a fuzzy PID controller with obtaining gains using the PSO method applied to an induction motor.Very similar cases can be seen in [31][32][33][34].c.Integration of the HMI with the Siemens PLC to enable real-time adjustments and efficiency optimization.d.Extensive interface testing and tweaking based on user feedback.

Development of the Piping and Instrumentation Diagram (P&ID)
The objective of this chapter is to provide a solution to the problem of water scarcity through rainwater treatment, which is achieved with automation.
This work improves by implementing work in the cloud (industry 4.0) and being able to monitor and control it from a computer or an intelligent computer.
In this subsection, the process for rainwater treatment is known, which consists of five stages.The first is the storage of rainwater; the second is the sand filter, which is responsible for removing a lot of sludge; the third is the storage of water free of visible solids; and the fourth is the elimination of odors, microscopic particles, and some heavy metals; finally, the fifth treatment stage involves anionic resins, where its function is to soften the water.This means eliminating minerals such as calcium (Ca) and magnesium (Mg).On the other hand, it also helps to eliminate nitrates and nitrites.It is worth mentioning that the final product is only used for domestic cleaning, hand washing, and toilets, and the option is left for treatment for human consumption.This can be seen in Figure 1.
In Figure 1, all processes are automated with the aim of visualizing the variables and controlling those variables.

Dynamic Model and Controller Design
In this chapter, a dynamic model of the project is created, the objective of which is to determine which method is the most optimal to be able to control certain parts of the process.The processes that need automatic control are as follows: 1.The level of the sand filter and the control of the TB50 tank level.2. The inlet and outlet pressure that exists in the anionic resin tank.
Knowing which method is the most optimal enables cost savings in the purchase of equipment.
For point number one, the control that can be used is "On-Off" and likewise by means of a PID controller.In Figure 2, the P&ID of the thread is shown, where the most ideal situation is to perform a regulated level control for the sand filter and "On-Off" control for the TB50 tank.The PID control is carried out in the sand filter because the pressure in it cannot be greater, and if the level is higher than expected, logically, the pressure inside this tank is higher, which causes the fine sands to mix with the coarse sands at 3 kg/cm 2 .Therefore, in Figure 3, a dynamic model of the sand filter thread is made, and in addition to this, a dynamic model is made where the sand filter and the TB50 interact.
In Figure 3, the P&ID for the anionic resin process is shown.The objective here is to control the pressure with which it enters the tank, because if it exceeds 5, the anionic resin goes toward the consumption intake.In terms of control type, it is a PID control applied on the V1 control valve, kg/cm 2 .
On the other hand, the closing and tightening of the V2 valve is controlled, taking into account that the outlet pressure must be 20% of an "On-Off" pressure of 5 kg/cm 2 .

Dynamic Model of the Sand Filter
Taking into account Figure 2, the sand filter part is made as a dynamic model.To develop such a model, the movement of a particle through a fluid is considered, as shown in Equation ( 1): We can solve  from Equation (1): where  is the mass of the particles in the fluid, and  is the exit velocity.
The tank outlet flow for the case of a cross-section is To make the equations of the inlet and outlet valve, considering the flow that circulates through the valve is in steady state, the following equation is proposed: where  is flow through the valve,  is a constant (m /s),  is a passage area, and  is the differential pressure across the valve 2 − 1.
In a practical way, a valve with an automatic behavior is taken, where it is able to make a more or less linear approximation between the flow  and the opening of the outlet valve, resulting in where  is the opening of the outlet valve, and  is the permeability of the water flow.
For the inbound flow, it looks like this: To find the differential equations that define the dynamics of the system, we start from Equation (7), where Equations ( 5) and ( 6) are substituted, resulting in Equations ( 8) and (9), where these equations are nonlinear.

Simulation of the Sand Filter Differential Equation
For the development of this section, Matlab and Simulink software are used, taking into consideration the ODE45 equation solver and the values of Table 1.
Table 1.Parameters of the dynamical system of Equation (9).To carry out the simulation, the equation is taken as a reference (9), and by making a block diagram, you can obtain the solution of the system, which is seen in Figure 4.In Figure 4, the maximum height it reaches is 46 m; this indicates that at this height, the system stabilizes since the inlet pressure with respect to the outlet is the same and does not allow further growth in the height.On the other hand, through Equation (10), it is possible to obtain the pressure exerted on the outlet valve (valve 1 of Figure 2),

Id
where  is the density of water, 1000 kg/m ;  is gravity; and ℎ is height.The results that are obtained are seen in Table 2.It is worth mentioning that the pressure exerted by a half-horsepower pump is 52.72927 kgf/cm , and can reach a height of 35 m.The interesting point of these calculations is how the dynamical model of the equation behaves (9).When water permeability is applied, the permeability is nothing more than a plug that prevents water from flowing, even through the opening of valve 1 of Figure 2. In fact, if the valve is closed, the pressure it will exert on the sand filter container will be much greater.Hence, it is important to perform PID control.

Development of the PID Driver
For the development of the controller, the equation is taken as a reference (9).This is linearized, which results in Equation (11), represented by two terms.The first term corresponds to the input flow, and the second term corresponds to the output flow.
Subsequently, the PID control is defined, which is shown in Equation ( 12): where Equation ( 12) can be represented in frequency as follows: Equation ( 13) can be defined as Taking Equations ( 11) and ( 14) into account, considering that it is a system is a feedback system, the following equation can be obtained: where By means of a Hurwitz polynomial, and taking into account the denominator of G, the gains for the PID can be found, which are seen in Equation ( 16), where the gain and  = 18,  = 12 = 6.6 + + 18. (16)

PID Controller Gains Optimization Using Genetic Algorithms
In this subsection, the objective is to improve the gains of the controller so that the output response of the system has a response with better performance; for this, an optimization method is used, which is known as a genetic algorithm.It is intended to evaluate the output function of the feedback system iteratively, where the genetic algorithm method selects the best gains that make the system error closer to zero.In Figure 5, you can see what is described.The profits obtained are as follows:  = 61.3731892931105, = 2.425  = 59.298Some works that talk about genetic processes and algorithms include [31][32][33][34].In general, the genetic algorithm (GA) starts with several solutions randomly to generate new answers until reaching the most optimal solution after placing the weights and setting the limits ([0.1, 01, 01] and [100, 100, 100]).The population size  is 100, and the maximum number of iterations is 300, with a mutation probability of 0.01%.The probability equation  for each individual to be selected becomes Equation (17): where  is the mean square error.
The iterations of the genetic algorithm are seen in Figure 6, where the average fitness is between iteration 9 and 45.This is because the maximum limit was 100 for each of the gains; subsequently, there was average fitness and better fitness.In iteration 168, they were closer, with a distance of 0.56.

Simulation of PID Control Applied to Level Control
To carry out the simulation, the equation is taken as a reference, ( 9) and (16).By making a block diagram, you can obtain the solution of the system, which is shown in Figure 7.The salt signal reaches the reference signal in approximately 5 s; the reason for keeping the water level at 0.8 m is due to the pressure it exerts on the sand filter.It can be neither less nor greater because the different granules of stones and sands can be combined, and this affects its filtering process.In the event that the pressure is lower, the water will not flow into the "TB50" tank.It is worth mentioning that through an automated process, when the pressure is lower than indicated, valve 1 will close.

Simulation of Optimal PID Control Applied to Level Control
To perform the simulation, Equations ( 9) and ( 16), Figure 5, and the gains of the optimal PID are taken as reference, which are  = 61.374, = 2.425 and  = 59.298.The resulting response is seen in Figure 8.
The use of these new gains greatly improves the response of the system, where I shortened the response time and eliminated overshoot.This avoids the concern that the sands will combine due to the pressure exerted by the peak height in Figure 7.
It is worth mentioning that the PLC can accept hundreds and hundredths; if any of the gains had been more than three figures before and after the decimal point, said gains could not have been placed in the PLC's PID.

Dynamic Model for Resin Tank
In this subsection, a procedure very similar to the previous one is carried out.The difference lies in the fact that the dynamic model to be found is focused on the behavior of the flow and pressure within the pipe.For this, the reference is taken as Figure 3.
For this case, it is necessary to know the behavior of the flow of the liquid through the pipe, and, in this way, know the pressure that is exerted at that point.The equation that describes this is (19), also known as Bernoulli's equation applied to a tube.
where  is the atmospheric pressure,  is the pressure that the fluid carries,  is the density of the liquid of the pressure gauge,  is the gravity, and ℎ is the difference in heights.This can be seen in Figure 9, and the Pitot tube used to determine the speed is shown in Figure 10.The mathematical expression that describes Figure 9 is seen in the following equation: where  is the speed.An interesting point in Equation ( 19) and ( 20) is that ℎ it is unknown and, in addition to that, is variable.For this, you can write a differential equation that represents ℎ.To find the pressure that is generated in a pitot tube in a variable way, we look for the mathematical expression that represents Figure 10, where, in this case, it depends on the outflow of the hole and the flow inflow through the Pitot tube.The mathematical expression that describes this is Equation ( 21) where  is the inflow,  is the outflow, and where  is the cross-section or area of the inlet pipe, which is greater than the outlet hole.

𝑄 = 𝜑 2𝑔ℎ (23)
where  is the cross-section or area of the exit hole.This can be found by  in Equation (20) or by the characteristics provided by the pump.In this case, the characteristics given for the pump are considered where the flow rate of the pump is of 42 L/min, which is equivalent to  = 0.0007 m /s. =  .The equation that represents the pressure is where ℎ is the solution to Equation (21).For  , the density of twice the density of water is considered:  = 992.92kg/m .

Simulation of the Differential Equation for the Resin Tank
In this section, the dynamics of water pressure through a tube are represented.The equation is considered to be (24).Table 3 is the same, which are the values for the simulation.The results of the simulation are shown in Figure 11.In Figure 11, the maximum displacement it reaches is 2.1 cm, considering the data in Table 3. Taking into consideration the maximum speed of the pump, the time it takes you to reach this height is about a second.Broadly speaking, this is coherent, since the maximum height of the tube is 12 cm, and the time must be in an instant.To further corroborate, the model is considered  = 0 m /s a, and it must give a displacement equal to zero.This can be seen in Figure 12.This gives as an indicator that if the inlet flow is controlled, the height and the pressure can be controlled, since they are related.
On the other hand, in Figure 13, you can see the behavior of the pressure, where it reaches a maximum pressure of approximately 20 kgf/m in one second.It should be clarified that this pressure is not the pressure you are looking for, since if you leave this pressure inside the resin tank, it will combine the resins with the already treated water.Therefore, it is necessary to carry out its control.In Figure 13, it is seen that the system is stable.In addition to this, it is fast.This gives it a lot of advantage when performing the control in closed loop, since the gains of the controller will be very small.

Optimization of the PID Controller Gains through Genetic Algorithms Applied to the Pressure Going to the Resin Tank
In this subsection, the objective is to implement an optimization strategy to improve the gains of the PID controller and, in this way, improve the response to its output.Figure 14 shows the procedure used to obtain these gains.For this case, its limits were [0.1, 01, 01] and [50, 50, 50].Its population size  was 50; the limit of iterations was 30, but 20 iterations were enough to assume the optimal values, a mutation probability of 0.05%.The results of the GA are seen in Figure 15, where in iteration number 20, it had the closest distance, with a value of 3.5621.

Simulation of PID Control Applied to the Pressure Going to the Resin Tank
This section takes into consideration Equations ( 24) and ( 14).The development in Section 2.2.3 is also taken into consideration.What is intended to be manipulated is the input flow ( ) of Equation ( 14), which translates into opening or closing the valve by a certain percentage.
In Figure 16, you can see the pressure signal when you apply the PID control.You can see that the reference value finds it quickly, and that in about 7 to 8 s, it finds the desired value.In this case, the reference value that is sought is of 3.5 ((kgf)/(m 2 )), which is indicated so that it does not affect the resin tank.
The small impulse that it generates does not physically affect the resin tank since it does not reach the 5 ((kgf)/(m 2 )), which is the limit for the treated water to mix with the resins and end up going out for consumption.
The value of the winnings that were used for this system are  = 22,  = 10,  = 1.For this section, Equations ( 14) and ( 24) and Figure 14 are taken as reference, where the genetic algorithm gives gains of  = 35,  = 18,  = 25, and the simulation results are seen in Figure 17.If the comparison is made between Figures 16 and 17, it can be seen that in Figure 17, there is an improvement in the response time, which is 2.44 s.Remark 1.These research findings apply when the integration is carried out and the PID is activated.The idea is not to obtain the gains from the controller by trial and error.In a few words, the profits obtained by the aforementioned methods will be placed and tested in the prototype.

Electrical and Electronic Process Connections
In this section, the electrical and electronic connections of the water collection and treatment process are made, which are focused on the electronic instrumentation and actuators that are going to be used.This section is based on Figure 1.Measuring the level of liquid inside the first storage tank is achieved through the arrangement of transistors, resistors, and LEDs, where the idea is to send a series of cables of certain measurements inside the tank that indicate the level of the tank when there is continuity.This diagram is shown in Figure 18.Subsequently, the diagram of the pressure sensor is made.This type of sensor is analog, which sends a signal of 0-10 Vcd, which is connected to analog inputs of the PLC.This diagram can be seen in Figure 19.It is worth mentioning that Figures 18 and 19 are repeated twice, one for the TB50 tank and another for the anionic resin tank (TRA).Taking into account the connections of Figures 18 and 19 and the push buttons to be used for starting, stopping, automatic or manual activations, and PID activation, the diagram of connections of the inputs of the PLC is made.This can be seen in Figure 20.It is worth mentioning that the PLC that is used requires the purchase of expansion modules for digital inputs and analog inputs.
To make the connections of the PLC outputs, Figure 1 is used to visualize the number of actuators that are used in the process.In general, there are eight actuators, which are generally pumps and solenoids.For the solenoid part, the solenoid valve has a spring return.As a description, when the solenoid is activated, the water passage is closed, and when the solenoid is deactivated, the return of the solenoid valve is through a spring.This helps to avoid using more outlets and, in addition to this, fewer relays are used and, in the same way, use a 24 vdc source with a higher current capacity.
On the other hand, an outlet is used to make a change of rotation of a variable solenoid valve.The diagram of the digital outputs can be seen in Figure 21.
In Figure 22, you can see the connections of the pumps, which have a basic protection with fuses and thermomagnetic switches.The starting of these pumps is at full voltage so the pumps should not exceed 6 amperes or half horsepower (1/2 ).If this happens, it is necessary to modify the fuses and thermomagnets or buy a soft starter for each motor.
In Figure 23, you see the solenoid connections for the solenoid valves that connect to the hydraulic pipes; such solenoid valves consume 0.5 amperes at 24 vcd.
Finally, the electrical, electronic diagram of the analog output is made, which also involves a digital output of the digital output module.The goal here is that when pressure sensors detect a variation in their pressures, control is exerted.
PID regulates an analog solenoid valve; in a nutshell, it opens or closes by a percentage automatically.To accomplish this, it is necessary to make a power stage, where the motor has to rotate in both directions and, in addition to this, stay in a position depending on the pressure sensors.For this, the TB6600 card is used; the analog input that reaches said card must be 5 Vdc.Otherwise, it can burn.To fix this, only Ohm's law applies; however, a better solution would be to use a solid-state relay.This wiring diagram is seen in Figure 24.

Scheduling the Water-Treatment Process
In this section, the programming of the water-treatment process is carried out.In order to achieve the programming, it is necessary to see the section of the P&ID and the electrical connections.The equipment to be used is a Siemens PLC model LOGO version 8.In addition, it is necessary to use expansion modules for digital inputs and digital outputs, as well as an expansion module for analog inputs and analog outputs.The software used is LOGOSoft version 8.
In Figure 25, you can see the ladder programming, which is handled in different stages.This depends on each of the sub-processes that there are for the water treatment.Within the former is a three-stage level control (low, medium, and high), where the bomb goes off if it is at a low level and defuses if it is at a high level.Subsequently, the level of the sand filter is programmed, where to measure the level of the sand filter, it is necessary to know the pressure that the tank has; it is worth mentioning that this is an analog signal.If the level sensor is low, two solenoid valves are closed until a high or medium-high level is reached; these are directed to a storage tank called TB50.Such programming is seen in Figure 26 and part of Figure 27.In the resin tank sub-process, the pressure at both ends of the tank must be monitored so that the resin does not leave the tank.In addition to this, the flow and pressure are controlled by means of an analog solenoid valve that closes and opens as a percentage, depending on the pressure of sensor 1 or sensor 2. It is worth mentioning that the pressure that the pipe must have is 2 to 5 kg/cm 2 .Within the programming, the average is 3 kg/cm 2 .In the same way, there are some buttons for the activation of the automatic mode (activation of the PID) and other buttons for the activation of solenoid valves that take the water to the drain or consumption.When the drain solenoid valve is activated, a cleaning process is carried out in the tank.This schedule can be seen in Figures 28-30

Industrial Communications and Networks
This section shows you how to configure the ethernet NETWORK to communicate.As a first point, a star-type industrial communication topology is created.This is used for the benefit it provides, where the first point of connection will be the PLC.This equipment is the one that will be communicating with the visualizations and the drives that occur within the HMI and, in the same way, will be processing the communication of the physical inputs and outputs.
The communication used for the PLC is a PROFINET-type communication.A STEREN brand router is used; this router has WiFi and ethernet-type access.The configuration is performed as follows: 1.The ethernet cable that comes from the main switch of the TESCo connects to the router's WLAN in order to maintain the internet on the computer equipment or smart equipment.2. On the router, you need to generate IP addresses for the WiFi part and the ethernet part.This is performed in order for all equipment to be in communication with the PLC and the web address.3.Each computer on the LAN port has its IP address, as shown in Figure 31.4. For smart devices, your WiFi port is configured with the IP address, as seen in Figure 32. 5.The connections between the different computers are checked for communication; this can be checked by pinging the computer.In Figure 33, you can see how this situation plays out.6.If there is communication between them, there will be communication when they enter the computer's web server.It is worth mentioning that all teams will be able to enter.7.In a Google or Edge search engine, you enter the IP address of the PLC; it sends you to a Siemens website.8. Enter your password.9.It opens a window where you can see the HMI that was made.This can be seen in

Experimental Results
For the experimentation section, virtual TAGS are made that exemplify real entries.The physical part in its entirety cannot be exemplified because the filters exceed the personal budget; however, in mid-March 2024, it is intended to participate in a call to download resources and will be able to carry out the physical part.
In Figure 35, you see the login to the Siemens WEB server, where the password is loaded.In Figure 36, you can see the cover of the HMI, where, on the left side of the cover, a brown triangle appears, which displays the different screens of the HMIs.In Figure 37, the start of the HMI is seen.
In Figure 38, the interaction of the HMI with the PLC and the PID is shown, where PV in the blue graph is the value of the sensor, SP is the reference value to which you want to reach (in this case, it is a value of 500 bits, or 50% of a signal ranging from 0 to 100%), and AQ is the value of the analog output (which is at a value from 0 to 1000 bits, where 0 equals 0 Vdc and 1000 bits equals 10 Vdc).
The goal here is for PV to take a 500-bit or 5 Vdc measurement on the PLC's analog input.For a better visualization of the process, you can see the following link.

Remark 2. Carrying out these projects with a Siemens controller and modules has a low cost.
Another advantage when implementing Siemens technology is its robust industrial work.In addition to this, the equipment comes very complete, which is integrated with different technologies such as PROFINET communication; LSD memory to read the HMI, connection to the cloud; reading of TP-100 thermocouples; advanced programming blocks, for example, arithmetic; trigonometric functions; and PWM and PID, among others.An example of this is at the time of purchase, the PLC and PLC software does not have blocks to be able to create a PID controller block or the generation of a PWM.Therefore, it is necessary to buy a separate controller or integrate microcontroller cards (Arduino, Raspberry), where the microcontroller performs the PID controller function, and the PLC performs the processing part.
It is worth mentioning that not everything developed uses Siemens equipment.An example of this is the controllers for the motors; in this case, very basic controllers are used.

Discussion
The aim of this project is for readers-whether engineers or researchers-to be able to read and reproduce this research and improve certain aspects of the work.
One of the points that came into discussion is the use of different control strategies, such as a model-free control, the application of a disturbance rejection control, and PID control-fuzzy, as well as signal enhancement using Kalman filters or observer applications.However, for the development of the project with the use of a PID, it is more than enough to obtain the desired answers.
Another point of discussion was which card to use, whether it is "Arduino", "Raspberry", or "PLC".It was decided to use a PLC since many of its protocols are already standardized.After this decision, it was necessary to see that PLC met all the requirements to develop the project and, in addition to this, that it was economical and easy to acquire.The PLC that was used is "6ED1052-1CC08-0BA1", with the expansion modules "6ED1055-1CB10-0BA2", "6ED1055-1MA00-0BA2", and "6ED1055-1MM00-0BA2".A point in favor of this team is that it can take the variables to the cloud and thus be able to visualize or control the entire process from a remote point.
On the other hand, one of the aims of future works is to reproduce this work in less ideal conditions and not in a prototype way and see if the PLC can cope with these needs or if it is necessary to use another type of microcontroller card.In the same way, another aim is to see if, in these conditions, the control strategy that is proposed can perform a good result in conditions that are no longer so ideal, such as implementing it at different heights, temperatures, atmospheric pressures, and greater volumes.
The results of the graphs of Figures 16 and 38 have variations.This is due to the sampling times of the simulation software (Matlab and Simulink) with respect to the sampling times of the PLC being different; however, both reach the desired value in times that do not affect the product that is being sought (water without anionic resins).
In Figure 38, the red signal "AQ" represents the number of output bits of the PLC; the green signal "SP" is the reference value that was left at 50% of its maximum value; and the signal "PV" is the measured signal from the sensor, which has a value similar to the value of the "SP".
One of the drawbacks of the results of Figure 38 is not being able to bring this graph to a figure format (*JPG, *PNG, or *SVG); one way to solve this in the future is by using a National Instruments data acquisition card "NI USB-6002 USB", which obtains the output data from the analog sensors, and this is visualized in Matlab or LabView.In the same way, an Arduino Mega 2560 card can be used; the drawback of this is the voltage that supports its input of 5 volts maximum.For this, you would have to perform scaling within its programming, which could alter the real signal.

Conclusions
This project aims to develop a comprehensive rainwater treatment system for the agricultural sector and has represented a significant step toward ensuring efficiency and sustainability in the management of water resources.By integrating advanced filtration and automatic control technologies through Siemens and HMI platforms, it has been possible to design a solution adapted to the complexities and demands of the agricultural environment, contributing to the improvement of water management practices in this sector.
In order to carry out linear programming of a product, it is necessary to know the manufacturing process of the product; in this case, of treated rainwater, it is necessary to carry out the processing system of transformation of rainwater to treated water (consumption for plants, cleaning in general for livestock, and agricultural consumption).This process can be called "manufacturing process for rainwater treatment", which is achieved in each of the chapters of development.One of the drawbacks is that it could not be performed physically due to the costs of the material to be used and some equipment.However, the idea is to participate in a project to lower resources and be able to implement it.
The creation and implementation of the P&ID have provided a detailed understanding of the physical and chemical interactions in the stormwater-treatment process.The integration of Siemens technologies for data acquisition has enabled specific adjustments to meet agricultural needs, thus improving the accuracy of the system.Obtaining the P&ID was complicated because there were points at which it was not known for sure if it was necessary to implement an automatic system; however, with the research carried out in Chapter 1, it can be read that it is necessary to eliminate certain minerals and heavy metals that can affect livestock or plants.The only way to achieve this is through the use of different filters, where these filters need to maintain adequate pressure so as not to damage them or generate a mixture of treated water with certain resins.At this point, it can be read that it is necessary to make an automated system that complies with a certain standard.
The development of the dynamics was complicated since the dynamic model must have a similarity very close to reality because the gains of the PID controller depend a lot on the dynamic model.Within the simulations and experiments that were carried out, the dynamic model was greatly adapted until reaching an adequate similarity; this was achieved without altering the laws that make up the dynamic model.
In the automation and design part of the human-machine interface, the objective was achieved, as it could be verified by making simulated signals that represent the manufacturing process in a real way.In this way, it is verified that the programming that is released works.However, the physical implementation would be best.
As a simulation within the website, the variables of pressure and level were varied arbitrarily; however, doubt remained as to whether the gains of the controller that were placed in the PLC were adequate.Therefore, Chapter 5 was born, which talks about the level and pressure in the most important filters-in this case, the sand filter and the resin tank.Then, the controller will be applied to this mathematical model.It is concluded that the system by nature is stable and can be controlled using low gains, either in the case of the level or pressure.In the same way, it is a matter of seeing that the overpluses of the output signal with control are not higher than the maximum values within the filters.
Taken together, these specific achievements and advances meet the overall objective of the project by providing a comprehensive and tailored solution for stormwater treatment in the agricultural sector.The implementation of Siemens and HMI technologies not only improves the efficiency and sustainability of water resources but also sets a standard for advanced water management practices in agriculture and livestock.This work represents a significant step toward building resilient and effective water systems in the specific context of agricultural activities.

1 . 6 .
Design and Implementation of the Piping and Instrumentation Diagram (P&ID): a.A comprehensive review of the existing literature on stormwater-treatment processes and their representation by means of a piping diagram and instrumentation.b.Identification of the key physical and chemical interactions in the rainwatertreatment process applied to the agricultural sector.c.Integration of Siemens technologies for data acquisition in the P&ID.d.Validation of the P&ID through preliminary simulations and adjustments according to the specific characteristics of the system.2. Dynamic Modeling of the Sand Filter and Resin Tank: a. Development of mathematical models that dynamically describe the behavior of the sand filter and the resin tank.b.Simulation of differential equations associated with a specific focus on Siemens technologies to optimize process performance.c.Validation of models by comparison with experimental data and adjustments to accurately reflect the behavior of the actual system.3. PID Controller Design and Tuning: a. Design of a specific PID controller using Siemens technologies to regulate the level of the sand filter and the pressure of the resin tank.b.Implementation of advanced automatic control techniques to improve process efficiency and stability.c.Controller tuning through simulations and hands-on testing in the stormwater treatment system.4. Establishing Electrical and Electronic Connections: a. Detailed definition of the electrical and electronic requirements of the stormwater treatment system.b.Selection of Siemens components that meet industry standards and are compatible with the safe and efficient operation of the system.c.Design of a diagram of electrical and electronic connections, considering the integration of Siemens technologies and ensuring compatibility with the selected components.d.Verification and validation of connections through preliminary safety and efficiency tests.5. Development of the Water-Treatment Process Programming: a. Definition of the specific programming requirements of the process, considering the optimal management of resources and adaptability to changing conditions.b.Programming of advanced control logic using Siemens automation systems.c.Integration of climate adaptability algorithms to ensure efficient operation in different weather conditions.d.Verification and testing of programming in simulated environments prior to practical implementation.Implementation of Industrial Communications: a. Selection of Siemens technologies for the implementation of industrial communications.b.Configuration of communication systems that allow remote monitoring, control, and data collection of the stormwater treatment system.c.Integration of standard communication protocols to ensure compatibility and efficiency in data transmission.7. Human-Machine Interface (HMI) System Integration: a. Selection and configuration of Siemens components for HMI implementation.b.Design of the graphical interface of the HMI for local monitoring and control of the process.

Figure 1 .
Figure 1.P&ID of the rainwater collection and treatment process implemented.

Figure 2 .
Figure 2. P&ID of the sand filter process and the TB50.

3 1 6
Flow constant  = 0.092 m /s 4 Valve Area Constant 1  = 0.015 m 5 Water ingress based on the flow pressure generated by the engine  = Opening the outlet valve valve 1

Figure 4 .
Figure 4. Dynamic model of the sand filter.

Figure 5 .
Figure 5.-Diagram of GA blocks for the sand filter.

Figure 6 .
Figure 6.Iterations of the sand filter genetic algorithm.

Figure 8 .
Figure 8. System output response with optimal gains.

Figure 12 .
Figure 12. -Dynamic pattern of the displacement of the Pitot tube when  = 0.

Figure 14 .
Figure 14.-AG block diagram for the resin tank.

Figure 16 .
Figure 16.-PID control applied to resin tank inlet valve.2.2.11.Simulation of Optimal PID Control Applied to the Pressure Going to the Resin Tank s

Figure 17 .
Figure 17.-System output response with optimal gains for the resin tank.

Figure 24 .
Figure 24.-Electricalconnection from the analog output to the analog solenoid valve.

Figure 34 .
Note: In the Experiments chapter, you can see in more detail what is proposed at this point.

Figure 32 .
Figure 32.Networking of computer equipment and smart equipment.

Table 2 .
Water pressure in different units of measurement.

Table 3 .
Simulation parameters for pressure in the pipeline.