2.1. Comparative Analysis of Sensor Structure and Actuator Layouts
The fundamental architecture of the developed sensor is illustrated in
Figure 1. The device comprised two integrated components forming a unified system. The first part consisted of a semi-cylindrical container cell designed to hold the target liquid. This cell featured a vibrating membrane at its base and lateral connectors to facilitate fluid circulation. It was fabricated via stereolithography (SLA) 3D-printing technology [
44] using a Formalbs® Form3 printer [
44] and Rigid10K resin [
45], a material validated in previous studies [
25,
26] for its mechanical robustness (Young’s modulus = 10 GPa). According to manufacturer specifications [
45], this resin also demonstrates good chemical resistance against fuel exposure, exhibiting only a 0.1% weight increase after 24 hours when a sample structure is immersed in diesel. Key printing parameters including dimensional tolerance, resolution, printing speed, and ultraviolet (UV) light exposure duration were controlled throughout the manufacturing process.
The second component comprised the piezoelectric actuators. Commercially available PZT sheets (PIC255, type 5A modified lead zirconate titanate [
46]), 100 microns thick, with top and bottom CuNi metallization, and a stiffness of 63 GPa, were manually sectioned and placed on the external surface of the cell membrane using a cyanoacrylate-based contact adhesive (Loctite® 401 [
47]). This configuration ensured isolation of the piezoelectric ceramics from the diesel medium, preventing potential chemical degradation. The adhesive selection was validated by previous comparative studies, which revealed negligible performance variation across different cyanoacrylate formulations, attributed to the minimal adhesive layer thickness employed and its relatively low stiffness compared to other structural components of the sensor. Prior to adhesive application, the cell was subjected to an oxygen plasma treatment to improve surface wettability. This process was conducted for 2 minutes at 50 W plasma power and 0.2 mBar oxygen pressure within a vacuum chamber equipped with a radiofrequency plasma generator.
To establish electrical connectivity, 100
Cu wires were soldered to each end of the piezoelectric patches. The opposite ends of the wires were connected to pins embedded in elastomeric plastic tubing for mechanical isolation. The integrity of the solder joints was verified by analyzing the impedance spectrum of the patches across a frequency range of 1 Hz to 1 MHz using an Agilent® 4294A impedance analyzer [
48]. These elastomer-coated pins were subsequently inserted into the cell’s side connector protrusions, yielding a compact assembly and minimizing the influence of unwanted variable mechanical coupling caused by the introduction of the cell into a ZIF socket interface for electronic connection.
The optimization of piezoelectric patch configurations was assisted by finite element simulations in COMSOL® Multiphysics [
49], enabling a comparative analysis of different actuator layouts based on their spectral response. In contrast, the design of the fluidic cell geometry was addressed experimentally due to the complexity of incorporating full three-dimensional fluid–structure interaction in the model. Multiple prototypes were fabricated and tested under controlled conditions, applying a performance metric focused on resonance amplitude, repeatability, and sensitivity to fluid changes to identify the most suitable sensor architecture.
The geometry and quantity of piezoelectric patches play a critical role in sensor design, as these components, being the most rigid elements, exert a dominant influence on the device’s response. Although simultaneous optimization of the host structure and patch geometry could be addressed as described in [
50], this work focuses on a simpler approach: a computational evaluation comparing various actuator configurations to identify the optimal designs. To facilitate this analysis, a simplified cell model was developed using COMSOL. Mechanical and electrical boundary conditions were accurately defined, while non-essential geometric features such as side connectors were excluded due to their less impact on the sensor’s dynamic behavior. A mesh-convergence study was performed to ensure that the finite element results were independent of mesh density while maintaining computational efficiency. Additionally, as previously explained, fluid-structure interactions were omitted to streamline the simulation within a three-dimensional framework.
Figure 2 illustrates the piezoelectric patch configurations analyzed through this approach. Performance assessment was based on the voltage amplitude spectrum within the operational frequency range of 1 kHz to 1 MHz. The optimization criterion aimed to maximize both the number and amplitude of resonance peaks in the spectra as these serve as sources of sensor data related to the target liquid [
51]. Simulation results indicated that geometries 1 and 6–8 yielded suboptimal spectral profiles. Complementing this analysis, we conducted natural frequency simulations of the standard cell model either with a single piezoelectric sheet on its membrane or with two patches aligned along the vertical axis. In-plane stress values were averaged across all resulting modal shapes, yielding the distribution shown in
Figure 3. We can observe that superposition of modes within this frequency range produced low-stress regions at the mid-width and mid-length of the structures, concentrating the effective action and sensing areas in the quadrants. As a result, structures such as 2-4 and 9-10 re-emerged (especially configurations 3, 9 and 10), further reinforcing the previous conclusions. Consequently, we concentrated the fabrication on configurations 2–4 and 9–10, which are also represented in the sensor schematic in
Figure 1, with the possible cutouts of actuators highlighted by a black mesh in the plan view.
The other key component is the fluidic container. As previously outlined, one objective of this study was to develop a sensor capable of producing spectral responses characterized by a high number of resonances with high amplitude in a certain frequency range. However, these spectral features must also exhibit sensitivity to fluid changes, maintain repeatability across measurements to attain good resolution, and demonstrate recovery upon reintroduction of the reference fluid. To achieve this, we experimented with the geometric parameters of the fluidic cell depicted in
Figure 1. Sensors were fabricated using parameter combinations within the ranges specified in
Table 1. Iterative adjustments were made based on comparative performance, with superior parameter values informing the design of subsequent prototypes. This approach enabled progressive refinement of the sensor architecture.
The method for optimizing the cell structure consisted of the following experimental procedure. A sensor fabricated with a given set of geometric parameters was subjected to two fluids via a peristaltic pump: one comprising pure diesel fuel, and the other consisting of a 90:10 volumetric mixture of diesel and commercial sunflower oil. Starting with pure diesel, spectral data were acquired using an Analog Discovery 2 (AD) instrument [
52] across a frequency range of 1 kHz to 1 MHz, discretized into 800 points. A sinusoidal input signal of 3.3 V was applied, preceded by a brief stabilization period to ensure fluid equilibrium. For each frequency point, measurements were performed over at least 10 signal periods and were averaged to enhance data robustness. Two spectra were recorded with a time interval of 5 minutes between successive acquisitions. Subsequently, the pure diesel was replaced with the adulterated mixture, using no further cleaning other than the entrainment effect of the new solution. The same measurement protocol was repeated, and finally, the system was flushed with pure diesel once more, and the measurement cycle was repeated. All measurements were conducted under static fluid conditions at room temperature (22±1ºC).
This experimental framework enabled the evaluation of three key performance metrics: sensitivity, reproducibility, and recovery. These were quantified as absolute differences between: spectra of different solutions (); spectra of different consecutive measurements corresponding to the same solution (); spectra of the same fluid measured before and after exposure to a different fluid (). The expression denotes the spectrum corresponding to measurement of liquid j (either pure diesel or the adulterated mixture). A higher sensitivity is desirable, indicating strong differentiation between fluid types, whereas elevated differentiation in resolution or recovery is undesirable, as it reflects inconsistency in repeated measurements of the same fluid.
Based on these definitions, to determine whether greater sensitivity `compensates’ for poorer resolution and recovery at each spectral point
i, we propose the following equation. This formulation also serves as a dimensionality reduction strategy for subsequent analysis:
where “max” denotes the greatest difference, corresponding to the worst result between resolution and recovery. To quantify the relative performance of each cell, two metrics are proposed: the first uses equation (
1) to compute
m over all points of the spectrum and
, while the second uses only the points where sensitivity compensates for resolution/recovery (
) and
. Then, in both cases, the mean value across all spectral points is calculated and the sensors with higher values of
m are considered the best. The two approaches produced comparable results.
2.2. System Description and Calibration-Drift Experiments
This section presents the architecture of the measurement system designed to operate the sensors optimized using the method described in the preceding subsection, together with the experimental protocol implemented for calibration and drift assessment.
The best sensors were integrated into a measurement system analogous to that depicted in
Figure 4, previously introduced in [
51] for MEMS-based detection of adulterants in olive oil. In addition to the sensor element, the system comprised electronic interfacing circuits designed to operate with an ESP32-S3-DevKitC-1-N32R8V microcontroller [
53]. Fluid samples were introduced into the sensor at maximum flow rate using a Gilson Minipuls 3 peristaltic pump [
54]. A transistor-based circuit was employed to amplify the Pulse Width Modulation (PWM) signal generated by the microcontroller, which served to excite the sensor’s input actuator patch(es). The PWM frequency was swept from 10 kHz to 1 MHz, yielding 530 discrete frequency spectra. A variable frequency step was used to account for the microcontroller’s limited frequency resolution. The sensor’s output signal was further amplified via a bipolar junction transistor (BJT) biasing circuit incorporating emitter and collector feedback to improve DC stability at the operating point. This amplified signal was processed by an envelope detector, also implemented using a discrete transistor circuit, and captured via the microcontroller’s analog-to-digital converter (ADC). For each excitation frequency, 1000 output samples were acquired, each comprising 10 response periods. Averaging across these samples improved data robustness. All electronic components were powered using the 5 V supply provided by the microcontroller.
The measurement procedure was repeated for each of the biodiesel solutions listed in
Table 2. These solutions were prepared by blending commercial diesel fuel with sunflower oil in proportions consistent with those reported in the literature and compliant with European regulatory standards [
28]. The table contains the physical properties of the fluids, determined by averaging three measurements obtained using a commercial Anton Paar DMA4100M densitometer equipped with a Lovis module [
55], maintained at 40ºC. Samples were introduced into the system in ascending order of viscosity. For each fluid, measurements were conducted under static conditions following a stabilization period of 5-15 minutes, and subsequently 33 spectra were collected over approximately 10 minutes. When changing the fluid, the sensor was flushed with the incoming fluid for 3 minutes without any additional cleaning protocol. All measurements were performed without active temperature control of the resonator; ambient temperature during the experiments was maintained at 23±1°C. Furthermore, the experiment was repeated using solutions
,
,
and
over a period of four days to assess whether spectral variations arising from temporal drift could be mitigated through data processing and AI techniques.
2.3. Deep Learning Algorithms Optimization
Following the acquisition of spectral data from all prepared solutions, machine learning models were constructed to establish predictive relationships between the spectra and the corresponding physical properties of the fluids. As demonstrated in our previous studies [
26,
43,
51], convolutional neural networks exhibit strong performance in the analysis and interpretation of spectral signals. The procedures employed to identify network architectures best suited to our data, together with the spectral drift compensation and dimensionality reduction strategies implemented, are detailed below.
The first step involved defining the data sets and applying appropriate scaling. Mixtures labeled
were designated as the training set, whereas mixtures labeled
were reserved exclusively for testing and were not used during parameter optimization. Prior to training, the data were preprocessed using a scaling method based on the standard deviation. Following this process, optimization of the neural network architecture was undertaken. To identify the best network configurations that improve predictive accuracy, we applied a hyperparameter fine-tuning strategy analogous to that used in [
43,
51]. Specifically, we varied the number of convolutional layers (up to five), the number of filters, their size and stride. The tested parameter values are illustrated in
Table 3, which summarizes the general architecture of the evaluated models. The filters and their associated parameters define distinct mechanisms for spectral feature extraction. The ReLU activation function was employed to facilitate gradient-based optimization via the Adam algorithm [
56], which has proven effective in CNN training. Learning rates ranging from 0.01 to 0.001 were explored to minimize the mean squared error loss function. To control model complexity, we incorporated either high stride values or max-pooling layers, which perform local subsampling by selecting the maximum value within a defined neighborhood. Following the final convolutional block, an average pooling layer was applied to reduce dimensionality, thereby removing the need for a flattening operation and fully connected layers. This design choice is critical, as the latter approach introduces additional parameters and computational overhead, which are incompatible with the constraints of microcontroller deployment. The network ended with a single output neuron using a linear activation function to predict the target physical properties, such as viscosity or density. To identify the most effective model architecture, a comparative evaluation was conducted by quantifying the prediction error. This error was computed as the arithmetic mean of the absolute differences between the model-predicted values of viscosity or density and the corresponding reference values obtained from the commercial laboratory-grade viscometer. This approach enabled the selection of the network configuration that yielded the highest predictive accuracy. All models were implemented and trained using TensorFlow 2.17 [
57].
The models were subsequently evaluated using data obtained from drift experiments. To simulate realistic operating conditions, liquid was selected as the reference fluid for measurements on different days. We employed this liquid as a reference because it constitutes a representative solution of the problem under study, namely biodiesels derived from mixtures of conventional diesel and sunflower oil, and it exhibits a comparatively low viscosity relative to other biofuels in our dataset, thereby enabling more efficient removal during the circulation of subsequent liquids to be measured. Following the measurement protocol described earlier, the mean spectrum was calculated from repeated measurements. The ratio between the average spectrum of the reference solution on the initial day (day 0) and that obtained on day n was then determined. This ratio defines a spectral factor , which encodes the relative variations in sensor response between day 0 and day n across all spectral components, each of which may evolve differently over time. The factor was then employed to adjust the spectra of subsequent solutions. Specifically, the adjustment consisted of multiplying the measured spectrum of a given solution by , thereby approximating a transformation of the data from day n back to day 0. The corrected spectrum was then reintroduced as input to the trained machine learning models, yielding more accurate predictions of viscosity and density compared to unprocessed spectra. In this way, the operational lifespan of both the sensor and the overall system can be extended simply by using one single unique calibration solution as reference.
In addition, a dimensionality reduction study was conducted as follows. Using the equation (
1) as a basis, the number of spectral points was progressively reduced, thereby decreasing measurement time while simultaneously evaluating the impact on neural network training and performance in both calibration and drift experiments.
It is important to note that the models were trained externally and subsequently deployed on the microcontroller via the TensorFlow Lite library, enabling a fully autonomous viscosity and density monitoring system. This machine learning framework not only enhanced system autonomy but also simplified the electronic requirements for signal processing, because any spurious effect originating from the parasitic elements of the resonator or the electronics remains constant across all measurements, so they can be learned and disregarded by the machine learning models.