0% found this document useful (0 votes)
57 views

An4636 Demonstration of LC Sensor For Gas or Water Metering Based On Stm32l073zeval and Stm32l476rgnucleo Boards Stmicroelectronics

Uploaded by

Márcio Ferreira
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

An4636 Demonstration of LC Sensor For Gas or Water Metering Based On Stm32l073zeval and Stm32l476rgnucleo Boards Stmicroelectronics

Uploaded by

Márcio Ferreira
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 70

AN4636

Application note
Demonstration of LC sensor for gas or water metering based on
STM32L073Z-EVAL and STM32L476RG-NUCLEO boards

Introduction
This application note describes the LC sensor metering feature included in the
STM32L073Z-EVAL and STM32L476RG-NUCLEO evaluation boards.
The STM32L073xx Arm® Cortex®-M0+ and the STM32L476xx Arm® Cortex®-M4
microcontrollers combine ultra-low power and performance, offering a complete set of
analog and digital peripherals, a subset of which is used to build the LC sensor-based
meter. This is the starting point for the implementation of gas or water meter applications
based on inductive reading of the rotation of a mechanical wheel.
The demonstration based on the STM32L0 can be executed with a single USB cable (type
A to B) connecting the host PC to the detection accessory PCB MB1199, both provided in
the evaluation board package.
The demonstration based on the STM32L4 can be executed with a single USB cable (type
A to B) connecting the host PC to the STM32L476RG-NUCLEO, and a custom LC sensor
board.
Firmware for each of the application examples is part of the demonstration software
included, respectively, in the STM32CubeL0 and X-CUBE-LCSENSOR firmware packages.

Reference documents
• STM32L073Z-EVAL user manual (UM1878)
• STM32Cube embedded software for STM32L0 Series including HAL drivers, USB, File
System, RTOS and Touch sensing (DB2318)
• STM32L476RG-NUCLEO user manual (UM1724)
• STM32Cube embedded software for STM32L4 Series including HAL drivers, USB, File
System, RTOS and Touch sensing (DB2602)
These documents are available from STMicroelectronics web site www.st.com.

September 2017 DocID027291 Rev 2 1/70


www.st.com 1
Contents AN4636

Contents

1 LC sensor metering principle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

2 Application description - STM32L073Z-EVAL . . . . . . . . . . . . . . . . . . . . 10


2.1 Hardware required . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.2 Hardware settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.3 LC sensor metering block diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11
2.4 Application principles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11
2.4.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.4.2 LC sensor metering capture window . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2.5 Getting started with the demonstration . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
2.5.1 LC sensor metering Mode Standard . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
2.5.2 LC sensor metering Mode Low Power . . . . . . . . . . . . . . . . . . . . . . . . . . 16
2.6 How to upgrade the LC sensor system up to three detectors . . . . . . . . . 18

3 Firmware description - STM32L073Z-EVAL . . . . . . . . . . . . . . . . . . . . . 20


3.1 STM32L073x peripherals used by the application . . . . . . . . . . . . . . . . . . 20
3.2 Description of “Mode Low Power” flow-charts . . . . . . . . . . . . . . . . . . . . . 21
3.2.1 LcSensorCountingDemoLowPower() function . . . . . . . . . . . . . . . . . . . . 21
3.2.2 StopEntry() function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
3.2.3 RTC_IRQHandler() interrupt subroutine . . . . . . . . . . . . . . . . . . . . . . . . 23

4 Application description - STM32L476RG-NUCLEO . . . . . . . . . . . . . . . 25


4.1 Hardware required . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.2 Hardware settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.3 Hardware settings for LC sensor custom board . . . . . . . . . . . . . . . . . . . . 26
4.3.1 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.4 Application principles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.4.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.4.2 LC sensor metering capture window . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.4.3 Parameters to define . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.4.4 Calibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
First calibration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Periodic calibration. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

2/70 DocID027291 Rev 2


AN4636 Contents

4.5 Getting started with the demonstration . . . . . . . . . . . . . . . . . . . . . . . . . . . 44


4.5.1 LC sensor metering basic counting demonstration with one sensor . . . 44
4.5.2 LC sensor metering counting demonstration with two sensors . . . . . . . 46
4.5.3 LC sensor metering tachometer demonstration with two sensors . . . . . 48
4.5.4 LC sensor metering counting demonstration with four sensors . . . . . . . 49
4.6 LC sensor metering Mode Low Power . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

5 Firmware description - STM32L476RG-NUCLEO . . . . . . . . . . . . . . . . . 51


5.1 STM32L476x peripherals used by the application . . . . . . . . . . . . . . . . . . 51
5.2 Description of flow-charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

6 Power consumption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

7 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

8 Revision history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

DocID027291 Rev 2 3/70


3
List of Tables AN4636

List of Tables

Table 1. I/O configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27


Table 2. Sensor configurations supported by STM32L476RG-NUCLEO board . . . . . . . . . . . . . . . . 38
Table 3. Document revision history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

4/70 DocID027291 Rev 2


AN4636 List of Figures

List of Figures

Figure 1. LC sensor oscillations example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7


Figure 2. LC sensor oscillations example with and without metal (air) . . . . . . . . . . . . . . . . . . . . . . . . 8
Figure 3. LC sensor metering jumpers configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Figure 4. LC sensor metering block diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Figure 5. Main signals during LC sensor activation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Figure 6. Oscillations collected with LC sensor in air on PB4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Figure 7. Oscillations collected with LC sensor in proximity of metal on PB4 . . . . . . . . . . . . . . . . . . 13
Figure 8. Using detection accessory board MB1199 with LC sensor metering . . . . . . . . . . . . . . . . . 15
Figure 9. LC sensor metering Mode Standard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Figure 10. LC sensor metering Mode Low Power: ammeter and capacitor connection. . . . . . . . . . . . 17
Figure 11. 3-sensor LC metering arrangement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Figure 12. 3-sensor LC metering system upgrade. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Figure 13. LCSensorCountingDemoLowPower() function flow-chart. . . . . . . . . . . . . . . . . . . . . . . . . . 22
Figure 14. StopEntry() function flow-chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Figure 15. RTC_IRQHandler() interrupt subroutine flow-chart. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Figure 16. Configuration of LC sensor metering jumpers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Figure 17. SB21 USER LED disconnection (only if PA5 is used) . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Figure 18. Schematic: one or two sensors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Figure 19. Schematic: up to four sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Figure 20. LC measurement sequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Figure 21. DAC output example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Figure 22. Cref leakage current during hold time. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Figure 23. Excitation pulse managed by GPIOs – Example with Texcit to VSS = 250 ns . . . . . . . . . . 33
Figure 24. Excitation pulse managed by GPIOs – Example with Texcit to VDD = 250 ns. . . . . . . . . . 34
Figure 25. Tcapture example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Figure 26. Time between sensors: 200 µs between Sensor1 (IO2) and Sensor3 (IO4) . . . . . . . . . . . 36
Figure 27. Calibration phases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Figure 28. First calibration example for a predefined maximum count number of 30 . . . . . . . . . . . . . 40
Figure 29. First calibration example for a predefined ∆ of 10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Figure 30. LC sensor with MB1199 accessory board . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Figure 31. Demo1, one sensor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Figure 32. Demo1 - USART communication output – Terminal software example . . . . . . . . . . . . . . . 46
Figure 33. Hardware for the two sensors demonstration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Figure 34. Demo2, two sensors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Figure 35. Basic 4-state machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Figure 36. Demo2 - USART communication output – Terminal software example . . . . . . . . . . . . . . . 48
Figure 37. Demo3 - USART communication output – Terminal software example . . . . . . . . . . . . . . . 49
Figure 38. Demo4 - USART communication output – Terminal software example . . . . . . . . . . . . . . . 49
Figure 39. Connections for the measurement of power consumption . . . . . . . . . . . . . . . . . . . . . . . . . 50
Figure 40. Interrupts profile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Figure 41. LcSensorDemo () function flow-chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Figure 42. StopEntry () function flow-chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Figure 43. RTC_WKUP_IRQHandler () subroutine flow-chart for one LC sensor . . . . . . . . . . . . . . . . 60
Figure 44. LC_calibration () function STATIC method flow-chart. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Figure 45. LC_calibration () function DYNAMIC method flow-chart. . . . . . . . . . . . . . . . . . . . . . . . . . . 62
Figure 46. Periodic calibration flow-chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Figure 47. Periodic calibration interrupt profile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Figure 48. Periodic calibration initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

DocID027291 Rev 2 5/70


6
List of Figures AN4636

Figure 49. Results of analysis in STATIC mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64


Figure 50. Results of analysis in DYNAMIC mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Figure 51. STM32L073Z - One sensor - IDD (average) vs. Sampling rate (VDD = 3.3 V) . . . . . . . . . 66
Figure 52. STM32L476RG and STM32L433RC - One or two sensors
IDD (average) vs. Sampling rate (VDD = 3.3 V) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66

6/70 DocID027291 Rev 2


AN4636 LC sensor metering principle

1 LC sensor metering principle

LC sensors are driven by an excitation pulse managed by GPIO (see Figure 1). Once the
pulse is delivered, the GPIO is reconfigured from output push-pull to alternate function
analog input. The LC oscillation has been generated.
The COMP peripheral collects the analog oscillations and compares them to a reference
voltage (Vcmp), delivering a digital signal on the comparator output. The low power timer
peripheral then counts these pulses.

Figure 1. LC sensor oscillations example

When a metal is in the proximity of the LC sensor, a part of the magnetic field emitted by the
inductor is absorbed and the energy is lost in the metal target. The oscillation amplitude and
the number of collected pulses are consequently lower compared to the case without metal.

DocID027291 Rev 2 7/70


69
LC sensor metering principle AN4636

Figure 2 shows the oscillations in the two cases (with metal in blue, while red refers to air).

Figure 2. LC sensor oscillations example with and without metal (air)

The detection is based on the comparison between the detected pulses in air and the ones
counted in presence of metal. The count result is treated by software to define the metal or
no metal state by comparison with a threshold count number.

Definitions

Vmid Middle voltage (VDD / 2) to energize LC sensor. It is delivered by an external


operational amplifier for STM32L0 and by DAC peripheral output for
STM32L4. To save power consumption, Vmid is disabled when the LC sensor
is not activated.
Vcmp Comparator threshold voltage is set above Vmid to provide a noise margin.
Texcit Excitation pulse width to drive LC sensor in output push-pull (pull-up or
pull-down).
Tcapture Time to perform the measurement. During this time, the comparator collects
oscillations, compares them to Vcmp and delivers pulses to the low power
timer.
Count Pulse count number generated by the LC sensor and conditioned by the
comparator.
CountDetect Detection threshold for the count number to define the sensor state (metal or
no metal).

8/70 DocID027291 Rev 2


AN4636 LC sensor metering principle

CountMax Maximum number of counted pulses, without metal, in proximity of the LC


sensor.
CountMin Minimum number of counted pulses, with metal, in proximity of the LC sensor

DocID027291 Rev 2 9/70


69
Application description - STM32L073Z-EVAL AN4636

2 Application description - STM32L073Z-EVAL

2.1 Hardware required


This demonstration uses STM32L073Z-EVAL evaluation board and especially the LC
sensor metering section. The board can be connected to the USB cable to the host PC and
does not need any external power supply for this example (JP11 is fitted between
3-4 U5V_STLINK). A detection accessory board MB1199 is provided with the evaluation
board and will be used to simulate the presence of metal over the LC sensor. It must be
oriented with the copper layer on the top side and placed over the inductor during the
detection tests (see Section 2.4.1).

2.2 Hardware settings


The SBx solder bridges should be set in their initial factory configuration. All jumpers JP1,
JP2, JP15 and JP17 must be set in the “DET” position (detection) and JP8 fitted as shown in
Figure 3, where these jumpers are marked in red. If the user wants to measure the average
current during the LC sensor metering in low-power mode (few µA range), an ammeter can
be inserted on JP10 between pin 1 (VDD) and 2 (VDD-MCU). Special attention must be paid
to the measurement of pulsed currents (refer to Section 2.5.2 for details). If some tests need
to be performed with an external LC sensor, SB29 and SB30 must be removed and the new
LC cell connected to CN8 (External LC sensor).

Figure 3. LC sensor metering jumpers configuration

10/70 DocID027291 Rev 2


AN4636 Application description - STM32L073Z-EVAL

2.3 LC sensor metering block diagram


Figure 4 shows the LC sensor metering block diagram.

Figure 4. LC sensor metering block diagram


'ULYHDQG6HQVH3%
&203 /37LPHU
'$&
RXWSXW

(PEHGGHGUHVRXUFHV
/&VHQVRU
([WHUQDOFRPSRQHQWV

9''2Q2II
9''
3'
JHQHUDWLRQ

06Y9

The LC sensor metering feature uses a LC network connected to a VDD / 2 bias voltage (AC
ground). This voltage is generated by an external operational amplifier, wired as a voltage
follower and externally controlled by the microcontroller pin PD7. This allows switching ON
and OFF the VDD / 2 generation circuit, in order to save power consumption, during the time
in which the LC sensor is not activated.
On the other side, the LC sensor is connected to PB4 pin through a serial resistor that limits
the DC current necessary to start oscillations. This current must be below the GPIO
maximum current capability (20 mA). PB4 is used both as a GPIO drive pin and as sense
pin connected to the comparator. When used as a drive pin, PB4 GPIO is set as an output
pin and delivers a positive excitation pulse to the LC sensor, whereas it is set as the
comparator positive input, to sense the oscillations signals as soon as they started. The
COMP2 comparator is internally connected to the DAC, as an input threshold signal on its
negative comparator input. The threshold signal is set approximately 100 mV above the
VDD / 2 bias voltage to provide a noise margin. Finally, the pulse train on comparator output
is redirected to the Low power timer input to be counted.

2.4 Application principles

2.4.1 Overview
As described above, the LC sensor is driven by an excitation pulse managed by PB4 GPIO.
The pulse needs a minimum approximately width of 2 µs, so that the oscillations amplitude
can reach and exceed the power signals rails (VDD and GND). Once this pulse is delivered,
the GPIO is reconfigured from output push-pull to alternate function analog input. The
oscillations then appear on comparator non-inverting input, which is high-impedance.
Figure 5 shows the main signals, including PB4 waveform (blue signal), VDD / 2 controlled
by PD7 (red signal) and COMP2 comparator output (yellow signal). VDD / 2 is first turned
ON (red signal), then the oscillations are generated by PB4 (blue signal) and collected by
the LPTIM after being conditioned by the comparator (yellow signal).

DocID027291 Rev 2 11/70


69
Application description - STM32L073Z-EVAL AN4636

Figure 5. Main signals during LC sensor activation

%OXH 9'LY
5HG 9'LY
<HOORZ 9'LY
7LPHEDVH—V'LY

06Y9

Once started, the amplitude of these oscillations decay exponentially until the signal comes
back to VDD / 2 bias as it is shown in Figure 6. This behavior is obtained when the LC sensor
is in air and when no metal is present. This is what is called undamped oscillations.

Figure 6. Oscillations collected with LC sensor in air on PB4

%OXH9'LY
7LPHEDVH—V'LY

06Y9

When a metal is in the proximity of the LC sensor, a part of the magnetic field emitted by the
inductor is absorbed, as eddy currents and the energy of the inductor are lost in the metal
target. In this case the oscillations observed on PB4 (measured on JP8) decay more rapidly

12/70 DocID027291 Rev 2


AN4636 Application description - STM32L073Z-EVAL

and the number of collected pulses is lower than in the previous case (see Figure 7). The
detection is based on the comparison between the detected pulses, obtained in air, and the
ones counted in presence of metal.
During detection, both the amplitude and frequency of these oscillations change. The
oscillations are damped, due to the presence of metal. The amplitude decreases with the
proximity of metal and the frequency increases approximately 15%.

Figure 7. Oscillations collected with LC sensor in proximity of metal on PB4

%OXH9'LY
7LPHEDVH—V'LY

06Y9

The theoretical oscillations frequency is determined by the inductor and capacitor values:
1
f = -------------------
2π LC

In this example, the value of the inductor L is 100 µH and the capacitor C is 1 nF. The
oscillations frequency is then approximately 503.3 kHz. These values have been selected
according to the comparator input bandwidth and the current consumption needed to excite
the LC sensor.
The damping time is mainly dependent on the Q factor of the inductor. The higher the Q
factor, the lower the energy loss and the longer the damping time during the oscillation
sequence.

2.4.2 LC sensor metering capture window


To save power consumption, the LC sensor metering is activated periodically and the
microcontroller is placed in the STOP mode (Low Power mode demonstration selected).
The different peripherals used in this application example are then switched ON during a
capture window and deactivated after, to minimize the power consumption, once the
measurements have been performed. An arbitrary 32 Hz capture frequency has been
selected to activate the LC sensor function. As the LC sensor metering could be used in a
gas or water meter detection system, it is considered that this frequency is high enough to
evaluate the rotation of a wheel, where only few turns per second are seen. The RTC wakes
up 32 times per second for the LC sensor measurement, with the CPU and selected digital
and analog peripherals in RUN mode. The rest of time is spent in STOP mode.

DocID027291 Rev 2 13/70


69
Application description - STM32L073Z-EVAL AN4636

The capture window lasts approximately 80 µs. During this period, the different peripherals
are first switched ON and the LC sensor excitation pulse delivered, until the complete pulses
collection is acquired. Then the microcontroller is set for the lowest power consumption
state.
The sequence can be divided in four main steps:
• Enabling of peripherals such as DAC used as COMP2 comparator threshold voltage,
VDD / 2 reference bias ON, COMP2 activation and LPTIM enable
• Generation of an excitation pulse on the LC sensor
• Collection of the LC oscillations and pulses count
• MCU configuration to enter STOP mode and reach lowest power consumption
Peripherals are initialized at the software start-up, then simply switched ON or clocked when
the capture window occurs. Due to some peripherals different stabilization times, a
switching order is defined, to comply with the corresponding waiting times. For instance,
COMP2 is initialized before DAC, due to a longer initialization time. Once the capture has
been performed, the peripherals are switched off, to save power consumption. The “sleep
on exit” feature is used to turn the device into STOP mode as soon as the interrupt has been
serviced and completed. Refer to Section 3.2 for the description of flow-charts.

2.5 Getting started with the demonstration


The LC sensor metering demonstration can be accessed by the main demonstration menu,
including other applications examples. The starting menu shows some icons including the
LC sensor demonstration located on the bottom left of the menu icons.
By the joystick (B3), the user can access the LC demonstration, by selecting the
corresponding icon and by pressing the joystick center push-button.
The LC sensor metering menu is then accessed. There are two available demonstrations:
• Mode Standard
• Mode Low Power
Mode Standard and Mode Low Power are similar except that Mode Standard does not
optimize the power consumption and that a graphical demonstration is available on the LCD
TFT screen.
When using the detection accessory board MB1199, the metal strip must be positioned over
the LC sensor as shown in Figure 8. Notice that the copper layer is oriented on the top side,
leaving a dielectric gap of 0.8 mm between the LC sensor and the copper, to simulate the air
gap between a rotating wheel and the detection coils.

14/70 DocID027291 Rev 2


AN4636 Application description - STM32L073Z-EVAL

Figure 8. Using detection accessory board MB1199 with LC sensor metering

2.5.1 LC sensor metering Mode Standard


Entering in “Mode Standard”, the menu shown in Figure 9 is displayed. A bar graph shows
the number of collected pulses (green area). The maximum graduation (“Max. Pulses” label)
is reached when the LC sensor is in air (no metal). In red area are displayed the missing

DocID027291 Rev 2 15/70


69
Application description - STM32L073Z-EVAL AN4636

pulses due to the proximity of the metal. The current pulse reading gives the number of
pulses especially when a piece of metal is placed above the LC sensor. If the damped
oscillations reach 20% less of undamped oscillations in air, then the LED LD1 toggles as
detection flag (green LED near B2 push-button) and the current pulse reading value is
turned to green.

Figure 9. LC sensor metering Mode Standard

If the detection accessory board is placed over the LC sensor (copper layer on top), then the
variation between damped and un-damped oscillations is approximately 40%. All relevant
signals can be monitored to evaluate the detection, including:
• VDD / 2 reference bias controlled by PD7
• PB4 signals where oscillations are present (can be monitored on JP8 jumper)
• DAC feeding the COMP2 negative input as comparator threshold voltage
• TP18 COMP2 comparator output wired to the LPTIM input.

2.5.2 LC sensor metering Mode Low Power


In this demonstration, the LCD TFT screen does not display any information from the LC
sensor metering system but the goal is to evaluate essentially the power consumption and
the different signals, while the LC sensor feature is active to mimic a real application case.
To measure the power consumption on the VDD-MCU signal, the JP10 jumper must be
removed and an ammeter must be placed between pin 1 (+) and pin 2 (-) of JP10 connector
(refer to Figure 10 for the ammeter wiring).
The ammeter will measure the current delivered by the VDD power supply to the MCU
exclusively. Knowing that the application changes from MCU running steps to MCU stop
modes, the power consumption observed on the microcontroller is not constant: when the
microcontroller executes processes in RUN mode, the power consumption can be up to few
mA, when it enters STOP mode (with RTC on LSE enabled), the power consumption drops
to a maximum value of 1.2 µA (at 25 °C).

16/70 DocID027291 Rev 2


AN4636 Application description - STM32L073Z-EVAL

The ammeter must be able to average the current value with a dynamic range from µA to
mA and extremely low duty cycles (80 µs RUN time for 30 ms STOP duration), is quite
challenging for most equipments. To ease the current average monitoring, a high value
polarized electrolytic capacitor (approximately 10000 µF) can be placed with its positive
terminal wired to the negative ammeter input and its negative terminal wired to the
application ground (GND). This will smooth the power consumption peaks. In these
conditions, the average power consumption for the LC sensor metering Mode Low Power is
lower than 7 µA.

Figure 10. LC sensor metering Mode Low Power: ammeter and capacitor connection

DocID027291 Rev 2 17/70


69
Application description - STM32L073Z-EVAL AN4636

2.6 How to upgrade the LC sensor system up to three detectors


This demonstration shows an example of LC sensor metering, having only one LC network
and it is intended to demonstrate the feasibility with the STM32L073x microcontroller. In gas
and water meters, several LC sensors are used to detect the rotation of the wheel and to
prevent errors that couldn’t be detected with 1-sensor systems.
The wheel offers a semicircle with a copper layer and the other one with dielectric material.
To detect the rotation sense of the wheel (clockwise or anticlockwise), at least two sensors
are needed and can be placed symmetrically around the wheel. One LC sensor is facing the
copper layer, while the other is in front of dielectric material. To complete the system and
offer much more security and flexibility, three LC sensors are generally used to guarantee
the operation, in case one of the three sensors is defective. These sensors are then placed
around the wheel, spaced by 120 degrees as shown below.

Figure 11. 3-sensor LC metering arrangement

&RSSHUOD\RXWRQ
WKHVHPLFLUFOH
ZKHHO

VHQVRU
VHSDUDWHGE\
GHJUHHV

06Y9

In our LC sensor detection system, based on the STM32L073 microcontroller, it is possible


to extend the number of LC networks, as shown in Figure 12.
Three sensors are now available and the selection can be done internally by the COMP2
positive input selection multiplexer.
As the LC sensors must be enabled sequentially, only one VDD / 2 generation circuit is
needed and controlled by PD7. On the comparator side, PB4, PB5 and PB6 are activated as
GPIO outputs, to drive the corresponding LC networks LC1, LC2 and LC3 and alternatively
configured as positive comparator inputs. Nevertheless, only one LC network can be
scanned at a time. During the activation of PB4 for the LC1 network, PB5 and PB6 are
placed in high impedance pins. PB4 can be set as GPIO output, to excite the LC1 sensor,
then immediately switched into COMP2 positive input to collect the generated pulses of the
LC1 sensor. In the same way, while PB5 and LC2 are controlled, PB4 and PB6 are placed in

18/70 DocID027291 Rev 2


AN4636 Application description - STM32L073Z-EVAL

high impedance. Again, while PB6 and LC3 are controlled, PB4 and PB5 are placed in high
impedance.

Figure 12. 3-sensor LC metering system upgrade

&203,136(/

3%
&203
3% ,QWHUQDO08;

3%

&203 /37LPHU

'$&
RXWSXW

/& /& /& (PEHGGHGUHVRXUFHV

([WHUQDOFRPSRQHQWV

9''2Q2II
9''
3'
JHQHUDWLRQ

06Y9

The drawbacks are that all the sensors cannot be scanned at the same time and that the
global power consumption of the system is multiplied by 3. If an 80 µs capture window is
needed for one LC sensor, the data for the three LC sensors can be acquired in
approximately 240 µs, still an adequate timing for low speed rotations wheels.
The sensors capture frequency (set here to 32 Hz) can be increased or decreased,
according to the system desired response.

DocID027291 Rev 2 19/70


69
Firmware description - STM32L073Z-EVAL AN4636

3 Firmware description - STM32L073Z-EVAL

3.1 STM32L073x peripherals used by the application


This application example uses the following STM32L073xx peripherals with the settings
described below.

GPIOs
Some GPIOs are used to control the signals needed for this LC sensor metering example:
• PE4 set as output GPIO to drive the LED LD1.
• PD7 set as output GPIO to control the VDD / 2 reference bias. This GPIO power
supplies the operational amplifier, that is designed to generate the VDD / 2 reference
voltage. This allows switching ON and OFF this amplifier and save power consumption.
• PB4 is alternatively used as output GPIO, to drive the LC sensor and put in alternate
function (positive comparator input), once the excitation pulse is delivered.

DAC
DAC_OUT1 is used to generate the input threshold voltage, needed by the comparator.
Oscillations signals from LC sensor are referenced to VDD / 2. The DAC peripheral allows to
provide a preset threshold voltage value near VDD / 2 but with a necessary positive margin
to eliminate noise. For further developments, using the DAC as comparator threshold
voltage, would allow to calibrate the threshold value according to different LC network
responses. Typically, LC network responses and collected noise vary from one material to
another, and the capability to adjust the comparison threshold, is an improvement compared
to fixed threshold voltages.

COMP2
COMP2 is connected to the LC sensor network. As soon as the excitation pulse has been
delivered, the COMP2 positive input collects analog oscillations referenced to VDD / 2 bias,
while its negative input is fed by the DAC threshold voltage. Finally, the LC sensor
oscillations are conditioned and this results in digital pulses are delivered to the comparator
output. This signal will be then transmitted to the LPTIM. COMP2 is used in high speed
mode, according to the signals frequency emitted by the LC. The DAC is internally
connected to the COMP2 negative input and PB4 is chosen as comparator positive input.

LPTIM
LPTIM is configured to count the pulses generated by the LC sensor oscillations and
conditioned by the COMP2 comparator. The LPTIM internal counter is read before the LC
sensor generates the oscillations. At the end of the oscillations period, the new LPTIM
counter value is subtracted from the previous value, to get the number of collected pulses
for the corresponding measurement. This avoids a time consuming LPTIM reset.

RTC
RTC peripheral is used to wake up the microcontroller at regular intervals once the MCU
has entered STOP mode. The RTC clock is connected to the LSE clock, whose frequency is
32.768 kHz. The wake up frequency corresponds to the LC sensor capture frequency and it
is set to 32 Hz for this example. This capture frequency can be increased or decreased,

20/70 DocID027291 Rev 2


AN4636 Firmware description - STM32L073Z-EVAL

depending on rotating wheel maximum speed. Modifications to the capture frequency will
lead to a change of the average power consumption.

TIM
TIM is configured to generate the precise timings used for the LC sensor metering
sequence, especially in the standard demonstration mode.

Interrupts
LC sensor metering “Mode Standard” and “Mode Low Power” are distinguished in the RTC
IRQ handler process.
To save the maximum time and then power consumption in MCU RUN mode, the RTC
Wake up Timer IRQ handler is directly processed inside the interrupt subroutine for the
“Mode Low Power”, while a specific RTC Wake up Timer call back function is used for
“Mode Standard”.

3.2 Description of “Mode Low Power” flow-charts


“Mode Low Power” software, including STOP mode entry procedure and wake up
processes, performing the LC sensor metering feature, will be described in this section.
The global demonstration includes several examples related to many features, called
“modules”, such as the “lc_sensor_metering_app.c”, “pressure_app.c”,
“thermometer_app.c” and others.
These examples are launched from a “main.c” file included in the “Demo” folder and
gathering all these modules in a single demonstration project.
The focus is on the function called by the LC sensor metering demonstration for the low
power mode, which is named “LcSensorCountingDemoLowPower()”. This function is the
entry point for the “Mode Low Power” LC sensor example, once the user has chosen the LC
sensor demonstration in the graphical menu, among the different examples and select
“Mode Low Power” in the submenu.
A detailed description will be done later in this section for the StopEntry() function, which is
intended to prepare the microcontroller for the lowest power consumption in STOP mode.
Finally, the RTC IRQ handler will be described to explain the wake up sequence, that
triggers the LC sensor measurement, while the microcontroller is in RUN state (capture
window).

3.2.1 LcSensorCountingDemoLowPower() function


As soon as this function is fully executed, a RTC interrupt is created to wake up the
microcontroller device at regular intervals. This function is then called once and the
application will later alternate STOP sequences and RUN slots at the frequency rate, given
by the RTC wake up parameters. In this example, the microcontroller is woken up 32 times
per second.
As shown in Figure 13, the function starts by setting the LCSensorMode variable to indicate
in which mode the current demonstration is. The LCSensorMode variable is used to identify
the “Mode Low Power” in the RTC_IRQHandler() and then to bypass callback functions to
save time and power consumption (refer to firmware file “stm32l0xx_it.c” for details).

DocID027291 Rev 2 21/70


69
Firmware description - STM32L073Z-EVAL AN4636

The LCD TFT display is updated to alert the user on the way to exit this “Mode Low Power”
demonstration. A reset must be applied to exit this example.
RTC, DAC, LPTIM and COMP peripherals are initialized with the settings described in
Section 3.1. Then, the StopEntry() function is executed to prepare the device to enter STOP
mode with specific settings and the microcontroller is placed in an infinite loop, waiting for
the RTC wake up interrupt. All processes are indeed performed in interrupt, using “sleep on
exit” mode, thus no activity from the microcontroller, is performed in main.c section. User will
exit the Low Power demonstration, by applying a reset sequence by pressing B1 (RESET
button).

Figure 13. LCSensorCountingDemoLowPower() function flow-chart

/F6HQVRU&RXQWLQJ'HPR/RZ3RZHU

/&6HQVRU0RGH 
&21),*B/&B6(1625B/2:B32:(5

'LVSOD\/&'7)7
/RZ3RZHU0RGH
PHVVDJH

57&,QLW
'$&,QLW
/37,0,QLW
&203,QLW

6WRS(QWU\

ZKLOH 

06Y9

3.2.2 StopEntry() function


The aim of this function is to prepare the device to enter STOP mode with parameters set to
minimize the device power consumption. It starts by enabling all GPIO clocks to perform
GPIO registers modifications. Then PB4 and PD7 output data registers are preset to logical
“1”. All GPIO can now be placed in Analog state to minimize power consumption and the
associated clocks disabled. The internal voltage reference is disabled by setting the ULP bit
in PWR_CR register. Fast wake up mode is disable to wait for VREFINT ready, before
waking-up the MCU and using COMP2. The feature “Sleep on Exit” is used to force the
MCU entering the STOP mode, as soon as the RTC wake up has been serviced and
executed. In that case, the StopEntry() function is executed once and the microcontroller will
return in STOP mode after each interrupt.
The MSI clock is set to 2 MHz to minimize the power consumption. The voltage scaling is
adjusted accordingly (range 3, 1.2 V), to further decrease dynamic consumption. The

22/70 DocID027291 Rev 2


AN4636 Firmware description - STM32L073Z-EVAL

Systick timer is disabled for the same reason. This operation must be performed after the
system clock changes. All wait states are disabled.

Figure 14. StopEntry() function flow-chart

6WRS(QWU\

(QDEOH$OO*3,2[FORFNV

6HW3% H[FLWDWLRQSXOVH
6HW3' 9''ELDV21

3XW$OO*3,2[WR$QDORJVWDWH

'LVDEOH*3,2[FORFNV
$OO*3,2SLQVLQ$QDORJWRVDYHSRZHU
FRQVXPSWLRQEHIRUHHQWHULQJ6723PRGH

(QDEOH8OWUD/RZ3RZHU
'LVDEOH)DVW:DNH8S
(QDEOH6OHHS2Q([LW 0&8HQWHUV6723PRGHDVVRRQDVLWH[LWV
WKH57&:DNH8S7LPHU,65

&ORFN 06,0+]
&ORFNLVVHWWR06,0+]WREHDEOH
FKDQJLQJWKHYROWDJHVFDOLQJ6FDOH
'LVDEOH6\VWLFNWLPHU

&KDQJH9ROWDJH
6FDOLQJ6FDOH

(QWHU6723PRGH

(1'
06Y9

3.2.3 RTC_IRQHandler() interrupt subroutine


The RTC IRQ Handler manages the RTC interrupt triggered by the RTC Wake Up time. In
this example, the interrupt occurs 32 times per second. To save time during the interrupt
execution and since the device operates in RUN mode, the interrupt subroutine is executed
in the Low Power demonstration mode, without performing any call back function in the
main program. The interrupt flag is first cleared. Then COMP2 and DAC peripherals are
switched on and a delay is inserted, to wait the peripherals stabilization times before they
can be operational. The VDD / 2 reference bias voltage is turned on by mean of PD7 GPIO
and the excitation pulse is delivered by PB4 pin when first placed in GPIO output mode. As
soon as the positive pulse is applied on the LC network, PB4 is switched into Analog state
and acts as the non-inverting comparator input. Application waits for an 80 µs capture time,
until all the pulses are collected and switches off the VDD / 2 reference bias voltage. DAC
and COMP2 are disabled to minimize power consumption. The capture of the LC sensor
oscillations has been performed during this interrupt.

DocID027291 Rev 2 23/70


69
Firmware description - STM32L073Z-EVAL AN4636

Figure 15. RTC_IRQHandler() interrupt subroutine flow-chart

57&B,54+DQGOHU

&OHDU57&,QWHUUXSW

(QDEOH&203
(QDEOH'$&

'HOD\ :DLWLQJ&203DQG'$&
,QLWLDOL]DWLRQWLPH

6HW3'9''ELDV21 3RZHUVXSSO\9''JHQHUDWLRQ
FLUFXLWU\

6HW3%H[FLWDWLRQSXOVH ([FLWH/&VHQVRU

6HW3%$QDORJVWDWH &KDQJHWRFRPSDUDWRU
FRQILJXUDWLRQ

'HOD\ 6HWWKHFDSWXUHWLPHa—V

6HW3'$QDORJVWDWH

'LVDEOH'$&
'LDVEOH&203

(1',65

06Y9

24/70 DocID027291 Rev 2


AN4636 Application description - STM32L476RG-NUCLEO

4 Application description - STM32L476RG-NUCLEO

4.1 Hardware required


This demonstration uses STM32L476RG-NUCLEO64 board and custom board for LC
sensing with external components (see Figure 18 and Figure 19). The board can be
connected to the USB cable of the host PC. The detection accessory board MB1199 can be
used to simulate the presence of metal over the LC sensor. It must be oriented with the
copper layer on the top side and placed over the inductor during the detection tests.

4.2 Hardware settings


Jumpers (red boxes in Figure 16) should be set in their initial factory configuration.

Figure 16. Configuration of LC sensor metering jumpers

The SBx solder bridges should be set in their initial factory configuration. DAC output
channel (Vmid) can be routed to PA4 or PA5 pin. If PA4 is used, no change is required, if PA5
is used, SB21 should be disconnected.

DocID027291 Rev 2 25/70


69
Application description - STM32L476RG-NUCLEO AN4636

Figure 17. SB21 USER LED disconnection (only if PA5 is used)

4.3 Hardware settings for LC sensor custom board

4.3.1 Requirements
A custom board with LC sensors must be developed and connected to the STM32L4 I/Os.
External components must be selected to minimize deviations due to external conditions
(such as temperature, humidity), the characteristics of the components used for this
demonstration are detailed below.
• LC sensors: all sensors must have identical Ls / Cs values. These values have been
selected according to the comparator input bandwidth and the current consumption
needed to excite the LC sensor.
– Ls = 470 µF (e.g. Murata 11R474C)
– Cs = 220 pF (e.g. Murata RPE5C2A221J2S1A03A)
• Reference capacitor: used to store energy for LC sensors oscillations.
– Cref = 470 nF (e.g. Murata RPER71H474K2M1C03A)
• Serial resistors: the LC sensor is connected to comparator inputs pin through a serial
resistor that limits the DC current necessary to start oscillations. This current must be
below the GPIO maximum current capability (20 mA for STM32L4x6, refer to product
datasheet).
– R = 150 Ω (for VDD = 3 V)
• Protection diodes: external diodes must be connected to IO and VDDA, see Excitation
time: Texcit to define if requested or not. The I/O type is “_a” with analog switch

26/70 DocID027291 Rev 2


AN4636 Application description - STM32L476RG-NUCLEO

function supplied by VDDA (see datasheet for details). For this example the diode used
is STMicroelectronics BAT43.

Table 1. I/O configuration


LC I/O Pin(s) LC function

IO1 PA4 or PA5 Vmid


IO2 PC5 Sensor1
IO3 PB2 Sensor2
IO4 PB4 Sensor3
IO5 PB6 Sensor4

Figure 18. Schematic: one or two sensors

/&VHQVRUERDUG 670/0&8
'$&&KDQ
9''$
,QWHUQDO6+
9''$ FDSDFLWRU
2XWSXW
33
5 ,23%

/6 &6 $QDORJLQSXW &203
9''$

$QDORJLQSXW
5 ,23& /37,0
9''$
/6 &6 2XWSXW
33

,23$

&5()

'$&&KDQ
069

DocID027291 Rev 2 27/70


69
Application description - STM32L476RG-NUCLEO AN4636

Figure 19. Schematic: up to four sensors

/&VHQVRUERDUG 670/0&8
9''$

9''$
2XWSXW
5 33
,23%
&6
/6
9''$
$QDORJLQSXWV
/37,0
5 ,13 ,13
,23& 9''$
&6 2XWSXW 
/6 33 &203


'$&&KDQ
,QWHUQDO6+FDSDFLWRU
9''$

9''$
2XWSXW 
5 ,23%
33 &203

/6 &6 ,13 ,13
9''$ /37,0
$QDORJLQSXWV

5 ,23%
9''$
/6 &6 2XWSXW
33

,23$
'$&&KDQ
&5()

069

28/70 DocID027291 Rev 2


AN4636 Application description - STM32L476RG-NUCLEO

4.4 Application principles

4.4.1 Overview
The application is based on the same principle seen for the STM32L0 application, the main
difference is that the Vmid level (VDD / 2) is generated with STM32L4 DAC peripheral instead
of an external circuitry.
The LC sensor is driven by an excitation pulse managed by GPIOs. Once the pulse is
delivered, the GPIO is reconfigured from output push-pull to analog input. The oscillations
appear on the non-inverting comparator and compared to Vmid level (VDD / 2).
Vmid level is generated by the internal DAC and can be stopped after measurement to
reduce the power consumption.
Once started, the amplitude of these oscillations decays exponentially until the signal comes
back to Vmid bias, as shown in Figure 20. This behavior is obtained when the LC sensor is in
air and when no metal is present.

4.4.2 LC sensor metering capture window


In order to save power consumption the LC sensor metering is activated periodically and the
microcontroller is put in the STOP2 mode (Low Power mode demonstration selected).

Figure 20. LC measurement sequence

DocID027291 Rev 2 29/70


69
Application description - STM32L476RG-NUCLEO AN4636

For each measurement, as indicated in Figure 20, the following steps are executed:
1. The LC sensor metering is activated and the microcontroller is put in the STOP2 mode
(Low Power mode).
2. The MCU is waken-up and enables the peripherals used by application, with a waiting
time inserted to let peripherals stabilize. “One pulse” timer is started and the MCU is
put in wait for timer event (WFE), as described in DAC configuration. After that, the LC
sensor excitation pulse is delivered (see Excitation time: Texcit). To perform the
measurement one pulse timer is started and MCU is placed in WFE (refer to Capture
window: Tcapture).
3. During the measurement phase the MCU is put in sleep mode and the LPTIMER
increments its counter according to the number of oscillations. The collection of the LC
oscillations and pulses count is done.
4. After timer event, the MCU returns in RUN mode, processes the LPTIMER result and
compares it with the detection threshold (CountDetect) to define if there is a Metal or
No Metal state. The software state machine can process counter results at this level.
5. The MCU goes back in STOP2 mode and reaches the lowest power consumption.

4.4.3 Parameters to define


Some parameters must be defined according to the application requirements:

DAC configuration
Two channels are used to generate Vmid and Vcmp levels:
• Vmid for reference level to VDD / 2: Channel 1 or Channel 2 connected to external pins,
respectively PA4 or PA5.
• Vcmp for threshold comparator level: Channel 1 or Channel 2 connected to on chip
comparator inverting input.
DAC peripheral is configured in Sample and Hold mode and managed in Wake Up interrupt.
It is enabled at each LC measurement and disabled before returning in STOP2 mode.

Reference voltage (Vmid)


The first DAC output is configured to deliver reference voltage to energize LC sensors at
VDD / 2.
DAC Vmid (to program) = 4096 * (Vmid / VDD) = 4096 / 2 = 2048

Comparator threshold voltage (Vcmp)


The second DAC output is configured to deliver the threshold voltage (Vcmp) needed by the
comparator. It is set higher than VDD / 2 bias voltage to provide a noise margin.
In this example: DAC output is configured to deliver Vcmp = Vmid + 750 mV
DAC Vcmp (to program) = 4096 * (Vcmp / VDD) = 4096 / 3 V * 2.25 V = 3072 = 0xC00

DAC Vmid refresh time (Trefresh)


To save power consumption, the DAC output is disabled between two LC measurements.
During this phase, the DAC output level is in analog state (high impedance) and the Vmid
level is hold by Cref capacitor. Vmid drop (Dv) depends to the holding time (time between
two measurements). Before each measurement, a DAC refresh time after DAC enabling is
required to reach the expected Vmid value.

30/70 DocID027291 Rev 2


AN4636 Application description - STM32L476RG-NUCLEO

Figure 21. DAC output example

Dv computing
Vmid drop (Dv) during holding time (the time between two measurements) depends upon the
leakage current (Ileak = 150 nA by I/O, as specified in the STM32L4x6 datasheet).
For each I/O Ileak = 150 nA (worst case on the I/O leakage on all the temperature range),
hence Ileak = Ileak1 + Ileak2 + Ileak3 + ... = n * 150 nA, where n is the total number of I/Os (see
Figure 22, where currents are indicated in red and voltage in blue).

Figure 22. Cref leakage current during hold time

/&VHQVRUERDUG 670/0&8
9''$

,OHDN
,23&
/6 &6

,OHDN
,23&
,OHDN &5()
9

069

DocID027291 Rev 2 31/70


69
Application description - STM32L476RG-NUCLEO AN4636

The tolerated voltage drop during the hold phase (dv) is represented by the number of LSBs
after the capacitor discharges with the output leakage current, that is Nlsb = (dv / VDD) * 212.
To compute dv use the relation Cref * (dv / dt) + Ileak = 0, so dv = - (Ileak * dt) / Cref.
For this example, a 10 mV error accuracy has been defined for power saving.
The settling back to the desired value with 10 mV error accuracy (14 LSB at 3 V) requires a
DAC constant time equal to ln (Nlsb / 14).
Lsbaccuracy = (V error accuracy) / lsb
lsb = VDD / 212 = 3 / 4096 = 0.00073 V

Trefresh computing
The DAC Vmid refresh time is set to let the time to reach the value according to the desired
accuracy error.
Trefresh = TstabBON + (RBON * Cref) * ln (Nlsb / (Lsbaccuracy))
The parameters TstabBON and RBON are specified in the datasheet.
DAC refresh time is managed with timer peripheral (TIM6) configured in “One Pulse” mode.
The HCLK frequency is decreased (divided by 64) during sleep to save power consumption.
Trefresh_to program = Trefresh_seconds * (Freq_MSI / 64)

Examples
For one sensor and Cref = 470 nF:
• Sampling time 500 Hz (hold time = 2 ms):
dv = -(2 * 150 nA * 2 ms) / 470 nF ≈ -1.3 mV → Nlsb = 2
– 1 mV accuracy error:
Trefresh = 237 µs, Trefresh_to program = 237 µs * 24 MHz / 64 = 89
– 10 mV accuracy error:
Trefresh_to program = 0, No more refresh time required because Dv < 10 mV
• Sampling time to 10Hz (hold time = 100 ms):
dv = -(2*150nA * 100 ms) / 470 nF ≈ -64 mV → Nlsb = 87
– 1 mV accuracy error:
Trefresh = 3.91 ms, Trefresh_to program= 3.91 ms * 24 MHz / 64 = 1468
– 10mV accuracy error:
Trefresh = 1.75 ms (10 mV accuracy error)
Trefresh_to program = 1.75 ms * 24 MHz / 64 = 656
Note: Oscilloscope probes connected to LC sensors change significantly the system behavior
because of their impedance.
Note: The MCU is in SLEEP mode during DAC Vmid refresh time. This time must be minimized to
save power consumption and a compromise with Vmid accuracy must be struck. For this
example an accuracy error of 10 mV has been used.
ileakprobe = V / Rprobe, where Rprobe is the probe input resistance
ileak = ileak1+ ... + ileakprobe1 + ileakprobe2 + ...

32/70 DocID027291 Rev 2


AN4636 Application description - STM32L476RG-NUCLEO

Examples for one sensor, Cref = 470 nF and one probe single ended with Rprobe = 1 MΩ:
• Sampling time = 500 Hz (hold time = 2 ms):
dv = -((2 * 150 nA + 1.5 V / 1 MΩ) * 2 ms) / 470 nF ≈ -7.7 mV, instead of -1.3 mV
without probe
• Sampling time = 10 Hz (hold time = 100 ms):
dv = -((2 * 150 nA + 1.5 V / 1 MΩ) * 100 ms) / 470 nF ≈ -383 mV, instead of -64 mV
without probe

Excitation time: Texcit


LC sensor excitation can be done to VSS (output push pull down) or to VDD (output push pull
up), the default value used in this example. The pulse width can be adjusted to set the
oscillation amplitude (Texcit).
If the maximum oscillation amplitude exceeds maximum voltage allowed, an external diode
must be added to protect the I/O. See product datasheet for details. For this example
Vin max = min (min (VDD, VDDA,VDDIO2, VDDUSB, VLCD) + 3.6 V, 5.5 V) = 5.5 V.

Figure 23. Excitation pulse managed by GPIOs – Example with Texcit to VSS = 250 ns

DocID027291 Rev 2 33/70


69
Application description - STM32L476RG-NUCLEO AN4636

Figure 24. Excitation pulse managed by GPIOs – Example with Texcit to VDD = 250 ns

Excitation is generated by assembler code and the size of excitation pulse is


Texcit_to program = Texcit_seconds * (Freq_MSI) / (Instructions Cycles)
For this example Texcit_to program = 250 ns * 24 MHz / 3 = 2

Capture window: Tcapture


The collection of LC sensor oscillation and pulse count is performed during this time,
managed with timer peripheral (TIM6) configured in “One Pulse” mode. The HCLK
frequency is decreased during sleep (divided by 64) to save power consumption.
Tcapture_to program = Tcapture_seconds * (Freq_MSI) / 64
For this example (see Figure 22) Tcapture_to program = 50 µs * 24 MHz / 64 = 19.

34/70 DocID027291 Rev 2


AN4636 Application description - STM32L476RG-NUCLEO

Figure 25. Tcapture example

To save power consumption, the capture window can be minimized and adjusted to the
maximum count number (without metal).
Tcapture_seconds = (CountMax / Freq_Osc) * (1+ x), where x is the margin in percent (default
value is 5%).
The theoretical oscillation frequency is determined as
1
Freqosc = -----------------------------------------------
2 ⋅ π ⋅ Ls ⋅ Cs

In this example, the value of the inductor Ls is 470 µH and that of the capacitor Cs is 220 pF.
The oscillations frequency is then approximately 495 kHz.

Time between measurements


Measurements must be done sequentially to avoid cross-effects between the LC sensors. If
more than one sensor is used, a waiting time between the measurements must be added to
account for the stabilization time of the next sensor.

DocID027291 Rev 2 35/70


69
Application description - STM32L476RG-NUCLEO AN4636

Figure 26. Time between sensors: 200 µs between Sensor1 (IO2) and Sensor3 (IO4)

TimeBetweenSensor is managed with timer peripheral (TIM6) configured in “One Pulse”


mode. The HCLK frequency is decreased during sleep (divided by 64) to save power
consumption.
TimeBetweenSensorto program =TimeBetweenSensorseconds * (Freq_MSI) / 64
For this example TimeBetweenSensorto program = 200 µs * 24 MHz / 64 = 75

36/70 DocID027291 Rev 2


AN4636 Application description - STM32L476RG-NUCLEO

Using up to four LC detectors


In the LC sensor detection system based on the STM32L4 microcontroller, it is possible to
extend the number of LC networks, as already seen in Figure 19, and summarized in
Table 2.
• One sensor
This configuration makes it possible only to detect the metal presence or the wheel
rotation
– Two increments by rotation
• Two sensors
This configuration makes it possible to detect both the rotation and the direction of the
wheel
– Sensors are placed around the wheel and spaced 90°
– Up to four increments by rotation
– Clockwise and anticlockwise counter
• Three sensors
This configuration results in a higher precision (eight increments per rotation) and
prevents some errors that cannot be detected with the two sensors system.
– Sensors are placed around the wheel and spaced 120°
– Up to eight increments per rotation
– Needs two comparators and two low power timers.
• Four sensors
This configuration is based on two wheels with two sensors per wheel, and features
rotation and direction detection capability.
– Sensors are placed on two wheels and are spaced 90°
– Two comparators and two low power timers are required

DocID027291 Rev 2 37/70


69
Application description - STM32L476RG-NUCLEO AN4636

Table 2. Sensor configurations supported by STM32L476RG-NUCLEO board


Configuration Schematic

0HWDO 6
One sensor

1RPHWDO

One 0HWDO 6
Two sensors(1)
wheel 6

1RPHWDO

0HWDO
Three sensors(2) 6
6
6
1RPHWDO

Wheel 1 Wheel 2
Two 0HWDO 0HWDO
Four sensors(3) 6 6
wheels
6 6

1RPHWDO 1RPHWDO

1. S1 and S2 are radially spaced 90°.


2. S1, S2 and S3 are radially spaced 120° from each other.
3. S1 and S2 are radially spaced 90°, and the same is true for S3 and S4.

4.4.4 Calibration
The examples described in this section detail a method to calibrate the system and
compensate LC sensors deviations. These examples must be tuned depending on the
application requirements.
In this demonstration, the system is calibrated in two steps:
• First calibration: performed during the system start (or factory calibration)
• Periodic calibration: performed during normal operation to compensate for small drifts
due to external conditions modifications (temperature, humidity, voltage).
Measurements are still carried out during this phase, so only small drifts can be
compensated.

38/70 DocID027291 Rev 2


AN4636 Application description - STM32L476RG-NUCLEO

Figure 27. Calibration phases

,QL]LDOL]DWLRQ /&PHDVXUHPHQWV

)LUVW 3HULRGLF 3HULRGLF 3HULRGLF 3HULRGLF


FDOLEUDWLRQ FDOLEUDWLRQ FDOLEUDWLRQ FDOLEUDWLRQ FDOLEUDWLRQ

069

For each calibration phase, two examples are presented, depending upon the application:
• “Static” method for basic detections: the calibration is done without metal in proximity of
the LC sensor (air).
• “Dynamic” method, typically with rotating wheel: the calibration is done with metal and
no metal transitions.

First calibration
The aim of this calibration is to adjust comparator threshold level to have a predefined
pulses count number. Based on this pulse count number, the detection threshold is set and
the capture time adjusted for power saving (see Section 5.2: Description of flow-chartsi for
more details).

Static method
This calibration is done without metal and based on the maximum pulses count number.
The predefined pulses count number must be defined carefully:
• A small number involves a small count difference between metal and no metal state.
The detection threshold is near maximum and minimum values, and instabilities can
appear.
• A number too large involves MCU RUN state and power consumption increases.
Moreover, noise can appear with small oscillations amplitude.
The following parameters are automatically defined (by software) during this calibration:
• Vcmp
The comparator threshold level (Vcmp) is adjusted to have a predefined maximum
oscillations count number without metal in the proximity of LC sensors.
• CountDetect = f(CountMax)
The detection threshold (metal / no metal) is based only on the maximum oscillations
number: CountDetect = CountMax * x, where x = value in percent
• Tcapture= f(CountMax)
To save power consumption, the capture time window is minimized and adjusted to the
maximum pulses count number: Tcapture = (CountMax * PeriodOsc) * (1 + x), where
– PeriodOsc = 2 π (Ls * Cs)1/2
– Ls = Sensor Inductor value
– Cs = Sensor Capacitor value
– x = margin in percent

DocID027291 Rev 2 39/70


69
Application description - STM32L476RG-NUCLEO AN4636

Example
• Comparator threshold level setting (Vcmp)
Vcmp is increased from 1.9 to 3 V. For each step, the CountMax value is compared to
the targeted pulse count number, increments are stopped when it is reached.
In the example (see Figure 28) PulseCount = 30 when Vcmp = 2.3 V.
• Detection threshold count number
CountDetect = CountMax * x = 24 (for example x = 80%)
Tcapture (CountMax = 30, Ls = 470 µH, Cs = 220 pF, x = 5%) ≈ 64 µs

Figure 28. First calibration example for a predefined maximum count number of 30

Dynamic method
This calibration is done with metal and no metal states to have respectively minimum and
maximum pulses count numbers.
Following parameters are automatically defined during this calibration:
• Vcmp
The comparator threshold is incremented to find the best ratio between the minimum
(metal) and the maximum (air) pulse count number. The goal is to have a minimum

40/70 DocID027291 Rev 2


AN4636 Application description - STM32L476RG-NUCLEO

difference (∆) in the pulse count to reach a satisfactory compromise between stability
and power consumption.
• CountDetect = f(CountMax, CountMin)
The detection threshold (metal / no metal) is based on the both maximum and minimum
pulse count numbers.
• CountDetec = (CountMax + CountMin) / 2
• Tcapture= f(CountMax)
To save power consumption, the capture time window is minimized to be adjusted to
maximum pulse count number: Tcapture = (CountMax * PeriodOsc) * (1 + x), where
– PeriodOsc = 2 π (Ls * Cs)1/2
– Ls = Sensor Inductor value
– Cs = Sensor Capacitor value
– x = margin in percent

Example
• Comparator threshold level (Vcmp)
Vcmp is increased from 1.9 to 3 V. For each step, the difference between CountMax
and CountMin is computed. Increments are stopped when the minimum ∆ to guarantee
is reached.
In this example (see Figure 29) PulseCountDeltaMin = CountMax - CountMin = 10 and
Vcmp = 2.7 V.
Detection threshold count number (CountMax = 25, CountMin = 15) CountDetec = 20
Tcapture (CountMax = 25, Ls = 470 µH, Cs = 220 pF, x = 5%) ≈ 53 µs

DocID027291 Rev 2 41/70


69
Application description - STM32L476RG-NUCLEO AN4636

Figure 29. First calibration example for a predefined ∆ of 10

42/70 DocID027291 Rev 2


AN4636 Application description - STM32L476RG-NUCLEO

Periodic calibration
This makes possible to compensate small drifts due to external variations such as
temperature, voltage, humidity. During periodic calibrations, measurements are still
ongoing.
The detection threshold is adjusted based on the calibration results (details are described in
HAL_RTCEx_AlarmBEventCallback () - Periodic calibration function).

Static method
This calibration is done without metal in proximity of LC sensor. Only the maximum pulses
count number is used. To check that calibration results are valid, no transitions should
appear during this phase (if this requirement is not met calibration results must be ignored).
To eliminate noisy results that could appear, a maximum drift is allowed:
• CountMax - CountDrift < Calibration CountMax result < CountMax + CountDrift
The following parameters are automatically defined during this calibration:
• CountDetect = f(CountMax), same as in Static method of First calibration
• Tcapture = f(CountMax), same as in Static method of First calibration

Dynamic method
This calibration is done with a rotating wheel. Maximum and minimum pulses count number
are used, so it is mandatory to have several transitions during this calibration phase. If not,
calibration results must be ignored.
To eliminate noisy results that could appear, maximum drifts are allowed:
• CountMax - CountDrift < Calibration CountMax result < CountMax + CountDrift
• CountMin - CountDrift < Calibration CountMax result < CountMin + CountDrift
The following parameters are automatically defined during this calibration:
• CountDetect = f(CountMax), same as in Dynamic method of First calibration
• Tcapture = f(CountMax), same as in Dynamic method of First calibration

DocID027291 Rev 2 43/70


69
Application description - STM32L476RG-NUCLEO AN4636

4.5 Getting started with the demonstration


There are four demonstrations available:
• Demo1: Basic counting demonstration with one sensor to use with the detection
accessory board MB1199 or other metal accessory.
• Demo2: Counting demonstration with two sensors: rotation/direction detections to use
with a rotating wheel.
• Demo3: Tachometer demonstration with two sensors: rotation/direction detections to
use with a rotating wheel.
• Demo4: Counting demonstration with two by two LC sensors: rotation/direction
detections to use with a rotating wheel.
Each demonstration can be run in standard mode (for debug) or in low power mode (for the
final application and to perform consumption measurements).
Counter informations are sent periodically on USART2 port and can be displayed with
UART terminal software on the host PC connected to the USB cable.

Warning: Thanks to the user button (Blue), the user can switch ON or
OFF the USART2 communication to read LC sensors results
(enabled by default). Before performing consumption
measurements it is mandatory to disable the USART2
communication.

Terminal software configuration


• Port: STMicroelectronics STLink Virtual COM port
• Baud rate: 921600
• Data rate: 8 bit
• Parity: none
• Stop: 1 bit
• Flow control: none
Note: To connect debugger and store the software in memory, it could be necessary to press the
reset button (Black) at the beginning of the connection. This is due to debug pins (SWD
PA13-PA14) put in analog mode by the previous low power software execution.

4.5.1 LC sensor metering basic counting demonstration with one sensor


This demonstration uses one sensor, IO1 and IO2 (one IO is needed for each sensor and
another, DAC output, to supply all the sensors). This basic demonstration allows to check
the presence of metal.
When using the detection accessory board MB1199, the metal strip must be positioned over
the LC sensor as shown in Figure 30.

44/70 DocID027291 Rev 2


AN4636 Application description - STM32L476RG-NUCLEO

Figure 30. LC sensor with MB1199 accessory board

When using one wheel, this basic demonstration makes it possible to collect the number of
turns with two increments for each rotation, as indicated in Figure 31.

Figure 31. Demo1, one sensor

The counter is updated at each metal / no metal transition, but, it is not possible to
differentiate between clockwise and anticlockwise rotations.

FW configuration
To enable this demonstration, “LC_SENSOR_DEMO 1” define must be selected in
“lc_sensor_metering.h” file.

DocID027291 Rev 2 45/70


69
Application description - STM32L476RG-NUCLEO AN4636

LcConfig and LcConfigSensorX variables, set in “LcSensorConfig ()” function, must be


defined according to application (Sampling rate, DAC refresh, Vcmp, Texcit, Tcapture)
Each two seconds, the transitions number (LcStatus.EdgeCount) and the current sensor
status (LcSensor1.status) are updated.

Figure 32. Demo1 - USART communication output – Terminal software example

In Figure 32 S is Sensor1 status (0 = No metal, 1 = metal), and E indicates Count number.

4.5.2 LC sensor metering counting demonstration with two sensors


This demonstration (Figure 33) uses two LC sensors (IO1, IO2 and IO3).
If the calibration is disabled or in “static” mode, no metal must be present over the LC
sensors during start of the system. In the case of “dynamic” calibration selection, the wheel
must be in rotation.

Figure 33. Hardware for the two sensors demonstration

46/70 DocID027291 Rev 2


AN4636 Application description - STM32L476RG-NUCLEO

It is possible to determine both the wheel rotation and its direction. Two counters are
updated, one for the clockwise rotation and the other one for the anticlockwise rotation.
• Rotation and direction detection
• Clockwise counter and anticlockwise counter (negative or positive variation defined by
previous sensor state)
• Four increments by rotation
• Sensors are spaced 90°

Figure 34. Demo2, two sensors

To interpret the results, a basic 4-state machine (Figure 35) has been put in place.

Figure 35. Basic 4-state machine

 

&RUUHFWWUDQVLWLRQ
(UURQHRXVWUDQVLWLRQ

 

069

Erroneous transitions are detected with the LcStatus.Errors variable.

DocID027291 Rev 2 47/70


69
Application description - STM32L476RG-NUCLEO AN4636

FW configuration
To enable this demonstration, “LC_SENSOR_DEMO 2” define must be selected in the
“lc_sensor_metering.h” file.
LcConfig and LcConfigSensorX variables, set in “LcSensorConfig ()” function, must be
defined according to application (Sampling rate, DAC refresh, Vcmp, Texcit, Tcapture,
TimeBetweenSensors).
Outputs: based on X4 encoder result, two counters are updated with four increments per
rotation:
• LcStatus.EdgeCountPos: Positive counter
• LcStatus.EdgeCountNeg: Negative counter

Figure 36. Demo2 - USART communication output – Terminal software example

In Figure 36 P stands for Positive counter and N for Negative counter.

4.5.3 LC sensor metering tachometer demonstration with two sensors


This demonstration uses two LC sensors, IO1, IO2 and IO3, and the same configuration of
Demo2. It allows to collect the rotation speed and direction. For a clockwise direction the
rotation per minute (RPM) number is positive, it is negative for anticlockwise rotation.
If the calibration is disabled or in “static” mode, no metal must be present over the LC
sensors during start of the system. In the case of “dynamic” calibration selection, the wheel
must be in rotation.

FW configuration
To enable this demonstration, “LC_SENSOR_DEMO 3” define must be selected in
“lc_sensor_metering.h” file.
LcConfig and LcConfigSensorX variables, set in “LcSensorConfig ()” function, must be
defined according to application (Sampling rate, DAC refresh, Vcmp, Texcit, Tcapture,
TimeBetweenSensors).

Outputs
The rotation per minute value is updated:
• LcStatus.RPM: Rotation per minutes

48/70 DocID027291 Rev 2


AN4636 Application description - STM32L476RG-NUCLEO

Figure 37. Demo3 - USART communication output – Terminal software example

4.5.4 LC sensor metering counting demonstration with four sensors


This demonstration uses four (two by two) LC sensors, IO1, IO2, IO3, IO4 and IO5. It is
possible to know both the rotation and the direction of two wheels. It is the duplication of
Demo2 configuration.
If the calibration is disabled or in “static” mode, no metal must be present over the LC
sensors during start of the system. In the case of “dynamic” calibration selection, the wheel
must be in rotation.
To interpret results, the basic 4-state machine used for Demo2 has been duplicated. Four
counters are updated.

FW configuration
To enable this demonstration, “LC_SENSOR_DEMO 4” define must be selected in
“lc_sensor_metering.h” file.
LcConfig and LcConfigSensorX variables, set in “LcSensorConfig ()” function, must be
defined according to application (Sampling rate, DAC refresh, Vcmp, Texcit, Tcapture,
TimeBetweenSensors).
Outputs: four counters are updated with four increments per rotation
• LcStatus.EdgeCountPos: Wheel 1 positive counter
• LcStatus.EdgeCountNeg: Wheel 1 negative counter
• LcStatus.EdgeCountPos2: Wheel 2 positive counter
• LcStatus.EdgeCountNeg2: Wheel 2 negative counter

Figure 38. Demo4 - USART communication output – Terminal software example

In Figure 38 P1and N1 refer to Wheel 1 (positive and negative counters, respectively), and
P2 and N2 to Wheel 2 (positive and negative counters, respectively).

DocID027291 Rev 2 49/70


69
Application description - STM32L476RG-NUCLEO AN4636

4.6 LC sensor metering Mode Low Power


To perform consumption measurements, it’s necessary to check that application is running
in low power mode:
• LC_SENSOR_LOW_POWER mode (enabled by default), selection is done by SW
• USART communication is disabled (enabled by default), can be switched off with blue
user button (B1) or can be disabled by SW
To measure the average current during the LC sensor metering in low-power mode (a few
µA), an ammeter can be inserted on JP6 between pin 1 (VDD_MCU) and pin 2 (VDD 3.3V).
Special attention must be taken to measure pulsed current (see Section 2.5.2: LC sensor
metering Mode Low Power).

Figure 39. Connections for the measurement of power consumption


+LJKYDOXHHOHFWURO\WLF
FDSDFLWRU •P)


7RDPPHWHU
SRVLWLYHLQSXW

7RDPPHWHU
QHJDWLYHLQSXW

069

50/70 DocID027291 Rev 2


AN4636 Firmware description - STM32L476RG-NUCLEO

5 Firmware description - STM32L476RG-NUCLEO

5.1 STM32L476x peripherals used by the application


This application example uses the following STM32L476x peripherals with the settings
described below.

GPIOs
Some GPIOs are used to control the signals needed for this LC sensor metering example:
• PA5 or PA4 as Vmid generator (DAC output) at VDD / 2 reference voltage (IO1)
• PC5, PB2, PB4 and PC6 are alternatively used as output GPIO to drive the LC sensors
and put in alternate function (positive comparator inputs COMP1 and COMP2) once
the excitation pulse is delivered
• PC5 to drive the LC sensor 1 (IO2)
• PB2 to drive the LC sensor 2 (IO3)
• PB4 to drive the LC sensor 3 (IO4)
• PB6 to drive the LC sensor 4 (IO5)

DAC
DAC_OUT1 and DAC_OUT2 are used to generate
• VDD / 2 reference voltage (Vmid)
• The input threshold voltage needed by the comparator. This reference voltage allows to
provide a preset threshold voltage value near VDD / 2 but with a necessary positive
margin to eliminate noise. It allows to calibrate the threshold value according to
different LC network responses and environment variations.
DAC outputs are configured in Sample and Hold mode and enabled/disabled in
RTC_WakeUp interrupt.

COMP1 and/or COMP2


Comparators are connected to LC sensors. As soon as the excitation pulse has been
delivered, the COMP2 positive input collects analog oscillations referenced to VDD / 2 bias
while its negative input is fed by the DAC threshold voltage. Finally, the LC sensor
oscillations are conditioned and this results in digital pulses delivered on the comparator
output. This signal will be then transmitted to the LPTIM.
COMP1 is enabled only if sensor 1 or sensor 2 are used.
COMP2 is enabled only if sensor 3 or sensor 4 are used.
Comparators are connected to the LC sensor network.

LPTIM1 and/or LPTIM2


LP Timers are configured to count the pulses generated by the LC sensor oscillations and
conditioned by the comparator. The LPTIM internal counter is read before the LC sensor
generates the oscillations. At the end of the oscillations period, the new LPTIM counter
value is subtracted to the previous value to get the number of collected pulses for the
corresponding measurement. This avoids a time consuming LPTIM reset.

DocID027291 Rev 2 51/70


69
Firmware description - STM32L476RG-NUCLEO AN4636

LPTIM1 is enabled only if COMP1 is enabled.


LPTIM2 is enabled only if COMP2 is enabled.

RTC
RTC peripheral is used to wake up the microcontroller at regular intervals once the MCU
has entered STOP mode. The RTC clock is connected to the LSE clock which frequency is
32.768 kHz.
• The WakeUpTimer is used to perform LC measurements. The wake up frequency
corresponds to the LC sensor capture frequency and is set to 500 Hz for this example.
This capture frequency can be increased or decreased depending on the rotating
wheel maximum speed. Modifications on the capture frequency will lead to a change of
the average power consumption.
• Alarm A is used to perform communications with user or others peripherals to interpret
LC sensors results. For this demo, results are send by USART2 communication.
• Alarm B is used to perform periodic calibrations to compensate thermal and voltage
deviations.
• Tamper1 is used to enable or disable Alarm A to save power consumption.

TIM6
TIM6 is configured to generate precise temporizations used for the LC sensor metering
sequence. This timer is configured in OnePulseCounter mode to generate event at the end
of pulse capture time.

Interrupts
To save the maximum time and power consumption in MCU RUN mode, the RTC Wake up
Timer IRQ handler is directly processed inside the interrupt subroutine.
RTC alarms interrupts are managed by alarm event call backs (see Figure 40).
Alarm interrupts have a lower priority compared to Wakeup timer interrupt. Frequency is
application dependent, it can range from several seconds to several hours for user
communications (alarm A) and from several minutes to several hours for periodic calibration
(alarm B).

Figure 40. Interrupts profile

52/70 DocID027291 Rev 2


AN4636 Firmware description - STM32L476RG-NUCLEO

TAMP_STAMP_IRQ is managed by Tamper1 event call back. It allows to enable or disable


AlarmA interrupt (used for communication).
LC measurements still working during communication and calibration phase. So, Alarm A
and Alarm B Execution needs to be performed between two measurements (between two
wakeup interrupts) and it is mandatory to control their execution time and to have a lowest
priority compared to that of Wakeup timer.

5.2 Description of flow-charts


This software demonstration allows the user to manage from one to four sensors
sequentially. Hardware configuration is done in “lc_sensor_metering.h” file by define
instructions.
Two hardware configurations have been implemented:
• “BOARD_CONFIG 1” define, to manage up to four sensors
– VMID on PA4 (DAC_OUT1)
– COMP1 and COMP2 inverting inputs connected to DAC_OUT2
• “BOARD_CONFIG 2” define, to manage up to four sensors
– VMID on PA5 (DAC_OUT2)
– COMP1 and COMP2 inverting inputs connected to DAC_OUT1
Four demonstrations are available:
• LC_SENSOR_DEMO 1: Basic counting demonstration with one sensor
• LC_SENSOR_DEMO 2: Counting demonstration with two sensors – Rotation and
direction
• LC_SENSOR_DEMO 3: Tachometer demonstration with two sensors – Speed and
direction
• LC_SENSOR_DEMO 4: Counting demonstration with two by two sensors – Rotation
and direction
These examples are launched from a “main.c” file. All LC sensor metering functions are in
“lc_sensor_metering.c” file and called by “main.c”.

Initializations
Configuration function “LcSensorConfig ()”:
• Fills all structures required to set LC sensor configuration
Demo function LcSensorDemo ():
• Initializes all peripherals
• Starts counting demonstration
Initialization function “LcSensorInit ()”:
• Allows to set all variables used by application.
StopEntry () function: Called in LOW_POWER mode
• Prepares MCU to enter in STOP mode

DocID027291 Rev 2 53/70


69
Firmware description - STM32L476RG-NUCLEO AN4636

Calibration
Calibration functions:
• LC_Calibration (): First calibration performed at the power up.
• HAL_RTCEx_AlarmBEventCallback (): Periodic calibration function.

Interrupts
• RTC_WKUP_IRQHandler () function to manage LC measurements:
– LC sensors excitation
– Process sensor state
– Execute state machine
– Process periodic calibration if required.
• HAL_RTCEx_Tamper1EventCallback () function to enable and disable AlarmA by user
push button (BLUE)
• HAL_RTC_AlarmAEventCallback () function to communicate with user by USART or
with other peripherals.
• HAL_RTCEx_AlarmBEventCallback (): function to perform periodic calibration.

Files and functions descriptions


Lc_sensor_metering.h

Hardware configurations
• BOARD_CONFIG 1: To manage boards with Vmid on PA4 pin
• BOARD_CONFIG 2: To manage boards with Vmid on PA5 pin

Demonstration selection
• LC_SENSOR_DEMO 1: Basic counting demonstration with one sensor
• LC_SENSOR_DEMO 2: Counting demonstration with two sensors and
rotation/direction detection
• LC_SENSOR_DEMO 3: Tachometer demonstration with two sensors and
speed/direction detection
• LC_SENSOR_DEMO 4: Counting demonstration with two by two sensors
USART2 communication
• USART2_ENABLE 0: Disabled
• USART2_ENABLE 1: Enabled
LC excitation mode selection:
• LC_EXCIT_MODE 0: LC sensor excitation to Vss
• LC_EXCIT_MODE 1: LC sensor excitation to Vdda
This file contains all macros used to manage LC sensor oscillations:
__LC_EXIT (): To do LC excitation (ASM code)
• GPIO in output state
• GPIO in analog state

54/70 DocID027291 Rev 2


AN4636 Firmware description - STM32L476RG-NUCLEO

__LC_WAIT (): To insert a waiting time for peripherals stabilization


• Set TIM6 in single shot
• Decrease HCLK during sleep
• Start TIM6
• Wait For Event (time to stabilize peripherals)
• Go back to full HCLK speed
__LC_MEASURE (): To perform LC measurements
• Set TIM6 in single shot
• Decrease HCLK during sleep
• Disable DAC output Vmid
• Start TIM6
• Wait For Event (time to do measurements)
• Go back to full HCLK speed

DocID027291 Rev 2 55/70


69
Firmware description - STM32L476RG-NUCLEO AN4636

LcSensorConfig () function
This function allows the user to configure the application.
Two structures are available to configure and manage LcSensor application:
1. “LcConfig” to configure application
• Mode: LC_SENSOR_STD (for debug only) or LC_SENSOR_LOW_POWER (default)
• Sampling: Value in Hz (up to 500, default being 100)
• DacVmidRefreshTime: Trefresh value or 0 to disable (default)
• DacVmid (default value is 0x800)
• DacVcmp (default value is 0xC00)
• TimeBetweenSensor (default value is 75)
• FirstCal
– Status: CAL_ENABLED or CAL_DISABLED (default)
– Mode: STATIC or DYNAMIC (default)
– Measures: Minimum measurements number to perform during calibration phase
(default is 50)
– DacVcmpMax: Starting value for Vcmp calibration (default value is 0xE00)
– DacVcmpMin: Stop value for Vcmp calibration (default value is 0x850)
– DacVcmpStep: Step value for Vcmp calibration (default value is 10)
– PulseCount: Pulses number targeted (default is 20), used for STATIC calibration
– PulseCountDeltaMin: Set the difference to guarantee between min and max pulse
count (default is 20), used for DYNAMIC calibration
• PeriodicCal
– Status: CAL_ENABLED or CAL_DISABLED (default)
– Mode: STATIC or DYNAMIC (default)
– CountDrift: Valid periodic calibration values only if the drift does not exceed this
value (default is 5)
2. “LcConfigSensorX” to configure sensors (X=1, 2, 3 or 4)
• Ls: Ls value in H (default value is 470 µH)
• Cs: Cs value in F (default value is 220 pF)
• CountDetectPercent: Detection threshold in percent ex: 0.8 – Not used if dynamic
calibration is enabled
• Texcit: Excitation time, minimum value is 1 (default value is 2)
• Tcapture: Capture time (default value is 19), value updated automatically when
calibration is enabled

LcSensorInit () function
This function allows the user to initialize structures used by application with default values. It
must be called before Wakeup interrupt enabling (called in “LcSensorDemo” and
“StopEntry” functions if low power mode is enabled).
Two structures are used to store results updated at each measurements (sensors status,
counter status, errors …).

56/70 DocID027291 Rev 2


AN4636 Firmware description - STM32L476RG-NUCLEO

1. “LcSensorX” to store individual sensor results


– Status: NO_METAL (0) or METAL (1)
– PreviousStatus: NO_METAL (0) or METAL (1)
2. “LcStatus” to store LC application status
• MeasuresCount: Measurements counter
• EdgeCountPos: Positive edge counter
• EdgeCountNeg: Negative edge counter
• Errors: Error counter
• Rpm: Rotation per minute value
• Rps: Rotation per seconds value
• WakeUpCounter: counter value loaded in RTC WakeUp timer
• Sampling: The real sampling value based on WakeUpCounter value
One structure to store GPIOs state for a fast I/Os modifications during LC sensors
excitation. It allows to minimize instructions number.
• “LcIO” store and modify GPIOs registers
– LcIO.IOx_GPIO_GROUP: Group of I/O used
– LcIO.IOx_OUTPUT_PP: pin in output state in Push Pull
– LcIO.IOx_ANALOG: pin in analog state

LcSensorDemo () function
As soon as this function is fully executed, an RTC interrupt is created to wake up the
microcontroller device at regular intervals. This function is then called once and the
application will later alternate STOP sequences and RUN slots at the frequency rate given
by the RTC wake up parameters. In this example, the microcontroller is woken up 500 times
per second.
GPIOs are initialized and system clock is configured.
RTC, DAC, LPTIM, TIM and COMP peripherals are initialized with the settings described in
Section 5.1: STM32L476x peripherals used by the application.
In this example, USART and RTC alarmA are initialized for periodic communication.
RTC alarmB is initialized if periodic calibration is enabled.
Then, the StopEntry() function is executed to prepare the device to enter STOP mode with
specific settings and the microcontroller placed in an infinite loop waiting for the RTC wake
up interrupt. All processes are indeed performed in interrupt, using sleep on exit mode, thus
nothing to do in main. User will exit the Low Power demonstration applying a reset
sequence (pressing the B2 (RESET) button).

DocID027291 Rev 2 57/70


69
Firmware description - STM32L476RG-NUCLEO AN4636

Figure 41. LcSensorDemo () function flow-chart


/F6HQVRU'HPR

/&B,QLWB*3,2

6\VWHP&ORFNB&RQILJ06,B0

/&B,QLWB57&
/&B,QLWB'$&
/&B,QLWB&203
/&B,QLWB/37,0
/&B,QLWB7,0

+$/B3:5B(QDEOH6(92Q3HQG
+$/B6XVSHQG7LFN

/F6HQVRU,QLW

/FB&DOLEUDWLRQ

/&B,QLWB86$57
/&B,QLWB$ODUP$
SHULRGLFFRPPXQLFDWLRQ

/&B,QLWB$ODUP%
SHULRGLFFDOLEUDWLRQ

6WDUW:DNHXS7LPHU

6WRS(QWU\
069

StopEntry () function
The aim of this function is to prepare the device to enter STOP2 mode with parameters set
to minimize the device power consumption.
All GPIOs are placed in Analog state to minimize power consumption and the associated
clocks are disabled.
SysTick timer is disabled to decrease further dynamic consumption.
Voltage scaling is set to RANGE2 to optimize the power consumption.
Set SEVONPEND bit, this causes WFE to wake up when an interrupt moves from inactive
to pending (to catch TIM6 event).
The feature “Sleep on Exit” is used to force the MCU entering the STOP mode as soon as
the RTC wake up has been serviced and executed. In that case, the StopEntry () function is
executed once and the microcontroller will return in STOP mode after each interrupt.
Lc variables are initialized with LcSensorInit ().
Enter in STOP2 mode and wait for interrupt.

58/70 DocID027291 Rev 2


AN4636 Firmware description - STM32L476RG-NUCLEO

Figure 42. StopEntry () function flow-chart


6WRS(QWU\

(QDEOH*3,2VFORFN

6HWDOO*3,2VWR$QDORJVWDWH

'LVDEOH*3,2VFORFN

'LVDEOH6\V7LFNWLPHU

6HW3RZHUUHJXODWRUUDQJH

(QDEOH6(9RQ3HQG
(QDEOH6OHHSRQ([LW

/F6HQVRU,QLW

(QWHU6723PRGH
069

RTC_WKUP_IRQHandler () interrupt subroutine


The RTC Wake Up IRQ Handler manages the RTC interrupt triggered by the RTC Wake Up
time. In order to save time during the interrupt execution and since the device operates in
RUN mode, the interrupt subroutine is executed in the Low Power demonstration mode
without performing any call back function in the main program.
The interrupt flag is first cleared.
Then COMP2 and DAC peripherals are switched on and a delay is inserted to wait the
peripherals stabilization times before they can be operational.
The excitation pulse is delivered by IO pin placed in GPIO output mode. As soon as the
pulse is applied on the LC network, IO is switched into Analog state and acts as the
non-inverting comparator input.
Application waits for a capture time in SLEEP mode until all the pulses are collected
If more than one sensor is enabled, a waiting time in SLEEP mode is added to let a
stabilization time between the two measurements. Another excitation pulse is delivered on
the next sensor with a new capture time in SLEEP mode until all the pulses are collected.
At the end of measurements, switched off the Vmid reference bias voltage. DAC and
COMP2 are disabled to minimize power consumption. The capture of the LC sensor
oscillations has been performed during this interrupt.

DocID027291 Rev 2 59/70


69
Firmware description - STM32L476RG-NUCLEO AN4636

Figure 43. RTC_WKUP_IRQHandler () subroutine flow-chart for one LC sensor


57&B:.83B,54+DQGOHU

&OHDULQWHUUXSWIODJ
&OHDU6/((3'((3ELW

(QDEOH'$&9PLG

BB/&B:$,7WRZDLW&UHIUHIUHVKIRU9PLGVWDELOL]DWLRQ

(QDEOH&203

(QDEOH'$&

6HTXHQFHWR 6HOHFW&203LQSXW
UHSHDWIRUHDFK
HQDEOHGVHQVRU BB/&B(;&,7WRVWDUWRVFLOODWLRQ

BB/&B0($685(WRSHUIRUPRVFLOODWLRQPHDVXUHPHQWV

'LVDEOH'$&DQG&203

3URFHVVVHQVRUVWDWH

([HFXWHVWDWHPDFKLQH

6HW6/((3'((3ELW
069

LC_calibration () function
This function is executed only if LcConfig.FirstCal.Status variable is set to CAL_ENABLED
(CAL_DISABLED by default).
The aim of this function is to perform a calibration at the power up.
Maximum and minimum pulse counts, capture time and detection threshold are updated
during this calibration according to components and external conditions.
Two examples are available, “STATIC” or “DYNAMIC”
• Static method example
There is no metal in the proximity of LC sensor, so only the maximum pulse count is
used to define the detection threshold count number and capture time for
measurements.
• Dynamic method example
A wheel is in rotation with metal and no metal transitions. The maximum and minimum
pulse counts are used to define the detection threshold count number and capture time
for measurements.

60/70 DocID027291 Rev 2


AN4636 Firmware description - STM32L476RG-NUCLEO

Figure 44. LC_calibration () function STATIC method flow-chart

/&BFDOLEUDWLRQ 67$7,& /&BFDOLEUDWLRQ

0D[LPL]H7FDSWXUH 57&B:.83B,54+DQGOHU

9FPS 9FPS6WDUW

&RXQW0D[ 

/&PHDVXUHPHQW

<HV
&RXQW!&RXQW0D[" &RXQW0D[ &RXQW

1R

1R
0HDVXUHV!"

<HV

<HV
&RXQW0D[”&RXQWWDUJHWHG"

1R

,QFUHPHQW9FPS

7FDSWXUH I &RXQW0D[
1R
9FPS!9FPS6WRS"
&RXQW'HWHFW I &RXQW0D[
<HV

&DOLEUDWLRQHUURU (QG/&BFDOLEUDWLRQ
069

DocID027291 Rev 2 61/70


69
Firmware description - STM32L476RG-NUCLEO AN4636

Figure 45. LC_calibration () function DYNAMIC method flow-chart

/&BFDOLEUDWLRQ '<1$0,& /&BFDOLEUDWLRQ

0D[LPL]H7FDSWXUH 57&B:.83B,54+DQGOHU

9FPS 9FPS6WDUW

&RXQW0D[ 
&RXQW0LQ 

/&PHDVXUHPHQW

<HV
&RXQW!&RXQW0D[" &RXQW0D[ &RXQW

1R

<HV
&RXQW&RXQW0LQ" &RXQW0LQ &RXQW

1R

1R
0HDVXUHV!"

<HV

&RXQW0D[±&RXQW0LQ <HV
”'HOWDBPLQ"

1R

,QFUHPHQW9FPS

7FDSWXUH I &RXQW0D[
1R
9FPS!9FPS6WRS"
&RXQW'HWHFW 
I &RXQW0D[&RXQW0LQ
<HV

&DOLEUDWLRQHUURU (QG/&BFDOLEUDWLRQ

069

HAL_RTCEx_AlarmBEventCallback () - Periodic calibration function


This function is executed only if LcConfig.PeriodicCal.Status variable is set to
CAL_ENABLED (CAL_DISABLED by default).
All calibration operations are managed in Alarm interrupt and must be done between two LC
measurements.
Calibration measurements are performed during standard measurements in WakeUp timer
interrupt handler.

62/70 DocID027291 Rev 2


AN4636 Firmware description - STM32L476RG-NUCLEO

The periodic calibration (Figure 46) is performed in three steps:


1. Calibration initialization, executed in HAL_RTCEx_AlarmBEventCallback()
Capture time is maximized to catch all pulses count and calibration variables are
initialized for each sensor.
– PeriodicCal.SensorXCountMax = 0, with X = 1, 2, 3 or 4
– PeriodicCal.SensorXCountMin = 0xFFFF, with X = 1, 2, 3 or 4
After that, the alarm is rearmed to ensure the time needed (few seconds) to perform
calibration measurements .
2. Calibration measurements, executed in RTC_WKUP_IRQHandler()
These measurements are performed in a routine executed during normal operation in
WakeUp timer interrupt handler.
3. Calibration results analysis, and value update, executed in
HAL_RTCEx_AlarmBEventCallback()
Flowchart depends upon the selected method.

Figure 46. Periodic calibration flow-chart

3HULRGLFFDOLEUDWLRQ +$/B57&([B$ODUP%(YHQW&DOOEDFN

6WHS,QL]LDOL]DWLRQ 57&B:.83B,54+DQGOHU

6WHS0HDVXUHPHQWV

6WHS5HVXOWVDQDO\VLV

(QGRIFDOLEUDWLRQ
069

Figure 47. Periodic calibration interrupt profile

DocID027291 Rev 2 63/70


69
Firmware description - STM32L476RG-NUCLEO AN4636

Figure 48. Periodic calibration initialization

3HULRGLFFDOLEUDWLRQLQLWLDOL]DWLRQ

0D[LPL]H7FDSWXUH

,QLWLDOL]HFDOLEUDWLRQYDULDEOHV

5HDUP$ODUP
069

STATIC method example


To check that calibration results are valid, the following points must be respected:
• No transitions during calibration phase
• Sensor state is no metal
• To eliminate noisy results, a maximum drift is allowed
After having checked the results, the new detection threshold counter and the new capture
time are computed.
After that, the alarm is rearmed for the next periodic calibration.

Figure 49. Results of analysis in STATIC mode

5HVXOWVRIDQDO\VLV67$7,&PRGH

7UDQVLWLRQV " 1R
6WDWH 12B0(7$/"

<HV

1R
5HVXOWVPD[GULIW"

<HV

&RXQW0D[ &DOLEUDWLRQ&RXQW0D[

&RXQW'HWHFW I &RXQW0D[

7FDSWXUH I &RXQW0D[

5HDUP$ODUP
069

64/70 DocID027291 Rev 2


AN4636 Firmware description - STM32L476RG-NUCLEO

DYNAMIC method example


To check that calibration results are valid, the following point must be respected:
• Transitions number must be non null to catch metal and no metal states (a minimum of
two rotations with four transitions)
• To eliminate noisy results, a maximum drift is allowed
After results validation, new detection threshold counter and new capture time are
computed.
After that, the alarm is rearmed for the next periodic calibration.

Figure 50. Results of analysis in DYNAMIC mode

5HVXOWVRIDQDO\VLV'<1$0,&PRGH

1R
7UDQVLWLRQV!"

<HV

1R
5HVXOWVPD[GULIW"

<HV

&RXQW0D[ &DOLEUDWLRQ&RXQW0D[
&RXQW0LQ &DOLEUDWLRQ&RXQW0LQ

&RXQW'HWHFW I &RXQW0D[&RXQW0LQ

7FDSWXUH I &RXQW0D[

5HDUP$ODUP
069

DocID027291 Rev 2 65/70


69
Power consumption AN4636

6 Power consumption

As shown by Figure 51 and Figure 52 the power consumption depends upon the
application, the main parameters to consider being the number of sensors, the inductance
and capacitor values, and the sampling rate.

Figure 51. STM32L073Z - One sensor - IDD (average) vs. Sampling rate (VDD = 3.3 V)

Figure 52. STM32L476RG and STM32L433RC - One or two sensors


IDD (average) vs. Sampling rate (VDD = 3.3 V)

66/70 DocID027291 Rev 2


AN4636 Power consumption

For the STM32L4 demonstration, the power consumption is higher for low sampling rates
due to the DAC Vmid refresh time. Indeed, Vmid drop increases with low frequencies and
must be compensated by a power consuming refresh time, see DAC Vmid refresh time
(Trefresh).
For the demonstration with Cref to 470 nF, a refresh time must be added for sampling rates
below 100 Hz (two sensors). If the application requests such sampling rates it is worth trying
with 100 Hz anyway, to save power consumption.

DocID027291 Rev 2 67/70


69
Conclusion AN4636

7 Conclusion

Digital flow meters are gradually replacing gas or water meter systems, using mechanical
switches and obsolete technologies. They are more accurate and bring much more flexibility
and security.
The demonstration examples based on the STM32L073Z-EVAL and on the
STM32L476RG-NUCLEO evaluation boards show reliable approach of the LC sensor
metering feature, and indicate possible further developments, based on these principles.
This because they describe the design of a 3-sensor LC metering system that can be used
in gas or water meter applications.
This LC sensor metering demonstration uses some of the microcontroller embedded
peripherals and also highlights how they can be configured to operate in low power mode to
reach a minimum power consumption. This is a key factor for battery-powered gas or water
meter applications.
The methodology described in this application note can be easily reused to target other
developments, which can specifically fulfill other user needs.

68/70 DocID027291 Rev 2


AN4636 Revision history

8 Revision history

Table 3. Document revision history


Date Revision Changes

09-Apr-2015 1 Initial release.


Introduced STM32L476RG-NUCLEO board and X-CUBE-LCSENSOR
firmware, hence updated document title and Introduction, and added
Section 4: Application description - STM32L476RG-NUCLEO,
Section 5: Firmware description - STM32L476RG-NUCLEO, and their
subsections.
26-Sep-2017 2
Added Section 1: LC sensor metering principle and Section 6: Power
consumption.
Updated Definitions, Section 2: Application description - STM32L073Z-
EVAL, Section 3: Firmware description - STM32L073Z-EVAL and
Section 7: Conclusion.

DocID027291 Rev 2 69/70


69
AN4636

IMPORTANT NOTICE – PLEASE READ CAREFULLY

STMicroelectronics NV and its subsidiaries (“ST”) reserve the right to make changes, corrections, enhancements, modifications, and
improvements to ST products and/or to this document at any time without notice. Purchasers should obtain the latest relevant information on
ST products before placing orders. ST products are sold pursuant to ST’s terms and conditions of sale in place at the time of order
acknowledgement.

Purchasers are solely responsible for the choice, selection, and use of ST products and ST assumes no liability for application assistance or
the design of Purchasers’ products.

No license, express or implied, to any intellectual property right is granted by ST herein.

Resale of ST products with provisions different from the information set forth herein shall void any warranty granted by ST for such product.

ST and the ST logo are trademarks of ST. All other product or service names are the property of their respective owners.

Information in this document supersedes and replaces information previously supplied in any prior versions of this document.

© 2017 STMicroelectronics – All rights reserved

70/70 DocID027291 Rev 2

You might also like