Abstract
Since the advent of industrialization, environmental pollution has become increasingly severe. Ensuring the ecological safety of water bodies and human health has made water quality testing an important means. Spectrophotometry, a commonly used water quality analysis method, boasts high sensitivity and simple operation. However, the many dangerous reagents involved in spectrophotometry pose significant risks to human health. Traditional manual dispensing methods are time-consuming, labor-intensive, and prone to errors, making it difficult to meet the efficiency and accuracy standards of modern environmental monitoring. Moreover, traditional manual handling and contact with toxic substances fail to ensure the safety of experimenters. This paper proposes and studies an automatic water quality testing dispensing system based on spectrophotometry. The system perfectly integrates the spectrophotometric testing system, automatic dispensing system, and artificial intelligence robot system to enhance testing efficiency, experimental safety, and accuracy. Through this system, reagents can be automatically formulated and accurately transported, allowing for the rapid and precise determination of the COD value of polluted water. Experimental results indicate that the system improves detection efficiency by at least 30% compared to traditional methods, while also reducing human error rates.
Keywords
Introduction
As industrialization and urbanization rapidly progress, water pollution has emerged as an increasingly severe challenge. The primary sources of water pollutants are domestic sewage and industrial wastewater discharge. Excessive pollution poses a significant threat to human health and safety. High levels of chemical oxygen demand (COD) can lead to oxygen depletion in water bodies, resulting in a decline in biodiversity. Elevated concentrations of ammonia nitrogen not only accelerate water eutrophication but also damage aquatic ecosystems. Excessive phosphate concentrations can cause an overgrowth of algae, ultimately disrupting the ecological balance of water bodies. Monitoring these pollutants is a crucial method for assessing the condition of the water environment.
To address these water pollution issues, Guangdong Weichuang Technology Development Co.LTD. 1 introduced a water quality sampler and an online water quality monitoring system featuring an integrated automatic dosing function in 2020. The sampler is highly automated and encompasses water intake, sample distribution, sample retention, control modules, and an automatic dosing system. In 2022, the Panjin Industrial Technology Research Institute of Dalian University of Technology 2 successfully developed a portable water quality ammonia nitrogen detection device. The device uses a reagent composed of potassium persulfate, sodium hydroxide, and hydrochloric acid at specific concentrations. In 2020, Balareso 3 and other researchers conducted a study on monitoring physical water quality parameters and the automatic control system for chlorination in an aeration treatment plant, in response to the challenging problem of chemical pollution treatment of water. The study evaluated the improvement of the general chlorine dosing system compared with the automatic monitoring and control system to maintain a stable supply of chlorine in drinking water.
In 2024, Tang et al. 4 and his team developed a portable analysis system for the rapid field analysis of CODMn. This system converts the oxidation of organic matter in water into a gas, transforming the CODMn concentration into a change in gas pressure signal. The change in pressure is then detected using a gas pressure gage. It is a promising field monitoring and analysis system for CODMn.
Most standard water quality testing methods are based on spectrophotometry, which indirectly determines contaminant concentrations by measuring the absorption of specific wavelengths of light by contaminants in a water sample. However, the preparation, addition, and transportation of reagents in the traditional testing process typically rely on manual operations and are prone to human error, leading to inaccurate test results. With the advancement of pharmaceutical chemistry and the growth of the pharmaceutical industry, 5 the application of automation technology 6 in pharmacies, hospitals, factories, and other drug-dispensing scenarios has become increasingly prevalent. Its principal automated drug supply system, intensive storage system, automated drug dispensing system, automated drug sorting system, database system, prescription information processing system, and interface with the HIS system. As early as last century, the concept of simplifying manual dispensing began to be gradually investigated and proposed, receiving attention from all sectors. In 1991, Hideo Ishizuka and other scientists 7 proposed a new computerized dispensing system to assist pharmacists, thereby reducing dispensing time and improving service quality for patients.
Upon entering the 21st century, people have become more adept at applying computer, robot, and other technological advancements, and the new dispensing system has evolved accordingly. In 2002, Ma et al. 8 designed an automatic metering and liquid adding system for online water quality monitoring instruments. The system is an automatic metering and dosing system based on a pneumatic pump, which is particularly suitable for precise sampling of corrosive liquids with high accuracy and stability. In the same year, Shu et al. 9 artificially advanced the modernization of the Traditional Chinese Medicine (TCM) industry and developed a new generation of TCM automatic dispensing system with functions of automatic dispensing, weighing, summarization, and packaging. This innovation significantly enhanced medication hygiene, dosage accuracy, and dispensing efficiency, ensuring the efficient operation of the system. In 2014, a team of scientists led by Chelvam et al. 10 conducted a preliminary study on a mobile robot for dispensing medicine for the elderly. By using the principle of the automatic dispensing machine M3DITRACK3R and an infrared sensor, the robot initially solved the problem that the elderly were finding it difficult to take medicine.
In recent years, science and technology have grown increasingly mature, and our dispensing system has also embarked on comprehensive development. In early 2022, Yuan et al. 11 proposed an autonomous drug dispensing robot designed for the COVID-19 virus at the conference. This robot can complete drug dispensing and transportation tasks through the Internet of Things (IoT). In 2021, O’Connor et al. 12 proposed a central pharmacy robot dispensing and replenishing system to address the current situation of significantly increasing drug demand and insufficient dispensing personnel. Utilizing a continuous-time Markov chain, they simulated the replenishment process of the RDS (Robot Dispensing System) and determined the optimal scheme through multiple experimental iterations. In 2024, George and Megalingam, 13 with the goal of alleviating the severe aging of the population and significantly increasing the demand for drugs, proposed a man-machine collaboration. They identified issues with the Automated Drug Regulation System and proposed a man-machine collaborative sorting system. Utilizing a design featuring both 1I/O and 2I/O points for consecutive prescription orders, they aimed to reduce the average time of the ADDS. The challenges posed by the aging population extend beyond excessive drug usage. In light of the vast number of elderly people living alone, the visually impaired elderly face difficulties in taking medication and make numerous medication errors. In 2023, scientists, including Sivakumar et al., 14 invented a smart, assisted dispensing machine designed for the visually impaired and the elderly. The dispenser utilizes a deep neural network, specifically the VGG-16 fingerprint recognition system, along with image enhancement technology to prevent unauthorized use. Given that the EVIP project received timely medical intervention, its implementation proved to be highly effective. Additionally, in the same year, the automatic distribution reagent cabinet studied by experts led by Liou et al. 15 also significantly reduced the error of human operation. In 2023, a paper published in the journal Informatics in Medicine Unlocked 16 proposed the use of pharmacy monitoring information systems to oversee the dispensing behavior of controlled drugs. The results indicate that monitoring the dispensing of controlled substances significantly enhances health outcomes and has significant implications. Additionally, digital sensors, 17 automatic labeling machines, and liquid medicine handling robots 18 have increasingly been utilized for auxiliary dispensing through a specialized approach, markedly enhancing the efficiency and precision of modern human-machine collaborative dispensing systems. 11 In the same year, researcher Nasir et al. 19 enhanced the safety of drug dispensing in automatic dispensing cabinets, and Youmbi et al., 20 along with other scientists, conducted an in-depth study of automated dispensing machines (ADCs) and adjusted the management of some ADCs’ coverage. As research progresses, when employing PLC 21 and other components for automatic dispensing, we must also consider their safety and rationality, and adjust the control scheme in a timely manner.
Considering the realistic scenario proposed by the aforementioned scholars, along with their hypothesis and demonstration, the current focus of automatic dispensing systems is primarily on hospitals, pharmacies, and other similar locations. However, the detection of Chemical Oxygen Demand (COD) and other pollutants in water resource protection areas cannot be accomplished without the use of toxic reagents. Moreover, most current water resource detection remains confined to the laboratory environment. Consequently, this paper proposes a water quality detection and distribution system that utilizes spectrophotometry. The system encompasses an automatic device designed to facilitate the preparation and distribution of reagents. It also incorporates vehicles and robotic arms for the transportation of samples, and employs spectrophotometry for field detection, thereby eliminating complex steps such as water collection. This approach significantly enhances detection efficiency and accuracy.
Experimental objectives and basic principles
Basic principle of spectrophotometry
Spectrophotometry is based on the quantitative analysis of the selective absorption of different wavelengths of light by A substance, 22 which essentially follows the Lambert-Beer law: A = ε × L × C. 23 Where: A is the absorbance, ε is the molar absorbance coefficient, C is the concentration of the substance being measured in the solution, and L is the optical path length.
Molar Absorptivity is a constant that indicates a substance’s ability to absorb light at a specific wavelength. The path length refers to the distance the light travels through the sample solution, often represented by the thickness of the cuvette, commonly 1 cm. Spectrophotometry typically utilizes ultraviolet (UV), visible light, and infrared radiation from the electromagnetic spectrum. The principle of spectrophotometry is detailed in Figure 1. In this study, visible light 24 is primarily utilized for analyzing the chemical oxygen demand.

Principle of spectrophotometry.
Meaning of chemical oxygen demand and its measurement method
Chemical oxygen demand is an important index in water quality testing, which is used to measure the total amount of reducing substances such as organic matter in the water body. The COD value reflects the degree of organic matter pollution in the water body. 25 The higher the COD, the more organic pollutants in the water body and the more serious the water quality pollution. Determining COD primarily involves assessing the concentration of organic matter 26 in water. These organic substances consume dissolved oxygen in the water, affecting the self-purification ability of the water body, which may eventually lead to anoxia in the water body and harm aquatic life. Measuring the chemical oxygen demand in water samples helps treatment facilities and environmental regulators monitor 27 and control water pollution.
There are many ways to measure chemical oxygen demand. In this paper, ultraviolet-visible spectrophotometry (UV-Vis) was used to determine the method. The chemical equation: 2KMnO4 + H2SO4 +O2 → Mn2++ CO2 + H2O is used, that is, under acidic conditions potassium permanganate is reduced to the biprice manganese ion (Mn2+). 28 It operates as follows:
Preparation of the reagent: potassium permanganate solution, usually configured as 0.01 mol/l of potassium permanganate solution, and filtered to remove impurities before use. Sulfuric acid solution: use concentrated sulfuric acid diluted to a certain concentration, usually 0.5 mol/l, as an acidic medium.
Sample treatment process: First, take 50 ml of the water sample to be measured. Add an appropriate volume of dilute sulfuric acid to achieve an acidic environment with a pH of approximately 1–2. A volume of potassium permanganate standard solution is then added, usually proportioned to match the expected contamination of the water sample. The mixed solution is heated at 60°C–70°C to accelerate the reaction and ensure the complete reaction of potassium permanganate, during which reagents such as mercury sulfate and silver sulfate are added to maximize the interference of excess elements such as chloride ions.
After the reaction is complete, the mixture is cooled and the following steps are carried out: First dilute with deionized water to a certain volume (such as 100 ml) for easy subsequent analysis. Then a spectrophotometer is used to determine the absorbance of the solution after the reaction at 525 nm. Finally, the data is recorded and the consumption of potassium permanganate is calculated.
According to the change of potassium permanganate concentration before and after the reaction, combined with the Bier-Lambert law, the concentration of chemical oxygen demand (COD) or reducing substance in the sample is calculated.
Feasibility demonstration of dispensing system scheme
Technically, the proposed automatic dispensing system for water quality monitoring instruments is highly feasible. Each research content is reasonable and realizable in technology. 29
The design of the drug-taking unit incorporates advanced chip programing control technology, enabling automatic and accurate selection of reagents required for weighing.The automatic weighing reagent unit uses high-precision sensing technology, and the weighing error range is controlled within ±0.1 g, which can ensure the accurate weighing of powdered reagents. Measuring reagent unit with precision liquid level measurement sensor and water level control technology, measuring accuracy of up to 0.1 ml, to achieve accurate control of the amount of liquid reagent added. Reagent water (gas) circuit design combined with circulation control technology, can make the reagent mixing uniformity of more than 95%, effectively ensure the reagent uniform mixing and supply. The intelligent dispensing process control design integrates automation technology, enabling rapid automatic control of the dispensing process. Pump valve control unit design uses advanced flow control technology, flow control accuracy within ±0.5 ml, can accurately control and truncate reagent flow. The design of information transmission and communication module relies on stable communication technology, the information transmission rate reaches 115,200 bps or more. Touch screen display and setting unit design adopts humanized interaction technology, which provides a convenient operation interface for the system. The minimum system design uses mature power supply technology, can provide stable 5 V DC power supply.
Secondly, regarding resources, the demand for technical, equipment, and human resources by this program is quite reasonable and affordable. The current technology and equipment are adequate to fulfill the program’s implementation needs.
Basic principle of trolley and robot arm
The STM32 single-chip microcomputer functions as the primary control unit for cars and robotic arms, equipped with a plethora of peripherals and rapid response capabilities, serving as the intelligent core of the entire system. By employing a camera for path identification and utilizing two-dimensional codes on various reagent bottles, the system aims to enhance path recognition for improved control over the car and robotic arm. Additionally, the system refines the output PWM pulse to effectively drive the steering gear, ensuring the task is completed efficiently. Operating as a typical closed-loop feedback system, the steering gear uses a motor to drive the reduction gear group, with its output connected to a linear proportional potentiometer for position monitoring. The potentiometer converts the angular position into a proportional voltage, which is then fed back to the control board in real-time. The control board compares this voltage with the input control pulse, automatically generates an adjustment pulse, and governs the motor’s direction of rotation to precisely adjust the output position and preset value of the gear group. This iterative process continues until the correction pulse is nearly zero, guaranteeing high-precision positioning of the servo motor. Figure 2 provides a detailed illustration of the basic process involved in this type of closed-loop control system.

Servo closed-loop control system diagram.
System design
Overall structure
The system comprises several key modules: firstly, the automated reagent preparation unit. This unit is responsible for automatically dispensing the necessary reagents for various test items and precisely controlling the volume of reagents added. Secondly, the man-machine interaction unit. The camera scans the QR code to accurately differentiate and identify different medicine bottles and perform path recognition. Utilizing the principles of the Internet of Things (IoT), remote control of the robot and robot arm via mobile phone Bluetooth or an app enables the removal of poison 0 and the transport of experimental drugs. Thirdly, the spectrophotometric detection unit. The spectrophotometer measures the absorbance of the solution, automatically converts the absorbance into the concentration of the reduced ion, calculates the COD value in the water sample, and then displays or outputs the data.
The purpose of this paper is to determine the chemical oxygen demand (COD). Utilizing the Lambert-Beer law and the principles of chemical reactions, it is established that the COD value, or absorbance, is proportional to the concentration of reducing ions. This paper compares the traditional manual dispensing experiment method with the automatic dispensing and automatic transportation potassium permanganate spectrophotometric method to better highlight the advantages of this system.
As depicted in Figure 3, within the 6 × 8 rectangular test site of the water quality testing station, the spectrophotometer is positioned on the right side to establish the spectrophotometer experiment area, while the automatic dispensing device is situated on the left side for setting up the dispensing area. To ensure the precision of our solution distribution, the instrument cleaning area is established in the central position. Given that at least eight reagent bottles are necessary for this experiment and the solution concentration must be precise, the reagent bottles used in the spectrophotometer must first be placed in the cleaning area for cleaning before being returned to the automatic dispensing system.

Distribution model of experimental environment.
Reagent automatic preparation unit
Design of automatic configuration unit
The research content of this system encompasses four important aspects: First, it involves designing a device capable of automatically selecting the required reagents. For powder reagents, a unit that can automatically and accurately weigh the reagent ensures precise dosage. For liquid reagents, accurate measurement is achieved to control the amount added. Secondly, the reagent water (gas) circulation circuit is engineered to ensure the safe and stable transport and dosing of the reagent. The third aspect is the development of an intelligent dispensing process control system to realize an automated dispensing process. This includes the appropriate assembly of control pump and valve units for accurate flow control and reagent truncation. Additionally, the system features a well-designed communication system for transmitting and exchanging data, ensuring the flow of information between units. Finally, the human-computer interaction and energy module are designed with a user-friendly touch screen interface for displaying dispensing parameters and setting related parameters. The smallest system, such as the power supply, is designed to provide a stable power supply and basic support for the entire automatic dispensing system. Figures 4 and 5 respectively depict the device connection diagrams for the drug dispensing module and the weighing module.

Structural design drawing of the drug dispensing device.

Design drawing of the weighing module device.
Design of automatic configuration unit components
As the heart of the system, the automatic dispensing unit is crucial for the meticulous selection of components in this domain. Regarding the main control module, since this unit is also governed by a single chip microcomputer and requires a more extensive array of peripherals and greater precision, this paper opts for the STM32F103RCT6 single chip microcomputer as the primary controller. Manufactured by STMicroelectronics, this 32-bit ARM Cortex-M3 microcontroller features a 72 MHz ARM Cortex-M3 core and includes multiple universal timers, USART, SPI, I2C, and other rich peripheral interfaces. Compared to the Arduino Uno, it offers superior processing power and a more comprehensive set of peripherals. The chosen development environment is STM32CubeIDE.
The medicine dispensing module utilizes a fine-mouthed 50 mm funnel for drug storage. It then integrates the KK-0520B push-pull electromagnet with a 2 mm transparent acrylic plate to create a drug delivery switch, facilitating the selection and delivery of medication. Regarding the selection of KK-0520B, the design employs a model with a DC voltage supply of 24 V, a current of 300 mA, a stroke of 5 mm, a thrust ranging from 0.2 to 5 N, and a weight of 23 g. These working principles, application fields, parameters, and specifications are detailed to ensure compatibility with the design requirements of an automatic dispensing system for water quality monitoring instruments.
The application of this dispensing system to the sensor is more complex and extensive. Firstly, the ZCT-YOF07 liquid level sensor is selected in this paper. The sensor is a non-contact flexible capacitive liquid level detection device, primarily used for non-contact detection of liquids. In this paper, the YZC-131 micro load cell and HX711 module are selected for the drug weighing part. They possess characteristics such as small size, high precision, good stability, and strong durability. Compared with other similar products, such as Load Cell and AD779X, they also feature lower cost, a simple interface, and compatibility, meeting the requirements of drug weighing. The selected Hall water flow sensor model, YF-S401 (2.0), has an interface size of 7 mm and operates within a voltage range of DC3.5–24 V. The pulse frequency is f = (90 × Q) ± 2%Q = L/min, meaning 5400 pulses per liter of water. The output pulse high level is greater than DC4.7 V (input voltage DC5 V), and the output pulse low level is less than DC0.5V (input voltage DC5 V). To enhance dispensing accuracy, the system also selects the TCS34725 color recognition sensor module, based on the AMS TCS3472XFN color optical digital converter. This sensor module provides RGB color and clear light digital signal output, equipped with an infrared filter to effectively reduce the influence of infrared light, ensuring the accuracy of color measurement. It also has high sensitivity, a wide dynamic range, and an infrared filtering function, which reduces interference from infrared and ultraviolet spectra, achieving accurate color recognition. Additionally, the module features ambient light intensity detection and supports the I2C communication protocol, with an operating voltage compatible with DC 3.3 and 5 V.
For the pump module application, this study selected a micro vertical pump to extract pure water into the reagent bottle. It is a submersible pump with a driving voltage of 5 V and a flow rate of 2 l/min. It boasts energy efficiency, ease of operation, and affordability, facilitating better reagent extraction. Additionally, a 365 motor pump was chosen for its ability to extract pure water into the reagent bottle. This is a diaphragm pump powered by a 12 V DC supply, capable of achieving a suction and lift of 2 m. To ensure quantitative extraction and stop control of the reagents, this paper proposes the use of a Hall water flow sensor in conjunction with the aforementioned pumps to meet experimental requirements. A 6 mm silicone tube, chosen for its high temperature resistance, toughness, corrosion resistance, and transparency, is used to connect the reagent bottle, water pump, and water flow sensor. These components are integrated into the valve pump control device of the system, which not only satisfies the requirements for quantitative extraction of reagents but also offers a cost-effective solution with precise error control.
In addition, the man-machine interaction module of the system chooses Kunlun on-state MCGS-TPC7062TX(KX) embedded integrated touch screen. The reagent mixing module selects a miniature DC waterproof vibration motor placed at the bottom of the reagent bottle. The WIFI module chooses ATK-ESP8266 module as the remote control communication of the automatic dispensing system of the water quality monitoring instrument, which supports LVTTL serial port and is compatible with 3.3 and 5 V single-chip microcomputer system, so that it can be flexibly integrated with a variety of hardware devices to realize the remote receiving control of the system’s working data.
After synthesizing the aforementioned ideas and components, we have rationally designed the drug weighing unit, the reagent mixing and measuring unit, as well as the dispensing and water sample testing unit. These three unit modules form the core of our automated dispensing system. Figure 6 presents the overall design block diagram of the system more clearly.

Overall system design frame diagram.
Circuit design of automatic configuration unit
The dispensing system module consists of the weight reduction and weighing unit, the drug-taking unit, the automatic water-adding unit, the reagent extraction unit, and the color recognition unit.
The YZC-131 micro weighing sensor produces an analog voltage signal, the amplitude of which is affected by the excitation voltage (power supply voltage). For example, with a DC5 V excitation voltage, the maximum output voltage of the pressure sensor would be 5 V multiplied by 1 mV/V, yielding 5 mV. This signifies that the output voltage spans from 0 to 5 mV; as the applied pressure increases, the output voltage value rises. The sensor not only responds swiftly, allowing for rapid reactions to changes in the input signal, but it also effectively reduces external interference. The operating current typically exhibits low power consumption, and the standby current is exceptionally low. Figures 7 and 8 illustrate the circuit diagrams of the weight loss weighing module and the medicine dispensing module, respectively.

Circuit schematic diagram of the weighing module.

Circuit schematic diagram of the medicine dispensing module.
This module integrates the ZCT-YOF07 liquid level sensor, a micro vertical water pump, a 5 V relay module, and a 5 V DC power supply to create an automatic water supply system. The sensor operates at 5 V DC and uses capacitive proximity sensing to detect liquid levels in flat, curved, single-layer, or multi-layer containers, achieving an induction distance of up to 3 mm. The peripheral circuit requires a pull-up resistance greater than 10K ohms, allowing it to directly drive loads up to 5 mA. The miniature vertical pump is a submersible type with a 5 V DC drive and a flow rate of 2 l/min. In this setup, a 5 V DC power supply and a 5 V relay are used to connect the miniature vertical pump. The detailed circuit principle is shown in Figure 9.

Circuit diagram of automatic water supply module.
The device also requires the use of the TCS34725 color recognition sensor module to determine if the dispensing process is complete. The operational principle of the TCS34725 color recognition sensor involves its integrated LED light source; the light reflected from the object is subsequently captured by the sensor. The reflected light is filtered through an internal component of the sensor, which then measures the intensities of the primary colors: red, green, and blue. Utilizing these measured RGB ratios, the sensor computes and outputs RGB values to identify the object’s color. The TCS34725 color recognition sensor typically employs I2C communication protocol and can directly output RGB values. It boasts advantages such as low power consumption, compact size, ease of installation, and adaptability to various working environments, as well as the ability to interface with microcontrollers and computers. The circuit schematic diagram of the TCS34725 color recognition sensor module is shown in Figure 10. The connection details between the TCS34725 color recognition sensor module and the STM32 microcontroller unit (MCU) are shown in Table 1.

Circuit schematic diagram of TCS34725 color recognition sensor module.
Pin connection of TCS34725 color recognition sensor module and STM32 single chip microcomputer.
Overview of automated dispensing unit operations
First, reset the single-chip microcomputer, place the unquantifiable drugs into the upper funnel, and connect the device to the computer via the 485 interface. Open the serial port and input the amount of powder required to configure the solution into the serial port. The system will accurately dispense the powder into the reagent bottle using the weight reduction method. Input fixed pumping instructions into the serial port, and the system will control the pump to automatically inject the water needed to configure the solution with a fixed concentration. Control the MCU peripheral, and the system can evenly stir the solution through the motor device. Additionally, because the system can identify the three primary colors through the color recognition module to determine if the dispensing is complete, and use the color change as feedback data to adjust the trial dose that should be extracted into the reaction pool, the entire dispensing system should be conducted in a shaded environment to reduce configuration errors. Figure 11 clearly illustrates the entire process of the drug dispensing system. This method effectively avoids the safety risks associated with manually preparing potassium permanganate, diluting sulfuric acid, and handling hazardous reagents such as mercury sulfate and silver sulfate, while significantly reducing human dispensing errors.

Flow chart of automatic dispensing.
Spectrophotometric detection unit
The spectrophotometric detection module employs a standard spectrophotometer that emits a beam of specific wavelength and measures the absorbance of a water sample. Ultraviolet-visible spectrophotometry (UV-Vis) was utilized to measure the CODMn. When the water sample is mixed with a reagent, the concentration of pollutants in the solution is indicated by changes in absorbance. Since the pollutant concentration, COD value, and reduced manganese ion concentration in water are proportional to absorbance and adhere to the Lambert-Beer law, by measuring the intensity of the absorbed light and calculating using the proportional standard curve corresponding to each parameter, the exact concentration of pollutants in the water sample can be automatically determined. Figure 12 illustrates the detailed process of spectrophotometry.

Spectrophotometric flow chart.
Robot and robot arm transport unit
The robot and arm transport unit comprises a robotic trolley and a steering gear arm mounted above it. The vehicle is equipped with a camera capable of effectively identifying the path. By scanning the QR codes corresponding to various reagent bottles, the vehicle can recognize the required reagents and log them, subsequently grasping them accurately with the mechanical arm to prevent unnecessary errors. Relying on the master stm32 microcontroller unit (MCU) programing, the vehicle adjusts its pulse-width modulation (PWM) output, thereby altering the motor output of the steering gear. It arranges a sequence of actions to fulfill the requirements for loading and transporting drugs. Figure 13 depicts the remote control flowchart for the automotive robotic arm.

Remote control flow chart of the robot arm of the car.
The standard PWM steering gear has three control lines, which are power, ground and control. The power line and ground line are used to provide the energy required by the internal DC motor and control line. The following Table 2 shows the position of the output of the steering motor when the positive pulse width of the input changes, it can be seen that under the condition of different PWM pulse width, the position of the steering output arm is different, which is the basic principle of the control of the steering machine by the single chip microcomputer, and the essential theory that we can arbitrarily and accurately configure different action groups to debug the robot action.
Pulse adjustment output arm schematic.
Debugging and experimental testing of dispensing system
Debugging of automated dispensing system
System circuit connection debugging
Before initiating the system power-on commissioning process, it is essential to meticulously inspect the lead connections of the single chip computer and other components, and verify their soldering quality. Subsequently, a thorough examination of all solder joints should be conducted to prevent any errors in polarity connections or instances of poor soldering. Lastly, employ a multimeter to test each module within the system to ensure that the hardware design remains intact and capable of conducting normal level signal transmission.
Automatic weighing module debugging
Before the drug-taking module is deployed for formal use, it is crucial to repeatedly adjust the stop plate of the drug-taking switch to ensure a high degree of fit. This adjustment is necessary to enable precise administration and cessation of the drug, preventing any leakage when the stop plate is closed. During the debugging of the weighing module, due to the varying sensor curves, it is essential to adjust the coefficient of the data calculation formula multiple times to achieve accurate measurement results. In the process of calibrating the weighing module, a 5 g standard weight is used to correct the calculation coefficient, ensuring that the measured weight is also 5.0 g. This completes the calibration and debugging of the weighing module.
During the debugging of the automatic weighing device, a tripod with adjustable height is used to adjust the device’s height, ensuring that the drug falling from the funnel mouth enters the reagent bottle without any significant leakage.
Debugging of automatic water-adding mixing module
During the debugging of the automatic water mixing module, the liquid level mark on the reagent bottle was measured multiple times to ensure that the desired amount of water could be obtained when the water level reached the mark, with minimal error. The liquid level sensor was also repeatedly adjusted to ensure it functions correctly at the reagent bottle’s water level mark, triggering a change in the sensor’s output signal when the water level in the bottle hits the mark. Additionally, the position of the vibration motor within the reagent bottle was fine-tuned multiple times to maximize the dissolution and mixing of the drug when the motor is activated.
Debugging of measuring reagent extraction module
When commissioning the metering reagent extraction module, it is essential to ensure that each component functions in unison to achieve precise control over the amount of reagent extracted. Initially, the amphibious micro-pump, YF-S401 (2.0) Hall water flow sensor, 5 V relay module, and 5 V DC power supply are tested individually to confirm their stable operation in isolation. The control program was iteratively refined to achieve precise control of the relay, as well as to interface with the data from the Hall water flow sensor, ensuring accurate readings from the flow sensor. The control logic has undergone numerous tests to guarantee that the pump automatically ceases operation once the reagent flow reaches the predetermined value. Through extensive testing, the precision and repeatability of the extraction module have been confirmed, and the control parameters have been adjusted to satisfy the design specifications.
Debugging of color recognition module
During the debugging of the color recognition module, the sensor is calibrated against standard color samples to ensure the precision and uniformity of the RGB values. Simultaneously, the sensor’s performance under various lighting conditions is evaluated to guarantee its stability and reliability in real-world application scenarios. Additionally, it is crucial to verify that the power consumption and response speed of the sensor module meet the system’s design specifications. Ultimately, the color recognition results are integrated into the comprehensive dispensing detection system, ensuring that when the mixed solution’s color matches the predetermined standard, the system accurately determines that the dispensing process is complete and ready for use.
Debugging of system software program
During the software program debugging process, various control programs are written to design automatic weighing flow control, and numerous program errors are eliminated. Ultimately, the control technology utilizing a state machine model is chosen to achieve automatic weighing flow control. For the design of the automatic water adding program, the state machine model is also employed, and the program undergoes multiple modifications and improvements to meet the system design requirements. In the design of the automatic weighing algorithm, the control of the medicine switch is revised several times, encompassing adjustments to the opening and closing times of the medicine switch and a reduction in the threshold value for the opening time. Finally, the algorithm with the highest weighing precision is selected as the algorithm for this design. Aiming at the debugging of serial communication instruction processing program, the consistency of communication parameters is ensured, including baud rate, data bit, stop bit, and check bit, to realize stable and reliable data exchange. The instruction analysis code has been optimized multiple times, ultimately achieving accurate identification of instructions, and completing the corresponding function setting and execution. The metering reagent extraction program’s debugging efforts concentrate on enhancing extraction accuracy and repeatability. Optimizing the control algorithm, adjusting the flow rate, and expanding the measurement range ensure the precision of reagent extraction. Special attention is given to verifying the accuracy of mechanical components and the synchronization of electronic controls to prevent errors. The debugging of the color recognition module aims to improve its accuracy and response speed. By refining the algorithm, the module’s adaptability to various lighting conditions and color variations is improved. A result verification mechanism is implemented, comparing outcomes with standard color data to guarantee the reliability of the recognition results.
Experimental test of automated dispensing system
During the physical testing phase of this design, the 485 interface is utilized to connect the automatic dispensing device to the computer. The serial debugging assistant is employed to communicate with the single-chip microcomputer via the serial port and to display the pertinent data. Following the tests, the system operates normally and successfully accomplishes all the functions that were designed.
The operation result of pharmaceutical weighing part
(1) System initialization. After the system is powered on and initialized, the results of peeling and weighing the total drug weight are shown in Figure 14.
(2) Results of adding medicine to the storage bucket. After adding solid powder medicine to the storage hopper, the serial port displays the total drug weight.
(3) Send the weighing instruction. Transmit the instructions through the serial port to the microcontroller, which then displays the set amount of medicine to be weighed and initiates the weighing process, offering a real-time display of the medicine being weighed.
(4) Drug weighing results. Upon completion of the drug weighing process, the serial port transmits the information indicating the end of the drug administration. The total drug weight is compared before and after the weighing, confirming that the weighing accuracy is high.

Results of adding medicine to the medicine storage hopper.
Reagent preparation test results
(1) Send instructions to add water and mix. The serial port transmits instructions to add pure water to the reagent bottle containing the powdered medicine to dissolve the drug mixture. The serial port then relays the information to initiate the water addition process. Subsequently, the pump extracts pure water and adds it to the reagent bottle, while the liquid level sensor monitors whether the water level has reached the calibration position as shown in Figure 15.
(2) Mixing with water is completed. Once the water reaches the calibrated level, the vibration motor initiates and mixes the reagent. Upon the completion of water addition and mixing, the serial port receives a completion message.
(3) The message “The water is full” signifies that the reagent bottle is already filled to capacity with water. If you attempt to enter the water instruction once more, it will reply with the message “The water is full” and will refrain from adding additional water.

Send the mixing instructions with water to prepare the reagent process.
Test results of reagent evenly mixing dispensing process
(1) Send the dispensing instructions to extract the reagents for dispensing. Include the required dose for each reagent in the instructions, and the serial port will display the trial dose set for extraction. The self-priming pump then operates to draw the reagent from the reagent bottle into the dispensing room, while the water flow sensor monitors the extracted test dose to ensure the precise input of the reagent, as illustrated in Figure 16.

Results of dispensing process.
Test results of color recognition in pharmaceutical preparation
(1) Issue the color recognition command. Once the dispensing process is complete, initiate the color recognition sequence. The system will then begin to identify the color of the solution in the dispensing room and output the chromaticity data via the serial port.
(2) Comparison of color recognition results. When comparing the recognition results with the color disk on the computer, it becomes evident that the color recognition is more accurate, as illustrated in Figure 17.

Comparison of color recognition results.
Validation of UV-Vis measurements of CODMn
Specimen collection
To thoroughly verify the feasibility of the system and analyze the efficiency and accuracy of the dispensing system for testing water quality, we have tested water samples from several water quality monitoring stations in Northeast China over the past few months. After removing the maximum and minimum values from the 290 sets of data, Table 3 summarizes and extracts the CODMn content from the remaining 288 sets of data, which are considered the most effective.
Sample statistical results.
Experimental parameters
In this study, the coefficient of determination (R2), mean absolute error (MAE), and root mean square error (RMSE) were used to evaluate the experimental results. When the R2 value is high and the RMSE and MAE values are low, it is considered better. The calculation formulas for R2, MAE, and RMSE are presented in equations (1)–(3), espectively:
Where y represents the actual value of the sample, ŷ is the model’s predicted value for the sample, ȳ is the average reference value of the sample, and N denotes the total number of samples. The R2, MAE, and RMSE calculated using the aforementioned formulas are displayed in Table 4.
Experimental parameter results.
Detection efficiency comparison
The preparation and digestion of reagents are crucial for the accuracy of water quality detection using the CODMn spectrophotometric method. In this study, the device was compared with manual spectrophotometry for CODMn water quality detection in a laboratory setting. The water samples tested were collected from the vicinity of a water quality monitoring station in Northeast China. The entire comparison experiment spanned from the collection of the water samples to the concentration of the tested water. The scatter diagram comparing the laboratory method of one of the detection stations with the method in this paper is shown in Figure 18. Some convincing comparative data results from the monitoring stations are shown in Table 5. It was observed that our intelligent dispensing testing system offers several advantages: (1) The process of this experiment revealed that fetching water to the laboratory typically takes about 20 min each time. Our improvements eliminate the need for transporting water to a laboratory for testing, significantly reducing time wastage and minimizing the risk of experimental inaccuracies due to secondary water contamination. (2) Compared to manual dispensing, our new system is more streamlined and stable, thereby also reducing the time required for the dispensing process.

Water sample comparison experiment scatter plot.
Efficiency comparison.
To assess the precision of the CODMn automatic detection instrument in identifying water pollutants and the accuracy of drug dispensing, we conducted a comparative experiment between manual detection and automatic instrument detection. The detailed procedure is outlined in Table 5. Analysis of the results clearly indicates that the time fluctuation in the conventional dispensing detection method exceeds that of the new method, a difference primarily due to water collection and other factors. By comparing the time differences between the two methods and the time required for the new dispensing detection method, it becomes evident that detection efficiency has increased by at least 30%.
Conclusion
This paper investigates and designs an automatic water quality detection, dispensing, and transportation system based on ultraviolet-visible spectrophotometry (UV-Vis), which can effectively enhance the efficiency, accuracy, and safety of water quality detection. In light of society’s demand for the accuracy of water quality monitoring and the health protection of monitoring personnel, a set of automated solutions has been developed.
The system is centered around the dispensing module. This module features an STM32 single-chip microcomputer as its core, incorporates a YZC-131 micro weighing sensor and an HX711 module, and achieves precise and automatic medicine weighing. Utilizing the pump valve control unit and the dispensing control unit, the system is capable of automatically transporting liquid reagents according to the dispensing plan and employs a color sensor to ascertain the completion of the dispensing process.
The system software includes driver programs, algorithm control programs, and human-computer interaction interfaces to ensure precise control of hardware components and a user-friendly operational experience. The embedded integrated touch screen facilitates intuitive and convenient setting of the dispensing test process, while displaying key information such as weighing data, water mixing information, metering reagent extraction data, and color recognition data in real time. Following the actual test, the designed automatic dispensing system of the water quality detection instrument demonstrates efficient and accurate automatic dispensing capabilities, achieving precise control of drug weighing, mixing, and conveying, and monitoring key parameters of the dispensing environment in real time. The final verification test demonstrates that the system diminishes the instability associated with manual operations, reduces harm to personnel, significantly enhances the efficiency of dispensing medications, and meets the stringent requirements of contemporary water quality monitoring. It offers users a practical, efficient, and easy-to-use automation solution, possessing good application value and market promotion potential.
The design innovation of this case is presented as follows: (1) Addressing the issues of low efficiency, instability, and the lack of human and environmental friendliness in traditional methods, a water quality detection and distribution system based on automation and intelligence is proposed. Smart dispensing not only enhances efficiency and stability but also eliminates the direct harm of toxic substances to the human body. (2) The application of data processing and control algorithms, MCU and its abundant peripherals and sensors enables the realization of an efficient and accurate automated dispensing detection process. (3) The spectrophotometric detection system, automatic dispensing system, and artificial intelligence robot system of the Internet of Things are ingeniously integrated. Simultaneously, physics, chemistry, software programing, and hardware programing are jointly applied to real life, genuinely combining theory with practice and demonstrating that knowledge transforms life.
This design has certain shortcomings: The paper primarily uses the potassium permanganate method for measuring COD. While the potassium permanganate method has advantages such as high sensitivity and simple operation, it is only suitable for measuring the concentration of pollutants in water with low concentrations or simple water quality. For some industrial wastewater measurements, it can result in significant errors. This issue arises from the inherent properties of potassium permanganate.When the concentration of pollutants in water is excessively high, it is more probable that other substances capable of reacting with manganese ions, in addition to the target pollutants, will be present. This significantly impacts the accuracy of the potassium permanganate method.In such cases, we need to use the potassium dichromate method, which requires more stringent experimental conditions, to test the water quality. If the potassium permanganate method must still be used, the water quality being monitored should undergo pre-treatment to maximize the exclusion of interfering ions that react with manganese ions, thereby minimizing errors.
Secondly, the mechanical arm powered by the STM32 single-chip microcomputer is unable to support the grasping of large and heavy objects. However, with technological advancements, the accuracy and response speed of the sensor can be further improved in the future. Additionally, large machinery such as hydraulic presses can be utilized for the measurement of large water bodies. If heated to over 160°, potassium dichromate can also be used to measure industrial wastewater with a high concentration of pollutants more accurately. This would enable the system to expand its functionality to the detection of additional water quality parameters, achieving comprehensive water quality monitoring. The system’s capabilities can be extended to a wider range of applications, including urban sewage treatment and industrial discharge monitoring, among others.
Footnotes
Ethical considerations
This article has no ethical statement.
Funding
The author(s) disclosed receipt of the following financial support for the research, authorship, and/or publication of this article: This work was supported by the Jilin Provincial Scientific and Technological Development Program (no. 20210203169SF) and by Education Department of Jilin Province (Grant No. 2020308).
Declaration of conflicting interests
The author(s) declared no potential conflicts of interest with respect to the research, authorship, and/or publication of this article.
Data availability statement
The data used to support the findings of this study are available from the corresponding author upon request.
Trial registration number/date
CODMn2024031823/2024.9.6
