2.1. Comparative Analysis of Sensor Structure and Actuator Layouts
The fundamental architecture of the developed sensor is illustrated in
Figure 1. The device comprises two integrated components, forming a unified system. The first part consists of a semi-cylindrical container cell designed to hold the target liquid. This cell features 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 Form3 printer (Formlabs Inc., Somerville, MA, USA) [
44] and Rigid10K resin (Formlabs Inc., Somerville, MA, USA) [
45], a material validated in previous studies [
42,
43] 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 h 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 printed cell was then subjected to an oxygen plasma treatment to improve surface wettability. This process was conducted for 2 min at 50 W plasma power and 0.2 mBar oxygen pressure within a vacuum chamber equipped with a radiofrequency plasma generator (Diener electronic GmbH + Co. KG, Ebhausen, Germany) [
46].
The second component comprised the piezoelectric actuators. Commercially available PZT sheets (PIC255, type 5A modified lead zirconate titanate, PI Ceramic GmbH, Lederhose, Germany [
47]), 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 (Henkel, Düsseldorf, Germany) [
48]. 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 the other structural components of the sensor.
We assessed the fabrication quality and surface morphology by measuring the roughness of both the 3D-printed part and the PZT films using a Wyko NT1100 optical profiler (VEECO, Plainview, NY, USA) [
49]. The results are presented in
Figure 2. The gap between the PZT and resin was filled with adhesive, forming an ideally uniform and elastic multilayer. Regarding the resin surface in contact with the liquid, its roughness may affect resonance behavior depending on its relative magnitude compared to the acoustic boundary layer thickness, as discussed in [
50]. For diesel fuel, the acoustic boundary layer thickness across the relevant resonance range (10–600 kHz) varies from approximately 10 μm to 1 μm. Although the resin surface can be considered relatively smooth compared to this scale, minor effects were expected and considered part of the sensing capability of the devices.
To establish electrical connectivity, 100 μm 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 up to 1 MHz using an Agilent
® 4294A impedance analyzer (Keysight, Santa Rosa, CA, USA) [
51]. 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. While fabrication tolerances may influence the final electromechanical response, each device was individually characterized and calibrated.
The sensors manufactured following the described procedure operate as follows: Excitation of the actuation piezoelectric plates by a periodic signal induces structural vibrations. These perturbations are modulated by the physical properties of the surrounding fluid [
52,
53], as density contributes to added mass while viscosity increases damping. Consequently, the spectra read at the detection ports exhibit shifts in their resonant frequencies depending on the density variations between different liquids. Moreover, changes in viscosity modify the quality factor of the peaks, and therefore their amplitude and bandwidth. By applying machine learning techniques, correlations between these vibrational responses and the fluid properties can be systematically established.
An additional key consideration is the structural optimization aimed at achieving multimodal responses. This process was divided into two primary components: the piezoelectric plates and the fluidic cell. The optimization of patch configurations was assisted by finite element simulations in COMSOL
® Multiphysics 6.3 [
54], 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 architectures.
The geometry and quantity of piezoelectric films 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 [
55], 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 lesser 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, fluid–structure interactions were omitted to streamline the simulation within a three-dimensional framework.
Figure 3 illustrates the piezoelectric patch configurations analyzed using this approach. Performance assessment was based on the voltage amplitude spectrum within the 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 [
56]. The 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 modal shapes to identify regions of maximum and minimum mechanical deformation, thereby revealing zones of enhanced piezoelectric coupling efficiency and enabling the strategic placement of structural elements to support multiple modal responses. The resulting distribution, shown in
Figure 4, demonstrates that the superposition of modes within the studied frequency range generated low-stress regions at the mid-width and mid-length of the structures, while concentrating effective actuation and sensing areas in the quadrants. This observation justifies the placement of patches according to the proposed arrangement (configurations 3, 9 and 10), further reinforcing previous conclusions. Based on the combined outcomes of both studies, fabrication efforts were focused on configurations 2–4 and 9–10, which are also depicted 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 cell. As previously outlined, one objective of this study was to develop a sensor capable of producing spectra 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 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 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 instrument (Digilent co NI, Austin, TX, USA) [
57] 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 improve data robustness. Two spectra were recorded with a time interval of 5 min 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 enables 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 (); and spectra of the same fluid measured before and after exposure to a different fluid (). The expression denotes the spectrum corresponding to measurement i of liquid j (either pure diesel or the adulterated mixture). In our case, the index i was restricted to , as only two resolution measurements were conducted at each step, thereby conditioning the mathematical definition of the three key metrics. Nevertheless, additional measurements could be incorporated with the same definitions applied iteratively and considering either the maximum or the average across operations. Furthermore, the inclusion of the absolute value in the metric expressions ensures insensitivity to the order in which the two liquids are compared. 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. The following 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 sensors with higher values of
m are considered the best.
2.2. System Description and Calibration–Drift Experiments
Here we present 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 highest-performing sensors were integrated into a measurement system analogous to that depicted in
Figure 5, previously introduced in [
56] 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 (Espressif Systems Co., Ltd., Shanghai, China) [
58]. Fluid samples were introduced into the sensor at their maximum flow rate using a Minipuls 3 peristaltic pump (Gilson Inc., Middleton, WI, USA) [
59]. 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 0.05 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 [
2]. This table contains the physical properties of the fluids, determined by averaging three measurements obtained using a commercial DMA4100M densitometer equipped with a Lovis module (Anton Paar GmbH, Graz, Austria) [
60], maintained at 40 °C. We can observe that both viscosity and density increase nearly monotonically with oil content, although with distinct slopes, thereby supporting their treatment as independent variables in AI models. Even minor compositional changes in certain mixtures lead to measurable variations in viscosity and/or density, influenced by factors such as mixture tolerances, temperature effects and the non-linear scaling of these properties with oil percentage at low adulteration levels.
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 min, and subsequently, 33 spectra were collected over approximately 10 min. When changing the fluid, the sensor was flushed with the incoming fluid for 3 min without any additional cleaning protocol. All measurements were performed without active temperature control of the resonator; the ambient temperature during the experiments was maintained at 23 ± 1 °C. The measurement system operated in real time and did not require opening of the fluidic circuit. We experimented by acquiring measurements under both continuous-flow and static conditions and examining the evolution of the spectral response across consecutive acquisitions, which exhibited reduced variability when the fluid was at rest. Furthermore, the experiment was repeated using solutions , , and over a period of four days to assess whether spectral variations arising from short-term temporal drift could be mitigated through data processing and AI techniques.
2.3. Deep Learning Algorithm Optimization
Following the acquisition of spectral data from all the 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 [
17,
43,
56], convolutional neural networks exhibited 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 [
17,
56]. Specifically, we varied the number of convolutional layers (up to five), the number of filters, their size and their 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 [
61], which was 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 performed 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 was 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 and 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 [
62].
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 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 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 estimation 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 remained constant across all measurements, so they could be learned and disregarded by the machine learning models.