Albin Westerlund Design and Implementation of an Autonomous Groundwater Monitoring System for Remote Deployment Using Low-Power IoT Technology Vaasa 2025 School of Technology and Innovations Master’s thesis in Automation and Computer Science Energy and Information Technology 2 Acknowledgements As this thesis comes to an end, I would like to thank my supervisor Professor Moham- med Elmusrati, and my instructor Mikael Palosaari for their guidance and feedback. I’m also grateful to Omicron Ceti Ab and Läkarmissionen International for giving me this opportunity. Lastly, I would like to give a big thank you to my family for all their valuable support throughout my academic journey. 3 UNIVERSITY OF VAASA School of Technology and Innovations Author: Albin Westerlund Title of the Thesis: Design and Implementation of an Autonomous Groundwater Monitoring System for Remote Deployment Using Low-Power IoT Technology Degree: Master of Science in Technology Discipline: Master’s Programme in Computing Sciences Supervisor: Mohammed Elmusrati Evaluator: Timo Mantere Instructor: Mikael Palosaari Year: 2025 Pages: 123 ABSTRACT: Several regions in Africa are dependent on groundwater as a source of water. Having access to a groundwater supply can additionally mitigate water shortage during droughts. Läkarmissionen International, a Swedish NGO, provides humanitarian aid to refugee camps and rural communi- ties including access to the groundwater table through wells and boreholes. To use groundwater sustainably, its level must be monitored continuously over long periods to identify its behavior from extraction and to predict level trends. Due to the high cost of commercial systems, Läkar- missionen International is interested in a more affordable approach for a groundwater monitor- ing solution that would meet their specific needs for use in challenging conditions inside active boreholes. This thesis explores the possibility of using low-cost and widely available components for an energy-efficient groundwater monitoring system while still meeting the set specifications. After evaluating existing methods and solutions available on the market, hydrostatic pressure sensing was determined as the most promising method. A groundwater logger prototype was then developed around an ESP32-S2 microcontroller chosen for its low cost, low energy con- sumption, high availability, and supported onboard wireless communication capabilities. A 4-20 mA submersible gage-type pressure sensor with an attached vent tube and communication wires was chosen for its simplicity and ability to automatically compensate for atmospheric pres- sure. After evaluating the performance of the prototype under real and simulated conditions, the prototype demonstrated its potential, however its performance did not meet the application specifications. To address the identified shortcomings, modifications are suggested for a new system layout, hardware components, and firmware functionality to improve the performance of the prototype. KEYWORDS: Groundwater Monitoring, Low-Power, IoT, ESP32-S2, Wireless Communication 4 VASA UNIVERSITET Fakultet inom Teknologi och Innovation Författare: Albin Westerlund Titel: Design and Implementation of an Autonomous Groundwater Monitoring System for Remote Deployment Using Low-Power IoT Technology Examen: Diplomingengörsexamen Läroämne: Master’s Programme in Computing Sciences Övervakare: Mohammed Elmusrati Utvärderare: Timo Mantere Instruktör: Mikael Palosaari År: 2025 Sidor: 123 ABSTRAKT: Flera regioner i Afrika är beroende av grundvatten som vattenkälla. Att ha tillgång till grundvat- ten kan dessutom mildra vattenbristen under torka. Läkarmissionen International, en svensk icke-statlig organisation, ger humanitärt bistånd till flyktingläger och landsbygdssamhällen bland annat genom att ge tillgång till grundvatten genom brunnar och borrhål. För att använda grund- vatten på ett hållbart sätt måste vattennivån övervakas kontinuerligt under långa perioder för att identifiera nivåförändringar vid användning och för att förutspå trender. På grund av de höga kostnaderna för kommersiella system är Läkarmissionen International intresserad av ett mera prisvärt tillvägagångssätt för en grundvattenövervakningslösning som skulle uppfylla deras spe- cifika behov för användning under krävande förhållanden inuti aktiva borrhål. I detta examens- arbete undersöks möjligheten att använda billiga och lätt tillgängliga komponenter för ett ener- gieffektivt övervakningssystem för grundvatten samtidigt som funktionskraven uppfylls. Efter att ha utvärderat befintliga metoder och lösningar som finns tillgängliga på marknaden fastställ- des hydrostatiskt tryck som den mest lovande metoden. En grundvattenlogger prototyp utveck- lades med hjälp av en ESP32-S2 mikrokontroller som valdes för sin låga kostnad och energiför- brukning, enkel tillgänglighet och stöd för trådlös kommunikation. En vattentät 4-20 mA mano- metertrycksensor med ventilationsrör och kommunikationskablar valdes på grund av sin enkel- het och förmåga att automatiskt kompensera för atmosfärstryck. Efter att ha testat prototypen under verkliga och simulerade förhållanden visade den potential men uppfyllde inte prestanda- kraven. För att förbättra de identifierade bristerna föreslås en ny systemlayout, hårdvarukom- ponenter och inbyggd programvara för att förbättra prototypens prestanda. NYCKELORD: Groundwater Monitoring, Low-Power, IoT, ESP32-S2, Wireless Communication 5 Contents 1 Introduction 11 2 Background Information 14 2.1 Limitations to consider 14 2.2 Typical well application in Sahel and Horn of Africa regions 16 2.3 Specific application requirements 17 3 Review of Existing Methods 22 3.1 Hydrostatic pressure 22 3.2 Depth gauge and water well sounder 24 3.3 Air line pressure measurement 26 3.4 Time-of-flight based techniques 28 3.4.1 LiDAR 28 3.4.2 Ultrasonic 30 3.4.3 RADAR 38 3.5 Additional methods from literature 40 4 Prototype Design and Implementation 43 4.1 ESP32-S2 microcontroller unit 45 4.2 Timekeeping 50 4.2.1 Analysis of internal 90 kHz RC clock deviation 54 4.2.2 Analysis of internal clock stability 58 4.3 Sensor side of prototype 63 4.4 Battery configuration 65 4.5 Local data storage 67 4.6 Wireless communication and user interface 69 4.7 Firmware and startup process flow 71 4.8 Communication mode 72 4.9 Logging mode 75 5 Evaluation and Testing 77 6 5.1 Prototype cost overview 77 5.2 Sensor stability analysis 78 5.3 Evaluation of sensor accuracy over range 82 5.4 Analysis of depth measurement noise 87 5.5 Wakeup latency, oscillations, and EMI 91 6 Concept for Improved Design 95 6.1 Improving timekeeping accuracy 95 6.2 Pressure sensor optimization 97 6.3 Firmware-based energy optimization 101 6.4 Proposed system layout 103 7 Future Development 104 7.1 Importance of accurate environmental variables 104 7.2 Opportunity for machine learning integration 110 8 Conclusion 112 References 114 Appendices 123 Appendix 1. Kalman filter implemented in python 123 7 Figures Figure 1. “Ultrasonic Waveform from a MassaSonic™ PulStar™ Plus Sensor Showing a False Target Being Detected Instead of the Echo from the Surface of the Water” (Massa, n.d. -a). 34 Figure 2. “MassaSonic™ PulStar™ Plus Ultrasonic Waveform With the Same Targets As In Figure 1, But With the Detection Threshold Modified to Ignore the False Target” (Massa, n.d. -a). 34 Figure 3. “2D Plots on Rectilinear Coordinates Showing the Beam Patterns of Four Different Circular Piston Radiators in an Infinite Baffle Having Diameter to Wavelength Ratios, D/λ, of 1, 2, 4 and 10” (Massa, n.d. -b). 35 Figure 4. “An optical diagram displaying the function of the radar lens. The falloff of radar intensity is illustrated in the orange background. Particular radar rays are displayed as dashed lines. Note how the radar lens focuses the rays from the radar module into a parallel beam reducing the intensity falloff with distance. b is the diameter of the lens, R the radius of curvature, and f the focal length. m is an arbitrary integer. ß is the beam width angle of the radar emission. Paths of the rays through the lens are reversed for incoming radar signals." (Catsamas et al., 2023). 39 Figure 5. Block diagram of prototype 1. 44 Figure 6. Circuit diagram of prototype. 44 Figure 7. Image of prototype. 45 Figure 8. Block Diagram of ESP32-S2 (Espressif Systems, 2024). 46 Figure 9. Pinout of ESP32-S2 QT PY microcontroller from Adafruit (adapted from AdaFruit Learning System, n.d.). 49 Figure 10. System Clock (Espressif Systems, 2020). 53 Figure 11. Flowchart visualizing program process flow during test of timing interval. 55 Figure 12. Log series of the internal 90 kHz RC oscillator circuit frequency in blue and temperature change in °C in orange over a sampling period of 9000 seconds. 59 Figure 13. Log series of the internal 8 MHz oscillator circuit frequency in blue and temperature changes in °C in orange over a sampling period of 9000 seconds. 60 8 Figure 14. Waterproof submersible 4-20 mA water pressure sensor with attached data cable and vent tube. 64 Figure 15. Extract from log file in csv format. 69 Figure 16. File browser running on the integrated web server on the system. 70 Figure 17. Firmware flowchart at system startup. 72 Figure 18. Program flowchart in communication mode. 75 Figure 19. Program flowchart in logging mode. 76 Figure 20. Sensor stability over approximately 80 hours with a 3-sample moving average, trendline, and water evaporation estimation with 30% and 60% relative humidity. 80 Figure 21. Conversion process from 16-bit ADC range, via sensor mA range, to distance in meters. 83 Figure 22. Expected depth compared to the average depth at each step measured by the sensor. 84 Figure 23. Measured depth compared to adjusted depth. 86 Figure 24. Measurements filtering using three different filtering techniques. 91 Figure 25. Measurements filtering using standard Kalman filter evaluated with different Q and R values. 91 Figure 26. Two different series of the MCU polling the ADC module with maximum frequency on the left y-axis. The absolute error to series average in centimeter distance on the right y-axis. 94 Figure 27. DS3231 Real Time Clock module on development board (adapted from AZ- Delivery, n.d.). 97 Figure 28. Water height above a submerged pressure sensor depending on gravity relative to latitude with a set pressure of 10 bar and water density of 1000 kgm-3. 106 Figure 29. Water height above a pressure sensor submerged in freshwater depending on water density relative to temperature with a set pressure of 10 bar and gravity of 9,81 m/s^2. Water density relative to temperature adapted from Density of Water (n.d.).108 Figure 30. Water height above a submerged pressure sensor depending on water density relative to salt content at a pressure of 10 bar and gravity of 9,81 m/s^2. Water density relative to salt concentration adapted from Cospheric (n.d.). 109 9 Tables Table 1. Density, acoustic velocity, and acoustic impedance for air and water (Toa & Whitehead, 2021). 31 Table 2. Current Consumption in Low-Power Modes (Espressif Systems, 2024). 50 Table 3. Calculated variables for RTC_SLOW_CLK frequency deviation test log. 59 Table 4. Calculated variables for RTC_FAST_CLK frequency deviation test log. 61 Table 5. Partition table for ESP32-S2 inbuilt flash memory used in the prototype. 68 Table 6. Prototype 1 component price breakdown. 78 Table 7. Statistics for original measurements versus filtered measurements. 90 Table 8. Statistics for original measurements versus filtered using Standard Kalman with three variations of Q and R values. 90 Algorithms Algorithm 1. Assembly instructions executed by the ULP FSM coprocessor after being woken up by its timer. 57 10 Abbreviations LMI Läkarmissionen International GPRS General Packet Radio Service GSM Global System for Mobile Communications IoT Internet of Things MCU Microcontroller Unit ToF Time of Flight FZP Fresnel Zone-Plate PLA Polylactic Acid GNSS Global Navigation Satellite System UAV Unmanned Aerial Vehicle GPR Ground Penetrating Radar UART Universal Asynchronous Receiver Transmitter I2C Inter-Integrated Circuit SPI Serial Peripheral Interface SoC System on a Chip CPU Central Processing Unit PMU Power Management Unit GPIO General-Purpose Input Output ULP Ultra Low Power ADC Analog-to-Digital Converter BMS Battery Management System FFD Fractional Frequency Deviation PCB Printed Circuit Board RTC Real Time Clock DFS Dynamic Frequency Scaling ML Machine Learning 11 1 Introduction This thesis is done in cooperation with Omicron Ceti Ab and Läkarmissionen Interna- tional (LMI), based in Stockholm, Sweden. LMI is a Swedish NGO active in 25 countries globally working in humanitarian and developmental contexts. The goal of this thesis is to research groundwater measuring solutions and techniques suitable for LMI’s applica- tions in Africa. One of LMI’s focus areas is water and sanitation work in sub-Saharan countries. The work includes water supply for large refugee camps as well as for rural communities. It includes siting and drilling of boreholes, installations of pumps, reser- voirs and pipe networks while also training stakeholders in long-term operation and maintenance of water points (LM International, 2024). The requirements and limitations of possible solutions will be presented in the following chapter. According to The African Development Bank, by 2025, 25 African countries will suffer from ongoing water shortages with half of the rural population lacking access to clean drinking water (Boucher, 2005). Lack of water can cause unrest among the population and between countries, especially in locations where different countries utilize the same transboundary aquifer (Robins & Fergusson, 2014). Using groundwater as a water source can mitigate the difficulties caused by droughts where surface water is inadequate. Many countries in Africa, especially rural population centers, sometimes depend to a high de- gree on groundwater for agriculture, industries, and domestic use, making access to safe drinking water essential (Farr et al., 2005). Monitoring groundwater levels offers numerous benefits and is important for several reasons. According to Fulton et al. (n.d.), groundwater levels can change over time due to pumping, climate change, or natural environmental events. Although small changes in the groundwater level are difficult to spot, analyzing long-term time series of ground- water levels for different aquifers can reveal positive or negative trends. This data can identify areas with underutilized groundwater resources or serve as an early warning system for future groundwater depletion allowing governments and organizations time to act. Additionally, monitoring groundwater levels can provide insights into the flow 12 direction of groundwater, the rate at which water flows inside the aquifer, and subse- quently the volume of groundwater that can be utilized. Furthermore, a model of the groundwater level and flow direction can be created with the help of data from ground- water monitoring. This resource is valuable when determining suitable locations for fu- ture boreholes (Fulton et al., n.d.). For LMI, continuous monitoring of groundwater levels is important to provide a baseline on natural and seasonal variations to help understand possible impacts of climate change effects. Only a small volume of all existing groundwater can be used without detrimental conse- quences according to National Academies (2022). Overuse of groundwater resources may result in a reduction of baseflow to rivers and water reservoirs causing them to shrink. Unmonitored and unregulated groundwater pumping activity near saltwater shorelines is one factor that can lead to saltwater intrusion into the freshwater aquifer system according to Water Resources Mission Area (2019). Salt in the water supply makes it unsuitable for farming and drinking. A declining groundwater level caused by overuse can alter the flow of freshwater which has a natural tendency to flow towards the sea. This causes the zone of transition between freshwater and saltwater to move inland closer to pumping stations (Water Resources Mission Area, 2019). In Stumm & Comos’ report from 2017, they state that the limited groundwater recharge on Manhat- tan Island, New York, has made it incapable of moving the saltwater front back towards the sea to any significant extent, despite the fact industrial pumping of groundwater stopped over 70 years ago (Stumm & Como, 2017). There exist several different methods and techniques for measuring groundwater levels. Most of the research supports in large the utilization of borehole-based measuring methods and techniques for measuring groundwater levels over short and long periods. These are, although not limited to, measuring water pressure with a transducer, meas- uring depth to water level using a measuring device lowered down from the surface (Ful- ton et al., n.d.), measuring air pressure caused by the rising water level inside an air line (Cunningham & Schalk, 2011), and measuring depth to water by reflecting a sound signal 13 off of the water surface (Solinst Canada Ltd., 2024). Geoelectrical (Wilopo et al., 2020) and Ground penetrating radar (Salih et al., 2022) are examples of nonintrusive surface- based approaches. Measuring changes in gravitational pull caused by moving groundwa- ter utilizing orbiting satellites is a novel solution for measuring groundwater but is be- yond the scope of this thesis (National Academies, 2022). No matter which commercially available measuring solution of the previously mentioned methods is considered, they all face the challenge of expensive equipment and installation which constitutes a signif- icant barrier for groundwater level measuring. 14 2 Background Information This thesis is made for LM International (LMI), which is a global nonprofit organization providing humanitarian aid and basic human needs including water, sanitation, and hy- giene for communities in need in several different countries. The focus of this thesis and its applications is primarily directed at LMI’s operations in Sahel and Horn of Africa re- gions. In these regions, LMI collaborates with and supports different countries to achieve the sustainable water and sanitation goals set out by the United Nations. With the help of donors, LMI can among other things help communities and refugee camps gain access to clean drinking water by drilling and constructing wells that provide access to the groundwater table if no other water source is suitable. 2.1 Limitations to consider After discussions with LMI, it became evident that they face several challenges in their operations in the region. These challenges impose requirements and limitations on in- frastructure and potential groundwater measuring solutions. Rivalries between commu- nities and villages are one problem leading to intentional malicious damage to wells and associated infrastructure causing operation problems, repair costs, and extensive wait- ing times depending on the location. To minimize deliberate and unintentional destruc- tion of surface equipment, LMI has experimented with installing solar panels and other equipment elevated from the ground on roofs or socially important buildings to make them less accessible. This problem sets requirements for the design of the sensor system such as size, durability, longevity, as well as where it can be installed. Placing the sensor inside the well can make it less accessible, however, in cases where it is not possible, an inconspicuous design of the system is advantageous to avoid drawing attention to it. The remote nature of some boreholes as well as the long distance between them puts limitations on data communication due to lacking or unreliable phone service, making wireless communication of data and information challenging. The electric grid poses 15 another challenge in these remote locations far from bigger population centers with more developed infrastructure. It is sporadic, unreliable, or lacking completely making it unsuitable to entirely rely on. This calls for an independently powered solution. LMI cir- cumvents this problem by using electricity produced directly from photovoltaic solar panels to operate the pumping equipment where manually powered pumps are not in- stalled. The use of batteries as energy storage is avoided to cut costs of installation and maintenance. Another limitation to consider when designing a sensor system is the local culture and superstition, consequently making the use of cameras for any type of data acquisition unfavorable. The general technical knowledge in the remote areas where LMI operates is limited, meaning the sensor system should be able to operate reliably for long periods requiring minimal maintenance once they are installed. LMI is currently testing in limited numbers a commercially available submersible ground- water level sensor called the TD-Diver. This sensor’s relatively high initial investment has made LMI interested in more cost-effective solutions to lower the economic barrier to groundwater monitoring. Depending on the specific model, the measurement accuracy of the TD-Diver is from ±0.5 cm to ±5 cm, the maximum range is 100 m, and with a bat- tery life of up to 10 years according to its manufacturer (Van Essen Instruments, 2024). Since the accuracy this sensor provides exceeds the requirements of LMI’s applications, they have decided to prioritize affordability over accuracy. When creating a groundwater monitoring program, it is important to utilize several ob- servation wells unaffected by human activities to be sure that the collected data is of high quality and represents groundwater conditions in diverse environments and differ- ent aquifers (Taylor & Alley, 2001). Although this is the optimal approach to measuring groundwater levels, LMI has opted to deploy the TD-Diver sensor in some of their active boreholes in Chad to avoid the additional cost resulting from drilling boreholes dedicated to monitoring. This is due to restrictions in available funding. 16 2.2 Typical well application in Sahel and Horn of Africa regions There are some variations in the well and pump design used in Chad. A typical drilled borehole has a diameter of 10 to 20 cm and a depth of down to 200 meters. The borehole is drilled down to a depth where the local groundwater aquifer or aquifers produce enough water to satisfy the needs of the community located near the well. The depth of where the groundwater table begins can vary greatly between different geographical lo- cations. In the case of Chad, the groundwater table can be expected to begin immedi- ately below ground level in the southern region, and in the north, groundwater can be expected at depths of more than 250 meters according to the British Geological Survey (2011). Both manually operated and electrically powered pumps are used. Manually operated pumps only require one pipe inside the well to extract water resulting in more space inside the borehole compared to using electrical submersible pressure pumps. This type of pump is lowered down the borehole until it reaches a suitable depth under the groundwater surface and is then used to pump the groundwater. The electricity used to power the pumps is generally provided directly by photovoltaic panels mounted on the surface. This design, without an energy storage solution, saves on installation and maintenance costs but only allows pumping to take place during the day when the sun provides enough energy for reliable operation. This leads to fluctuations in the ground- water level during the day in the case of electric pumps. Water levels in boreholes in- stalled with manual pumps experience water level fluctuations whenever the pump is used and are not affected by the time of day. At night and during other times when the sunlight is insufficient for electricity production and the electric pumps are offline, the water level inside the boreholes starts to rise and, after enough time, recovers to the stable level of the surrounding aquifer. If regular and heavy pumping takes place at loca- tions with low flow rate aquifers, a stable water level might never be reached. Fluctua- tions in the groundwater level caused by seasonal events are expected to be low com- pared to fluctuations caused by pumping activities. The water level inside an active bore- hole is estimated to change by up to 20 meters in height daily. An electric pumping 17 installation consists of the pump itself, an electrical cord, and a water raising pipe made of PE, PVC or steel with a diameter of around 50-100 mm which is used to transport water from the pump to a surface storage tank. This tank serves as a buffer storage from which water is then used. LMI operates in different locations within Chad to support communities in need of water. They range from more permanent small villages, which have some resources, electricity, and pre-existing wireless communication capabilities, to refugee camps located in arid desert environments with minimal natural resources and no permanent infrastructure. According to the Climatic Research Unit (2024) of the University of East Anglia, the aver- age surface air temperature in Chad between 1991 and 2020 varies from below 15 °C to over 40 °C, with precipitation ranging from negligible to over 120 mm in a single month depending on location and time of year. In these conditions, the expected lifetime of a submersible pressure pump is between 5 and 10 years, with some pumps lasting up to 15 years in service. 2.3 Specific application requirements The main priority for LMI is to get data on the groundwater level inside their boreholes to get a better picture of the water usage, long-term groundwater level trends, and an early warning signal of decreasing water levels to prevent boreholes from running dry and subsequent water shortage. A measurement accuracy of 10 cm is deemed sufficient for these purposes. Currently, their knowledge of the condition of the boreholes after construction is limited. Implementing a cost-effective sensor solution that makes it pos- sible to install in both newly constructed and older boreholes can provide insight into this problem but requires the sensor package to be versatile and adaptable across vari- ous settings. The limited space inside a borehole, typically 10 to 20 cm in diameter and partly occu- pied by the pumping equipment, creates limitations on the sensor design in terms of size. 18 Although no specific target size is set, the TD-Diver submersible sensor currently being tested by LMI measuring 22 mm in diameter and 110 mm in length (Van Essen Instru- ments, 2024) serves as a benchmark for size considerations. Generally, a smaller design offers increased flexibility and can be adapted for a wider range of boreholes. To prevent entanglement between the sensor and its safety wire and pumping equipment, which can be especially problematic in deeper spiraling boreholes, LMI uses a PE or PVC pipe to guide the sensor down to a suitable water depth. Since the sensor system should ide- ally be installed inside the borehole casing or guided down through the hose to prevent easy access, it must be capable of operating in harsh conditions for extended periods. Components that are submerged must be waterproof, while other parts not in direct contact with water can still experience water splatter or moisture. Therefore, the entire system must be water-resistant to ensure maximum service life. Additionally, any com- ponent that has a possibility to contaminate the water supply must be constructed from non-toxic materials. The minimum service life of the sensor is not specified, however, minimizing downtime and service expenses is important when considering the price and quality of individual components. More expensive components constructed to a higher standard can achieve a longer lifespan but would also lead to an increase in price. Contamination of sensors that are submerged or otherwise in contact with groundwater is a possible problem that can affect their measurement accuracy, and service life, and create maintenance needs. In this regard, a noncontact sensor solution is more favorable. When assessing the ser- vice life for a sensor in terms of battery life and storage capacity, the TD-Diver submers- ible sensor serves as a useful comparison. It can store 72000 data points consisting of date and time, pressure, and temperature, and can achieve a battery life of up to 10 years depending on temperature and usage, for example measuring frequency (Van Es- sen Instruments, 2024). The TD-Diver’s data storage of 72000 data points is approxi- mately 8 years of continuous operation if a measurement is taken once every hour. Measuring frequency is a determining factor when designing a sensor’s data storage ca- pabilities, including backup storage. A higher measurement frequency results in more 19 data and requires increased storage capabilities. As many sensors will be deployed in remote locations, frequent service visits are not possible. Therefore, the storage needs to be sufficiently sized to store measurements taken over extended periods without the need for frequent manual data unloading if the sensor has no wireless communication capability. Equally important as the storage capacity is how to power the sensor independently for extended periods. Although the pumping equipment is powered by photovoltaic solar panels on the surface, visible or otherwise easily accessible components should be avoided to minimize the risk of vandalization. Hiding the sensor system inside the bore- hole would make it less accessible but also require an integrated energy storage solution. Energy storage in remote IoT devices is commonly made of primary or secondary chem- ical batteries but recent advances in supercapacitor research have shown its potential as IoT energy storage according to Hasan et al. (2023). Despite this potential, supercapaci- tors will not be considered for this application due to their low volumetric and specific energy densities. A novel solution for powering the sensor would be to draw a small amount of electricity from the electricity supply of the pumping equipment if present. This energy source could power the sensor directly or charge a small battery pack that can power the sensor at all times. The expected battery life of a sensor system can vary depending on its chosen battery configuration. When deciding on a battery configuration, several factors need to be con- sidered. They include battery chemistry, size, specific and volumetric energy density, power delivery, longevity, safety, rechargeability, and specific energy consumption of the IoT platform to be powered (Hasan et al., 2023). Rechargeable batteries can give a sys- tem a longer service life since the batteries can be recharged several times but require more frequent maintenance compared to a non-rechargeable battery with higher energy density. Energy consumption of an IoT device when active can be several times greater compared to when it is idle and sleeping in a low-power state (Klements, 2020). Maxim- izing the time a system is spent in a low-power state is important to achieve the longest 20 possible battery life. Configuring a sensor system to enter a low-power state between measurements, along with less frequent measurements, results in decreased energy consumption and a longer battery life. IoT devices enabled with wireless communica- tions generally have higher energy needs due to wireless communication many times being the most power-intensive component in a system (Hasan et al., 2023). Selecting an appropriate method for retrieving data from the deployed sensors is an im- portant decision in a groundwater monitoring program. Wireless communication be- tween sensors and a central location used for data collection, analysis, and storage is the optimal solution in terms of efficiency and minimizing manual labor. Sensors having the ability to wirelessly communicate a live data feed to a central location and receive soft- ware updates enables faster response times to sensor issues and easier software mainte- nance if an error occurs after deployment. A General Packet Radio Service (GPRS) or Global System for Mobile Communications (GSM) modem enables a sensor to be con- nected to cellular networks for long-distance wireless communication (Teguh & Usup, 2021), however, in locations where network infrastructure is lacking or unreliable, other approaches need to be explored. Satellite-based wireless communication technologies that provide wide coverage are a viable option for remote locations lacking other ground-based means of wireless com- munication. According to Chen et al. (2023), a new and innovative satellite network tech- nology specifically designed to cater to Internet of Things (IoT) devices is emerging. Sat- ellite IoT is still in its infancy and more research is needed to solve problems this tech- nology suffers from. Widespread wireless IoT devices in remote places operating from limited power sources benefit from the strict design requirements set upon the satellite IoT technology in terms of low cost and low-power consumption (Purivigraipong et al., 2020). An alternative approach to retrieving data from a sensor is to use a local smartphone or other smart device capable of working as a relay. The sensor transmits data to a 21 smartphone using low-power, short-range wireless communication, and the next time the smartphone connects to a cellular network, the data is automatically transferred to a database. This method is particularly beneficial for sensors in remote locations where wireless network service is not available, as it eliminates the need for a qualified techni- cian to travel to the sensor to offload data. The process could be automated with soft- ware and would require minimal technical knowledge for the person performing the task. Wireless sensor network technology is worth considering in locations with several bore- holes but only some of them are in reach of cellular networks. Sensors within range of other sensors in a network are interconnected with each other and can relay data be- tween themselves. This allows sensors without the possibility of a direct cellular network connection to relay their data through other sensors to reach a sensor node connected to a cellular network. This node can then forward all the data to a database using its connection. 22 3 Review of Existing Methods This chapter discusses existing and potential methods, techniques, and ideas for meas- uring a water level, and the potential for use inside an active borehole. Several methods have been proven to work for water level measuring applications, but using existing tech- nologies in active boreholes creates new challenges. Size limitations, obstructions, elec- tromagnetic interference, measuring depth from surface level, and drawdown distance are some challenges that must be considered. 3.1 Hydrostatic pressure One approach to measuring water levels is by using hydrostatic pressure. Hydrostatic pressure sensors are a well-established technology and are used by several industries. This type of sensor works by measuring the pressure of a column of liquid directly above the sensor, which is at a known depth measured from the surface according to Behera et al. (2022). The height of the liquid column above the sensor can then be derived from the hydrostatic pressure using the following formula ℎ = 𝑝 𝜌∗𝑔 , (1) where ℎ is the distance from the surface of the liquid to the point of measured pressure 𝑝 in Pascal, the density of the liquid is represented by 𝜌, and gravitational acceleration is represented by 𝑔 (Behera et al., 2022). Depending on the sensor configuration, the measured hydrostatic pressure can be the absolute pressure which includes both the pressure of the liquid and the atmospheric pressure which must be subtracted to get an accurate distance (Van Essen Instruments, 2024). Several different variations in the operating principle exist. Some common principles in- clude the piezoresistive effect, piezoelectric effect, capacitance change, and strain gauges (RayMing, 2023). These types of sensors function by measuring the force applied 23 from a liquid through a liquid-proof diaphragm onto a pressure-sensitive material. The electrical characteristics of the material change when it interacts with the pressure through bending or deforming. This physical change of the material causes it to change in capacitance, or to produce a voltage differential which can then be measured (RayMing, 2023). Another operating principle relies on giant magnetoresistance. This type of sensor uses a Hall effect sensor to measure changes in the magnetic field caused by a moving magnet attached to a deformable diaphragm (Behera et al., 2022). Pressure sensors come in three different categories called gauge, differential, and abso- lute based on what the sensor pressure reading is referenced to. Absolute pressure is a pressure measured relative to an absolute vacuum. Gauge pressure is a measurement of the difference in pressure between the applied pressure of a medium and the ambient pressure surrounding the sensor, usually atmospheric pressure. A differential pressure sensor measures the difference in pressure between two locations in a system and is unaffected by changes in the surrounding pressure or the atmospheric pressure. This type of sensor can be used to determine if the flow of a medium in a pipe is obstructed, for example by a closed valve, by measuring the pressure difference before and after. The greater the obstruction, the greater the pressure difference (Avnet Abacus, n.d.). Hydrostatic pressure sensors offer some advantages over other water level measuring techniques such as ultrasonic and laser according to Behera et al. (2022). In active bore- hole applications, rapid changes in water level and pumping can introduce bubbles and foam into the water which can interfere with ultrasonic and laser-based sensors since they rely on a clean water surface for signal reflection. According to the author, hydro- static pressure sensors remain unaffected by this. Zheng et al. (2024) mention the prob- lem with electromagnetic interference on strain gauges and piezoresistive-based pres- sure sensors. This can cause significant problems in active boreholes that are equipped with electrical pumping equipment. Zheng et al. (2024) suggest shielding and filtering to mitigate these effects. Temperature variations are another cause of accuracy deviation and need to be taken into account according to Keeland et al. (1997), however, they state 24 that groundwater temperature is expected to remain relatively stable. The measurement can be compensated with the help of a temperature sensor if the temperature variations are high enough to cause a significant error. Additionally, the sensor should avoid coming into contact with the bottom to prevent sediment-related issues. Several important factors need to be considered when selecting a pressure sensor to make sure it is suitable for the application. Different sensors at different price points differ in quality and accuracy. This includes specifications such as linearity, repeatability, hysteresis, and error span. Additionally, pressure sensors typically have a specified pres- sure range which the sensor can safely operate within. If the pressure goes outside of this range, the sensor can get irreversible damage. The optimal installation of a water pressure sensor is below the lowest expected level. This means that the sensor should be capable of safely measuring the pressure from the highest expected water level (Un- derstanding Pressure Sensor Specifications, n.d.). LMI has tested some submersible water pressure sensors with positive results proving this method works for the application, however, commercially available sensor systems with acceptable accuracy are not affordable. This type of sensor has a clear advantage over ultrasonic and laser-based sensors since they are less affected by obstructions found in an active borehole with less-than-perfect environmental conditions. A draw- back of this type of sensor is its susceptibility to electromagnetic interference. This could prove to be a problem in boreholes equipped with electrical water pumps. The extent of this problem is unknown and would require testing. 3.2 Depth gauge and water well sounder Depth gauges and water well sounders come in different designs and methods of oper- ation with more advanced measuring devices being electrical. The wetted tape method is perhaps one of the simplest implementations and is accurate to a depth of around 27 meters (Trimmer, 2000). This method works by lowering a measuring tape down the well 25 until it comes into contact with the water table. At this point, the user should check the length of the measuring tape against a point with permanent or otherwise known ele- vation. After removing the measuring tape from the well, the user can calculate the ac- tual distance to the water table by removing the wet part of the tape from the length of tape used. Although this is a cheap and simple method, the short maximum measurable distance that still provides accurate measurements is a disadvantage. An electric sounder is a more advanced method that takes advantage of the electrically conductive property of water. In its most basic form, it consists of an insulated wire with a weight at the end, low voltage electricity provided by a battery, and a light bulb or electrical multimeter if a higher sensitivity is needed. A wire consisting of two conductors can be used if the well casing is made from a non-conductive material and therefore cannot act as the second conductor. The method works by lowering the wire down the well until it reaches the water table. The electrical conductivity property of the water creates continuity when the wire comes in contact with the water surface allowing elec- tricity to flow through the completed circuit. This flow of electricity can be observed using the light bulb or multimeter. At this time, the user takes a reading of the length of the wire lowered down the well compared with a static reference point at a known ele- vation (Trimmer, 2000). The main advantages of the wetted tape and electric sounder techniques are the low initial investment and simplicity yet outnumbered by their disadvantages. An electric well sounder device has further reach than the wetted tape method but is still limited to shallow wells and boreholes. According to Trimmer (2000), a drilled borehole spirals as it goes down. This can cause interference between pumping equipment inside the bore- hole and the measuring tape or wire and possibly cause it to become entangled. There is a risk in this case that the measuring equipment brakes if removed by force. These methods require manual measurement taking and logging of data as well as repeated access to the water table inside the wells. Regular, frequent, and long-term measure- ments are essential to get high-quality data, which is challenging due to the manual 26 nature, in addition to the increased risk of water contamination from outside sources. Sercu (2023) states that these methods for measuring water levels are outdated and newer automated methods should be preferred. Manual measurements are needed to calibrate hydrostatic pressure measurements from pressure sensors. However, to get information on not only seasonal variations but also weekly and daily groundwater fluctuations caused by factors such as variable borehole extraction requires extensive manual measurements, making it very labor intensive and ineffective. 3.3 Air line pressure measurement Using air pressure as a proxy measurement is another technique that can be used to indirectly measure groundwater levels. This technique, commonly found in drilling and water operations, provides a fast and easy method for measuring the water table ac- cording to Garber and Koopman (1968). This method works by measuring air pressure inside a pipe that is affected by the groundwater level. This method requires a pipe ca- pable of withstanding internal air pressure, a pressure gauge, and a source of com- pressed air. The pipe is lowered down a borehole until the end of the pipe is lower than the lowest possible water level resulting from pumping or other natural events. Next, compressed air is introduced into the system until the pressure reading becomes stable. At this point, all water has been pushed out of the air line. After detaching the com- pressed air connection, the pressure reading will decrease and settle if the system is working correctly without leaks. This pressure value can then be used in the formula below to calculate the distance between the water table and the surface 𝑑 = 𝑘 − (𝑝 ∗ 2.307 ft 𝑝𝑠𝑖 ), (2) 27 where d is the water level measured from the surface in feet, k is the length of the air line in feet, p is the pressure reading measured in pounds per square inch, and last the conversion value of 2.307 ft/psi (U.S. Geological Survey, n.d.). Trimmer (2000) suggests that “An air line provides the most convenient method for re- peated testing of deep wells over 300 ft deep” and U.S. Geological Survey (n.d.) states that one advantage the air line method provides over the wetted tape method is its abil- ity to being unaffected by a disturbance in the water caused by pumping. They also state that this method’s accuracy is not affected if used in spiraling boreholes. There are, how- ever, other factors that influence the accuracy of this method. A calibrated system using an accurate analog or digital pressure gauge can provide an accuracy of 0.1 foot, but, according to the U.S. Geological Survey (n.d.), “Water-level measurements using a pres- sure gauge are approximate and should not be considered accurate to more than the nearest foot”. The two biggest causes of deviation in measurement accuracy in an air line system are imprecision in the length of the air line and the accuracy of the pressure gauge used to take measurements according to Garber and Koopman (1968). Other additional factors that have an impact on the accuracy to a lesser extent are changes in air density relative to altitude and temperature changes, which have an effect on air and water density as well as the thermal expansion of the system (Garber & Koopman, 1968). The pressurized air line method can be used to measure a water level, however, its re- quirements and limitations make it unsuitable for the use case of LMI. It requires an additional pressure-capable pipe which adds cost and makes the borehole more ob- structed. The existing water pipe could potentially be used, but this would disrupt nor- mal pumping operations while measuring, and information related to the pumping pro- cess, including the rate at which the water changes during pumping, cannot be measured. Having a reliable source of compressed air in remote locations without electricity is chal- lenging in addition to the space required by the hardware, which ideally should be 28 installed inside the borehole to not be visible. Lastly, the low precision this method pro- vides is not within an acceptable range and it is not capable of measuring with a high enough frequency needed for the use case of LMI, making this method less than ideal. 3.4 Time-of-flight based techniques Time-of-flight (ToF) is a method used by some sensors to measure the distance to an object. Light Detection and Ranging (LiDAR), Radio Detection And Ranging (Radar), and ultrasonic are types of sensors utilizing this ranging method. In general, these types of sensors work by sending out signal pulses and measuring the time it takes to receive an echo, and from this calculate the distance between the sensor and the object. Based on the time and known signal speed, a distance of as low as a few millimeters can be calcu- lated, although several different factors contribute to how accurate the measurement is (Paul et al., 2020). These types of sensors are in the family of noncontact sensors able to measure a distance through air in contrast to previously mentioned methods which are in direct contact with the water. An advantage noncontact sensors have is less hardware degradation over time due to better operating conditions compared to contact sensors. Ultrasonic and radar sensors are currently used to a small extent to measure water levels in rivers, while LiDAR technology is less used in water-measuring applications and more commonly found in other applications (Paul et al., 2020). 3.4.1 LiDAR One of the main challenges with using LiDAR technology in water level measuring appli- cations is the water reflectivity according to Paul et al. (2020). A small amount in the range of a couple of percent of the incoming signal is reflected from a water surface with low rugosity and turbidity according to the research paper. The amount of the signal 29 reflected towards the sensor also depends on the signal’s angle of impact. The research- ers tested LiDAR technology for its suitability to water level measurements using a com- mercially available LiDAR sensor produced by Garmin, called the Garmin Lidar Lite range- finder sensor costing 130 USD in 2020. During testing, the LiDAR sensor provided an ac- curacy of 1 cm in a distance measurement of up to 10 meters and 3 cm for a distance of up to 30 meters, both of which are within the specified limits of the sensor. This results in an approximate accuracy error of 0,1 % of the measured distance. Paul et al. (2020) also tested the impact of water rugosity on the measurement accuracy by measuring the water level in different rivers at an angle of 90° to the water surface. They concluded that the measurement accuracy of the sensor improved from 8,2 cm down to 1,7 cm with higher surface rugosity in the range of 5 cm to less than 1 cm. The measuring distance varied between 3,6 meters and 10,2 meters. Higher water turbidity results in better signal reflectance but was concluded to not have an impact on the ac- curacy of the measurement. The angle of impact is another factor that has an effect on the accuracy of the sensor and needs to be taken into account. Decreasing the angle of impact increases the amount of the signal being reflected away from the sensor resulting in worse accuracy. Lastly, the impact temperature has on the accuracy was investigated. Based on the test results, the highest accuracy was achieved at around 20 °C while the deviation increased at both lower and higher temperatures with a maximum deviation of 9 cm at 80 °C. The negative effect temperature has on the sensor’s accuracy can be decreased with im- proved temperature compensation of the sensor and its sensitive electronics (Paul et al., 2020). As Paul et al. (2020) concluded, there has been little research done on LiDAR technology as a water level sensor. Although LiDAR technology proved to be capable of measuring a water level, the low reflectivity of water makes it challenging to use especially as the distance increases. The need for a clear line of sight to the water surface limits this 30 technology to wider wells with fewer obstructions and shorter distances between the sensor and water since deeper boreholes are not necessarily straight. Another factor to consider is the cost and energy needs of this technology compared to other technologies. Paul et al. (2020) state that an increase in light energy gives better precision and less noise, but this would increase battery requirements. The suitability of LiDAR technology for the use case of LMI remains unknown as it is not a proven method for water level measuring applications in deep boreholes and would require more research. 3.4.2 Ultrasonic According to Toa and Whitehead (2021), ultrasonic sensors use sound waves with high frequency outside the audible frequency range of humans as their wave signals. They operate by emitting ultrasonic sound pulses and timing how long it takes for the pulses to be reflected by a surface and echo back to the receiver. Distance can then be calcu- lated using the formula below where the time difference is t, and the speed of sound is v. 𝐷𝑖𝑠𝑡𝑎𝑛𝑐𝑒 = 𝑡 ∗ 𝑉 2 (3) What medium the soundwave propagates through must be known to calculate a dis- tance. This is because the speed of sound is dependent on the medium it travels through. Another factor that affects the speed of sound is the temperature of the medium. Air humidity affects the speed but to a lesser degree than previously mentioned factors (Toa & Whitehead, 2021). Ultrasonic sensors can be used to detect different kinds of liquids and solid materials if they can reflect enough sound energy for the sensor to detect. The acoustic impedance mismatch between two mediums determines the acoustic reflectivity and how much energy is reflected. Higher impedance mismatch reflects more sound energy. This means 31 materials with a low impedance mismatch are difficult to measure. The energy reflection caused by impedance mismatch between two mediums can be calculated using the fol- lowing formula 𝑅 = ( 𝑍2−𝑍1 𝑍2+𝑍1 ) 2 , (4) where R is the reflection coefficient, Z2 impedance of the reflecting medium, and Z1 impedance of the travel medium (Toa & Whitehead, 2021). The reflection coefficient between air and water can be calculated to be approximately 0,988 using the impedance mismatch formula and the acoustic impedance values from Table 1. This means close to 99 % of the incoming sound energy is reflected, while the remaining continuous through the water. Table 1. Density, acoustic velocity, and acoustic impedance for air and water (Toa & Whitehead, 2021). Material Density 𝑘𝑔𝑚−3 Acoustic Velocity 𝑚𝑠−1 Acoustic Impedance 𝑘𝑔𝑚−2𝑠−1 ∗ 106 Air 1,3 330 0,00429 Water 1000 1450 1,45 Another factor to consider when using ultrasonic sensors is energy attenuation. Qiu et al. (2022) state in their report that a sound wave loses its energy to absorption of the surrounding medium and leads to the received echo having less energy than the initial emitted energy. The further an ultrasonic wave propagates through a medium, the more energy is lost on the way and less is received by the sensor. A higher sound frequency can offer greater accuracy but at a shorter range since sound energy attenuation in- creases as the sound frequency increases. 32 Sound waves have a relatively slow propagation speed according to Qiu et al. (2022). This allows them to use less precise computing hardware giving ultrasonic sensors a price advantage in the field of ToF sensors. Another advantage ultrasonic sensors have is their low sensitivity to interference from outside sources. These sensors are less affected by surrounding lighting conditions and electromagnetic interference since they use sound waves instead of radar waves or light. The advantages the technology provides have made ultrasonic sensors reach widespread adoption by different industries. They are used in a range of applications including distance measuring, vehicle positioning, and object detection and avoidance. Although ultrasonic sensors can achieve millimeter ac- curacy, Qiu et al. (2022) claim their maximum measurable range is usually less than 10 meters, however, sensors capable of measuring longer ranges do exist. Two examples of sound-based ranging devices available on the market are the Well Watch 670 from Eno Scientific (Eno Scientific, 2024) and the Sonic Water Level Meter from Solinst (Solinst Canada Ltd., 2024). Solinst claims their sensor can measure a water level down to 600 meters with an accuracy of 3 cm inside wells and boreholes while accounting for ob- structions and angles that can cause false readings. Eno Scientific on the other hand claims up to 1200 meters and 3 cm accuracy. Solinst claims 500 hours of use with one charge while no specific battery operation time was found for Eno Scientific. As mentioned earlier, ultrasonic sensors emit a sound pulse and measure the time it takes until the sound echo is received, and based on this calculate a distance. This simple measuring method relies on only receiving one easily recognizable echo and does not work in environments where more than one echo is received. False echoes occur when something else than the intended surface to be measured reflects all or a portion of the emitted sound energy back to the sensor receiver according to Massa (n.d. -a). This can cause the sensor to calculate the wrong distance if not configured correctly. Massa says this problem can be mitigated by adjusting the sensor threshold for the time interval of the wrong echo. Figure 1 and Figure 2 show a graph of a sensor’s threshold magnitude in red and signal echo magnitude in black as a function of distance. Both figures show a false echo resulting from an obstruction and the desired echo from the water surface. 33 Massa says that a false echo can result from obstructions like a pipe located in the sen- sor’s measuring path. In Figure 1, the false echo causes the sensor to show the wrong distance but by increasing the sensor detection threshold, as is shown in Figure 2, the sensor ignores all echoes of lower magnitude than the threshold. In Massa’s example, this leads to the sensor calculating the distance to the water instead. This works for all water levels, even if the water level would rise to the same level as the obstruction since the echo from the water is greater in magnitude than the threshold magnitude set at the distance of the obstruction. Although this technique looks promising for avoiding false echoes, it requires more advanced sensors since all ultrasonic sensors are not capable of being configured this way (Massa, n.d. -a). 34 Figure 1. “Ultrasonic Waveform from a MassaSonic™ PulStar™ Plus Sensor Showing a False Tar- get Being Detected Instead of the Echo from the Surface of the Water” (Massa, n.d. - a). Figure 2. “MassaSonic™ PulStar™ Plus Ultrasonic Waveform With the Same Targets As In Figure 1, But With the Detection Threshold Modified to Ignore the False Target” (Massa, n.d. -a). False echo detection in the previous example made by Massa (n.d. -a) is relatively trivial compared to false echo detection inside a borehole. The false echo shown in Figure 1 and Figure 2 is visible and there is only one obstruction causing a false echo, but using this technique inside an active borehole is most likely a greater challenge since obstruc- tions exist at all distances causing several false echoes. 35 One factor that affects an ultrasonic sensor’s performance is its beam angle. The beam angle is how wide of an angle the sound waves have when emitted from the sensor. How wide or narrow the beam angle is depends on the design of the sensor. Increasing the diameter of a sensor’s vibrating surface while producing sound with the same wave- length results in a narrower beam angle. Figure 3 shows a 2D plot of beam patterns for different diameter to wavelength ratios with the highest ratio producing the narrowest beam and the lowest producing the widest beam. Although an ultrasonic sensor has a specific beam angle at which the soundwaves are emitted, it may still detect sound re- flections arriving from an angle outside the original beam angle due to secondary lobes (Massa, n.d. -b). Figure 3. “2D Plots on Rectilinear Coordinates Showing the Beam Patterns of Four Different Cir- cular Piston Radiators in an Infinite Baffle Having Diameter to Wavelength Ratios, D/λ, of 1, 2, 4 and 10” (Massa, n.d. -b). According to Smoot (2021), a sensor with a narrower beam angle has a longer signal reach compared to one with a wider beam angle because the radiating sound energy is concentrated into a smaller area. Reducing the beam angle also leads to a reduced area of detection. Long-range and small areas of detection are beneficial in a borehole 36 application since the desired water surface to be measured has a small surface area and fluctuations cause large measuring distances. A small area of detection additionally leads to fewer false echoes from the borehole casing and pumping equipment. One approach to modifying an ultrasonic sensor’s beam angle and wave propagation pattern is by funneling the waves through a sound tube attached to the sensor. Mahler et al. (2022) evaluated sound tubes and their impact on cheap ultrasonic sensors. They managed to achieve improvements in accuracy in their specific test application and en- vironment by using a sound tube compared to not using one, but they also saw some interference caused by the tube. They concluded that the design of the sound tube in- fluences how the soundwaves propagate after leaving the tube. They further suggest the beam angle of the sound waves after leaving the sound tube could be reduced by using tubes of different lengths, diameters, and geometry. Another approach to modifying an ultrasonic beam is by using a Fresnel Zone-Plate (FZP). Schindel et al. (1997) assess the effect of using a micromachined FZP as a lens for focus- ing high-frequency ultrasonic waves. According to the authors, FZP works by having rings of different diameters machined on a thin plate. The rings are designed to either be in- phase with the sound wave to let it pass through or out-of-phase with the sound wave to decrease the sound energy. This leads to a more focused energy beam compared to not using an FZP. The authors tested an FZP designed to focus the ultrasonic beam into a point and managed to achieve a focus point of less than 3 mm. Other designs of Fresnel Zone-Plates can, according to the authors, be used for different beam patterns including a line-focus which can potentially be beneficial for borehole applications. Recent ad- vances in 3D additive manufacturing printing technology have made it possible to print FZP ultrasonic lenses with promising results according to Wang et al. (2021). Sound-based distancing is a proven technology for measuring water levels and is suitable for boreholes with obstructions according to the previously mentioned solutions availa- ble on the market. Additionally, they have an acceptable accuracy and a low sensitivity 37 to electromagnetic interference which is beneficial for the use case of LMI. The drawback of the commercially available solutions is their high cost and installation. They are de- signed to be installed on top of the borehole casing making them challenging to hide. It is unknown if this type of sensor works reliably if installed inside the casing. The stated battery life is also not suitable for long-term autonomous operation without an external power source. As previously mentioned, the speed of sound is dependent on temperature. The Solinst sensor incorporates temperature compensation by automatically measuring the surface temperature using an internal sensor, and a user measured and manually added tem- perature from the water surface. The manufacturer does not explicitly state how the measurement adjustment is calculated but appears to rely on these two points to calcu- late a linear temperature gradient. Although this is a simple approach that may work adequately in many cases, the temperature gradient is not always linear, especially in locations affected by human activity according to Kłonowski et al. (2024). This design is not capable of automatically adjusting for a change of temperature at the water level as well as a nonlinear gradient. This would require installing additional temperature sensors or manual temperature readings at regular intervals inside the borehole from multiple depths. Continuous battery operation time is another problem with the discussed products. The time is shorter than ideal in good operating conditions, and it is unknown how operating in high surface temperatures in Africa will affect the battery. The high acoustic reflectivity of the air-to-water interface is helpful since it reflects most of the sound energy, however, the signal loses energy as the wave propagates through the air. This means measuring longer distances in deeper boreholes requires more emitted sound energy decreasing battery time. The commercially available systems do not fully meet the requirements of LMI, making it necessary to develop a custom system addressing the limitations, but this would 38 involve solving technical challenges. One of them is to develop an algorithm to identify the correct echo from a multitude of false echoes resulting from the borehole casing and obstructions. In some boreholes, it may not even be possible to reliably identify the cor- rect water surface reflection. While this technology may work with acceptable results in some use cases of LMI, it would need thorough field testing to know its feasibility. 3.4.3 RADAR Compared to ultrasonic and LiDAR, RADAR distance sensors emit electromagnetic radio waves with a wavelength in the millimeter range to measure a distance. The short wave- length of millimeter radio waves gives radar sensors the ability to sense a change in dis- tance of less than a millimeter. Traditional RADAR sensors use pulsed signals, but modern RADARs can use signal modulation techniques. One type is the frequency-modulated continuous wave which can be used to measure the distance to an object, its velocity, and its angle (Iovescu & Rao, 2020). Catsamas et al. (2023) explored the possibility of using a relatively cheap off-the-shelf RADAR module for measuring the height and speed of river water. They used the radar model XM132 by Acconeer, which can be bought for less than 20 € at the time of writing. The XM132 radar is a pulsed coherent radar, meaning it transmits pulses of radio waves at a known starting phase according to its manufacturer (Acconeer, 2025). This radar module operates at 60 GHz, and it can achieve millimeter precision (Catsamas et al., 2023). Catsamas et al. (2023) created a sensor housing and radar lens using polylactic acid (PLA) and 3D printer technology to keep the cost low together with a potting compound for waterproofing the electronics. A lens to decrease the radar wave beam angle was needed since the radar beam angle is between 40° and 80° and a smaller angle would give better accuracy with fewer false readings according to the researchers. The radar lens they designed focuses the wide-angle spread of radar waves into a narrower beam 39 as illustrated in Figure 4, as well as focusing incoming radar waves into the radar receiver creating a gain of 21 dB compared to not using the lens. This gain increases the sensitivity of the receiver. Figure 4. “An optical diagram displaying the function of the radar lens. The falloff of radar inten- sity is illustrated in the orange background. Particular radar rays are displayed as dashed lines. Note how the radar lens focuses the rays from the radar module into a parallel beam reducing the intensity falloff with distance. b is the diameter of the lens, R the radius of curvature, and f the focal length. m is an arbitrary integer. ß is the beam width angle of the radar emission. Paths of the rays through the lens are re- versed for incoming radar signals." (Catsamas et al., 2023). Catsamas et al. (2023) conducted field tests comparing their radar sensor against a com- mercially available submerged water velocity and depth sensor in the field. The meas- ured distance ranged from 100 mm to 550 mm. The measurements obtained by the ra- dar sensor closely follow the measurements of the submerged sensor proving the radar sensor to be successful in river measuring application. The measurements can addition- ally be improved by using a simple algorithm to remove outliers according to the re- searchers. 40 The results from the experiment conducted by Catsamas et al. (2023) demonstrate that radar technology can be used to measure the distance to a water surface with acceptable accuracy, however, it is not proven to work inside active boreholes, and no off-the-shelf solutions are available on the market. As with sound-based distancing methods, using radar technology inside a borehole would require developing a new system and address- ing several issues. While the negative effect of noise in the signal can potentially be re- duced through frequency modulating techniques (MATLAB, 2023), the ability to reliably detect the correct echo from false echoes remains unclear. An alternative radar-based sensor, for example, guided wave radar, may offer advantages by avoiding obstructions. This method works by transmitting the radar wave from the antenna through a guiding cable down to the medium to measure. When the wave hits the medium transition in- terface, a part of the wave is reflected which the sensor then times to calculate a dis- tance (Instrumentation Tools, 2019). 3.5 Additional methods from literature García-López et al. (2022) present a novel cost-effective solution for automated large- area groundwater monitoring by using a UAV-borne LiDAR system. The system utilizes LiDAR and a Global Navigation Satellite System (GNSS) module attached to a quadcopter, also known as an Unmanned Aerial Vehicle (UAV), to fly autonomously on a preconfig- ured flight path between groundwater access points. The LiDAR system scans the ground below and subsequently measures the distance to the water surface inside wells or other points where access is available. In situ level measuring systems that are currently used are simple and reliable according to García-López et al. (2022), but frequent mainte- nance combined with large distances make them less cost-effective than the tested UAV- borne LiDAR system. Reducing overall cost by phasing out traditional in situ level sensors and related installation and maintenance is what makes this system a better choice for some applications, however, it has big drawbacks influencing its effectiveness. The 41 maximum flight time of the tested quadcopter is 55 minutes, which limits its maximum flight range. This makes a system like this better suited for smaller areas with a high den- sity of measuring points and less suited for large-area, low-density applications where flight distances are too long. Additionally, the need for access to the groundwater table either through wells with a wide accessible uncovered opening, bodies of water that are linked to the groundwater table, or other points where access to the groundwater is available makes a system like this feasible only in some locations. Another limiting factor of this method is the low measuring frequency. For an application where the measuring frequency needs to be several times a day or hour, this UAV LiDAR approach is not feasi- ble. Mahmoudzadeh et al. (2012) suggest using a non-intrusive Ground Penetrating Radar (GPR) to collect accurate and highly detailed depth data. This method works by transmit- ting radio waves into the ground and recording the signal reflections coming from differ- ent ground layer interfaces. Based on this data, the depth to where the saturated soil interface starts can be calculated. The authors claim that by choosing the most optimal antenna frequency for the GPR, it is possible to locate the groundwater interface among different types of ground material layers. While this groundwater measuring technique has some advantages over other traditional measuring methods, it has some key limita- tions. The process of getting accurate depth data using a GPR demonstrated by Mahmoudza- deh et al. (2012) does require some manual labor and estimations, which can impair the results. To be able to scan a large ground area, the GPR system needs to be moved. This was achieved by the researchers by pulling the GPR on a wheeled cart behind a manned motor vehicle. Another challenge using this system is varying signal attenuation in dif- ferent types of soil which must be estimated using other additional technologies, for example, frequency domain reflectometry or groundwater level data from existing wells. Since the dielectric constant varies between soil types, using only one constant when processing the data can impair the accuracy of the measurement. Mahmoudzadeh et al. 42 (2012) stated that the groundwater table may be impossible to find using a GPR in cases where a layer of soil with a high dielectric constant lies above the groundwater table. High signal attenuation was also observed by Salih et al. (2022) and they concluded that layers of clay can cause high signal reflectivity limiting accuracy and ground penetration range. They also saw errors in groundwater table estimations caused by saline ground- water and capillary action. After data conversion and processing, Mahmoudzadeh et al. (2012) observed a meas- urement error of 4 cm compared to the calculated depth of groundwater. Other re- searchers have reported less accurate depth estimations. Bentley and Trenholm (2002) state that “Theoretical analysis and field experiments indicate that, under favorable cir- cumstances, the elevation of shallow water tables can be estimated with an accuracy on the order of 0.20m.” Additionally, Salih et al. (2022) state that when using a radar fre- quency of 200-250 MHz the maximal achievable penetration depth is 10-15 meters while keeping adequate accuracy as good as 5 cm. Lower frequencies can penetrate deeper into the ground but at the cost of reduced accuracy since frequency and accuracy are related. 43 4 Prototype Design and Implementation This chapter presents a prototype as a proof-of-concept solution for an autonomous hy- drostatic pressure-based water level sensor. The primary objectives for this prototype are to test the individual components working together as a complete system, evaluate the performance of the sensor and system as well as energy efficiency, and finally discuss the functionality of the system and firmware. The first tested prototype is based on a submersible water pressure sensor with an in- cluded sensor wire. This type of water pressure sensor minimizes the need for water- proofing of the rest of the system since only the sensor and part of its wire will be sub- merged and submitted to higher water pressure. The other major component of the sys- tem is the Microcontroller Unit (MCU). Firmware running on the MCU, in combination with the integrated hardware features of the MCU, controls the logging process and wireless communication. Other necessary hardware components needed for this design include an external Analog-to-Digital Converter (ADC) module, a boost circuit, and a bat- tery. The boost circuit increases the relatively low 5 V USB to the 24 V required by the sensor to operate optimally. Figure 5 shows a block diagram illustration of the connec- tions and functionality between these components and Figure 6 shows the system circuit diagram. All connections and components, except for the pressure sensor itself, are housed inside a plastic box with a cable passthrough for the incoming sensor cable (see Figure 7). 44 Figure 5. Block diagram of prototype 1. Figure 6. Circuit diagram of prototype. 45 Figure 7. Image of prototype. 4.1 ESP32-S2 microcontroller unit Choosing the correct MCU is crucial since it will be the core controller responsible for managing and interacting with all other components of the system. The MCU is the only component of the system that cannot be completely powered down, making energy ef- ficiency a key factor in minimizing the overall system energy demands and prolonging battery life. The ESP32-S2FN4R2 microcontroller, referred to as ESP32-S2 for simplicity, from the ESP32 microcontroller family made by Espressif, proved to be suitable due to its high availability, low price, and included features. It is a low-cost, low-power system on a chip (SoC) with a single 32-bit Central Processing Unit (CPU). Figure 8 shows the SoC architecture and its features including which features are supported in which power mode. The ESP32 family of microcontrollers varies in its support for wireless 46 communication. As shown in Figure 8, the ESP32-S2 specifically includes support for wireless communication in the 2.4 GHz frequency spectrum using Wi-Fi. The microcon- troller also supports the proprietary wireless communication protocol ESP-NOW (Espres- sif Systems, 2024). Figure 8. Block Diagram of ESP32-S2 (Espressif Systems, 2024). The ESP32-S2 has a big-little CPU configuration using three cores. One of them is a faster general-purpose CPU supporting all features of the MCU, while the other two are scaled- down Ultra Low Power (ULP) coprocessors. Although it has two ULP coprocessors, only one of them can be used simultaneously. One of them is a ULP finite state machine (FSM) type which can be programmed using assembly code. The other coprocessor is a more advanced RISC-V core with support for the open-source RV32IMC instruction set 47 architecture. The RISC-V coprocessor can be programmed using the C language. These coprocessors are designed to perform simpler tasks, for example, continuous sensor monitoring, while the main CPU is turned off in a low-power mode. Using the ULP co- processor instead of repeatedly waking up the main CPU to monitor a sensor or to per- form a simple task decreases the overall chip energy consumption while still being able to execute code (Espressif Systems, 2024). The ESP32-S2 has native hardware support for several wired communication protocols including Universal Asynchronous Receiver Transmitter (UART), Inter-Integrated Circuit (I2C), and Serial Peripheral Interface (SPI). These communication protocols are useful for debugging during development and runtime while also providing MCU-to-MCU commu- nication and communication between MCU and peripheral devices, for example sensors. The UART port serves as the main wired communication between the MCU and the user. Although it provides a wired connection for general communication between two de- vices, its main purpose in this prototype is to provide debugging of the firmware and system as well as providing low-level user control through a command line interface. This simultaneous two-way communication functionality, where both the MCU and an exter- nal computer can send and receive data at the same time, is made possible by the full- duplex capability of the UART protocol. The integrated SPI is by default only used for interfacing with non-volatile external SPI flash memory chips or external Random Access Memory (RAM) chips but can also be used to interface with other external hardware components and sensors (Espressif Systems, 2024). Two successive approximation register ADCs are integrated into the ESP32-S2 and ena- bled on analog GPIO pins of the MCU. These can be used to convert an analog voltage, for example from an analog sensor to a digital binary value which can be further pro- cessed by the MCU. These ADCs are, however, not suitable for precise measurements. Makerfabs (2022), reports an average error of 37 mV and 45 mV for the models ESP32- S3 and ESP32 respectively, while the ESP32-C3 has an average error of 200 mV. After using Espressif’s official inbuilt calibration for the ESP32, Makerfabs observed an 48 improvement in average error of 18 mV in the voltage range 0,1 V to 3,2 V but it still struggles with the lowest and highest voltage ranges 0 V to 0,1 V and 3,2 V to 3,3 V. Due to the relatively bad performance of the integrated ADC, it was decided to use an exter- nal ADC module with support for digital communication over I2C. This enables the MCU to communicate and request data from the ADC. Additionally, an external ADC is not affected by the varying temperature of the microcontroller compared to the integrated ADC. Previously mentioned communication and interfacing methods are configured in the firmware, including which GPIO or RTC GPIO pins the interface will use through the GPIO multiplexer. With some limitations, most GPIO pins can be routed through the multi- plexer to allow them to perform various functions. This feature simplifies hardware de- velopment since the GPIO pins can be assigned different functionalities and are not con- strained to one function only (see Figure 9). While GPIO pins can only be used when the main CPU is active in a high-power mode, GPIO pins with RTC support can be configured to work in low-power modes. The prototype utilizes this feature when in deep sleep mode to provide a means of communication between the MCU and the user through a pushbutton. These GPIO RTC pins can additionally be controlled by the ULP coprocessor while the main CPU is not active to, for example, communicate over UART and I2C with other devices (Espressif Systems, 2025). 49 Figure 9. Pinout of ESP32-S2 QT PY microcontroller from Adafruit (adapted from AdaFruit Learn- ing System, n.d.). The ESP32-S2 has several built-in watchdog timers used for different purposes. Watch- dogs can give priority to a task, reset a task, or reset the CPU and reboot the entire sys- tem if needed. These functionalities make systems more reliable by being able to restart themself without manual intervention in case a problem arises. It is especially useful in remote applications that are difficult or impossible to manually reset, for example in a deep borehole. The supported watchdog timers by the ESP32-S2 include the interrupt watchdog timer, task watchdog timer, and XTAL32K Watchdog Timer. The interrupt watchdog timer monitors Interrupt Service Routines (ISR). Whenever an interruption oc- curs, its attached ISR will be executed. The interrupt watchdog timer steps in and gives priority to the ISR if it is blocked by other tasks or ISRs with lower priority. The task watchdog timer is used to monitor tasks. It makes sure the system does not freeze indef- initely in case a task hangs, not yielding to other tasks after a specified time, or gets stuck in a loop for example. The XTAL32K Watchdog timer can be used if the ESP32-S2 internal RTC_SLOW_CLK is configured to use an external 32 kHz clock signal as its source. The watchdog monitors the incoming clock signal and can create an interruption or switch the clock source for the RTC_SLOW_CLK to an internal clock if it detects a problem with the external clock signal (Espressif Systems, n.d.). 50 The ESP32-S2 chip has a Power Management Unit (PMU) controlled by firmware and it allows the MCU to enter different power modes depending on the use case. The power modes activate or deactivate modules and their integrated hardware features enabling the chip to use the most optimal power mode for a specific task. Table 2 shows the dif- ferent sleep modes and what the energy usage is depending on what component is pow- ered on. Depending on the preferred system operation, the ESP32-S2 should spend most of the time in deep sleep using either of the three modes where the ULP coprocessor is powered down. When the main CPU is woken up by the ULP coprocessor, internal timer, or external interruption, it will boot and start executing code from the start. Table 2. Current Consumption in Low-Power Modes (Espressif Systems, 2024). Mode Description Typ (uA) Light-sleep VDD_SPI and Wi-Fi are powered down, and all GPIOs are high impedance 750 Deep-sleep The ULP co-processor is pow- ered on ULP-FSM 170 ULP-RISC-V 190 ULP sensor-monitor pattern 22 RTC timer + RTC memory 25 RTC timer only 20 Power off CHIP_PU is set to low level, the chip is powered off 1 4.2 Timekeeping System time of the ESP32-S2 can be set through firmware at compile time and can in a later stage be synchronized from an external source, for example, Simple Network Time Protocol if the MCU has a network connection or manually over the wired UART com- munication port. Accurate timestamps of when the groundwater levels are measured included in the data logs are important and help when analyzing the data. For example, correlations between fluctuations in the water level and pumping activities can be made 51 if the level drops consistently at a certain time of day when an electric pump is expected to run. When logging data periodically over a long time, it is also important to consider the time deviation. A correlation between an increasing water level and precipitation or pumping activities and a falling water level may be possible to accurately observe from the data in a short time frame after equipment installation or after a time synchronization event. However, the same correlation may be difficult to observe if the timestamp error increases signif- icantly, although the time of pumping stays consistent. For example, if the timestamp error increases by ten seconds over a period of 24 hours, the cumulative time error would amount to nearly one hour after one year. Synchronizing the time at regular in- tervals can minimize this problem. How frequently the time needs to be synchronized depends on the maximal allowable error and the speed at which the time deviates. One source for the timestamp error is the clock source it is relying on. The greater its fre- quency deviation is, the greater the error will be. A possible alternative to regular syn- chronization of time, which can be difficult, expensive, or impractical, is to correct the timestamps while post-processing the data. If the frequency deviation is known and stays consistent over time, and the exact logging start and end times are known, all timestamps can be shifted forwards or backward the amount of time they are expected to have changed. Later in this section will be discussed the result of a timestamp error test. The task of keeping system time is performed by hardware timers integrated into the MCU. The ESP32-S2 version used in the prototype has two available hardware timers for this purpose, the RTC timer and the high-resolution timer. One or both timers can be configured to keep system time depending on the system design and which power modes are used. The RTC timer can be configured to run in all power modes and does only reset in the event of a power loss reset, while the high-resolution timer is only avail- able while in an active power mode. The high-resolution timer uses APB_CLK as its clock source and provides a resolution of 1 μs and less than ±10 ppm frequency deviation with 52 a typical frequency of 80 MHz. To maximize battery life, the MCU is configured to use deep sleep power mode while waiting dormant for the next logging. This makes the high- resolution timer unsuitable to be used for keeping system time (Espressif Systems, n.d.) The RTC clock domain is split into the RTC slow clock and the RTC fast clock (see Figure 10). The RTC timer used for system time relies on the RTC slow clock, which remains active in low-power modes, unlike the RTC fast clock, which is deactivated. The RTC timer has a resolution of 6.6667 μs and its accuracy depends on the clock source of the RTC slow clock. It is configurable to use one of three clock sources. The options are an ad- justable frequency from an internal RC oscillator which by default is 90 kHz, the internal 8 MHz oscillator clock signal divided by 256 to achieve a lower frequency of 31,25 kHz, and an external 32 kHz signal originating from a crystal or other clock circuit. In Figure 10, these are called RTC_CLK, RTC8M_D256_CLK, and XTAL32K_CLK respectively (Espres- sif Systems, 2024). 53 Figure 10. System Clock (Espressif Systems, 2020). According to the documentation for the ESP32-S2, the internal 90 kHz RC oscillator has the lowest power consumption, but its accuracy is affected by changes in temperature during deep sleep. The datasheet claims the 8 MHz oscillator to be more stable than the 90 kHz oscillator, but no parts-per-million (ppm) accuracy measurement is mentioned. The 8 MHz oscillator additionally results in an increase of deep sleep current by 5 μA. An external crystal can provide better frequency stability compared to the 8 MHz and the 90 kHz RC oscillators but at the expense of an increased current consumption in deep sleep of 1 μA. Using an external crystal or clock circuit requires supported GPIO pins for interfacing to not be used for other functions. An external clock circuit does not increase the current consumption of the ESP32-S2, albeit the circuit itself does use some amount 54 of energy which will be part of the total energy consumption of the system (Espressif Systems, n.d.). Minimizing energy consumption is a priority, especially during deep sleep which is the power state the MCU will use most of the time, therefore, the 90 kHz RC oscillator would be the optimal clock source. The problem with using this clock source is, however, its accuracy. Due to the limited availability of data on the accuracy and the effect changes in temperature have on the clock frequency deviation, it is difficult to determine if using it would have a significant negative impact on the system time. Two tests were per- formed to evaluate and get a better insight into the potential of using this 90 kHz signal. The second test also includes frequency analysis for the 8 MHz signal. Due to the lack of an appropriate oscilloscope, the tests relied on a practical testing method and inbuilt frequency calibration functions. 4.2.1 Analysis of internal 90 kHz RC clock deviation The 90 kHz clock signal is analyzed in the first test with default clock configurations. The default timer configuration includes both the RTC timer and the high-precision timer in combination with the internal 90 kHz RC oscillator as the clock source. Although both timers are used by default, only the RTC timer is active during deep sleep mode. Both timers are enabled while awake. The test was performed by using the ULP processor to wake up the main CPU at a specified interval of one second over a recorded arbitrary period. Later the recorded wakeup count was compared to the recorded elapsed time. No significant ambient temperature changes were observed during the test period. Figure 11 shows the timing process flow of the main CPU on the left side and the ULP process on the right. After being woken up by the start timer, the ULP coprocessor disa- bles and then re-enables the sleep timer which will cause it to restart counting. After re- enabling the sleep timer, the ULP coprocessor tries to wake up the main CPU by sending an interrupt to the RTC controller. The interruption is expected to be successful since the 55 main CPU is in deep sleep mode and not blocked by another process. After sending the wakeup interrupt, the ULP coprocessor goes back to sleep. Figure 11. Flowchart visualizing program process flow during test of timing interval. The ULP coprocessor was chosen to manage the timing interval because it can run inde- pendently of the main CPU once started, and the time deviation caused by its code exe- cution is relatively short and known. The other methods supported by the firmware framework, used during development, and the hardware for creating a wakeup interruption proved to be insufficient to accu- rately and consistently wake up the main CPU with a set interval. The main CPU can be woken up from several sources including a timer set by the main CPU, ULP interrupt, and external interrupt through one of the GPIO pins. Using the timer creates a problem since 56 it is restarted only once the main CPU goes to deep sleep. The main CPU needs time after waking up to execute code for reading, processing, and writing the data logs to memory. The time these processes take to execute would need to be subtracted from the timing interval before entering a deep sleep state creating unnecessary complexity and uncer- tainty because the code execution time was observed to vary between logs. After running the test for an arbitrary time of 26250 seconds, the system was observed to have logged 26229 times. It can be concluded based on the test result that the system time error was 21 seconds over a test period of close to seven hours. Since the system should log once every second, there should be the same number of logs as seconds. There are two main possible sources of this error. First is the ULP assembly code execu- tion time, and second is the frequency instability of the RC oscillator, which was used as the clock source for the ULP wakeup timer. Algorithm 1 includes a code snippet of the assembly instructions executed by the ULP FSM coprocessor after its wake-up timer overflows. After the wakeup timer overflows, the ULP coprocessor needs 2 clock cycles to wake up and then it waits for 16 clock cycles until the 8 MHz clock is stable according to the documentation for the ESP32-S2. The ULP coprocessor starts at the memory address where the entry point is stored. The first in- struction is executed two times. It first disables and then re-enables the ULP wakeup timer by writing a 0-bit and then a 1-bit to the RTC register controlling the ULP timer. This write instruction does not have documentation for execution clock cycles but is ex- pected to need the same as REG_WR, which needs 8 cycles to execute, and fetching the next instruction needs 4 cycles. The remaining instructions will not have an impact on the time interval deviation since the timer has already been restarted, however, the doc- umentation is unclear if the HALT instruction restarts the timer if it has been restarted earlier. If this is the case, an additional 4 to fetch WAKE, 2 cycles to execute, 4 cycles to fetch HALT, and 2 clock cycles to execute. Another 2 cycles are needed after HALT for the ULP to go to sleep according to the documentation (Espressif Systems, n.d.). This results in either 42 or 56 clock cycles. Since the ULP is clocked from the 8 MHz clock signal 57 calculated to have an actual frequency of approximately 8,8 MHz, each clock cycle exe- cution time is approximately 113,6 ns. Scaled up to the complete test runtime of 26250 seconds, the time error is approximately 125 ms or 167 ms. Two conclusions can be made from this test. The ULP coprocessor can in some applica- tions be used as a reliable timer for waking up the main CPU for further sampling and data processing, and the RC oscillator frequency deviation is most likely the main cause of the error in time. The frequencies of the RC oscillator and the 8 MHz oscillator are analyzed in the following subchapter. #include "soc/rtc_cntl_reg.h" #include "soc/rtc_io_reg.h" #include "soc/soc_ulp.h" .bss .text .global entry entry: // Disable the ULP sleep timer WRITE_RTC_REG(RTC_CNTL_STATE0_REG, RTC_CNTL_ULP_CP_SLP_TIMER_EN_S, RTC_CNTL_ULP_CP_SLP_TIMER_EN_S, 0) // Re-enable the ULP sleep timer, starting the countdown immediately WRITE_RTC_REG(RTC_CNTL_STATE0_REG, RTC_CNTL_ULP_CP_SLP_TIMER_EN_S, RTC_CNTL_ULP_CP_SLP_TIMER_EN_S, 1) WAKE HALT Algorithm 1. Assembly instructions executed by the ULP FSM coprocessor after being woken up by its timer. 58 4.2.2 Analysis of internal clock stability In this test, the deviation of clock frequency for the 90 kHz and the 8 MHz internal oscil- lators of the ESP32-S2 are analyzed. As was mentioned in the previous chapter, the 8 MHz oscillator has better frequency stability than the 90 kHz oscillator, but no accuracy measurement was provided in the datasheet. This chapter will compare the accuracy of both internal oscillators and their potential to be used for keeping accurate system time. Both clock frequencies were logged once every second with a sample size of 9000. The firmware framework used, called ESP-IDF, has inbuilt methods for calibrating clock fre- quencies against the external 40 MHz crystal called XTAL. These methods were used to get a frequency reading with an accuracy within the XTAL frequency error range of ±10 ppm (Espressif Systems, n.d.). The temperature was additionally recorded in the same process in case it affects the stability of the frequencies. The temperature sensor used is the internal sensor of the ESP32-S2 which measures the internal temperature of the mi- crocontroller chip. It has a claimed accuracy error of less than 1 °C in the range -10 °C ~ 80 °C (Espressif Systems, n.d.). By analyzing the RTC_SLOW_CLK clock signal plotted in Figure 12, we can see small fluc- tuations in the frequency with soft transitions except for the last samples where the fre- quency shows a sudden increase. The last 250 samples in the range increase in frequency to an average of 91022 compared to the rest of the samples that have an average of 90934 Hz. All samples in the range have an average frequency of 90936 Hz (see Table 3). After a decrease in temperature at the beginning of the test from 29 °C to 27 °C, the temperature does not change significantly