Elektor 09 10 2023
Elektor 09 10 2023
95
*
1
*
IN
CE 196
Raspberry Pi Pico
as Spectrum
Analyzer
FFTs on a Low-Cost
Hardware Basis
FOCUS ON
Wireless &
Communication
Is Cellular the
Lowest-Power
Option for IoT?
DIY SDR Time LTE-M and NB-IoT Energy
Signal Receiver Requirements in LPWAN
Deployments
In Touch with Time
LoRa — A Swiss
Army Knife
The LoRa Protocol
and Its Advantages
+ F
5V POWER SUPPLY
N
̱
230VAC
TOROID
Motor Driver Breakout Board Cloud-Based Energy Meter ±40 V Linear Voltage
5 A DC Motor Driver at p. 56 With ESP32 and PZEM-004T p. 102 Regulator Power for the p. 18
Just 3×3 mm Voltage/Current Sensor Fortissimo ... and Others!
COLOPHON EDITORIAL
Jens Nickel
Volume 49, No. 524 International Editor-in-Chief, Elektor Magazine
September & October 2023
ISSN 1757-0875
Distribution
IPS Group, Carl-Zeiss-Straße 5 The Team
53340 Meckenheim, Germany
International Editor-in-Chief: Jens Nickel | Content Director: C. J. Abate | International Editorial
Phone: +49 2225 88010
Staff: Asma Adhimi, Roberto Armani, Eric Bogers, Jan Buiting, Stuart Cording, Rolf Gerstendorf (RG),
Ton Giesberts, Hedwig Hennekens, Saad Imtiaz, Alina Neacsu, Dr. Thomas Scherer,
PEFC Certified
Clemens Valens, Brian Tristam Williams | Regular Contributors: David Ashton, Tam Hanna,
This product is from Ilse Joostens, Prof. Dr. Martin Ossmann, Alfred Rosenkränzer | Graphic Design & Prepress:
sustainably managed
forests and controlled
sources Harmen Heida, Sylvia Sopamena, Patrick Wielders | Publisher: Erik Jansen | Technical questions:
PEFC/30-31-151 www.pefc.org [email protected]
Raspberry Pi Pico
as Spectrum Analyzer
FFTs on a Low-Cost Hardware Basis
Regulars Features
3 Colophon FOCUS
36 LoRa, a Swiss Army Knife — Part 1
FOCUS
The LoRa Protocol and Its Advantages
30 €5,000 up for grabs!
Join the STM32 Wireless Innovation Design Contest 50 Two New Arduino UNO R4 Boards
Minima and WiFi
33 2023: An AI Odyssey
Getting Started with ChatGPT’s Code Interpreter FOCUS
78 YARD Stick One
53 Developer’s Zone
A Sub-1 GHz Wireless Test Tool
Logarithmic Potentiometers
112 A Bare-Metal Programming Guide — Part 2
62 From Life’s Experience
Accurate Timing, the UART, and Debugging
Hazardous Electronics
81 Peculiar Parts
Industry
Latching Relays
92 Ethics in Action
Due Diligence Directive
FOCUS
94 Starting Out in Electronics… 64 Is Cellular the Lowest-Power Option for IoT?
Voltage Amplification LTE-M and NB-IoT Energy Requirements for LPWAN
FOCUS
LoRa, a Swiss Army Knife (1) 76 Matter Adoption
The LoRa Protocol and What Does It Take to Deploy Matter Devices?
Its Advantages
36
4 September & October 2023 www.elektormagazine.com
MCU Wireless Two New Arduino
Communication UNO R4 Boards
Made Flexible Minima and WiFi
EEPROM Opens Networking
Prospects for Wireless MCUs
24 50
FOCUS ON
Wireless &
Communication
lektor September & October 2023 5
PROJECT
Raspberry Pi Pico
as Spectrum Analyzer
FFTs on a Low-Cost Hardware Basis
of 500 kS/s is very well suited for 500 kS/s and PC Connection
audio measurements. With an For initial experiments, the Raspberry Pi Pico is wired as shown
external ADC, even 50 MS/s can in Figure 1. R2 and R3 raise the ADC zero point to half the level
range. C1 removes DC voltage components from the input signal.
be achieved! The input used, ADC2, uses Pin 34 together with GPIO28. T1 is
used together with R1 to establish a TTL level for data output to
the PC via the serial interface at 115,200 baud. Since the circuitry
is quite simple, it can be easily implemented on a breadboard, as
shown in Figure 2.
+5V
The ADC initially operates with the default sampling rate of 500 kHz.
R1 It transfers its 12-bit samples to a FIFO unit, from where they enter
K1
1
a buffer that can store N values. N typically has a value of 1,024.
2k2
6
2 Whenever the buffer is full, the values are sent serially to the PC.
7 BS170 +5V
D Raspberry Pi PICO
DFT and FFT
3 T1
8 G 1 USB 40
GP0 VBUS
4
S
2
GP1 VSYS
39 The spectrum is calculated using discrete Fourier transform (DFT).
This algorithm takes N samples sn (with n = 0 to N-1) of the input
9 3 38
GND LED GND
5 4 37
GP3 3V3_OUT R3
RS232 Out transformation rule applied is the following:
6 35 In
GP4 ADC_VREF 10k C1
115200 Bd 7 34
GP5 GP28
8 33
GND GND 10k 10µ
9 32
GP6 GP27 R2
10 31
GP7 GP26
11 30
GP8 RUN
12 29
GP9 GP22
13 28
The DFT consists of N complex numbers. If the input signal is real,
GND GND
14 27
GP10 GP21
15
16
GP11 GP20
26
25
as in this case, the resulting DFT is symmetrical and the follow-
17
GP12
GP13
GP19
GP18
24 ing applies:
18 23
GND GND
19 22
GP14 GP17
SWCLK
SWDIO
20 21
GND
GP15 GP16
230078-004
N DFT in s FFT in s
256 0.590 0.008
1,024 9.437 0.041
4,096 150.995 0.197
16,384 2,415.919 0.918
with the prefactors u and v. It is also possible to calculate the RMS value of the spectral values.
We then get:
If the input signal is composed of several oscillations
sn = cos(2 π m n / N) with different frequencies m, this results and
in exactly the individual oscillations in the spectrum. A signal
sn = A cos(2 π m n / N) with amplitude A results in a value Zm = A N / 2
in the spectrum. This value depends on the number of samples. Interestingly, the following now applies:
To eliminate this, the DFT is scaled by a factor of 2 / N. The new
spectrum then has the values Wk = 2 Zk / N. A cosine signal with or
amplitude A then results in a spectrum value of exactly A. The
amplitude value A is the peak value of the cosine signal. For the This means that the RMS value can also be calculated in the
effective value, it must be divided by √2. frequency domain instead of the time domain. For this, only the
prefactor has to be considered. This relation is also called Parse-
Computing Time val’s identity [1]. The energy in the time domain is thus accurately
The computing time of the DFT grows quadratically with the reflected by the sum of the energies of the individual oscillations in
number N of samples. It can therefore take quite a long time with the frequency domain. Energy or power ratios are often expressed
a larger N. Measurements with the Raspberry Pi Pico led to the in dB in communications engineering. For the power ratio v = P1 / P0,
approximation TDFT ≈ 9 N2 µs. If N is a power of two, you can use the we get vdB = 10 log10(P1 / P0). For absolute levels, the reference level
Figure 6: The signal multiplied by the window function has a continuous double windowFun(int k) {
curve at the edges. double alpha=0.16;
double a0=(1-alpha)/2;
double a1=0.5;
double a2=alpha/2;
return a0-a1*cos(2*PI*k/(N-1))+a2*cos(4*PI*k/(N-1));
}
float getWindowFactor() {
float mean=0; Figure 8: The “normal” DCF77 spectrum (white) and its averaged spectrum
for (k=0; k < N ; k++) { (green).
mean += abs(windowFun(k));
}
return mean/N ;
}
Analyzer Options
The spectrum analyzer offers several configurable options. In the
most simple case, the µC samples the signal, calculates the spectrum,
outputs it and repeats this endlessly. Sample rate fs is equal to the Figure 9: Spectrum of DCF49 (EFR at 129.1 kHz) with MAXHOLD function.
sampling frequency. At the same time, it defines the frequency
range of the spectrum because in principle this ranges from 0 to
fs / 2. Thus, at 500 kS/s, we can analyze frequency components up
to 250 kHz. Signal length N determines how many samples are used
for the spectrum, and thus defines the resolution of the FFT. Two
adjacent spectral lines (called bins) have the distance Δ = fs / N. At
500 kS/s and N = 1024, the resolution is Δ = 500 kHz / 1024 ≈ 488 Hz.
That’s sufficient to resolve broadcast RF signals.
C3 OPA305a
C1 OPA305a 2 7
OUT
2 7 120p 6
R3 R4 IC2
120p 6 3
IN R1 R2 IC1 4k7 4k7
3 4
4k7 4k7
4 C4
C2
120p
120p –2V5
230078-015
–2V5
Figure 11: Sub-sampling of a 225 kHz square wave signal with fs = 500 kHz. Figure 12: Anti-aliasing filter using two 2nd-order Sallen-Key filters with a
A number of spectral lines show up at fk = 225 kHz * k with k = 1, 2, 3… cut-off frequency of 280 kHz.
Sampling Theorem You can clearly see in the spectrum of the filtered signal shown in
According to the sampling theorem, the signals to be analyzed may Figure 13 that the harmonics are heavily attenuated and that only
only contain frequencies up to a maximum of half the sampling rate. the 225 kHz fundamental wave stands out clearly above -40 dBm.
Either this is respected, or an appropriate low-pass filter is added However, our filter already attenuates quite heavily at 225 kHz. A
before the ADC. Up to this point, no suitable filter has been suggested, filter with steeper edges would therefore be more ideal.
since this always depends on the specific application. Furthermore,
it is also interesting to study the conditions when analyzing higher Noise and ENOB
frequencies. If we sample signals with infinitely short (Dirac) pulses, So far, only signals composed of individual sinusoidal oscilla-
we get a periodic spectrum with period width = sampling rate. The tions of different frequencies and amplitudes have been inves-
spectral lines contained in the signal are thus periodically repeated tigated. In practice, however, there are also noise signals with
with the width fs. Accordingly, frequencies larger than fs also appear different bandwidths. Their treatment in terms of communica-
in the spectrum. They are “folded” down into the fundamental inter- tions engineering is not exactly trivial, which is why only simple
val, so to speak. If the sampling distance is longer, higher frequencies cases are described. As an example, noise values nk with an ampli-
are attenuated more strongly. The relationships are illustrated in the tude of A are generated for binary noise with a noise frequency fn.
following example: Sampling rate fs is 500 kHz. A square wave signal In each case, a die is rolled to determine whether sk = +A or sk = -A
with a frequency of 225 kHz and a duty cycle of 10% is analyzed. should apply for the next value. Initially, fn = 1 MHz applies, so that
the values are generated faster than the ADC can sample them.
In the spectrum in Figure 11, the fundamental wave at 225 kHz Thus, the samples are independent of one another and the value
appears farthest to the right and has the highest level. The first is ±A in each case. Consequently, the noise signal is almost “white,”
harmonic (k = 2) has the frequency 2 * 225 kHz = 450 kHz, which is which means that all frequencies occur equally in its spectrum. The
already beyond fs / 2. Due to the symmetry, it therefore appears at signal is generated by software on the Raspberry Pi Pico. To enable
f = 500 kHz - 450 kHz = 50 kHz in the spectrum below the dotted this task to run in parallel with the spectrum analyzer software, it
vertical line labeled “2” with a still-considerable amplitude. The uses the second core of the RP2040 CPU. It is implemented using
frequency for q is equal to 225 kHz * 9 = 2025 kHz. Since this is a PIO state machine, which allows up to 125 Mb/s to be generated.
equivalent to 4 * 500 kHz + 25 kHz, this peak at 25 kHz appears on
the far-left of the spectrum under the cursor line labeled “9.” The As a rule, the RMS value of the noise voltage is commonly used.
cursor line indices k = 1...9 represent the theoretically expected Since the signal is not periodic, we cannot formally use the formula
positions of the harmonics of the analyzed signal with frequencies for RMS. However, for large numbers of samples M, the RMS value
of k * 225 kHz, known as “alias frequencies.” Although the frequen- can be approximated with:
cies go up to over 2 MHz, ten peaks appear in the window extend-
ing up to 250 kHz. This means that the ADC can certainly handle
higher frequencies than fs / 2. This effect is used in what is known
as undersampling. Before sampling, the signal can be filtered by
a bandpass filter with a passband of fs / 2 in such a way that only For binary noise, the RMS value can thus be calculated easily
the relevant areas of the spectrum are captured. For this purpose,
a fast sample-and-hold function would be added to the setup in
order to still be able to process the high frequencies with the ADC.
If this effect interfered, however, the signal would be filtered with
a low-pass filter (antialiasing filter) to suppress higher-frequency
signal components before sampling.
Antialiasing Filter
The effect of an antialiasing low-pass is demonstrated below. Here,
a symmetrical square wave signal with 225 kHz and a duty cycle
of 50% is filtered through the low-pass filter shown in Figure 12
before the ADC. The filter was simulated with LTspice [3] and built
with op-amps of the type OPA2350. Figure 13: Spectrum of the square wave signal after antialiasing.
In the next example, the bit rate of the noise source is reduced
to fn = 25 kHz. Therefore, 20 successive samples are always equal,
which is equivalent to a kind of low-pass filtering. The resultant
spectrum is shown in Figure 16.
1M
K1 5
C3 R8
3 JP1 7
1k R5 IC1B
1 6
BNC 10µ IC1A 47k
C4 2
R6 R4
4k7 47k
Raspberry Pi PICO
R1 +5V
1 USB 40
GP0 VBUS 33Ω
2 39
GP1 VSYS
3 38
GND LED GND
4 37
GP2 3V3_EN
5 36
BOOTSEL
GP3 3V3_OUT
6 35
GP4 ADC_VREF
7 34
GP5 GP28
8 33
GND GND R2
9 32
GP6 GP27
10k
+5V 10 31
GP7 GP26
11 30
GP8 RUN +1V6
12 29
GP9 GP22
IC1 15 26
GP11 GP20
4 100µ 16 25 10µ
GP12 GP19
17 24
GP13 GP18
18 23
GND GND
19 22
GP14 GP17
is not activated, in this case (division by 1). The ADC is operated in
SWCLK
SWDIO
20 21
GND
GP15 GP16
230078-021
free-running mode, in which it continuously acquires and outputs
values. The timing is generated by an ADC counter which is
Figure 18: Preamplifier with an input resistance of 1 MΩ. For IC1, alternative triggered by the ADC clock. The ADC counter overflows at the
op-amps AD823 or MCP602 may be used. value ADCclkDiv and then retriggers the ADC. Since a conversion
requires 96 clock pulses, ADCclkDiv ≥ 96 must be fulfilled. At the
interesting. We can clearly see from the averaged spectrum (green) smallest value of ADCclkDiv = 96, we get the highest sample rate
that this is about -65 dBm. With the formula given above, we can of fs = 48 MHz / 96 = 500 kHz. The ADC counter is a fractional 16.8
convert the level into the effective noise voltage of about 2 mVRMS counter: The integer part is 16 bits wide and you can fraction-
(approx. 5 mVSS). The resolution of the ADC is 3.3 V / 4096 = 0.8 mV. ally divide by 8 bits to produce even uncommon sampling
The noise thus covers about six quantization levels. More than 2 bits rates as accurately as possible. The slowest sampling rate is fs
are thus lost due to the noise. Nevertheless, spectral peaks with = 48 MHz / 65,536 = 732 Hz.
-55 dBm still stand out well from the noise. The dynamic range is
therefore at least 14 dBm - (-55 dBm) = 69 dB - a factor of ≈2800. The In the next experiment, the ADC is operated far outside its specifi-
actual resolution or the ENOB (effective number of bits) of the ADC cation for a sampling rate of 1 MHz. For this, the ADC clock must be
reaches more than 11 thanks to averaging, which is not bad at all. By 96 MHz. The USB PLL clock with its 48 MHz is not sufficient. The
the way, the noise experiments were done without windowing so ADC is therefore clocked by the PLL for the system clock SYS-PLL.
that the levels are kept exactly and Parseval’s identity is applicable. The clock rate generated for the processor is normally 125 MHz.
However, if it is set to 96 MHz, it can be used to clock the ADC directly
Preamplifier with 1 MΩ Input and enable a sample rate of 1 MHz. Unfortunately, the processor then
Oscilloscopes usually have an input resistance of 1 MΩ. This means runs about 23% slower. This is not a problem, however, because the
that they normally do not put a significant load on the measure- CPU is not used to capacity by the software anyway.
ment objects and allow the usual 1:1 and 10:1 probes to be used.
This convenience should also be offered by a spectrum analyzer, A 400 kHz sinusoidal signal with an amplitude of 2 VSS is used
which is why the preamplifier shown in Figure 18 was designed. as the test signal. Figure 20 shows the resulting spectrum.
The useful signal is shown with the correct level at the correct
Opamp IC1A acts as an impedance converter. The input impedance position. However, the first harmonic at 800 kHz is folded down
is determined by R7. IC1B acts as a preamplifier with a gain of 1 or 10 to 1 MHz - 800 kHz = 200 kHz. The noise level of -65 dBm is not
selectable via JP1. IC1A must have a low bias current, otherwise this worse than at a sampling rate of 500 kHz. So, there seem to be no
current at R7 would cause too large a voltage drop, thus moving the serious objections against clocking the ADC at 96 MHz.
zero line of the signal away from the center of the ADC acquisition
range. For example, the AD8042 type with its bias current IB = 1.2 µA LCD
would result in an offset shift of 1.2 µA * 1 MΩ = 1.2 V. Suitable opamp Since fine details are often of interest in spectra, the MAR3502
types are shown in Figure 18. With C4, an adaptation to a probe can Arduino Shield was chosen thanks to its relatively high resolution
be realized, if necessary. Figure 19 shows the prototype built on a of 320×480 pixels. It is connected in parallel to the Pico board as
breadboard together with the Pico board and display. shown in Figure 21. This allows a spectrum analyzer to be set up
as a stand-alone device - but the controls are still missing.
ADC Clock and Sampling Rate
According to the data sheet, the ADC clock must be 48 MHz. This Figure 20 shows the spectrum of an FM multiplex audio signal
clock is normally generated by the USB PLL. The 16-bit prescaler on the display. You can clearly see the mono signal (L+R) in the
BOOTSEL
GP3 3V3_OUT
6 35
GP4 ADC_VREF
7 34
GP5 GP28
8 33
GND GND
9 32
GP6 GP27
10 31
GP7 GP26
11 30
GP8 RUN
12 29
GP9 GP22
13 28
GND GND
14 27
Figure 20: Spectrum of a 400 kHz sinusoidal signal at a sampling rate of 15
GP10 GP21
26
GP11 GP20
1 MHz. 16
GP12 GP19
25
17 24
GP13 GP18
18 23
GND GND
19 22
GP14 GP17
SWCLK
SWDIO
20 21
range at 17 kHz. At 19 kHz, the spectral line of the stereo pilot tone
GND
GP15 GP16
SD_D0
SD_SCK
D2
D3
D4
D5
D6
D7
D0
D1
SD_SS
SD_DI
12-Bit, 50 MS/s ADC 3.5" TFT LCD Shield
For lower frequencies, the 500 kHz sampling rate of the ADC built SD
into the RP2040 is sufficient, but there are also interesting spectra
+3V3
GND
RST
+5V
WR
RD
CS
RS
in the RF range. For this purpose, the Pico board can be extended J3 J4
with a fast, external ADC using the ADS807E chip. With this 12-bit 1 2 3 4 5 6 7 8
2k2
1
During the first experiments with it, the data 6
K1 +5V +3V3
former frontend.
+5V +3V3
Raspberry Pi PICO
By the way: If the ADS807 is too expen- +5V
C4 C5 C6
1 USB 40
sive, or you don’t need its 12 bits, you can 100n 100n 100n 2
GP0
GP1
VBUS
VSYS
39 C1
sampling routine.
–IN –IN IC1 BIT10 GP5 GP28
6 23 10 8 33
CM CM BIT9 GND GND
7 22 9 9 32
REFT REFT +3.0V BIT8 GP6 GP27
8 21 8 10 31
Fast Sampling via PIO, FIFO, and REFB REFB +2.0V BIT7 GP7 GP26
9 7 11 30
GND BIT6 GP8 RUN
DMA 19 6 12 29
K2 nOE BIT5 GP9 GP22
18 5 13 28
nINT/EXT BIT4 GND GND
The RP2040 CPU is normally clocked at 17
OTR BIT3
4 14
15
GP10 GP21
27
26
16 3
125 MHz. The following listing shows the FSSEL BIT2
BIT1
2 16
GP11
GP12
GP20
GP19
25
SWDIO
C3 C2 20 21
for (k = 0; k < N; k++) {
GND
1 20 26 GP15 GP16
gpio_put(ADCclock,0); 230078-025
gpio_put(ADCclock,1);
} Figure 22: Connection of the external ADC ADS807 to the Pico board.
arrived in the ISR), the ISR value is written to an output FIFO. The
data is quickly written to the memory via DMA (direct memory
access). The actual sampling therefore runs completely autono-
mously. The CPU only has to fetch the values from the buffer after
each DMA transfer.
In principle, the same software used for the ADS807 ADC can be
used for the integrated ADC. Only the sampling routine needs to
be adapted. To achieve the maximum sampling rate of 53 MHz,
for example, you can configure a CPU clock of 106 MHz and set
the PIO prescaler to 1. Now, the PIO program runs at 106 MHz.
Since each sample requires two clocks, the sampling rate is exactly
53 MHz. Unfortunately, the CPU is thus clocked a good 15% slower
Figure 23: Extra Pico board with ADS807 and 50 Ω transformer frontend. than usual. However, this is sufficient to achieve the tasks at hand
without any problems.
According to my measurement, the RP2040 CPU achieves a Figure 24 shows the spectrum of a square wave signal with a duty
maximum of 15 MS/s - still quite a long way from the 53 MS/s of cycle of 10% at a sampling rate of 50 MHz. The harmonics up to
an ADS807. However, the CPU has a peripheral input-output (PIO) 25 MHz are clearly visible. Due to the duty cycle of 10%, every
unit as a special feature, which consists of eight programmable 10th harmonic is missing. Via subsampling, you can still analyze
state machines. These state automata can be controlled with the signal components up to approximately 200 MHz using the ADS807
CPU clock and programmed with simple commands. In the follow- without any problems.
ing, some aspects of the sampling application are highlighted.
The full details are quite complex, so please refer to the RP2040 Analog Front-Ends
documentation [4] for this. Differential inputs +IN and -IN of the ADS807E have a high signal-
to-noise ratio even at higher frequencies. However, the chip is
The PIO program consists of only two commands: somewhat more difficult to drive than ADCs with an unbalanced
input. Possible frontends that can be connected to K2 in Figure 22
.wrap_target are described below. The dynamic range of the ADS807 is 2 VSS,
in pins,12 side 0b0 resulting in a resolution of 2 V / 4096 = 480 µV.
nop side 0b1
.wrap
causes 12 bits to be moved from the ADC into the ISR (input shift 50Ω
R2 2
+5V
each instruction, the side option is used. With this, GPIO pins can 4
+IN
1M
K2
systems. If you want to wind transformer L1 yourself, you should
C5 R6
3
1k
wind the three windings in a trifilar way (i.e. one winding with
1 5
BNC 10µ IC1A
C6 2 7
IC2B
three wires spooled together) to achieve a good coupling even at 6
at frequencies up to 25 MHz.
+5V
R3
K1
1k
1
+2V5 +5V
Front-end 3: 25 MHz Preamplifier with 1 MΩ 2
NC
IC1 = OPA2350
For certain measurements, even a fast spectrum analyzer requires IC2 = AD8042 3 4
+IN
tance of 1 MΩ due to R5. The OPA2350 type is not only fast, but also 100n
IC1
4
IC2
4 100n
C3
100n
has a low bias current and low input noise. IC2A and IC2B serve as 10µ
bipolar drivers for the ADC. Since the unipolar input is converted 230078-030
K2
+5V
L1 R1 R2 K1
1
100Ω
100Ω
+5V
2
NC
4
+IN
5
–IN
6
CM
7
4 x 4.7 mH C2 C1 REFT
Common Mode 8
REFB
10µ 9
100n GND
230078-029
Figure 26: Transformer-coupled 50 Ω frontend. Figure 28: Stand-alone spectrum analyzer based on two Pico boards.
Related Products
> Joy-IT JDS6600 Signal Generator & Frequency Counter
https://elektor.com/18714
WEB LINKS
[1] Parseval’s identity: https://en.wikipedia.org/wiki/Parseval%27s_identity
[2] Web page of this article: https://www.elektormagazine.com/230078-01
[3] LTspice: https://tinyurl.com/3zpwzk4y
[4] RP2040 data sheet: https://tinyurl.com/2sf4uvfm
Concept
The wireless equipment market has grown
unimaginably. Smartphones, cable modems, anti-theft
labels, remote data logging, embedded Bluetooth
devices, wireless internet: radio frequency (RF)
technology has permeated all aspects of everyday life.
or la • Elekt
b
kt
Ele
or
ORIGI
lab
NAL
±40 V Linear
Ele k
ab
rl rl
to
ab
• Ele k to
Voltage Regulator
An Alternative Power Supply for the
Fortissimo-100 Power Amplifier… and Others!
For those who frown upon any shape or form of switched- the SMPS800RE does a good job. Still, there
mode power supply (SMPS) for the high-end Fortissimo-100 may be compelling reasons to favor a linear
regulator built from through-hole components
Power Amplifier, this project yields a 500+ VA, linear, only, like the amplifier itself.
symmetrical voltage regulator marked by low dropout
voltage, high output current, and excellent stability — all For the voltage regulator to work without
dropouts (output voltage dips), the input
obtained from discrete components and built from a kit! voltage of the circuit must exceed the output
voltage by at least 3 V higher, or even more in
case of mains voltage fluctuations. Compared
Bearing in mind that nearly all high-perfor- Design Considerations to most SMPSes (with a wide AC voltage input
mance audio power amplifiers benefit from The Elektor Fortissimo-100 high-end audio range), a linear regulator is less efficient and
a stabilized supply voltage, this linear power power amplifier [1] was proven to work best a large power transformer is called for with a
supply is specifically designed for a symmetri- with a regulated ±40 V power supply, ruling higher power rating than without the linear
cal output voltage of ±40 V and peak currents out a “bare-bones” supply consisting of a regulator.
of 13 A (15 A peak achievable). As an example, transformer, a (bridge) rectifier, and a set of
the average current drawn by a Fortissmo-100 thick reservoir capacitors. A switched-mode Today, most off-the-shelf power (“mains”)
amp driving a 3 Ω load is roughly 4 A per power supply may not quite fit the bill either transformers are marked by standardized
regulator. but this is more a matter of personal taste as secondary voltages. To create ±40 VDC
Figure 1: Schematic of the ±40 V linear voltage regulator, principally, but not exclusively, intended for the Elektor Fortissimo-100 audio power amplifier.
VKA = 2.495 × (1 + R2 / R3) + IREF × R2 The voltage across collector resistor R6 is used The dropout voltage is the sum of the transis-
to drive the output stage. R5 and C3, as well tors’ saturation voltage and the voltage drop
The TL431’s adjust current, IREF, is typically as C4 and C5, form the frequency compen- across the emitter resistors. A lower value for
1.8 µA, so the reference voltage is theoreti- sation to keep the regulator stable, even with the emitter resistors would reduce the dropout
cally 33.95 V. However, this is specified at a SOA (safe operating area) protection T3/R7/ voltage a little, but the currents through the
cathode current of 10 mA, while in the proto- R8/R9 active. Potential divider R16-P1-R17 two transistors can divert too much. At high
type this current is lower and so is the voltage: measures the output voltage and presents collector currents, the transistors’ gain is very
33.55 V was measured in practice. The TL431 the negative feedback for the differential low, and an additional transistor (T4) is needed
is decoupled by C1 while C2 improves the amplifier. To compensate all tolerances, P1’s to buffer the output of the differential stage. To
overall stability. output voltage range is approximately 38.6 V prevent the saturation voltage of T4 increas-
to 41.1 V. With the trim pot wiper at mid-travel, ing the dropout voltage of the output stage,
Differential Amplifier the output voltage will be pretty close to 40 V. its collector is connected to ground through
The differential amplifier is minimalistic, a series connection of resistors.. This limits
consisting of T1 and T2 with R4 as a current Output Stage T4’s power dissipation as well as its heatsink
source. The voltage at the base of T1 is fairly Although there are transistors that can handle requirement. However, there’s a catch in doing
constant. Ditto for the voltage across R3, the maximum output current called for when this: Should — by whatever cause — the input
even with the slightly varying voltage — a constant 50 V input voltage is applied to the voltage fall below the dropout voltage, T4 will
with temperature — across the base-emitter regulator, two transistors, T5/T6, are chosen conduct permanently and the dissipation
junction of T1 and across D1. Schottky diodes to: in its collector resistor will be quite high at
D1 and D2 limit a ( just conceivable) reverse 16 watts at 100 Ω total resistance and 40 V
voltage of T1 and T2’s base-emitter voltages. > limit the power dissipation per device to input voltage applied. This should never occur,
safe levels; though, hence three 5-watt resistors are used
To reduce the influence of the voltage drop > increase the overload range; to prevent a burnout of this collector resistor.
across each diode, while not affecting the > achieve lower dropout voltage and
input offset voltage of the differential pair greater safe operating area. An additional advantage of this collector resis-
too much due to changes in temperature, the tor is its limiting of T5 and T6’s base currents
pair is positioned next to each other on the Implementing these criteria reduces the risk of and thus acting as a simple current limit.
PCB so both diode junctions are at the same damage to the output stage in case there’s an The real protection, though, is formed by T3.
temperature. A few millivolts — or even tens overload condition or even a short circuit. The The output current is measured by voltage
of millivolts — offset also caused by differ- larger PNP power transistors are type TIP36C divider R7/R8 as the voltage drop across the
ences between T1 and T2 have no real effect (cf. the NPN TIP35C in the negative regulator) emitter resistor of T5, and this drives the base
on the much higher 40 V output voltage. and are easily available from several manufac- of T3. When, for instance, the current through
Even an offset change of 30 mV means under turers. PNP transistors are used in the positive R14 is about 7 A, the total output current is
1% variance in the output voltage, which is regulator to keep the minimum voltage drop of 14 A. The highest expected output current is
inconsequential to the operation of the power the output stage as low as possible, the base a little over 12 Apeak with a 3 Ω load on the
amplifier. currents flowing toward ground. amplifier output. T3 will start conducting,
and — due to R9 — even sooner, depending or component list). This superb kit hopefully in drawings and photographs, a few of which
on the voltage across T5. The exact level at defeats readers’ efforts in purchasing parts are shown here as a collage in Figure 2. It
which T3 is forward-biased is temperature-de- (electronic and mechanical) and having PCBs also contains many tips and details on precise
pendent and will be lower as temperature rises made to order. soldering, part positioning, tool handling, and
— an additional protection, and, with music, simple mechanical work required to complete
this won’t be an issue. Along with the kit comes a 12-page Construc- the project’s build.
tion Manual giving step-by-step instructions
D3 protects the output stage in case the input on assembling the project and hopefully Since the proposed regulator isn’t a complete
voltage is suddenly disconnected or short-cir- reaching a perfect result. The manual is rich power supply without the usual circuitry of a
cuited. T5 and T6 are decoupled with a pair of
1000 µF, low-ESR capacitors. LED1 indicates
the presence of the +40 V output voltage.
Although from the photos it appears that D6 is
reverse-fitted on the PCB, in fact, both D6 and
D3 can be fitted either way around and still
function correctly. The HTR20L120CT diode in
its 3-lead TO220 case has two internal diodes
with a common cathode connected to the
device’s center lead.
Resistors
R1, R19 = 4.7 kΩ, 1%, 0.6 W
R2, R21 = 150 kΩ, 1%, 0.6 W
R3, R20 = 12 kΩ, 1%, 0.6 W
R4, R22 = 3.3 kΩ, 5%, 1 W, body size 5×12 mm max.
R5, R23 = 47 Ω, 1%, 0.6 W
R6, R7, R16, R24, R25, R34 = 1 kΩ, 1%, 0.6 W
R8, R26 = 300 Ω, 1%, 0.6 W
R9, R27 = 15 kΩ, 1%, 0.6 W
R10, R28 = 100 Ω, 1%, 0.6 W
R11, R12, R13, R29, R30, R31 = 33 Ω, 5%, 5 W, body diam. 6.4 mm max. (axial, mounted upright)
R14, R15, R32, R33 = 0.1 Ω, 10%, 5 W (body 7.8×25 mm max.)
R17, R35 = 6.8 kΩ, 1%, 0.6 W
R18, R36 = 22 kΩ, 1%, 0.6 W
P1, P2 = 500 Ω, 0.15 W, trimmer, top adjust (Piher PT10LV10-501A2020-S)
Capacitors
C1, C11 = 22 μF, 20%, 63 V, pitch 2.5 mm, diam. 6.3 mm max.
C2, C5, C12, C15 = 10 nF, 10%, 100 V, ceramic X7R , pitch 5 mm
C3, C13 = 15 nF, 5%, 100 V, PET, pitch 5 mm
C4, C14 = 47 nF, 10%, 50 V, ceramic X7R, pitch 5 mm
C6, C7, C16, C17 = 1000 μF, 20%, 50 V, pitch 5 mm, D 12.5 mm, 5000 h @ 105 °C (EEUFC1H102L, Panasonic)
C8, C9, C10, C18, C19, C20 = 100 nF, 10%, 100 V, pitch 5 mm, ceramic X7R
Semiconductors
D1, D2, D4, D5 = SD101A SB00018/D8, DO-35
D3, D6 = HTR20L120CT, TO-220
LED1, LED2 = LED, green, 5 mm (T-1¾)
T1, T2, T9 = BC546B, TO-92
T3, T7, T8 = BC556B, TO-92
T4 = MJE15035, TO-220
T5, T6 = TIP36C, TO-247
T10 = MJE15034, TO-220
T11, T12 = TIP35C, TO-247
IC1, IC2 = TL431BCLPG, TO-92
Miscellaneous
K1, K2, K3, K4, K5, K6 = Faston PCB tab, two pins, hole diam. 1.4 mm, 6.35×0.83 mm
F1, F2 = Fuse clips, 20 A, Littelfuse 01000020Z, for 5×20 mm fuse
F1, F2 = Fuse, Cartridge, fast acting, 15 A , 5×20 mm
HS1, HS2, HS2, HS4 = heatsink MC33271 (for T5/T6/T11/T12), 2.7 °C/W
4× heatsink type FK231SA220, 24 K/W (for T4/T10, two each)
10× M3 washer, plain, steel
6× M3 screw, 10 mm, pan head
6× M3 nut
Related Products
> ±40 V Linear Voltage Regulator Kit
https://elektor.com/20439
Figure 4: Here are the results! Fortissimo-100 output signal frequency while running 1 W into 8 Ω and
powered by ±40 V Linear voltage regulator board no. 220581-1.
WEB LINKS
[1] Fortissimo-100 High-End Amplifier: https://elektormagazine.com/magazine/elektor-280/61057
[2] ±40 V Linear Voltage Regulator kit: https://elektor.com/elektor-40-v-linear-voltage-regulator-kit
[3] ±40 V Linear Voltage Regulator project on Elektor Labs website:
https://elektormagazine.com/labs/linear-voltage-regulator-for-fortissimo-100
MCU Wireless
Communication Made
Flexible
EEPROM Opens Networking Prospects for Wireless MCUs
By Gamal Labib (Egypt) (WPS) feature supported by many APs and routers. WPS allows an
MCU board to join the user’s preferred network at will. However, a
When connecting a microcontroller question arises: Do we have to go through the joining steps of either
to a Wi-Fi network using the ESP8266, the interactive dialog or the WPS every time the MCU board reboots?
The answer is no, as long as we keep the newly specified WLAN
you might want a more flexible settings in non-volatile memory accessible to the MCU. Fortunately,
approach than hard-coded, fixed the ESP8266 has an internal Electrically Erasable Programmable
WLAN credentials. In this article, I Read-Only Memory (EEPROM) that can be manipulated by user
code to store and retrieve data. I have utilized this feature to store
will demonstrate a solution with a set up to 10 WLAN credentials set by either of the aforementioned
of preferred AP networks to choose methods. This approach not only provides networking flexibility
from interactively. Additionally, we but also enables the MCU board to connect to the WLAN with the
best coverage out of the stored 10, if the developer chooses to do so.
can leverage the Wi-Fi Protected Setup
(WPS) feature supported by many APs However, it is important to note that extensive writing to the inter-
and routers. nal EEPROM is not recommended due to the expected lifespan of an
EEPROM being based on the number of write cycles it undergoes.
To work around this restriction and preserve the MCU’s designated
role, I have included an external EEPROM chip into the project
The ESP8266 is a popular microcontroller unit (MCU) module hookup to make it possible for the user to explore doing the same
that supports wireless communication and serves various appli- job with an external EEPROM. However, for our WLAN configura-
cations in the Internet of Things (IoT). The boards based on this tion example here, we do not do extensive writing, so I opted for
module usually have hard-coded Access Point (AP) credentials, using the internal EEPROM.
such as Service Set Identifier (SSID) and passphrase, in their
Arduino sketches. In some cases, developers also specify fixed Hardware
IP settings. However, these hardcoded settings can cause issues The Bill of Materials (BOM) for this project is quite compact. I used
when the wireless local area network (WLAN) topology changes. the WeMos D1 Mini, which is an ESP8266-based board known for
It becomes a headache return to the Arduino IDE or similar devel- its simple handling within the Arduino IDE and its small footprint.
opment environment just to update the sketches on deployed MCU A 0.9" OLED graphic display module with a resolution of 128×64
boards, as the boards need to be recovered or replaced. pixels is used to display informative and debugging messages.
It is connected to the MCU’s I2C bus, along with an external 8 KB
In this article, I will demonstrate a solution that provides flexibil- EEPROM chip. To select from the MCU’s eight modes of operation
ity in joining an MCU board to a WLAN. Instead of hard-coding (see Table 1), I used a combination of three DIP switches, which
a single set of WLAN credentials into project sketches, why not are wired to three of the WeMos’s digital GPIOs (e.g., D5, D6, and
have a set of preferred AP networks to choose from interactively? D7). Since the DIP switches’ connectors are tiny, they don’t fit in the
By establishing an interactive dialog between the user and the breadboard, so I constructed a daughter board to accommodate
MCU board through a touch screen, web page, or similar means, it them. The project’s breadboard implementation and screenshots
becomes possible to specify new WLAN settings for the MCU board of the WeMos in action are shown in Figure 1. The wiring diagram
on the fly. Additionally, we can leverage the Wi-Fi Protected Setup of the project components can be seen in Figure 2.
Figure 2: Project wiring using Fritzing breadboard tools and showing an extra fourth DIP switch for extended networking options.
Note that the ESP8266 module that forms the heart of the WeMos 230268-01
board automatically stores the recent successful networking creden-
tials in the internal EEPROM, so we need to place our housekeeping
structure, depicted in Table 3, elsewhere in the EEPROM so as to About the Author
avoid conflict with the MCU’s other mechanisms. Gamal Labib has been an enthusiast of embedded systems for two
decades and is currently a mentor (at codementor.io). He holds an
Mode 8: Interactive WLAN Setup MEng and a PhD in IT. Besides writing for technical magazines,
In this mode, the WeMos checks the sanity of the credentials in he is a visiting associate professor at Egyptian universities and a
EEPROM first. If the MCU succeeds in connecting to an AP, this certified IT consultant.
mode ends and the loop() function takes over. If not, then the MCU
enters the interactive mode, in which it scans the WLANs in its
vicinity and launches a web server with IP address 192.168.4.1 to Questions or Comments?
display the detected AP SSIDs. The user needs to set their comput- If you have technical questions or comments about this article,
er’s WLAN adapter to the fixed IP settings for the WeMos private feel free to contact the author at [email protected] or the
network, since the WeMos will provide no DHCP service. A webpage Elektor editorial team by email at [email protected].
close to that shown in Figure 8 will show the scan results, and
enable the user to choose the preferred network. The user then
clicks on the Submit Query button to save the WLAN credentials
in EEPROM and establish a connection to the selected WLAN.
Related Products
> WeMos D1 mini Pro – ESP8266 based WiFi Module
https://elektor.com/19185
WEB LINKS
[1] Software download: https://elektormagazine.com/230268-01
[2] Using the EEPROM with the ESP8266: https://aranacorp.com/en/using-the-eeprom-with-the-esp8266
[3] Arduino with an I2C EEPROM: https://playground.arduino.cc/Code/I2CEEPROM
[4] Library for I2C EEPROM: https://github.com/RobTillaart/I2C_EEPROM
Flexibility to adjust
In-process charging
your payload
more details at
www.wheel.me
lektor September & October 2023 29
CONTEST
€5,000
up for grabs!
Join the STM32 Wireless Innovation Design Contest
Figure 2: The
buttons and LEDs, as well as a voltage regulator. An STM32WB5MM-DK
STLINK-V3 debugger/programmer module sits on the Discovery kit features
underside of the board. Although intended for making many sensors and a
small OLED display.
application development for the WBA52CG module easy,
you might be tempted to desolder it and use it as a stand-
alone STLINK-V3 debugger/programmer pod instead.
The NUCLEO-WBA52CG board comes preprogrammed audio data captured with its digital microphone to the
with a demo application that can communicate with the connected app on a smartphone. The app can send audio
ST BLE Sensor app on a smartphone. The app shows data back to the board. When running the demo in full-du-
the status of pushbutton B1, and the app lets you switch plex mode, make sure to keep the phone or tablet at some
on and off an LED on the board. This is nice, of course, distance from the board to avoid audio feedback (a.k.a.
but we are certain that you can do better. The board has the Larsen effect) blowing your eardrums.
many more application possibilities. The MCU’s power-
ful security features allow for sensitive and secure IoT Because the dev kit has so many peripherals, there’s a lot
applications. that you can do with it without having to add anything
else. It is great for IoT and home automation applications,
More information: https://st.com/en/evaluation-tools/ but, with a bit of creativity, you can easily come up with
nucleo-wba52cg.html other exciting use cases.
STM32WB5MM-DK
The STM32WB5MM-DK Discovery kit is a demonstra-
tion and development platform for the STMicroelectron-
ics STM32W5MMG module. This dual-core 32-bit Arm NUCLEO-WL55JC
Cortex-M4/M0+ device integrates an ultra-low-power The NUCLEO-WL55JC board is an evaluation board for
radio compliant with Bluetooth Low Energy (BLE) 5.2, the STM32WL-series of microcontrollers, and, in partic-
802.15.4 with Zigbee, Thread, and proprietary protocols. ular, the STM32WL55. This so-called sub-GHz wireless
microcontroller is based on a dual-core 32-bit ARM
The strangely-shaped board comes with many periph- Cortex-M4/M0+ with a clock frequency of 48 MHz. It
erals, such as an 0.96-inch 128×64 OLED display, a features ultra-low power consumption, an integrated RF
temperature sensor, an accelerometer/gyroscope sensor, transceiver with a 150 MHz to 960 MHz frequency range,
Time-of-Flight (ToF), and gesture-detection sensor. It 256 KB of Flash memory and 64 KB of SRAM.
also has a digital microphone, an RGB LED and an
infrared LED, two user push buttons and a touch key The RF transceiver inside the MCU supports LoRa, (G)
button. For applications that need storage space, there FSK, (G)MSK, and BPSK modulations. Being a fully
is a 128-Mbit Quad-SPI NOR Flash memory chip. An open wireless system-on-chip, it is compatible with
STMod+ and Arduino-compatible expansion connectors standardized as well as proprietary protocols such as
let you connect other devices to the board. LoRaWAN, Sigfox, wM-Bus, and more. The transmitter
has a high-output-power mode, programmable up to
One might think that the STM32 processor sitting in the +22 dBm, and a low-output-power mode, programma-
middle of all these circuits is the board’s main proces- ble up to +15 dBm. In Europe, the uplink transmission
sor, but that’s not the case. It is the integrated ST-LINK/ power is limited to 14 dBm (25 mW), so it is important to
V2-1 that provides embedded in-circuit debugging and check regulations for the area where you are planning
programming facilities and a USB-to-serial bridge. The to use this board.
main MCU is hiding behind the tiny metal can on the
board’s top-left corner. The board the MCU is mounted on is equipped with
extension headers (Arduino and ST morpho compatible),
The STM32WB5MM-DK Discovery kit comes prepro- configuration jumpers, pushbuttons, and LEDs, and a
grammed with a Bluetooth audio application. It sends voltage regulator. There is also an on-board STLINK-V3
!
Innovate to win
€5,000 in prizes!
Libraries and Development Toolchains
All STM32 products are supported by the STM32Cube platform. STM32Cube
is ST’s original initiative to simplify and ease the life of the developer by
reducing development effort, time, and cost. It provides developers with a
How to Participate?
hardware abstraction layer (HAL) and the low-layer (LL) APIs, a consistent To inspire and incentivize participants,
set of middleware components, and many application examples that can be STMicroelectronics is offering the following
easily reused for custom application development. prizes:
The stm32duino boards package for the Arduino IDE supports the STM32WB-
elektormagazine.com/st-contest
5MM-DK board. It also knows about the WL55JC, but without LoRa support.
The WBA52CG board is not (yet) supported.
https://github.com/stm32duino
Both the STM32WB5MM-DK and WL55JC boards are also compatible with
ARM’s mbed OS, so that is another avenue to explore.
https://os.mbed.com/platforms/DISCO-WB5MMG/
https://os.mbed.com/platforms/ST-Nucleo-WL55JC/
2023:
An AI Odyssey
Getting Started with ChatGPT’s Code Interpreter
Close the dialog, and start a New chat. At the top of the chat window,
you’ll be given the option of selecting between GPT-3.5 and GPT-4. Figure 3: Getting to
The latter has a drop-down menu, which will allow you to select Code Interpreter in
between the Default mode, Code Interpreter, and other plugins. GPT-4.
Click on Code Interpreter (Figure 3).
Trying It Out
Besides being a Python run-time environment, Code Interpreter
is capable of parsing and analyzing a wide variety of files, from
PDFs, to Excel spreadsheets, to comma-separated values (CSV).
With so many use cases, we’re overwhelmed for choice, but one such
toe-wetting experiment I did was to analyze a complete Elektor book
that I edited last year. These are the basic steps I followed, which
you can use to get started finding insights from your own data:
Upload its PDF by clicking on the “plus” sign to the left of the input
field (Figure 4), navigating to the file and select it for uploading.
The book I used, Develop Your Own Bluetooth Low Energy Applica-
tions for Raspberry Pi, ESP32, and nRF52 with Python, Arduino, and
Zephyr, by Koen Vervloesem (see the Related Products box), is a Figure 4: Click on the “plus” sign to the left of the
41-megabyte file consisting of 258 pages, so I expected to encoun- input field to upload your document.
ter challenges from ChatGPT.
First, I uploaded the file in its entirety, and asked ChatGPT to tell
me about it (Figure 5). The rest of the chat between me (BTW) and GPT: Sure, let’s try the PDFMiner library instead of PyPDF2. The
Code Interpreter (GPT) is too verbose to reprint here, but here’s a first 2,000 characters tell me the book is about.
summary and some takeaways: BTW: Read the entire book, not just the first 2,000 characters.
GPT, trying to get out of work, just like a human: This will be
BTW: Tell me about this book. difficult and resource-intensive. Let me tell you more basics about
GPT: It has 258 pages and its basic metadata tells me it’s about the book.
BLE. Must I look inside and tell you more? BTW: Read the entire book — I need to ask specific questions.
BTW: Yes, please. GPT: Fine.
GPT: Error! The way I’m parsing this in Python is not working.
Read the book’s table of contents yourself. After convincing it to actually look at the full document, there
were still some niggles that the environment had to go through,
When you hit this wall, you may be tempted to give up, but you due to the size and complexity. The code execution environment
can often coax the model into using a workaround. crashed and had to be reset (by ChatGPT automatically), librar-
ies were misplaced (but not by me), and the entire book had to
BTW: Can you use another method to parse the PDF? be uploaded again. Eventually, I was able to glean some insights:
WEB LINKS
[1] OpenAI’s ChatGPT: https://chat.openai.com
[2] OpenAI announces Code Interpreter [Tweet]: https://twitter.com/OpenAI/status/1677015057316872192
[3] OpenAI blog post introducing Code Interpreter: https://openai.com/blog/chatgpt-plugins#code-interpreter
[4] Chat Log: Discussing and Visualizing Discrete Mathematics: https://tinyurl.com/discretegptchat
By Gilles Brocard (France) In essence, LoRa is a radio signal transmission protocol that uses a
“chirped” multi-symbol format to transmit data. LoRa chips operate in
This article describes the the ISM bands and convert radio frequencies into data. For this, they
practical application of the LoRa use LoRa technology, which is a low-level physical layer. We’ll come
back to these terms in a moment.
transmission protocol using Ebyte
modules based on Semtech’s The use of wired modules is a simple solution for low-speed data
LLCC68 transceiver, with simple transmission between two distant points. The Semtech company [3]
owns the LoRa patents, and has developed a whole range of LoRa
resources and a limited budget. transceiver circuits.
This first part presents the LoRa
protocol and its advantages. Ready-to-Use Modules
Currently, the best-performing circuit is the LLCC68, but it’s not easy to
use. First of all, it’s a very small SMD — 4 mm square for 24 pins — and
therefore very difficult to solder. In addition, it needs to be surrounded
by RF components compatible with the gigahertz frequencies, all on a
Today, transmitting and receiving data via radio waves has become so printed circuit board adapted to the constraints of these high frequen-
commonplace that we don’t really pay attention to it. 3G, 4G, and now cies. Chinese company Ebyte, specialized in the RF field, has devel-
5G enable us to transmit and receive information at high speed, but oped a whole family of small modules integrating Semtech’s circuits.
over relatively short distances, mostly a few hundred meters. Wi-Fi and
Bluetooth is even less. But, some fields have different needs. Let’s take The Ebyte range comes in many models. Models E220-900T22D
the example of a farmer who wants to send data to a central collection (Figure 1) and E220-900T30D (Figure 2) contain an LLCC68 with a
system for animal counting, local temperature (frost monitoring) or microcontroller located between the single access, the UART commu-
any other activity requiring the use of measurements supplied by a nication port, and the LLCC68. However, this microcontroller prevents
sensor several kilometers away. To meet these needs, solutions have direct communication with the LLCC68, which considerably limits the
been developed with some interesting innovations. You can find more configuration possibilities of the LLCC68. Figure 3 shows, with the
on LoRa in several Elektor articles, for example in [1] and [2]. shield removed, the LLCC68, the microcontroller (ARM CX32L003),
Figure 1: Ebyte’s E220-900T22D module. Figure 2: The E220-900T30D module Figure 3: The E220-900T22D module without its
incorporates an 8 dB power amplifier, increasing shielding.
transmission power to 30 dBm or 1 W.
125 khz
5.18
2.59
1.428
0.22 0.43 0.79
5 6 7 8 9 10 11 SF
17560
9375
s (bps)
5468
3125
1757
976
537
0 1 2 3 4 5 6 7 8 9 10 d (km)
Figure 6: The influence of the spreading factor (SF, in bold) on transmission speed and range (bottom), and consumption (top).
Time-sharing: With LoRa, transmissions can and must be of short up to 14 dBm (25 mW). In fact, this 14 dBm is the power radiated by
duration and spaced out over time. In this case, the same band can the antenna. But, between the module’s HF output and the antenna,
be used successively by several devices. Although this technique is there are many causes of attenuation, which will reduce the power
prone to collisions, it is widely used in LoRa modulation. One way of reaching the antenna. If you’re lucky enough to still have an excess of
limiting collisions is to monitor the frequency band and only transmit transmit power, and you can measure it, the LoRa module’s settings
when the band is not in use. The LLCC68 makes it easy to automate will enable you to reduce it.
this procedure (see RSSI below).
A Practical Example
Spread-spectrum sharing: This mode is specific to LoRa, which > Emission: 14 dBm power (limited by your settings).
digitizes the message using chirps (frequency deviations) — hence > Transmitting antenna gain: +2.15 dBi (for a standard 86 mm
the name of this modulation (CSS for chirp spread spectrum). The quarter-wave ground plane antenna).
LLCC68 lets you choose between seven spreading codes (spreading > Maximum signal attenuation over a distance of 11 km through
factor — “SF” in the datasheet). The values, from 5 to 11, depend on the air: −111.2 dB (see formula for calculating this rating below;
the bandwidth chosen (Figure 6). The SF is one of the most important negative value indicates attenuation).
parameters in LoRa modulation. In particular, it determines the range, > Receiving antenna gain: +2.15 dBi (for an identical 86 mm
the transmission speed, and the power consumption during transmis- standard ground plane quarter-wave antenna).
sion. Bandwidth (BW) and CR (code rate / coding redundancy) are > Receiver sensitivity (LLCC68 for BW = 125 kHz, SF = 7),
the other two important LoRa parameters. max receive gain: −124 dBm (data sheet, page 19, first line of
Sensitivity LoRa paragraph).
Link Budget > Add −5 dB for losses due to links (cables, connections, etc.) for
The link budget is the difference between the maximum transmit the transmitter module and −5 dB for losses due to the receiver.
power, in this case 30 dBm, and the minimum input level required
to receive and decode a message (sensitivity), in this case, 129 dBm. The link budget can be obtained simply by adding the values in dBm,
It is valid for the most favorable setting with BW = 125 kHz and with dBi, and dB — that’s the whole point of decibels:
the receiver preamplifier activated. The maximum link budget is
therefore 30 + 129 = 159 dBm. European regulations limit transmit 14 + 2.15 − 111.2 + 2.15 − 5 − 5 = −102.9 dBm
power to 14 dBm, which, in our example, produces a link budget of
14 + 129 = 143 dB. This value is well above the threshold of 124 dBm, which is the LoRa
reception threshold for this module (receiver sensitivity). We have
You may be surprised that we’ve chosen a module that can transmit a margin of 21.1 dBm between the two, which should enable us to
at a power of 30 dBm (1 W), whereas European regulations only allow receive a usable signal.
BW BW BW
SF Chirps SNR
125 kHz 250 kHz 500 kHz
5 32 −2.5 yes yes yes
6 64 −5 yes yes yes
In compliance with European regulations, the maximum link budget
7 128 −7.5 yes yes yes of 143 dB with our E220-900M30S in 14 dBm, the calculation gives a
−124 dBm −121 dBm −117 dBm range of 388 km. But let’s stop dreaming, this theoretical distance will
8 256 −10 yes yes yes never be reached in practice. Nevertheless, under the right conditions,
9 512 −12.5 yes yes yes a maximum range of between 10 km and 20 km can be achieved, on
−129 dBm sight and outside urban areas.
10 1024 −15 no yes yes
As an example, in April 2020, a distance of 832 km was reached by a
−129 dBm
LoRa module of performance quite comparable to LLCC68. However,
11 2048 −17.5 no no yes the transmission and reception conditions were highly optimized. In
−127 dBm fact, an antenna was attached to a weather balloon at an altitude of
38 km, and reception was via a LoRaWAN gateway located in the middle
Table 1. The summary of measurements presented on page 19 of a mountainous area, thus rather well isolated from HF interference.
of the LLCC68 data sheet concerning the Spreading Factor.
First column Transmission of a Symbol
The spreading factor SF depends on bandwidth BW. For LoRa modulation can be visualized directly with SDR software and
example, for BW = 125 kHz, SF can have a value between 5 an associated SDR key, as shown in Figure 7.
and 9; for BW = 250 kHz the value 10 can also be used; and for
BW = 500 kHz the value 11.
Third column
The signal-to-noise ratio (SNR) as a function of the SF
parameter value.
Don’t be surprised to see negative SNRs, as the LoRa
demodulator is capable of recovering a signal well below the
RF noise level. For example, at BW = 500 kHz and SF = 11, the
recoverable signal may be 17.5 dB below noise. This means that
the signal can be 56 times weaker than the radio noise level…
Second column
The second column will curb our enthusiasm, as it gives the
transmission coding size required to achieve this performance.
Transmission time is directly proportional to these values,
and so is power consumption. The module’s instantaneous
consumption remains constant; it simply occurs over a longer
period of time.
Fourth, fifth, and sixth columns
For BW = 125 kHz and SF = 7, the LLCC68 is able to extract the
payload from a received signal of -129 dBm (79 nVRMS). This
value is particularly low: The LLCC68 is extremely sensitive for
the analog part and very efficient for the digital part applying
the LoRa protocol!
Scope Evaluation
Disregarding ambient electromagnetic interference, which we can
obviously never achieve in practice, it is possible to calculate a link’s
theoretical maximum distance. The formula for the distance is:
1,024 ms
BW = 500 kHz their value is reduced to 2 µs and 8 µs for 125 kHz.
Sym4
Ts
This is why, with LoRa, the transmission time of a message is inversely
M L proportional to BW and, on the other hand, it doubles for each incre-
J ment of 1 of the value of SF.
K
1,024 ms
Sym3
Ts
This modulation process, borrowed from RADAR technologies, involves
I the transmission of symbols that are a linear frequency deviation of
H a sine wave around a center frequency. These frequency sweeps are
G called CHIRP (compressed high-intensity radiated pulse). For LoRa,
1,024 ms
F
Sym2
Ts
only linearly increasing chirps are used for symbol transmission, such
D E as those between points M and N. Linearly decreasing chirps are only
used at the end of the preamble for synchronization.
C B
1,024 ms
Sym1
The frequency deviation is made in small increments, the resolution of 4. An optional error check (CRC). It checks whether the data received
which depends on the SF value. For SF = 8, 2SF = 28, i.e. 256 intervals; is complete and error-free.
CR = 4/8 CR = 4/(4+n)
Figure 9: The LoRa package consists of four parts, some of which are optional and/or configurable.
Related Products
> Great Scott Gadgets HackRF One Software Defined
Radio (1 MHz to 6 GHz)
https://elektor.com/18306
WEB LINKS
[1] Norbert Schmidt, “LoRa, a Concise Introduction,” Elektor 7/2016: https://elektormagazine.com/magazine/elektor-201607/29115
[2] Mathias Claussen, “LoRa GPS Tracker,” Elektor 11/2020: https://elektormagazine.com/magazine/elektor-159/59110
[3] Semtech: https://semtech.com
CELLULAR
Join our free webinars on:
www.we-online.com/webinars
TECHNOLOGY
Adrastea-I is a Cellular Module with High Performance, Ultra-Low
Power Consumption, Multi-Band LTE-M and NB-IoT Module.
Despite its compact size, the module has integrated GNSS, integrated ARM Cortex
M4 and 1MB Flash reserved for user application development. The module is based
on the high-performance Sony Altair ALT1250 chipset. The Adrastea-I module,
certified by Deutsche Telekom, enables rapid integration into end products without
additional industry-specific certification (GCF) or operator approval. Provided that a
Deutsche Telekom IoT connectivity (SIM card) is used. For all other operators the
module offers the industry-specific certification (GCF) already.
www.we-online.com/gocellular
© eiSmart
Adjustable Current
Sink with Integrated
Clock Generator
Test Power Supplies, Voltage Converters and Batteries
By Roland Stiglmayr (Germany) How do you test your power supplies, DC/DC
converters, or batteries? You probably have
A current sink, also called an electronic a collection of power resistors that you can
load, doesn’t usually come standard use to apply a load to the device under test,
and you measure the current and voltage.
in an electronics lab, even though it Then you perform a series of measurements
offers many benefits for the thorough to determine the static characteristics of
testing of all sorts of power sources. the control loop at different loads and input
voltages. In addition, you can calculate the
Unfortunately, commercial devices internal resistance of the power source from
are fairly expensive, so it’s worthwhile these measurements. This procedure works,
taking your soldering iron and side but it is complicated and time-consuming.
cutters in hand and building your own It would be a lot better and easier to use an
electronic load. adjustable current sink that draws a constant
current regardless of the applied voltage.
However, even with an adjustable current sink,
L a bs.c it’s not possible to capture the dynamic behav-
o r- o
kt ior of a power supply, i.e. how it responds to
m
Ele
.
t o r- L a b s voltage, which can cause malfunctions or even
damage in the equipment connected to them.
Furthermore, power supply control loops are
often instable and tend to generate high-fre-
quency oscillations, particularly with fast load
changes. They have the same negative effects
as overshoots.
R43* C20*
150Ω V++
100n LM317T
JP6 R40* R30
MP_In+ IC1 R1
22k
200Ω
1 JP1
240Ω
R41* 1W R6 R5 R4 R3 R32
X1
3Ω3 2 DVM
2Ω2
2Ω2
2Ω2
2Ω2
10k
C1
In+ R42* 1W
R2
100mV/1A
not placed
In0 100n
3Ω3 C2 C3 1W 1W 1W 1W
F1 3
JP5 R7 R31
100n 200Ω 100n 22k
2A Slow
D T2
D R11 IRLR7843
T1 BstDis C5
IRLR3114ZTRPBF
220Ω
R21 R18
R13 G
G 1k8 47k
10k 1µ 1 JP2
25V
S
S R33 2
220k
Trig
3
V++
D2
R16
LL4448 R23 R26 R19
/Dis
220k
150k
150k
47k
T5 IC5 D4
R12
LM4041CIDBZ 8 4 1 JP4
R17 LL4448
VCC /R
10k
BC857C T7 7 2
R15 DIS /CurDis
1k
1M IC3
6 3
T4 R22 THR OUT 3
R20
180k
BC847C
TLC555CD
BC847C T6 2
150k
R25 TR
22k GND CV
R28
1 5
2k7 BC847C JP3
D1
R29 C6 C11 R24 C12 C13 C15 C14
CkDis
10k
5k6
SJ2*
V++ R10
BC847C
2Ω2
T3
R14
8 7
330k
R8 V+ OSC
1 –1V25
8k2 FC
IC2
R9
2 5
D3 C7 C8 C+ OUT 180Ω
LM2662
R27
LED1 4 (LM2663)
1µ 1µ C–
3k3
LL4448
25V 25V
GND LV IC4
QTLP650D4 3 6
LED2 C9 C10
LM4041CIDBZ Features
330k
SJ1*
QTLP650D4
1µ
25V
1µ
25V
R34
> Input voltage: 3.3 to 30.0 V
220,88-012 > Adjustable current range: 30 to
1900 mA
Figure 2: Schematic diagram of the current sink. > Maximum power dissipation: 18 W
(50 W with booster)
> Clock (switchable): approx. 50 Hz,
design is simple and does not contain any The specifications in the Features box testify 50% duty cycle
exotic components, and it avoids the need to the capabilities of this current sink. > Rise time/fall time: <3 µs
for a separate power supply. Depending on > Reverse polarity protection at input
the heat sinks for the semiconductor devices, How It Works > Overtemperature protection
the current sink can handle a power dissipa- Almost every current source or current sink is > Undervoltage shutdown
tion of up to 18 W (or 50 W with the booster essentially based on a linear circuit that gener- > Trigger signal for oscilloscope
circuit) and is suitable for a maximum input ates a constant voltage. This voltage is loaded > Output for current measurement
voltage of 30 V. Although the maximum with a fixed resistor. In accordance with Ohm’s > Powered from the device under test
power dissipation may not seem so high, the law, a constant voltage over a fixed resistance
ability to clock the current sink also allows a results in a constant current through the resis-
good estimation of the dynamic characteris- tance. If we ignore the internal quiescent
tics of relatively heavy-duty power supplies. current, this current flows through the circuit
Figure 11: Measuring the internal resistance of a used three-cell LiPo battery at 2 A.
WEB LINK
[1] Project downloads at Elektor Labs: www.elektormagazine.com/labs/adjustable-current-sink-with-integrated-clock-generator
Two New
Arduino UNO R4 Boards:
Minima and WiFi
or lab • Elekt
kt
Ele
or
lab
TEST
ED
Ele k
Announced a few months ago [1], the Arduino UNO R4 Minima [2]
and the Arduino UNO R4 WiFi [3] have now been released officially.
ab
rl l
to
ab
• E l e kt or
So, now that they really exist, let’s take a closer look at them.
By Clemens Valens (Elektor)
The Renesas Family
The powerful Arduino UNO R4 is A few months ago, Arduino released the Portenta C33 board, which
the newest member of the iconic has an ARM Cortex-M33 microcontroller from Renesas: the RA6M5.
The two new boards also feature a device from Renesas, the RA4M1
Arduino UNO family. It even (Figure 1). This 32-bit ARM Cortex-M4 runs at 48 MHz and has
comes in two versions. Let’s take a 32 KB of RAM and 256 KB of flash memory. It seems that a family
look at the Minima and WiFi. of Renesas boards is starting to develop.
Interesting to note is that the RA4M1 can work with a power supply
of up to 5 V, whereas most other ARM-type microcontrollers require
3.3 V. This makes the MCU a suitable candidate for enhancing the
5 V, 8-bit AVR-based family, of which the Arduino UNO R3 is a
famous member.
accessible, but a few nice ones are. These include a CAN bus and new software tends to introduce issues, so it will probably take
USB 2.0 Full-Speed (host or device). some time before the UNO R4 experience will become as smooth
as that of the UNO R3.
A USB-C connector replaces the USB-B connector.
Luckily, the UNO R4 Minima makes resolving issues somewhat
Serial and Serial1 easier, as it has an SWD interface, which allows for serious (serial)
The RA4M1 integrates two SPI ports, two I²C ports, and four serial debugging (Figure 2). The UNO R4 WiFi even takes this a step
communication interfaces (SCIs). An SCI can be either an UART, an further as its ESP32-S3 module can act as an on-board CMSIS-DAP
I²C master, or a simple SPI port (i.e. up to six I²C or SPI ports), and debugger.
even a smartcard interface. According to Arduino, these ports are
available, at least to some extent . However, looking at the Minima’s Wi-Fi Modem
schematic, only one I²C port appears to be connected. Pins A4, A5, Now that we mentioned the Arduino UNO R4 WiFi, let’s see in what
D4, and D5 expose a second SPI port, even though the board speci- way it differs from the UNO R4 Minima. Firstly, there is, of course,
fications mention only one. the Wi-Fi & Bluetooth LE module — an ESP32-S3 from Espres-
sif. It communicates with the MCU over a serial port (Serial2) in
Important to note is that the traditional Serial port on both USB AT-command mode. The Wi-Fi module’s other pins are exposed
and Pins 0 and 1 has been split into Serial and Serial1. By default, as tiny solder pads. Reprogramming the module is possible, as the
Serial refers to the UNO R4’s USB port, while Pins 0 and 1 are for required pins for this are accessible on a 2×3 header (and on the
Serial1. It is possible to map Serial to Pins 0 and 1 by defining bottom side of the PCB). The new Arduino library WiFiS3 provides
NO_USB before explicitely including Arduino.h, but this disconnects high-level software support for the module.
the serial port from the USB port. Programs and libraries that
rely on the UNO R3 way may encounter problems on the UNO R4. LED Matrix
A 96-pixel (8×12) red LED matrix (Figure 3) enables users to plot
The UNO R4 Has Better Analog data, create animations and provide more complex and sophisti-
The UNO R4 features a 12-bit digital-to-analog converter (DAC) cated feedback in projects. A new library provides functions to show
for producing real analog signals instead of PWM-based surro- animations on it (before the LED matrix library became available, I
gates. There’s also an opamp and a comparator together with an had already written a little program to display a scrolling message
internal 8-bit DAC, and the analog-to-digital converter is 14 bits on the UNO R4 WiFi - you can download it from GitHub [4]). A web
wide instead of the 10 on the UNO R3. The analogWave library was tool for designing animations has also been announced.
added to make using the DAC easy. Generating a sine, sawtooth,
or square wave is as easy as calling a library function. Of course, The matrix uses Charlieplexing [5] to connect the 96 LEDs to only
you can do much more with it. Therefore, on the analog side, the 11 GPIO ports (D28 to D38 in Arduino notation). This means that
UNO R4 has much more to offer than the UNO R3. only a few LEDs can be active at any one time, as pixels consist of
two LEDs connected antiparallel, and pixels share ports. ,Because
Added Software Complexity the human eye is slow, fast time-multiplexing tricks the brain into
Regarding the Arduino IDE, switching to a new, hitherto unsup- seeing complete images. The refresh rate must be high for this
ported processor family also implies adding software support. when serving almost one hundred pixels. The timer-driven library
As we have learned over the years in our computer-controlled world, therefore runs at 10 kHz.
A Second I2C Port I had to manually install a special Arduino UNO R4 boards package
The UNO R4 WiFi features two I²C ports (Wire & Wire1 ). A in the IDE 1.8.19 before I could do any programming. The IDE v2
Qwiic-compatible (SparkFun standard) I²C connector provides detects the UNO R4 and proposes to install the required software.
access to the second port. These connectorsmay be annoyingly Therefore, to most users, the UNO R4 will be a drop-in replace-
tiny, but, as the Qwiic standard imposes a 3.3 V supply voltage, the ment for the UNO R3.
board comes with a level shifter. This means that the board can
handle both 5 V and 3.3 V I²C communication. The UNO R4 is a Great Step Forward
Finally, very interesting is the debugging connector on the Minima
Power Supply and the CMSIS-DAP debug capabilities of the ESP32-S3 module on
When not powered by its USB port, the power supply on the the WiFi, a feature many developers have been waiting for since
Arduino UNO R3 is a basic linear voltage regulator. On the UNO R4 about the beginning of Arduino. This takes the Arduino UNO into
boards, this has been replaced by a switching regulator. It allows the pro development arena, finally. Therefore, the Arduino UNO R4
a much wider input voltage range of from 6 V to 24 V (Figure 4). can be considered a powerful step forward.
The regulator, also a Renesas product, can deliver up to 1.2 A with 230443-01
an efficiency of around 90%.
Note that the UNO R4 WiFi also has a connector to power the Questions or Comments?
real-time clock (RTC). If you have any technical questions, you can contact the Elektor
editorial team by email at [email protected].
Conclusion
The two Arduino UNO R4 boards, the Minima and the WiFi, look
like credible successors to the UNO R3. They have the same outline,
extension connectors, and full 5-volt I/O. The UNO R4 WiFi is a bit
like a UNO R4 Minima with an extension shield built in. With its Related Products
Wi-Fi module, LED matrix and Qwiic connector, it’s easy to build
IoT applications.
> Arduino UNO R4 Minima
https://elektor.com/20527
The UNO R4 is way more powerful than the UNO R3, with more > Arduino UNO R4 WiFi
of everything, from memory to peripherals to operating speed. https://elektor.com/20528
WEB LINKS
[1] Clemens Valens, “The Arduino UNO R4 is Coming,” elektormagazine.com: https://elektormagazine.com/news/arduino-uno-r4
[2] Arduino UNO R4 Minima: https://elektor.com/arduino-uno-r4-minima
[3] Arduino UNO R4 WiFi: https://elektor.com/arduino-uno-r4-wifi
[4] GitHub repository: https://github.com/ClemensAtElektor
[5] Charlieplexing: https://en.wikipedia.org/wiki/Charlieplexing
Logarithmic
Potentiometers They ’re Exponential!
Sref is the lower limit of the sensitivity of the human ear, thus 20 Pa, and
Nature designed us to perceive acoustic signals whose range of ampli- Fp is a parameter calculated for a maximum volume at around 100 dB
tudes varies from 1 part to 1,000,000 parts and more, which is repre- above the lower threshold. Reference [2] recommends a range of varia-
sented by a 120 dB ratio or more. The so-called Weber-Fechner law tion of 90 dB for an audio volume control, so, a value very close to this.
specifies
Potentiometers in the Real World
sensation = k • log(physical stimulation) The construction of an ideal potentiometer, one that’s exactly exponen-
tial, might be possible, but the technical complexity would make it an
Here, sensation is the impression that we perceive, and physical stimu- expensive component. Manufacturers have overcome these difficul-
lation is the acoustic pressure at our ears [1]. The k factor is specific ties by making tracks with two or three sections of different resistiv-
to each one of us because our hearing characteristics are just as ity to create enough linear segments to approximate an exponential
unique as your hair or eye color. Your hearing sensitivity depends on function. This compromise is deemed perfectly satisfactory for current
the frequency, the effective amplitude of the audio stimulation, and applications.
on your age, because hearing degrades with age.
Linear Potentiometer Loaded with a Resistance
The lower limit of human hearing has been measured at a sound Another way of approximating an exponential response is to load a
pressure level of 20 Pa, which has been fixed as the 0 dB value on linear potentiometer with a resistance connected between its wiper
the scale of acoustic pressures, expressed in decibels. It is also useful and ground, as illustrated by the circuit in Figure 1. The response thus
to know that an acoustic level approaching 130 dB begins to cause obtained is characterized by the following function:
physical pain. Regular exposure to sound levels above 100 dB can
cause permanent hearing damage. VOUT / VIN = α / (α (1−α)+ ) (II)
Rp
R1
210082-004
Here, α represents the rotation or translation of the control element Thermal Noise
defined by (II), and the ratio between load resistor R1 and the An ideal resistor produces a thermal noise voltage equal to
total resistance of potentiometer Rp. For example, if Rp = 1 MΩ and
R1 = 39 kΩ, then = R1 / Rp = 0.039. en = √(4•k•T•R•B) (III)
The graphed curves in Figure 2 represent the ideal exponential function where k = 1.38·10-23 (Boltzmann’s constant), T the temperature in kelvin
(green), and the function obtained with a value of 0.039 (red). This (here 298.15°K being 25°C), R the resistance value in ohms and B the
choice of and the corresponding resistance values give results closest frequency bandwidth (here 20 kHz) at which the measurement is taken.
to the exponential function. There is, however, a discrepancy between
the ideal curve and this approximation, which appears at very low levels, The series resistance introduced by a potentiometer in the circuit of
and the attenuation shows a small but abrupt jump at the start of the Figure 1 contributes at most a quarter of its total value (α (1−α)•Rp
curve. For this reason, this solution is not recommended for volume with α = 0.5), so 250 kΩ if Rp = 1 MΩ, and the corresponding noise
control in hi-fi equipment [2]. voltage will amount to
Taking into account the parameters defined by Equations I and II, load en = √(4•1.38•10−23•298.15•250,000•2•104) ≈ 9.07 V
resistance RL(α), as seen by the stage preceding the R1 / potentiom-
eter assembly, will be The maximum noise voltage will be attenuated by the divider consisting
of the potentiometer’s series resistance and of R1 (39 kΩ). Its contri-
RL(α) = Rp α (1 − α) + α+ bution will thus be reduced to 1.22 V.
The values are respectively equal to Rp for α = 0 and Rp//R1 for The noise generated by the 39 kΩ resistor must also be considered.
α = 1. This equation presupposes that the impedance of the stage that It will be up to 3.58 V for a temperature of 25°C and a bandwidth of
follows the volume control is sufficiently high to have only a negligible 20 kHz. Its contribution to total noise will be 3.1 V. Thus, the maximum
effect. The stage that precedes the volume control must be capable thermal noise voltage is
of powering the volume control.
en,max = 3.1•10−6 + 1.22•10−6 = 4.32 V
Also note that the total value of a potentiometer’s resistance Rp is
generally specified with a tolerance of ±20%, which makes it one of This represents an improvement of 6.4 dB over a potentiometer alone.
the components with the highest tolerances.
In most commercial potentiometers, the track is made of carbon, which
produces a noise level higher than that calculated with Equation (III).
Some manufacturers offer potentiometers with a track made of plastic
1
or “cermet,” a combination of a metal and a ceramic. They are not
0.9 as sensitive in use and generally present a noise voltage lower than
0.8 = 0.039 carbon potentiometers. Of course, it is better to choose a low-noise
0.7 component for R1, for example, a metal film resistor.
0.6
A generally evident conclusion from the foregoing is that in electron-
Vout / Vin
0.5
0.4
ics, in order to avoid thermal noise, the circuits should use resistors
of the lowest possible value.
0.3
0.2
Comparison of Solutions
0.1
The difficulties of constructing a potentiometer presenting an exponen-
0
0
0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1
tial characteristic have been overcome by the two methods above.
α
Which of them is better?
Figure 2: The ideal exponential curve (green), and the actual curve obtained
In the case of a volume control for consumer equipment, the approxi-
with value of 0.039 (red). This value of gives the closest results to an mation by linear segments offered by manufacturers in their so-called
exponential function. “logarithmic” potentiometers gives a perfectly acceptable solution
WEB LINKS
[1] Equal-loudness contour: https://en.wikipedia.org/wiki/Equal-loudness_contour
[2] D. Self, “Small Signal Audio Design (2nd Edition),” Routledge, 2014: https://elektor.com/18046
Join the
Elektor C mmunity
The Elektor web archive from 1974! Take out a Ge mOb eLD
m rship
8x Elektor Magazine (print)
8x Elektor Magazine (digital) membership!
10% discount in our web shop and
exclusive offers
Access to more than 5000 Gerber files
www.elektormagazine.com/Member
Motor Driver
Breakout Board
A BoB for a 5 A DC Motor Driver with a 3×3 mm Size
> It’s not just marketing talk: The chip can indeed
handle 24 V and 5 A. It is well protected against
This article is a journey of discovery to a MP6619 break- overload, short circuit, and reliably recovers from
out board (BoB). This chip is a new compact H-bridge fault situations.
for controlling low-cost brushed DC electric motors > Adding a choke coil or a filter improves performance
and solenoids. These DC motors are the most accessi- significantly. The need for that depends on your
ble and affordable for hobbyists involved in building application and the motor.
small robots, modelmaking, and creative projects. > The integrated N-channel MOSFETs have a low
This is a story about the educational journey I had to Rds(on), of 65 mΩ, which is essential for limiting
go through to develop and test this breakout board. dissipation. The necessary boost circuits to drive
their gates are also integrated. Their capacitors are
The Adventure Begins connected externally.
One day, I received an email from a component distrib- > The MP6619 chip is produced without bonding
utor about a brand-new H-bridge component: the wires to achieve a good thermal performance in a
MP6619. Figure 1 shows its internal block diagram. QFN-19 package.
This tiny “miracle” of just 3×3 mm with impressive > The footprint’s islands are extra long in order to dissi-
specifications such as 24 V and 5 A, and other aspects, pate heat from the chip to the PCB.
caught my attention (see the Chip Features frame). > The PCB must be carefully designed, taking into
How can this be possible? So much current, no account not only electrical but also thermal
heatsink, and all protection features in such a minia- requirements.
ture package? This must be marketing talk, I thought.
The alternatives are easily 10 times larger.
But, there was no BoB available for this tiny Quad, Flat, I quickly made the first version of the BoB PCB layout
No-lead, 19-contact (QFN-19) footprint. So, I had to without in-depth study, as I wanted to start testing
develop such a board myself. My adventure with the soon, but I rejoiced too soon. The first BoB included
MP6619 H-bridge began! two MP6619 chips, LEDs, resistors, capacitors, and
connectors. At that time, I still thought PCB termi-
Designed with KiCad nal blocks would be useful. Four copper layers were
To develop an MP6619 breakout board, I started needed, I placed many vias, a ground plane, and used
by studying the datasheet [1] and drawing the BoB the widest possible traces due to the high currents.
schematic in KiCad. First, I drew the symbol and That was a day’s work. A week after sending the data
footprint (these were not available in the library or to a Chinese manufacturer, I had the boards on my
SnapEDA), and then the layout. workbench. Soldering the QFN was the greatest
challenge, as the chips were smaller than anything
I paid extra attention to the placement of the R(i-sense) I was used to.
shunt resistor and the connection of power pads. This
shunt resistor is used to measure the MOSFET drivers’ To get the QFN in place with all connections correct,
current. This is crucial for the proper functioning of a stereo microscope, a good temperature-controlled
the breakout board. Voltage drop across the traces soldering iron, a hot-air soldering iron, plenty of flux,
should be considered, too, during the PCB layout and even more patience were required. Once the QFN
process. was in place and the sweat wiped from the forehead,
The MP6619 internally consists of two half-bridges, I experimented with decreasing the shunt resis-
with each half-bridge having one input (IN1, IN2). The tance and increasing the Rset resistor to get the motor
chip itself ensures the correct timing of the high-side moving, which ultimately resulted in a “human error”
and low-side MOSFETs so that no short-circuit between — 12 V on IN1, a burnt BoB as result, and a deep sigh of
the power rails occurs. frustration. The PCB went up in smoke, and I needed
to stuff a new BoB with components.
The chip is protected against all typical problems.
Its integrated UVLO (under voltage lockout), OVP Another BoB and More Tests
(overvoltage protection), OCP (overcurrent protection), Eventually, I found out that the motor is equipped with
and OTP (over temperature protection) should safely noise suppression capacitors connected in parallel to
handle nearly all error situations, which we’ll see! the commutator. As a result, the motor behaves less
inductively and more capacitively. This causes the
Connecting IN1, IN2, and EN OCP to immediately kick in when there is a current
The inputs are equipped with pull-down resistors. spike to the motor. This “overload” causes a timeout
As soon as the EN input receives a High level, the of 1 ms before the MP6619 tries again. This process
chip is activated, and the internal voltage regulator repeats again and again, resulting in a soft, squeaking
sound from the motor.
J5
2
+
1
–
C7 C8 C10
6...28V
J4
2 4µ7 100µ 4µ7
+ 35V 35V 35V Shunt
1
– 0Ω04
JP1
R10
Figure 4: The revised
1k
R5
BoB’s schematics.
100k
D2
VIN
12 11 10
Error C3
NC
VIN
OUT1
R3
13 9
nFAULT BST1 10Ω
14 100n J6
VCC 1
8
LSS
R9 15 2
IN1
7
IC1 LSS
1k
C5 16
IN2
6
Motor
D4 MP6619GQ-P LSS J2
R13 17 1
100n ISET
5 2
EN
18
Power NC
80k
R1 C1
19 OUT2 4
AGND BST2 10Ω
VIN
IFB
100n
1 2 3
J3
6
VCC
5 VIN
nFAULT
4
EN
3
IN1
2
IN2
1
GND
Control 210657-016
Semiconductors
D2 = LED, red, SMD 0806
D4 = LED, green, SMD 0805
inductors, the solution seems to be suitable for use IC1 = MP6619GQ-P, QFN-19
in projects.
Miscellaneous
Under some conditions, the motor returns energy, J2, J4, J5, J6 = 2-pin pin header, 1/10″ (2.54 mm)
which flows back into the H-bridge. This energy is J3 = 6-pin pin header, 1/10″ (2.54 mm)
dumped onto the power rails through the diodes in the BoB PCB (see text)
MOSFETs, as the motor also functions as a generator (a
DC motor’s EMF). In my tests, I used low-ESR electro-
lytic capacitor C8 in parallel to the power source. With
this last improvement, the BoB was stable.
low-voltage signals and prevents strong pulses gener-
Optocouplers ated by the motor and its driver from reaching the
Figure 8 shows my test circuit. I decided to use sensitive microprocessor and other electronics.
optocouplers to provide galvanic isolation between
Figure 8: This circuit
the controlling side and the motor drivers, because The optocouplers’ input LEDs can be driven directly
with optocouplers
sitting between the the power supply of a motor usually carries consid- from a microprocessor pin using a 470 Ω resistor
microcontroller and the erable noise levels. EMI can also cause problems. in series. On the output side, the phototransitor’s
BoB was used for testing. The isolation reduces the risk of interference in the emitter is connected to the BoB’s IN1, and therefore
to the MP6619’s input, and its collector coupled to a
logic voltage provided by a 3.3 V LDO voltage regula-
tor powered by the motor’s power supply — in my
case, a battery. This is sufficient to ensure reliable and
F1
+V +3V3
stable operation.
5A Slow
3V3
LDO
Figure 8 also shows how you can also bring the
H-bridge’s nFault signal (Open-Drain output) to the
Bt1
+3V3 C1 C2
VIN
OUT1
GPIO IN
3 2 13
nFAULT BST1
9
larly shaped pads, often arranged in long, narrow
VCC 14
VCC
8
strips. Unlike regular QFN packages, heat is dissi-
LSS
Microcontroller
R7
+3V3
15
IN1
7
pated through many of these pads instead of one
large central pad. This poses some challenges for PCB
LSS
470Ω
16
IN2 MP6619 M
6
design since there are many pads, all with different
LSS
17
1 4 ISET
5
signals, that need to be connected with copper areas.
EN
18
NC
U3
19 4
PC817
OUT2
AGND BST2
VIN
IFB
Epilogue
Related Products
In this article, I shared my experiences in design- > Dogan Ibrahim, Motor Control – Projects with
ing and building a breakout board for the MP6619 Arduino & Raspberry Pi, Elektor 2017
H-bridge motor driver. I discussed the importance https://elektor.com/18322
of using optocouplers to provide electrical isolation,
> Cytron Maker Drive – H-Bridge Motor Driver
and shared my insights into working with flip chip https://elektor.com/18923
QFN packages and the challenges involved in solder-
ing small components. > Peter Dalmaris, KiCad 6 Like a Pro —
Fundamentals and Projects (E-book),
Elektor 2022
The MP6619 breakout board offers a very compact
https://elektor.com/20159
solution for driving low-cost DC motors with brushes,
making it a great choice for hobbyists and makers who
WEB LINKS
[1] MP6619 Datasheet @ Monolithic Power Systems: https://tinyurl.com/452pk4sv
[2] First version on Elektor Labs: https://tinyurl.com/299prw8n
[3] DC Planetary Geared Motor: https://tinyurl.com/23nxnr4k
[4] Motor Driver PCB Layout Guidelines — Part 2: https://tinyurl.com/2p8ry9hd
[5] Author’s GitHub: https://github.com/edwin-oetelaar
Experience
Arsenic, once used for delightful green wallpa-
per in Victorian times, is now used in large
quantities in the electronics industry for
doping silicon and in the production of gallium
arsenide, another important semiconductor
Hazardous Electronics material for ICs and some transistors. The
now-notorious PFAS and PFOS [1] are used
in processes for exposing and etching silicon
wafers, and residues of these substances
By Ilse Joostens (Belgium) occasionally remain in the finished product.
Component packages contain not only epoxy,
If you regularly order components from large overseas but also flame retardants in the form of organic
electronics vendors, there’s a good chance that, sooner bromine and chlorine compounds in combi-
nation with antimony trioxide [2]. These
or later, you will encounter a package marked with the substances are not highly toxic, but they still
notorious “California Proposition 65” warning. In my case have a questionable reputation, so efforts are
this involved PCB connectors, and “Big Brother” kindly made to limit their use.
advised me that contact with these connectors put me at risk Then, there is beryllium — a real horror show
of developing cancer or experiencing fertility problems. It that makes arsenic look harmless. In the old
looks like electronics has become the new smoking. I don’t days there was a zinc-beryllium silicate in the
white phosphor of fluorescent lamps, until a
take such warnings too seriously, but, even so, if you work lot of factory workers came down with beryl-
with electronics, you do run a risk of exposure to hazardous liosis, a nasty, chronic lung disease [3]. At
substances — and I’m not talking about lead solder, solder present, beryllium oxide is still used, among
other things as a thermally conductive ceramic
fumes, flux, etchant, solvents, varnishes, or chemical material in high-frequency power transis-
products with unclear compositions. tors. Before you have a panic attack: Beryl-
lium copper contacts (often in used as spring
contacts) are relatively harmless, as long as
you don’t file, grind, or sand them.
A Little Bit Extra However, in practice there’s a little bit extra in
We’ve all heard that integrated circuits are ICs. Not only ICs, but also many other compo- If you’re past a certain age, you most likely
made from sand. Sand is essentially silicon nents — semiconductors or not — have a dark remember selenium rectifiers (Figure 1) in the
dioxide, and nowadays silicon is the most side and sometimes contain highly exotic form of a stack of thin square plates joined
commonly used semiconductor material. chemical substances. together in the middle. There’s no problem,
WEB LINKS
[1] PFAS: chips’ poisonous ingredient that doesn’t go away:
https://euractiv.com/section/digital/news/pfas-chips-poisonous-ingredient-that-doesnt-go-away/
[2] Wikipedia: Brominated flame retardant: https://en.wikipedia.org/wiki/Brominated_flame_retardant
[3] Environews Focus: “Beryllium: A Chronic Problem:” https://ehp.niehs.nih.gov/doi/pdf/10.1289/ehp.94102526
[4] YouTube: BigCliveDotCom: Selenium rectifiers - the smelliest components ever: https://youtu.be/OOA1NaoKV6I
[5] YouTube: Kempton Steam Museum: The Mercury Arc Rectifiers: https://youtu.be/YhaQqgXrMMU
[6] YouTube: AE Laboratories: Radioactive Vacuum Tubes: https://youtu.be/m-6-aJv7GCI
[7] YouTube: That Chemist: Somebody Vaped a Smoke Detector: https://youtu.be/14UggnpN39w?t=627
[8] Special Nuclear Material: Analysis of Soviet smoke detector plutonium:
https://carlwillis.wordpress.com/2017/02/07/analysis-of-soviet-smoke-detector-plutonium/
Is Cellular the
Lowest-Power Option
for IoT?
LTE-M and NB-IoT Energy Requirements
in LPWAN Deployments
By Stuart Cording (Elektor) One of the challenges around adoption could be the confusion the
entire cellular IoT ecosystem has with its nomenclature, making it
When tackling your next IoT project, it’s challenging to know what to choose and why. At the top level, we’re
worth casting an eye over the cellular now used to the transition from 4G to 5G, but these marketing terms
are only relevant to consumers and businesses for smartphone and
LPWAN offering. While LoRaWAN high-speed data connectivity. For lower data rate applications used in
seems low power on paper, researchers machine communication, there are separate standards to consider.
have seen wild variations in battery life Higher Data Rate Cellular IoT
with real-life deployments. LTE-M and The first is LTE-M, which stands for Long-Term Evolution Machine
NB-IoT are both very competitive when Type Communication. This branches into two current standards,
it comes to power budgets and offer a LTE Cat M1 and LTE Cat M2. The 3rd-Generation Partnership Project
(3GPP) defines these standards, with new capabilities ratified in
range of other benefits on top. But, like “releases.” Thus, LTE Cat M1 was part of Release 13 in 2015, and LTE
all good things, they have their own host Cat M2 was part of Release 14 in 2017. Cat M1 offers 1 Mbps uplink
of challenges to deal with. and downlink, while Cat M2 offers around 7 Mbps uplink and 4 Mbps
downlink. Both support full- and half-duplex (Figure 1). For context,
The ability of cellular networks to provide global access to connec- 5G smartphone networks average around 100 Mbps [1].
tivity became clear to me in the early 2000s. I was enjoying being
a passenger during a business trip through the Swiss Alps when a Part of the benefit of a lower data rate is the reduced power demands
colleague called, requesting a presentation for a customer meeting. of LTE-M hardware. According to the 3GPP specification, the aim
With my trusty Ericsson T68i balanced on the dashboard, an early was to achieve ten years of operation on a 5 Wh battery. However,
Bluetooth-enabled handset, and laptop between my knees, I quickly while that lifetime may be achievable, Brian Ray [2], an engineer now
set about sending the file using the blisteringly fast 115 kbps offered by with Google, notes that achieving a 23 dBm transmit power during
GPRS. Admittedly, it took several attempts due to losing the connec- an uplink, the highest supported level, results in peak currents of
tion in the tunnels. Still, the ability to be linked to the world in the around 500 mA. This poses a not-insignificant design challenge.
middle of nowhere indicated that the era of limitless wireless connec-
tivity had arrived. Coverage is also better than standard LTE thanks to a higher
Maximum Coupling Loss (MCL). This figure defines the point at
First Glimmer of IoT which a wireless system loses its ability to deliver its service. In a
Thanks to Bluetooth, the phone could also be accessed through a study by Sierra Wireless [2], an MCL of up to 164 dB for LTE Cat-M1 was
terminal window like the old wired modems that had been replaced determined, a significant improvement over the 142 dB of legacy LTE
by DSL technology. That meant that a Bluetooth-capable microcon- and much better than the 155.7 dB target that 3GPP set itself. In terms
troller and some software handling AT commands were all that was of capability, this means better connectivity inside buildings, which
required to connect to the world. We were implementing the Inter- is important for smart metrology applications where the building
net of Things (IoT); we just didn’t know it at the time. Now, 20 years can contribute a 50 dB penetration loss, and better range outside.
later, IoT is established, and we have even better cellular networks.
But, we would probably be hard-pressed to name a product or appli- Like smartphones, LTE-M also supports mobile data, meaning that
cation we know of that isn’t a smartphone or tablet using cellular your device continuously connects to the nearest cell tower, making
for data connectivity. it ideal for sensors monitoring perishable goods on the move or
tracking fleets of vehicles. Additionally, if you need voice occasionally The next mode is eDRX, or extended Discontinuous Reception. This
as part of the system, such as in a fire alarm panel or a monitoring lighter sleep mode saves power for up to 40 minutes with LTE-M or
system for the elderly, Voice over LTE (VoLTE) is included. Finally, up to three hours with NB-IoT. Waking up from sleep is also faster
with a latency of under 15 ms, LTE-M could support an application than PSM. Despite these power-saving levers, they are not always
that seems responsive to a human. available in all locations. Their configuration depends on the service
provider’s equipment [6], meaning that battery life in one country
Cellular for Static IoT Nodes could be less than in others because a setting cannot be negotiated.
The alternative IoT technology for cellular is NB-IoT. This also comes Use of a service provider offering a roaming SIM may also limit access
in two flavors. LTE Cat NB1 was formalized in Release 13, while LTE to these low-power features [7].
Cat NB2 has been about since Release 14. NB-IoT targets non-moving
applications, such as smart meters in agriculture, weather stations, or Because cellular IoT implementation varies so much and is depen-
sensor deployments at water treatment plants, as it doesn’t support dent on so many factors, it’s no wonder that searching for guidance
cell tower handoff or VoLTE (Figure 2). Instead, there is a peak of on power consumption is a fruitless task. More often than not, a
power consumption as the device registers itself with its nearest Google search delivers pages stating the “10 years of battery life”
tower, after which the wireless module can enter a sleep mode statement, seemingly for both LTE-M and NB-IoT and without details
knowing that, upon wake, it can continue from where it left off. on battery capacity.
NB-IoT data rates are much lower than those of LTE-M. LTE Cat NB1 Cellular IoT in the Lab
achieves 26 kbps downlink and up to 66 kbps uplink, while LTE Thankfully, teams at various institutes have taken the time to study
Cat NB2 reaches 127 kbps in the downlink and around 160 kbps in power consumption. Their results provide some guidance on what
the uplink. Unlike LTE-M, NB-IoT only supports half-duplex mode. to expect and show how cellular IoT performs when compared to
Latency is also much higher, with 1.6 to 10 seconds typically quoted. the alternatives. For example, Tan [8] compares LoRa and NB-IoT. In
However, considering the intended use case, responding with a new the experiment, MQTT packets are sent, each containing 50 bytes of
actuator setting for a greenhouse window or water treatment sluice data. Using an optimal configuration and good connection condi-
after receiving some sensor data won’t be an issue. It should also be tions, NB-IoT requires around 200 mJ per transaction.
noted that this is much better latency than competing low-power
wide area networking (LPWAN) technologies such as LoRaWAN
[4] and Sigfox [5].
WEB LINKS
[1] “5G vs 4G: What’s the difference?,” EE Limited, September 2020: https://bit.ly/3MTuUYd
[2] B. Ray, “What is LTE-M?,” Medium, May 2017: https://bit.ly/45QDq2U
[3] G. Vos et al., “Coverage Analysis of LTE-M Category-M1,” Sierra Wireless, January 2017: https://bit.ly/3OYpoGG
[4] “What are LoRa and LoRaWAN?,” The Things Network: https://bit.ly/43EgYc5
[5] Sigfox website: https://sigfox.com/
[6] “PSM and eDRX: Power saving in cellular LPWAN - possibilities and limitations,” 1NCE GmbH:
https://bit.ly/43p6a10
[7] P. Marshall, “Sleeping Battery: How eDRX and PSM Can Save Energy in LPWA IoT Edge Devices,” Eseye, May 2021:
https://bit.ly/3Ne1WUh
[8] L. Tan, “Comparison of LoRa and NBIoT in Terms of Power Consumption,” KTH Royal Institute of Technology, January 2020:
https://bit.ly/43mXrwl
[9] R. K. Singh et al., “Energy Consumption Analysis of LPWAN Technologies and Lifetime Estimation for IoT Application,” Sensors
(Basel, Switzerland), August 2020: https://bit.ly/3qvfmm7
[10] Website of the DASH7 Alliance: https://www.dash7-alliance.org/
[11] M. Kleinman, “Vodafone dials up sale of stake in £1bn Internet of Things unit,” Sky UK, May 2023: https://bit.ly/3MQZUbt
Wireless Communication
in IoT Systems
Using Arduino MKR Modules
The Right Board for Wi-Fi, LoRa, and Many More Standards
One of the biggest problems currently facing data exchange over long distances, but also from the MKR family, prepared for rapid proto-
the Internet of Things (IoT) [1] device market remote cameras transmitting high-resolution typing of IoT devices using wireless communi-
is its high fragmentation. The multitude images in real time. Thus, the specificity of cation with standards such as Wi-Fi/Bluetooth,
of devices and communication protocols these designed devices forces the designers LoRaWAN/Sigfox, GSM/3G, or NB-IoT.
makes it very difficult to build a uniform and to select the appropriate wireless communi-
functional system if you decide to use compo- cation technology for the requirements. You Wi-Fi/Bluetooth: Arduino
nents from different manufacturers. There are must consider, among other things, battery MKR 1000/1010
many reasons for this, and they are not always life, communication range, or amount of data Communication in the ISM 2.4 GHz band,
solely related to the designers’ desire to push transferred. Responding to the needs of the using Wi-Fi and Bluetooth standards, has been
through their own licensed solutions. market, manufacturers of development kits on the IoT device market for several years.
(including those from the Arduino [2] platform) For the rapid implementation of hardware and
The term “IoT” covers many types of devices. made sure that their portfolios cover the needs software prototypes using Wi-Fi communi-
These could be, for example, small measure- of IoT device designers to the fullest extent cation, Arduino has developed the Arduino
ment sensors powered by alternative energy possible. In this article, we present a brief MKR WiFi 1000 [3] and MKR WiFi 1010 [4]
sources and requiring small amounts of overview of selected Arduino development kits development kits. The former is based on
Figures 1 and 2: Arduino MKR WAN 1000 (left) and MKR WAN 1010 (right) modules. Figure 5: The Arduino MKR FOX 1200 module for
communication in Sigfox networks.
Figures 3 and 4: Arduino MKR WAN 1300 (left) and MKR WAN 1310 (right) modules. Figure 6: Arduino MKR GSM 1400 module for
GSM/3G communication.
To improve the process of software develop- For rapid prototyping of NB-IoT end nodes, Figure 7: Arduino MKR NB 15 module for
ment, the manufacturer provides the MKRGSM Arduino has prepared the MKR NB 1500 [15] narrowband IoT network communication.
library (relieving the programmer from operat- kit, equipped with the u-blox SARA-R410M-
ing the module using low-level AT commands), 02B [16] module, enabling LTE Cat M1/ NB1
together with a rich set of examples (includ- connectivity in the following frequency bands:
ing GPRS communication, receiving/sending 1, 2, 3, 4, 5, 8, 12, 13, 18, 19, 20, 25, 26, and 28.
text messages, and handling voice calls). In addition, the MKR NB 1500 kit is equipped
The MKR GSM 1400 module can work with with Microchip’s ECC508 [17] authentication
both Arduino IoT Cloud software and alter- chip, a micro SIM card connector, a Li-Po
native cloud solutions: Google IoT Cloud, battery charge controller, and an external
Blynk, or SORACOM Air IoT, for which the antenna connector.
manufacturer has prepared a set of example 230468-01
implementations.
WEB LINKS
[1] Internet of Things: https://tme.eu/en/katalog/embedded-and-iot-systems_113611
[2] Arduino @ TME: https://tinyurl.com/4b97h9j7
[3] MKR1000 WIFI: https://tinyurl.com/2dxxebu7
[4] MKR WIFI 1010: https://tinyurl.com/4uxfn6sy
[5] ATSAMW25 module: https://tinyurl.com/6dbdmssr
[6] WINC1500 radio path: https://tinyurl.com/45ejhpbn
[7] ECC508 authentication chip: https://tinyurl.com/yx2dvtp7
[8] u-blox: https://tme.eu/en/linecard/p,u-blox_1320
[9] Arduino NANO 33 IoT: https://tinyurl.com/2s3a2jm5
[10] MKR WAN 1300: https://tinyurl.com/4hk3xtjf
[11] MKR WAN 1310: https://tinyurl.com/dra5pske
[12] Arduino Pro Gateway LoRa Connectivity: https://tinyurl.com/4fmenacd
[13] MKR FOX 1200: https://tinyurl.com/2jem6ver
[14] MKR GSM 1400: https://tinyurl.com/ta7rp56s
[15] MKR NB 1500: https://tinyurl.com/yc599x74
[16] SARA-R410M-02B module: https://tinyurl.com/57bvupw4
[17] Microchip Technology @ TME: https://tme.eu/en/linecard/p,microchip-technology_632
AC Losses in
Magnetic Components
Avoid Hot Inductors!
Depending on topology, a third contributor calculating AC core loss do not account for This skin effect is because, at high frequen-
to AC loss is the effect of DC bias. At first, this, adding further to an unexpected surprise. cies, the current density is no longer constant
this seems counterintuitive because a static across the conductor cross-section because
current does not cause any movement of Finally, excess losses are attributed to the the current is displaced toward the surface of
the magnetic dipoles in the domains beyond difference between calculated losses and the conductor due to finite inductances. The
the initial change. However, when an AC measured losses. These result from things changing current in the conductor creates a
waveform is DC-biased (as a DC current such as relaxation effects, excess eddy magnetic field around the wire, again accord-
offset of an alternating current), the minor currents, stray losses, and other less-under- ing to Faraday’s law, but which, by Lenz’s law,
hysteresis curve changes its shape as a stood phenomena. induces a current back into the conductor in
function of the polarity and amplitude of the the opposite direction. These eddy currents
current at different positions along the BH What Is Winding Loss? cause cancellation at the center and reinforce
curve (Figure 1). Measurements show that, at DC winding loss comes from the DC resis- currents near the outer surface (Figure 2).
low bias levels, the influence is small, but at tance of the conductor used for the winding. Skin effect, as commonly defined, is only
higher levels there is a significant increase in This is simply the measured DC resistance valid for a single conductor in free space far
losses. It is understood that, as the magnetic multiplied by the DC current portion of the from other conductors. This is not the case
material approaches saturation, when almost current waveform squared: P = I2 × R. The in inductors or transformers, where there are
all magnetic dipoles are aligned, more energy AC winding loss consists of skin and predom- normally many turns and layers of wire tightly
is required to align the remaining domains’ inantly proximity losses from the AC portion wound together.
magnetic dipoles. Traditional methods for of the current waveform.
Proximity effect describes the influence of
adjacent magnetic fields on the currents in
Table 1. Losses sources, types, and influences. a conductor. There are two effects: Adjacent
wires with currents flowing in the same direc-
Source Current type Loss type Influenced by tion will attract each other (the fields between
Hysteresis Core material, temperature, waveform, them cancel) leaving the facing surface areas
permeability with little current, as in Figure 3a. Adjacent
AC wires with opposing currents will repel each
Eddy currents Applied voltage, duty cycle, resistivity,
other (fields between add together) and the
Core permeability, permittivity
facing surfaces will have a greater concentra-
(Hysteresis) Shifts hysteresis curve, distorts minor tion of current, with the opposite sides having
DC bias loop, topology-dependent considerably less (see Figure 3b).
Excess Unexplained losses*
DC Resistive Material, temperature In transformers, the current is in the same
direction within a winding but in the opposite
Skin effect Frequency, waveform (harmonics),
direction between primary and secondary
temperature, position*
windings. Inductors with one winding have
Winding Proximity effect Frequency, waveform (harmonics),
AC current only in the same direction. One of
position, number of layers, temperature,
the most important influences in AC winding
leakage flux, layering of windings
losses is the number of layers. This is especially
(interleaving)
prevalent with inductors because, with each
* Explanation in the text layer, the MMF (magneto motive force)
Measurement
for Optimal
Cloud Deployment
By Stuart Cording, for Mouser Electronics
With the advent of the Internet of Things properly. While telecoms operators provide
(IoT) and Industry 4.0, traditional embedded coverage maps, the reality on site can differ
systems have been augmented by cloud significantly, especially inside a building.
technology. Real-time computing, such as that
used to control a robot arm or conveyor belt, Test equipment such as the Siretta SNYPER-
is linked to servers that collect and evaluate LTE Spectrum (EU) [2] places a high-per- Figure 1: The SNYPER-LTE Spectrum delivers a
usage data. With essentially unlimited storage formance portable spectrum analyzer in wealth of data that eases antenna selection and
optimal location for cellular wireless equipment.
and masses of processing power, predic- the hands of users, simplifying site surveys
tive maintenance, energy-use analysis, and (Figure 1). Targeting EU mobile networks, the
other big-picture assessments can be made device comes in a practical carry-case with
— something that was, previously, challeng- everything neatly placed in foam sections. moved within the building using the standard
ing to implement at scale. These systems Besides the spectrum analyzer, the kit includes antenna to determine hotspots with optimal
often use machine learning technology to a multi-regional mains and car charger, and signal strength. Switching to the directional
analyze the data and make predictions about USB and RF cables. Two short antennas are antenna enables the user to find the direc-
trends. While much of this may still seem like included, one for general-purpose 4G/3G/2G, tion of the highest signal strength. Optimal
science fiction, many projects are underway and a second dedicated to 2600 MHz LTE. antenna choice and the location for wireless
to investigate the technical challenges. One A third directional antenna supports direc- cellular equipment is then defined using
example is Audi, who, together with Erics- tional liveSCAN measurements. Users need this data. Results are provided on-screen
son, demonstrated real-time robot arm control to provide an activated 4G-capable SIM to or can be downloaded in comma-delimited
using the ultra-reliable low-latency commu- perform measurements. (CSV) and HTML formats for reporting and
nication (URLLC) capability of 5G for factory documentation.
automation [1]. The SNYPER-LTE Spectrum can perform
single-point surveys of a location to collect Test System Development in the
Site Surveys for Wireless the network’s characteristics, including L-Band
Connectivity cell ownership and signal strength. The Complex RF test systems are increasingly
Running cables for connectivity is costly and integrated battery provides operation for simpler to develop using software-defined
challenging, and it fixes the installation point of 48 hours of individual surveys (assuming radio approaches (SDR), thanks to their
equipment. This goes against the current trend 20 surveys per day) or up to 15 hours of high-quality RF front-ends coupled with
for manufacturing flexibility, which foresees continuous operation for a liveSCAN survey. configurable hardware, such as FPGAs. The
factory layouts adapting to new use cases, The device also has space for the results of BittWare RFX-8440 [3] is a radio frequency
requiring wireless connectivity. In other appli- 50 surveys. system-on-chip (RFSoC) data capture card
cations, such as autonomous guided vehicles that targets applications in the L-Band
(AGV), wireless is the only option. Before the liveSCAN measurements build upon single- (1 – 2 GHz), used by applications as diverse
rollout of such systems, it is prudent to survey point surveys to generate more detailed as GPS, telecommunications, aircraft, and
the site to understand the telecoms landscape analysis. The spectrum analyzer can be astronomy.
The capture card (Figure 2) couples a two channels each offer 1:4 switches plus a Oscilloscopes and Remote Data
Xilinx Zynq UltraScale+ ZU43 RFSoC with not-connected option that functions as the Acquisition
an analog front-end featuring low-noise, default selection at power on. Via a USB 2.0 With powerful laptops widely available and in
variable gain (-40 to 0 dBm) signal condi- interface, the multiplexer can be controlled regular use by development engineers, test
tioning prior to the digitizers. Alternative using a DLL in C/C++, C#, and Python, or and measurement vendors have introduced
front-end configurations are also available, integrated into development environments a broad range of compact desktop oscillo-
extending the input range to 4 GHz. In total, such as LabVIEW and MatLab. A simple scopes that rely on your computer’s screen
there are four 14-bit, 5 GS/s ADCs, and four software utility is also available for manual for displaying measurements. This places
14-bit, 10 GS/s DACs, complemented by clock, control (Figure 3). Each channel offers 1 billion high-performance analog front ends into the
reference, and trigger signals. The RFSoC, in switching cycles thanks to RF microelectro- developer’s hands for minimal outlay, while
addition to its programmable logic, offers a mechanical systems (MEMS) switches. integrating a range of advanced analysis
quad-core Arm Cortex-A53 and a dual-core and protocol-decoding features. Digilent’s
Arm Cortex-R5. Although the capture card Getting ‘Cloud-Ready’ Analog Discovery Pro 3000 [6] is just such
features PCIe, it can also be used standalone Of course, there is still plenty of untethered a measurement tool, available in four-chan-
thanks to the Ethernet, USB, and Display machinery in use, free from cloud integra- nel (ADP3450) and two-channel (ADP3250)
Link interfaces. Further expansion is possi- tion. However, because data analysis enables options.
ble via the eight-channel OCulink port that optimized decision-making, many manufac-
offers PCIe Gen4 ×8, a connection for NVMe turers wish to fit data capture solutions retro- In addition to the 14-bit, 0.5 GS/s analog
storage, or dual, 100 Gbit networking. spectively. With eight channels of analog inputs are 16 digital I/Os and a program-
inputs, the DFRobot DAM-3918 [5] can be mable digital power supply. Together with
Test systems typically require programmable used to share analog sensor data over its Digilent’s WaveForms software [7], the Discov-
switches, allowing RF signals to be routed to optically isolated RS-485 interface using the ery Pro 3000 also offers waveform generation,
the correct ports. Teledyne’s programmable RF Modbus RTU protocol. With an accuracy of spectrum analysis, and operation as a network
multiplexer T3SP-D4MX-BUNDLE [4] comple- ±1%, it is suitable for use with 2, 3, and 4-wire analyzer, to name but a few features. Each
ments the BittWare capture card with a DC to transmitters and transducers (e.g., 0–5 V, instrument can also be controlled using code
10 GHz bandwidth- and phase-matching. The 4–20 mA). Each of the 12-bit input channels written in JavaScript or via the WaveForms
device comes with a pair of phase-matched is configurable separately, with 50 S/s for a software development kit (SDK) in C/C++,
(±2 ps), 8-inch (20 cm) cables for the inputs, single channel and 400 S/s available in total. C#, Visual Basic, or Python.
and four pairs of phase-matched, color-coded Power must be provided from an 18–30 VDC
24-inch (60 cm) cables for the outputs. The source. A unique feature is its Linux Mode, with which
the unit operates standalone as a powerful
hardware test solution. Coupled with the
WaveForms SDK, this terminal-based mode
enables the creation and programming of
custom tests or applications. The results can
be streamed via its Ethernet interface or stored
in the local capture buffers, where there is
space for millions of data points.
WEB LINKS
[1] 5G for factory automation: https://ericsson.com/en/news/2020/2/5g-for-factory-automation
[2] Siretta SNYPER-LTE Spectrum: https://bit.ly/46DLXqf
[3] BittWare RFX-8440 Card: https://eu.mouser.com/new/test-measurement/bittware-rfx-8440
[4] T3SP-D4MX-BUNDLE: https://bit.ly/3D0q476
[5] DFRobot DAM-3918: https://bit.ly/3D3gPTC
[6] Digilent Analog Discovery Pro 3000: https://bit.ly/3PR8XMR
[7] Digilent WaveForms : https://digilent.com/shop/software/digilent-waveforms
[8] Keysight Smart Bench Essentials: https://bit.ly/3JRekaP
Matter Adoption:
What does it take to deploy
Matter devices?
By Sujata Neidig, NXP Semiconductors
Matter Device Types
Owned by the Connectivity Standards Alliance (CSA), Matter is how devices communicate with each other, it
Matter is a universal and open IoT protocol, a common defines the characteristics and capabilities of devices at
language, that enables smart home devices to work with the application level. At launch, Matter supported seven
each other across brands and smart home platforms, categories of devices and will expand to many more, as
e.g., Amazon, Apple, Google, Samsung SmartThings, etc. seen in Figure 1. CSA members drive expanding Matter
Matter removes walled gardens and brings interoperabil- into more device types.
ity so that consumers can have flexibility and choice in
the devices they purchase and confidence that they will Design Considerations
work together seamlessly. For a deeper dive into Matter, Matter presents developers with several considerations
see the Matter — Making Smart Homes Smarter paper [1]. to evaluate in order to architect their system, select
the components and plan how to implement security
Matter also raises the bar on security. Every Matter device protections.
must be able to prove its identity and authenticate that it
is a Matter certified device before it’s allowed to join the First, a developer must decide what functionality the
Figure 1: Matter’s Matter network. Once the device is on the network, all device needs based on the Matter device type, associated
expanding device
categories (Source:
communications are encrypted. For a deeper dive into application clusters, and features needed beyond Matter.
Connectivity Standards Matter security, see the Matter — Making Smart Homes For example, the user interface and power envelope
Alliance - CSA). More Secure paper [2]. targets (e.g., mains or battery powered, battery size
and life, etc.). Next, the developer should determine the
connectivity requirements. As an IP-based technology,
Matter currently supports Wi-Fi, Thread, and Ethernet,
and devices can use one or more of these options. Wi-Fi
is ideally suited for high bandwidth use cases, such as
streaming audio or video, while Thread is ideally suited
for low bandwidth control use cases where reliability and
low-energy usage are a priority. In addition to connec-
tivity, the developer must determine what role or roles
the device will support such as Thread Border Router,
Matter Commissioner, Matter Controller, Matter Bridge,
etc. The final step is to assess the application’s security
requirements above what Matter defines. For example,
a smart door lock might implement protections against
physical attacks.
Figure 2: System
architecture options
for Matter devices:
Standalone and Hosted.
(Source: NXP
Semiconductors)
> A single MCU is used to implement the application Since Matter is at the application layer, every Matter
and wireless connectivity. This is an ideal architec- device must go through Matter certification. Pre-test-
ture for simpler device types that are cost, size, and ing can be done by the developer using tools provided
power sensitive. by CSA. Once ready, the developer takes the device to
> A host MPU or MCU is used to implement the appli- an ATL and applies for certification to CSA. CSA will
cation with a separate wireless MCU or transceiver confirm the Matter certification, the dependent certi-
that has the hardware for the radio. This architecture fications and issue the certification ID. The device is
is used for more complex device types that have then added to the CSA’s certified products listing and
richer user interfaces and/or are managing multiple Distributed Compliance Ledger.
networks and roles.
Since Thread is a network layer that is usually not altered
NXP provides a portfolio of Matter Development Platforms by the application, Thread Group’s certification program
to address the range of device types and use cases. These supports certification by similarity. If the device uses a
platforms include the key components needed for the Thread Certified Component (from the chosen silicon
overall system: processing, connectivity and security. supplier) and makes no firmware changes, certification
Visit NXP’s website [3] for details. can be granted through a paperwork application without
using an ATL.
Deploying your Matter Device
Certification is the next step after designing the device, The last step is to set up a production flow for obtain-
which is an essential to delivering interoperability. ing and injecting a Device Attestation Certificate (DAC)
Additionally, certification provides the license grant to into every device. NXP’s EdgeLock 2GO service is a
use the technology royalty-free and the rights to use CSA approved Matter Product Attestation Authority
the technology badges. The CSA provides a certification which allows NXP to deliver Matter DACs to custom-
program for Matter which includes test scripts, tools and ers’ manufacturing sites over the cloud.
services (via Authorized Test Labs) to aid in the process
including the Dependent Certification requirement which The product can then be launched to the market and be
validates certification of the underlying technologies used a part of delivering the autonomous home experience
– Thread, Wi-Fi and Bluetooth. Note: These technologies to consumers! And, enhancements and new security
are owned by other standards bodies which each provide vulnerability patches can be seamlessly delivered to users
membership options. through over-the-air updates.
230488-01
WEB LINKS
[1] Matter – Making Smart Homes Smarter: https://www.nxp.com/webapp/sps/download/preDownload.jsp
[2] https://www.nxp.com/webapp/Download?colCode=MATTERSMRTHOMEWP
[3] Matter – NXP Semiconductors: http://www.nxp.com/matter
By Wim Ton (Ireland) Unless the system under test uses a similar SoC, it’s less frustrating
and cheaper to use an SDR.
The YARD Stick One is a compact
“hardware-defined radio” that can send The YARD Stick One is only supported by rfcat, Python-based
middleware that abstracts the most-used options in a sort of descrip-
and receive in the UHF band. It’s a sort tive methods. For fine-tuning, rfcat also offers raw register access.
of breakout board with a USB interface
to enable its use on hosts such as PCs As delivered, the device is a bare board, and must be treated with
suitable care. Third-party enclosures are available.
and Raspberry Pis. The YARD Stick
One is delivered with USB software The term “sub-1 GHz” is a bit broad; the YARD Stick One is limited
preloaded in its 8051 core. The radio by its TI CC1111 radio, which covers the lower UHF ISM bands:
300–928 MHz. Notably, the 13.56 MHz band, used for RFID, is not
is controlled by writing a few dozen covered.
configuration registers, but the Python
middleware can abstract many of the The YARD Stick One works slightly more stably on Linux than on
Windows 10. Windows often does not recognize the device at all,
details. but you can get away with repeatedly unplugging and reinserting
the device on Linux.
The main advantage of the YARD Stick One from Great Scott Installing the Software
Gadgets is that it’s one of the cheaper devices (compared to the Using the YARD Stick One requires a good understanding of OSI
HackRF [1] or LimeSDR [2]) that can also transmit and works more layers 1 and 2. Some Python knowledge and familiarity with the
or less “plug and play,” whereas common, low-cost devices such as intended OS is also beneficial to iron out installation issues. The
the RTL SDR dongles can only receive. software recommended in the Elektor store [4] was installed on
Windows 10, Kali, and Ubuntu 18.
As all low-level functions are implemented by a CC1111 chip [3],
using the radio is a matter of writing the configuration registers Installation of rfcat [5] on Linux with Python 3.10 worked well.
correctly. The CC1111 is targeted at complex Layer 2 protocols, with The only difference from the documentation was that rfcat must
features such as sync words, framing, interleave and scrambling. be started with
As the CC1111 is designed as a SoC for commercial RF applications,
the use of the YARD Stick One for signal analysis is very limited. ./rfcat
Install the libusb-win32 driver. The easiest way is probably using To help with the configuration of the many registers of the CC1111,
Zadig [6], which usually comes with SDR#. If the device is absent, the utility SmartRF Studio from TI [12] helps. The calculated
you get the “No Dongle Found” exception from rfcat. In case of a values can be written to the YARD Stick One with the appropriate
“ChipconUsbTimeoutException,” unplug and reinsert the device. setXxx(value) function.
All in all, installation and use on Windows 10 is a bit more tricky
than on Linux. It is mandatory to call setmodeIDLE() at the end of The firmware as delivered with the YARD Stick One in the Elektor
the script, or a “device not found” error will follow on the next start. Store acts as a bridge between the CC1111 registers and the USB
WEB LINKS
[1] Denis Meyer, “HackRF One SDR Transceiver,” elektormagazine.com:
https://elektormagazine.com/news/hack-rf-one-sdr-transceiver
[2] Jan Buiting, “LimeSDR Mini,” elektormagazine.com:
https://elektormagazine.com/news/digital-tv-transmitter-based-on-raspberry-pi-zero-and-limesdr-mini
[3] CC1110Fx / CC1111Fx datasheet: https://ti.com/lit/gpn/cc1110-cc1111
[4] YARD Stick Software & Documentation: https://github.com/greatscottgadgets/yardstick
[5] RfCat GitHub: https://github.com/atlas0fd00m/rfcat
[6] Zadig: https://zadig.akeo.ie/
[7] SDCC: http://sdcc.sourceforge.net/
[8] YARD Stick One notes: https://bit.ly/3ql6mjo
[9] Hacking Everything with RF and Software-Defined Radio - Part 1: https://bit.ly/3qpIGul
[10] Universal Radio Hacker: https://github.com/jopohl/urh
[11] Radio Communication Analysis using RfCat: https://bit.ly/42kxvAj
[12] SmartRF Studio from TI: http://ti.com/tool/smartrftm-studio
[13] Hacking Everything with RF and Software Defined Radio - Part 2: https://bit.ly/43ITm5D
[14] IM-me: http://ossmann.blogspot.com/2010/03/16-pocket-spectrum-analyzer.html
[15] CC111x breakout board: https://aliexpress.com/item/32963409008.html
Latching
Relays
Peculiar Parts, the Series Figure 1: Typical power latching relay used in remote
mains power switching devices.
By David Ashton (Australia) switch the load off when the battery is getting low, without constant
draw on the battery.
It’s easy to make a standard relay
latch. Use a spare contact to switch Figure 1 shows a typical power latching relay used in remote mains
power switching devices mentioned above. This one has a 24 V coil
power to the coil as soon as it is with PCB pins and 10 A contacts with spade connectors. A red projec-
operated, and the relay will stay tion on top shows which position it is in.
operated or “latched.” But this still
Figure 2 shows some smaller Panasonic relays with four change-
requires a current in the coil, and over contacts. These are two-coil latching relays from Panasonic,
true latching relays stay latched type DS4E-ML2-DC5V, with 1500 V isolation. Smaller latching relays
with no coil current. like this would be useful in battery-powered equipment for power
or signal switching without constant battery consumption — maybe
switching attenuators in and out, for example.
Latching relays can perform the trick either with two coils — one to Latching relays are components that find a home in very specific
operate the relay and one to release it — or they use one coil, where designs, where their power-saving properties make them very useful.
one polarity operates the relay and the reverse polarity releases it. With For simplicity, isolation, and low-power consumption, there is not much
both types, the advantage is that only a short pulse of coil current is that can beat their specifications. It’s worth knowing about them, as
sufficient to change the relay’s state, and thereafter the relay remains they can perform functions that would otherwise be very difficult to
in that state until you pulse the other coil or give it a pulse of reverse obtain.
polarity. Some types depend on permanent magnets to accomplish 220653-01
the change of state.
PIC O’Clock
In Touch with Time
Designing an SDR Time Signal Receiver
bandpass filter. Although this approach is avoiding a preselector that eliminates the bulk
simple and low-cost, it means you can only of the noise. Figure 2: Basic preselector circuit.
receive signals at 77.5 kHz ±10 Hz. Ultimately,
it became clear that without massive (and as An LC resonant circuit with a variable capac-
it later turned out, digital) filtration, the goal of itor (Figure 2) is often used as a preselector.
trouble-free time signal reception was doomed The resonant frequency of the tuned circuit If you use a ferrite rod antenna with a typical
to remain elusive. is given by the formula: inductance of 1500 µH, as commonly used for
reception in the longwave band, you will need
First, let’s look at the block diagram of the Formel 1 a variable capacitor with a range of 400 pF
fully configured time signal receiver (Figure 1). to 6.7 nF if you want to cover the frequency
range of 50 to 200 kHz. Unfortunately, there
are no variable capacitance diodes available
that meet this specification.
Mixer
MCP2036 Inductive
I recalled that every semiconductor device
Preselector 1 Preamplifier 1 Touch Frontend Preamplifier 2 Preselector 2
has an inherent (and unintentional) junction
capacitance that generally depends on the
size of the junction and is voltage-depen-
IN
dent. My first measurements on a power
OUT MOSFET looked promising, and, from a
LO variety of different types, an IRF640 yielded
the best results, with a capacitance of 500 pF
at 20 VUDS and 3 nF at 1 VUDS. To make it easier
LPF to tune through the frequency range, I added
a number of additional capacitors (C30…C34)
that could be connected in parallel with the
DAC NCO PGA ADC PWM
power MOSFETs (T35 and T36) as needed
with the aid of bipolar small-signal transis-
tors (T30…T34). With this arrangement, the
DMA CPU preselector in Figure 3 can be tuned over
PIC18F46Q71
the range of around 30 to 300 kHz with an
inductance of 1500 µH.
PWM SPI PWM PWM
210244-019
2k2
R133 OSC1 ST31
VCC 5
33k ANT1
4
2k2
2
100n
T38
1
OSC OUT1
To allow different ideas to be tested, I used a
FB1
OSC1 connector (ST31, Figure 3) so that this part of
T37 OUT
ST30
BC560C the circuit could be swapped out.
ANT1
S
T35
J113
Figure 4 shows a simple way to implement
G
R36 C37 the feedback. Here, the required phase shift
R30 D IRF640 470Ω HF1 and additional gain are implemented using
an extra transistor (T80). This circuit has the
1M 100n
C35 D
T36
R31 R32 R33 advantage that it only has a slight damping
C38
100n G effect on the resonant circuit, but it turned out
470Ω
10M
ND
S IRF640
100n
to be difficult to achieve reliable resonance
over a wide frequency range.
Figure 3: The preselector with the connected amplifier for the antenna signal. On the second try, I adapted an old circuit
that implements an LC meter with the aid of
a comparator (Figure 5). It resonates over a
ST80
5
wide range of inductance and capacitance
values and matches the expected resonant
ANTB
4
OSC VCC2
frequency very well. As so often happens in
3 R81
OSC GND2 C81
2
OSC OUT2
electronics, however, an improvement in one
1k
1
FB2 100p
place comes at the expense of a degrada-
R82
1M
R80
tion somewhere else. Although the terminals
and feedback were implemented with very
1M
T80
C80
high impedance, the input impedance was
10n BC548 significantly higher than with the previously
described solution. Three 470 kΩ resistors
(R70, R71, and R73) connected in parallel in
210244-004
Figure 4: Oscillator implemented with transistor feedback. terms of HF, amounting to around 150 kΩ,
strongly dampen the resonant circuit. In
practice, this had hardly any effect on recep-
R70 R72
tion quality, other than that the overall gain
R73 had to be increased a bit.
470k
470k
1k
ST70 C72
ANTA
5 3
IC70A
For this variant, I would have liked to use one
OSC VCC
4
10µ C70 LM393
1
of the comparators integrated into the MCU.
3 2
OSC GND
2
100n
Although the pin multiplexer in the MCU offers
OSC OUT
FB
1 R74 a lot of different ways to feed out signals to
different I/O pins, with intensive use of the
10k
R71
C71
analog peripherals you run into limits here, at
470k
Ultimately, I ended up with the circuit in Alternatively, you can excite the resonant Cx F-LO F-HI
Figure 6 as a compromise. Here, the resonant circuit at a known frequency and adjust the 0 127,000 227,200
circuit is reliably excited into resonance by capacitance until you get the least damping 1 106,300 147,500
a short pulse (200 ns) on ST31/90 (Pin 2) and the highest amplitude. For this, you can 2 91,400 113,900
via R90/D90. Without feedback, however, connect a very high-value resistor to the
3 82,700 98,200
the resonance only lasts for a few periods, binding posts (ST31, Pin 2, Pin 5) and use
which is too short to allow it to be measured a highly precise reference frequency on the 4 74,400 84,900
accurately enough by the integrated timers. I/O pin (more about this later) to excite the 5 69,400 77,700
For this reason, the amplified signal is fed resonant circuit. 6 64,800 71,400
via ST31 (Pin 4) to one of the comparators
7 61,300 66,900
integrated in the MCU, and the comparator In addition, I placed a trace around the entire
output on ST31 (Pin 2) provides additional board layout that is also sufficient to excite 8 56,000 60,000
energy to keep the circuit resonating (see the antenna at the desired tuning frequency. 9 53,800 57,300
also Figure 2). Here the reference voltage This works very well, but in comparison to 10 51,400 54,600
on the comparator, which can be set via a the previously described solution, it takes a 11 49,700 52,600
DAC, determines how well you can match the long time because many iterations are neces-
12 47,700 50,200
expected resonance frequency. Maybe one of sary. It therefore seems to me that the most
the readers of this article has an idea for how reasonable approach is to combine the two 13 46,300 48,700
this can be adjusted automatically in normal solutions. First, you roughly approach the 14 44,800 46,900
operation so that it works reliably at different target frequency with the oscillator, and then 15 43,700 45,600
target frequencies. do the fine-tuning by excitation and tuning 16 39,800 41,200
to maximum resonance. The screenshot in
17 39,000 40,400
No matter which of these three options you Figure 7 shows a typical calibration and
choose, in the end you have a digital signal tuning process at 77.5 kHz. 18 38,100 39,400
of decent amplitude that you can feed to one 19 37,400 38,600
of the counters in the microcontroller. As the Unfortunately, as can be seen in Figure 8, the 20 36,500 37,600
desired frequency resolution does not need capacitance versus voltage characteristic of
21 35,900 36,900
to be better than 100 Hz, it is sufficient to the junction capacitance is not linear (note
22 35,200 36,100
measure the frequency with a time window the logarithmic scales on the chart). In other
of 10 ms (1/100 s). words, the capacitance changes are large at 23 34,600 35,600
low voltages and become smaller and smaller 24 33,500 34,400
On startup, the software first measures the at higher voltages. 25 33,000 33,800
frequency ranges that can be achieved by
26 32,500 33,200
connecting capacitors C30 to C34, in each To remedy this, we can take advantage of a
case with the minimum and maximum tuning special feature of the DAC in the microcontrol- 27 32,100 32,800
voltage. The best-match band is then selected ler: It can be supplied with a variable internal 28 31,500 32,200
for the definitive tuning process and the tuning reference voltage. For low output voltages, we 29 31,100 31,700
voltage is adjusted stepwise upwards or choose a reference voltage of 1.024 V, resulting 30 30,600 31,300
downwards, starting at half the voltage range. in a correspondingly low voltage swing. For
31 30,300 30,800
The total time required to tune to a defined higher tuning voltages, the reference voltage
receive frequency is less than 100 ms. can be increased in steps up to 4.096 V.
Now, the signal from the preselector is avail- TUNING ... (5)
able for further processing. Unfortunately, the [512] 77,760 >
A/D converter integrated in the microcontrol- [256] 76,570 <
ler has a maximum conversion rate of 300 kHz. [384] 77,280 <
ST90
5
D90
Mixer and More [448] 77,540 >
4
1N4148 As the sampling rate for a software imple- [416] 77,420 <
3
2
R90 mentation of the receiver should be at least [432] 77,480 <
1 * twice the highest received frequency, and [440] 77,510 >
preferably four times, the received signal
210244-006
[436] 77,490 <
must first be down-mixed to a lower frequency
so that it can be further processed by the [438] 77,500
Figure 6: The oscillator is excited by a resistor
and a diode. microcontroller. Figure 7: Checking the tuner.
R20
As six bits are actually enough to reliably
MIX decode the signal (as demonstrated below),
100Ω
VDET– 13 47p
1M
Most microcontrollers contain a timer/counter
6 DRVIN DRVOUT 5
R22 that can divide the clock signal by a factor n.
This is sufficient for many applications, but
9
/CS Voltage VREF 1
Refference
the resolution is very poor. Suppose the refer-
10
ISCL C23
VSS
11
2µ2
ence frequency is 16 MHz. Using a divisor of
80 results in an output frequency of 200 kHz,
210244-009
but with the next larger divisor (81) the output
frequency is 197.5 kHz — a step of 2.5 kHz.
Figure 9: Internal structure of the MCP2036. (Source: Microchip)
Along with these standard timers, the
PIC microcontroller used here also has
More or less coincidentally, I learned about necessary, low-pass filter the output to remove an additional peripheral called a numeric
an interesting component, the MCP2036 from unwanted mixer products. controlled oscillator (NCO). As shown in
Microchip, which is actually intended to be Figure 11, this is an adder that each time
used as a front-end for touch sensors, but Then, the fully conditioned and down-mixed adds a predefined value to its current result
also contains a mixer (Figure 9). signal is fed to the A/D converter. There, the to generate a new result. This occurs at very
signal is sampled at four times the interme- short intervals, in this case at the microcon-
The signal to be mixed is fed in via the two diate frequency to allow the I/Q components troller clock frequency of 64 MHz.
inputs, LREF and LBTN. The local oscillator to be obtained downstream, enabling digital
frequency is fed in via the CLK input as a demodulation of the received signal. Each time the adder generates an overflow,
digital signal, resulting in an intermediate either a result is generated or an output is
frequency of several kilohertz at the output. But, to be able to receive amplitude-modu- toggled. At low frequencies, this allows
This device also has other practical features, lated stations such as the DCF77 time signal resolutions as small as several tenths of a
including a reference voltage source, a driver transmitter, the gain of the input stage must hertz. Of course, there is a certain amount of
(not used here), and an opamp that can be be regulated so that the input to the A/D jitter in the output signal, but it can be ignored
used to further amplify the signal and, if converter is in the right range — not too high in this case.
The Microcontroller
I’ve already talked a lot about the microcon-
troller. With the many functions and tasks
Binary Output Q Output this MCU must provide and perform, it’s very
PIR
Q Adder Register Q surprising that I opted for an advanced 8-bit
Number
Input N IN N N
SUM
IN microcontroller (Microchip PIC18F46Q71 [1])
Q+N
Step
MSB MSB
instead of a high-performance 32-bit micro-
controller. And what’s more, the PIC18F46Q71
CLK
is available in a maker-friendly plastic
Direction
DIP package. It has a wealth of peripheral
Kernel Speed Clock hardware, which I used extensively here. As
for extraordinary features in its class, it has a
PIR = Phase Increment Register
210244-011 MSB = Most Significant Bit 12-bit ADC with a 300 kHz sample rate, two
integrated opamps each with a gain-band-
width product of 5.5 MHz, a multichannel
Figure 11: Numeric controlled oscillator. DMA controller, multiple fast PWM channels
with deadtime generator, two UARTs, and a
numeric controlled oscillator (the heart of the
receiver circuit). It also contains other inter-
+4V3
esting peripherals, including programmable
logic cells (which, for example, can be used
R8
to generate a signal with a 90-degree phase
ST3
C12 C13 ST1 6
PGM
10k
A Suitable GUI
16MHz
33p 33p
Figure 12: The brains of the time signal receiver: the PIC18F46. display and control buttons, along with a
MCU SCL
+4V3
MCU CS
MCU A0
MCU SI
LED
R1 IC50
AUDIO 1
R50
3 6
33k
10k C53 SPK
S1 8
R3 R8 5
LM386
3k3 10k 2
LED1 C52 100µ
R7 4
S2 7
R4 10k
47n
+4V3 3k3 R6 R51 R52
C50 C51
330Ω
S3
10Ω
R2
1k
R5
100n 10µ
3k3
330Ω
210244-014
C2 C4
R26
R43
R40
R41
R42
10k
10k
10k
10k
C10 C8 C7 C6 C1 C3 C5
10µ 1µ 1µ 1µ 1µ 1µ 1µ
ZPD3
C11
40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23 22 21
+5V +4V3
RST
A0
VDD
VDD2
VSS
VOUT
CAP3 P
CAP1 P
CAP2 P
VSS
V4
V3
V2
V1
V0
CS1B
SCL
SI
CAP1 N
CAP2 N
10µ
LP2950-3.0
IC2
+5V LCD 122 x 32 +5V R10
EA-DIP122-5NLED
1k
R27 R34 1 2
ST2 VBUS D–
56Ω
56Ω
C1–
C2–
A1+
A2+
USB -B GND D+ D2
1 2 19 20
D 5 4 3
T20
1N4148 C9
G
BL D3
R25 100n
BSS138 S
100k
1N4148
210244-015
210244-013
Figure 13: The user interface consists of a display, an LED, and some pushbuttons. Figure 15: The 5 V supply voltage from the USB AC adapter is
reduced to 4.4 V for the digital portion…
potentiometer (Figure 13). I opted for one conversion, I used series resistors in combi- So, I built a conventional analog amplifier
of the well-known display-on-glass (DOG) nation with parasitic bulk diodes present in based on the tried-and-true LM386. The
modules, which is connected to the host the display inputs. audio signal is first processed digitally by the
microcontroller through an SPI interface. microcontroller because it is present in digital
Annoyingly, the SPI interface of the display Audio form as I/Q components after the A/D conver-
is implemented as one-way only, which means As some radio stations are also within the sion, in any case. At the output, the computed
that data can be written to the display but reception range (for example, BBC World at samples are fed to a PWM unit operating at a
cannot be read from the display. 198 kHz), I additionally included a loudspeaker high clock rate, after which they pass through
and amplifier in the project. I aimed to make a low-pass filter and are then fed to the input
For this reason, the graphic image to be maximum use of the peripherals present in of the amplifier IC (Figure 14).
displayed must first be created in the micro- the microcontroller to implement the amplifier.
controller RAM and then periodically sent to The PWM unit used here can be clocked
the display. For this, I again used one of the Initially, I opted for a Class-D design, with directly from the 64 MHz system clock,
microcontroller’s peripheral hardware units, in the output stage transistors driven digitally resulting in a PWM frequency of 15,625 kHz
this case the DMA controller. It cyclically sends by the microcontroller and switched either (64 MHz / 212) with a resolution of 12 bits.
the content of the display RAM to the display fully on or fully off. Interference to the receiver Along with the audio output, this also makes
via the SPI interface. This runs completely in could be avoided by choosing a suitable clock it possible to set the volume level. The chosen
the background and does not require any CPU frequency with as few harmonics as possi- loudspeaker measures 40×40 mm and also
processing power. ble in the receiver frequency range. But, what serves as a mechanical brace.
worked so well in the implementation of the
The overall current consumption of the voltage booster (see below) turned out not to Power Supply
display is only a few hundred microamperes, be possible here, perhaps due to the signifi- A few brief words about the power supply
so I implemented the additional 3.3 V supply cantly higher power or the considerably longer (Figure 15): The idea was that the entire
voltage with a Zener diode. For signal level cable path to the loudspeakers, or both. receiver should operate from a single USB port.
Antennas
The antenna is joined to the receiver through As ready-made ferrite rod antennas and even cantly lower signal amplitude but with aston-
a matched pair of SMB connectors. This bare ferrite rods have now become hard to ishingly good reception quality: I could easily
arrangement allows the antenna to be rotated, find, and because winding coils is not every- receive DCF77 over a distance of 800 km. I
so it can be oriented to the transmitter direc- one’s favorite pastime, I went looking for an tried mounting the inductors both radially
tion as well as possible. alternative antenna. On the clearance page and axially, and they worked both ways. If
of a mail-order electronics distributor, I found you combine the two variants (alternating
For the initial reception experiments, I removed a loop antenna and glued it to a piece of radial and axial orientation), you should have
a ferrite rod antenna from an old radio alarm circuit board material. The reception results an antenna that’s largely omnidirectional. If,
clock and glued it to a piece of circuit board. were comparable to those with the ferrite rod for example, the field lines passing through the
Of course, I first had to remove the tuning antenna. axially oriented inductors are at a maximum,
capacitor because it is now simulated in the the radially oriented inductors will not see any
preselector. Based on that, I designed a circuit board effective field lines, and vice versa.
with notches as a winding aid (Figure 17)
and made the antenna myself. I had to use Software
very thin enameled copper wire to make an The software basically operates on the princi-
antenna with the required number of turns. ple of a conventional SDR, which means the
+5V +33V All in all, a very tedious process, but doable. I/Q components are used for demodulation of
L140
D140 the signal. How this works has already been
220µH When digging around in my component described in many articles in Elektor [2] [3], so
1N4148
drawers, my gaze fell upon a large bag of fixed it’s not necessary to go into all the detail here.
4Ω7
R140 D141
inductors that I’d acquired a short time earlier. The software excerpt in the Two receivers are
C140 C141
Would it be possible to use them to build an better than one box is the only thing that is
D
22µ T140 4µ7
50V ZPD33
BOOST
G unconventional antenna? If several of them really new and therefore deserves mention.
BSS138 are connected in series, the arrangement is
S
similar to a ferrite rod antenna, but divided into This circuit makes use of many of the
210244-016
multiple parts (Figure 18). It turned out that, integrated peripherals, for example generat-
Figure 16: …and boosted to 33 V for the tuning with this arrangement, I was able to achieve ing the local oscillator frequency for the mixer
voltage. comparable reception results, with signifi- and using the DMA controller, so the load on
the microcontroller is very low. As a result, approach and implement it as planned. If I were controllers, but that could be kept within
even this 8-bit microcontroller has enough designing this again, I would do the following: limits. One CPU could handle the digiti-
processing power available to demodulate zation and processing of the received
the received signal. > Add a rotary encoder to the user interface data, while the other CPU could support
to make it easier to set the frequency. the GUI. As both microcontrollers would
The last link in this chain is the GUI, which > Try out the PIC18F26Q71 (the little brother be operated from the same clock source,
evaluates newly calculated values and updates of the PIC18F46Q71 I used), but use a one-wire UART interface operating in
the display as necessary. two of them. The required board space the Mb/s range would be easily possible.
would be nearly the same, and this way I > Replace the SMB connectors, which
Outlook would have two NCOx, four opamps, and have become nearly unaffordable, by
It’s a familiar story: After building the first four comparators. From an HF perspec- old-fashioned jack sockets. A 2.5 mm
prototype, you come up with many new ideas tive, this would allow better routing. version would work well here, and rotat-
about how to improve things on a second try. A drawback would be the necessary ing the antenna would still be possible.
Nevertheless, I decided to stick with my first communications between the two micro- These plugs and jacks are also available
WEB LINKS
[1] MCU PIC18F46: https://microchip.com/en-us/product/PIC18F46Q71
[2] Martin Ossmann, “AVR Software Defined Radio,” six-part series, Elektor 3/2012 to 10/2012:
https://elektormagazine.com/magazine-archive/2012
[3] Martin Ossmann, “SDR Radio Controlled Clocks,” Elektor 1/2023: https://elektormagazine.com/magazine/elektor-288/61435
TOPPQUALITY PCBS
Our cutting-edge technology ensures
flawless PCBs for your projects.
YOUR ULTIMATE LIGHTNINGPFAST TURNAROUND
PCB MANUFACTURING Experience industry-leading
turnaround times.
PARTNER ! HASSLEPFREE ORDERING
Simply upload your design, and
WHY CHOOSE PCBWAY? we'll take care of the rest!
TOPPQUALITY PCBS
www.pcbway.com Our expert support team ensure a
s e r v i ce @ p c bway. co m seamless experience from start to finish.
Due
Diligence
Directive
Business as Usual Will Not Do
92 September & October 2023 Partner Content by Ethics in Electronics (EiE) ethicsinelectronics.com
rights violations or negative environmental impacts have demands of any SME they work with in order to
known. Companies have to provide a complaint proce- be able to fulfil their own due diligence duties. EU
dure to support this, and inform relevant parties, as countries are expected to support their SMEs by setting
well as provide appropriate followup. Companies need up dedicated websites, portals, and platforms — and
to check on the implementation and effectiveness of perhaps provide financial support to build capacity.
their policies and on those of their business partners Big companies are expected to invest in the SMEs with
continuously. Such check-ins must be done at least whom they work, in order to help them to comply.
once a year, or when new issues arise in the supply
chain. All of this must be done transparently and More Moral
communicated publicly. I think this directive is a good example of how law
slowly becomes a formal version of the values we
Sanctions are mentioned in the directive, but it hold as a society. Of course, you don’t have to wait
is left to every EU country to enforce them in line around for laws to be established, and it makes good
with national laws and proportional to the compa- business and moral sense to be ahead of the curve. One
ny’s revenue. In the EU, they will set up a European example of this is RS Group, providers of industrial and
Network of Supervisory Authorities to help and electronics products to engineers. They have already
oversee countries do this. started to build an ethical supply chain seriously [4].
A director of such a big company has a duty to oversee Many SMEs will soon discover what power (if any)
the corporate due diligence, to establish a code of they have in their supply chain, and, perhaps for the
conduct and to integrate this into the corporate first time, undertake an ethical examination of their
strategy. The CEO must ensure that sustainability, companies’ actions. This forced self-reflection will
human rights, climate change, and environmental likely come with compulsory forms to fill, new report-
consequences are properly considered in the short, ing practices and self-certifying quality control marks,
medium, and long run. Making a profit is not a valid along with big companies usurping more parts of the
counterargument. supply chain in order to maintain control and fulfil
their legal responsibilities. If you are part of an SME
Adjust to Size that works with bigger companies, yesterday would
Big companies will be liable if they fail in their due be a good time to start investigating and reporting
diligence and preventable bad things happen or on your due diligence. Many will already have made
continue to happen. This does not mean that compa- many moral business choices. Now, these need just
nies have to guarantee that bad things will never be formalized and communicated.
happen. Companies must take measures appropri- 230428-01
ate to their level of power in the chain and respond
to human and environmental rights violations when
they find them (and they are obligated to look).
WEB LINKS
[1] EU CSDDD portal: https://bit.ly/43MAiUu
[2] Supply Chain Act (Wikipedia): https://en.wikipedia.org/wiki/Supply_Chain_Act
[3] Actual CSDDD: https://bit.ly/43Pg1Oa
[4] WEEF 2022 - Building an Ethical and Sustainable Supply Chain with Andrea Barrett: https://youtu.be/tuu88ePQwYQ
Starting Out in
Electronics...
…Voltage Amplification
But, before we jump into the emitter circuit, a word of caution is Figure 1: Common-emitter circuit.
justified. This concerns the article in the May/June 2023 issue,
and in particular the astable mutivibrator outlined in Figure 3 on
page 40. As Elektor reader Ruedi Schwarzenbach from Switzerland The Emitter Circuit
wrote to us, this circuit has some potential dangers that can spoil The circuit shown in Figure 1 involves an emitter circuit (not to
the fun of novice electronics enthusiasts quite a bit. be confused with an emitter-follower!), where the emitter is the
common reference for the input and output signal. The emitter
What is actually the case: Although we have not mentioned a circuit is very similar to the collector circuit from the previous
specific transistor type in the schematic and the text, it is in fact installment, except that a collector resistor is now present, while
obvious to use the BC547, a general-purpose transistor, for this the output voltage is taken from the collector. The emitter resistor’s
purpose. And, because the calculations in the text assume a supply main task now is to prevent the operating setpoint from drifting;
voltage of 12 V, things could go wrong. This is because, according its value is now a lot smaller. Assuming, again, a quiescent current
to the datasheet, the BC547 does not tolerate a high base/emitter of 1 mA, we end up with a value of 1 kΩ for the emitter resistor.
reverse voltage, 5 to 6 V is just about the maximum. And that
means that the transistors in the aforementioned Figure 3 circuit The output voltage can vary from 1 V to 12 V, i.e. within a range of
can already become damaged at a supply voltage of greater than 5 V. 11 V; we choose the idle voltage in the middle of this — a voltage of
6.5 V is then present on the collector, while a voltage of 5.5 V falls
Although we mentioned that “the base of the left-hand transistor across the collector resistor. We can now calculate RC:
carries a negative potential and is therefore turned off,” one should
bear in mind that at a negative potential of 5…6 V, the base/emitter
path shows a kind of Zener effect. A current flows (the capacitor is
in fact shorted via the two transistors), which could possibly cause
the transistor to fail. We take a default value of 5.6 kΩ for RC here. As for R2, we choose
(arbitrarily) a value of 100 kΩ and calculate R1 as follows:
To avoid this kind of issue, it’s better to use a voltage source of 4.5 V
for the power supply (like a 4.5 V flat battery, for example) and to
do all calculations with this voltage.
Just to be clear, that 1.7 V follows from the voltage across the emitter
resistor of 1 kΩ at a quiescent current of 1 mA, plus the voltage of Figure 3: The Darlington circuit.
0.7 V falling across the base/emitter junction.
The question now, of course, is where the voltage gain comes from Because of the omitted emitter resistor, the circuit does deliver a
and how large it is. If we assume that as a result of an applied AC very large gain, but the temperature stability of the overall circuit
voltage, the voltage at the base of the transistor increases by 0.1 V, is awful: If the temperature changes by only a few degrees, the base
the emitter voltage also increases by 0.1 V, which means that the current — and therefore also the collector current — increases (or
current increases by 100 µA. As a result of this larger current, a decreases) and the operating setpoint drifts. Moreover, the current
higher voltage falls across the collector resistor (0.56 V more, to be gain of a transistor is not a reliable parameter because it has a very
precise). In other words, the voltage at the collector of the transis- strong exemplary spread — so the value of R1 can only be deter-
tor is now 0.56 V lower. mined by experiment.
A voltage increase at the base results in a corresponding voltage The omitted emitter resistor also results in a very low input imped-
decrease at the collector, and not only that — the voltage change ance, so as a result the value of C1 should be selected to be much
at the collector is greater than that at the base. The voltage change larger to avoid the lower cutoff frequency becoming too high.
at the base is therefore amplified!
To make a long story short: A circuit as shown in Figure 2 is not
Also in this numerical example, we have neglected the difference useful. Those who need very large amplification are better off
between IC and IE. If we allow ourselves this modest freedom, we connecting several amplifier stages in series or using an opera-
can write the following for the voltage gain of the common emitter tional amplifier (opamp) beforehand.
circuit:
The Darlington Circuit
For many applications, we need a larger current gain than can
be provided by a single transistor. In such cases, the Darlington
circuit (Figure 3) comes in handy. In this circuit, two transistors
So, in this example, the gain is -5.6×. The minus sign simply means are switched in such a way that the emitter of the first transistor
that the input signal and the output signal are in antiphase. Or, put is directly connected to the base of the second transistor. Here, we
in another way, we are dealing here with an inverting amplifier. may (as a good approximation) multiply the individual current
gain factors by each other, so that values of 10,000 and more are
It is possible to amplify a signal much more with this circuit, but in achievable with small-signal transistors. It should be noted that
that case, a smaller emitter resistor and/or a higher supply voltage the base/emitter voltages of the transistors are added together,
should be selected. Under all circumstances, we should avoid a which means that a Darlington circuit requires a setup voltage
‘design’ like the one shown in Figure 2. For convenience, in that (bias) of at least about 1.4 V.
circuit, the designer omitted resistor R2 and emitter resistor RE.
As for power transistors, whose current gain is often very modest,
rather use the Darlington circuit. In many cases, both transistors in
the circuit are already integrated in one package by the manufac-
turer — we then refer to it as a Darlington transistor.
10k
I1 I2
T1
D1 T2
I [mA]
10
D2 I1
8
R2 R3
D3 6
100Ω
2k2
4
I2
230372-007 2
In the case of the constant-current source, the current increases Editor’s Note: This series of articles, “Starting Out in Electronics,” is
noticeably less steeply (the graph is flatter), meaning that the circuit based on the book, Basiskurs Elektronik, by Michael Ebner, which
would still be usable at significantly higher supply voltages. The fact was published in German and Dutch by Elektor.
that the current is not perfectly constant, which would make the
graph horizontal, is due to the voltage increase across the diodes
— a Zener diode would provide a significantly better result, and a Questions or Comments?
“two-stage” stabilization would have been even better. If you have any technical questions or comments about this article,
feel free to contact the Elektor editorial team at [email protected].
By the way, a constant-current source performs way better when
the supply voltage is constant (12 V in Figure 6) and the load resis-
tor (where the LED is located) is varied.
Related Products
At higher load resistance values, the current decreases as other-
wise the product of the current and the resistance would be higher > B. Kainka, Basic Electronics for Beginners (Elektor, 2020)
than the supply voltage — which is impossible. However, as long as Book (Paperback) https://elektor.com/19212
the voltage across the load resistor remains well below the supply Ebook: https://elektor.com/19213
voltage, the current through the load is pretty constant.
230372-01
Infrasound Recorder
with the Arduino Pro Mini
A Sample Project from Elektor’s “Arduino & Co.” Book
books
books
books
Arduino & Co
By Robert Sontheimer (Germany)
Arduino & Co
Min
something for everyone
mple 47 ki grees
entire
CNC laser machines and
has even
rsion 3950 ct or at
invented a matching suction
{17.3, 12 -30 to +1 lo
30 degree ohm)
Besides these very practical system:
.8
0.81, 0.65 , 9.59, 7.25, 5.51
projects, the book also provides his “self-changing toilet
paper filter.”
knowledge for you to create
projects based on your
the necessary In his office, he has a magnet
s (steps
and editor have done their best to preclude such instances and are However, it is much more interesting to use an audio editing
happy to help with queries. Contact details are in the Questions program to look at the air pressure and temperature waveforms
or Comments? box. later — especially if the recording ran over several days. The left
channel then shows us the air pressure graph, and the right the
temperature graph.
The BMP180 air pressure sensor delivers a maximum of about
100 temperature and air pressure values per second. So, we could Here, I have simply recorded over almost three days, opened the
generate a stereo audio file (in PCM format with the .wav file exten- finished .wav file with an audio editing program, and then normal-
sion) from this data, over minutes, hours, or days, recording the ized both channels separately, amplified as much as so that the
air pressure on the left channel and the temperature on the right full range is used. Pictured in Figure 1, the upper graph with
channel. We set the regular playback frequency (sampling rate) to the pressure readings still looks a bit thick and frayed due to the
44,100 Hz, for example. This is a common value that’s also used fact that each pixel on the X axis consists of tens of thousands of
for audio CDs and many other things. measurements, and these also contain some noise and thus fluctu-
ate to a certain degree.
This way, the file will be played back later (e.g. on a laptop or with an
audio player) at 441 times the normal speed, and we can hear infra- Figure 2 shows the results after processing. The recording was
sound! With the original sampling rate of 100 Hz when recording, resampled and 4,000 values were averaged into a single value.
we can record all frequencies below 50 Hz. An infrasonic sound at The noise is gone, and we can see the pressure and temperature
10 Hz becomes 4.41 kHz when played back. 1 Hz becomes 441 Hz, curves more clearly.
etc. Theoretically, there are no limits below that.
From the graphs, we can now see a few things: From the pressure
OK, admittedly, the BMP180 is not really suitable as a highly sensi- graph at top, in terms of time, it became somewhat windier in
tive microphone. Although it already detects pressure deviations the second half of the measurement, as many small fluctuations
at low altitude changes, infrasound has to be quite loud to hear it increase there. In a real storm, the fluctuations would be even
against the noise during playback. more extreme.
The temperature curve at the bottom clearly shows the day-night 1h along with discussions below. The complete program is much
rhythm. The almost continuous small spikes are the thermostat longer than can be shown here with the partial listings. The program
switching cycles of the room’s heating. One could count how often and subprograms mentioned below are contained in the software
the thermostat had switched on and off during these three days. companion file released for the book, available for free download
Further, one recognizes two quick downward deflections: The from the Elektor Books support website [1]. On the webpage, go
window was opened for a short time. to the Downloads tab. To be able to follow this extract, please have
13.9.ino ready for reference.
Construction
To implement the project, we need: Listing 1a: Since we combine the air pressure sensor with the SD
card module, we have to include three libraries: the I²C interface for
> 1 Arduino board (16 MHz ATmega328) the air pressure sensor, the SPI interface for the SD card module,
> 1 BMP180 sensor module and the special SD card functions.
> 1 (Micro)SD card module
> 1 push button Then, we define two pins where we can attach a pushbutton to
> wires or jumpers start and stop the recording. Pin 3 is switched to Low and serves
> 1 (Micro)SD card, max. 32 GB as a ground pin for the button. This is very practical, because the
button’s two pins are then right next to each other. Of course, we
Construction is quite simple. In addition to the BMP180 sensor, we could also use the real ground (GND) instead of pin 3.
need to connect the SD card module, as well as the push button for
starting and stopping the recording. Simply follow the connection The other definitions and variables, as well as all program parts
diagram in Figure 3. Soldered wires are always best, but we can from the air pressure sensor and the SD card sketches discussed in
also use jumpers. Then, we need two VCC lines, but the Pro Mini the book, are not shown here. We are now only interested in what
has only one VCC pin. There’s a very simple solution: Since the concerns the recorder, specifically.
BMP180 consumes hardly any power, we can also power it using
one output (e.g., with Pin 9 instead of VCC). Then, we only have Listing 1a
to define the pin as an output in setup() and switch it to High. #include <Wire.h> // library for I2C interface
#include <SPI.h> // library for SPI interface
Sketch for the Infrasound Recorder #include <SD.h> // library for SD card
A good section of the sketch named 13.9.ino written for this project #define record_pin 2 // switch pin to ground for
will be presented in partial listings numbered Listing 1a through // recording
#define low_pin 3 // Set output pin to LOW
// (used as GND for button)
…
Listing 1c Listing 1f: Now, the calculate() function. The actual tempera-
// system time at which the data are available ture and actual pressure are first determined from the measured
unsigned int next_time; values, as long as the pressure has already been measured. I have
abbreviated this now again with “...”, because I’m sure no one wants
long zero_value; // pressure zero line to read these calculations (with the many formula lines from the
long record_value;// pressure value to save datasheet of the BMP180) again.
long zero_temp; // temperature zero line
long temp_value; // temperature value to save Then, we check whether the zero baselines for pressure and tempera-
ture are already defined. If this is not the case, the first measure-
// indicates whether recording is activated ment is now defined as the base value. If, on the other hand, no
boolean must_record = false; measurement has yet been made, we exit the function completely.
// indicates if recording is currently running
boolean is_recording = false; Otherwise, the values are now prepared for recording. For this, we
// indicates whether pushbutton is pressed subtract the pressure zero value from the pressure. If the value
boolean pressed = false; is overridden, it is limited to the permissible range of -32,768 to
// actual file size 32,767. We then do exactly the same with the temperature. Thus,
unsigned long file_size; both values are now ready for recording.
// actual file number
unsigned int file_number = 0;
Listing 1f
// counts how long button is not pressed anymore // calculate temperature (in tenth degree) and
byte state_counter = 0; // pressure (in pascals)
File wave_file; // recording file void calculate() {
Listing 1g: In the recording() function, two conditions are first Usage
checked: whether the recording should run (because it is switched At the beginning of the sketch, we can set three variables:
on and has also not yet reached the maximum file size), and whether
the recording is actually running. These two distinctions now > oversampling should be set to 0 to use the fastest recording
result in four possibilities. In the first case, the recording should frequency of 100 Hz.
be running, but it is not running yet. > audio_rate specifies the later playback frequency. There, we
can also use a value lower than 44,100, so that the time factor
Listing 1g (44,100 / 100 = 441) is not quite so high. Common values are
void recording() { // recording function 8,000, 11,025, 16,000, 22,050, 32,000, 44,100, and 48,000. Not
// if recording should run every player can play other frequencies.
if (must_record && file_size < max_file_size) { > with max_file_size, we define the maximum file size.
// if recording is not running yet 105,840,044 corresponds to a playback time of 10 minutes at
if (!is_recording) { 44,100 Hz, but from a recording time of more than three days.
…
} We should then “normalize” the completed recording, that is,
} increase the volume of the signal so that the full range is used,
} but without exceeding the maximum. Without normalization,
the signal will be too quiet. Of course, we could add a gain factor
when recording, but we don’t know beforehand how much the
Listing 1h: Here, a new recording is started. For this, the file number temperature and air pressure will vary during recording. Normal-
is increased in the do-while loop until this (together with the further ization can be done with audio editing programs in a few clicks. It
text) results in a file name that does not exist yet. A new file is then should be done separately for both channels. With such a program,
opened with the corresponding file name, and a corresponding we can then also view the recording as measurement graphs. The
message is also output serially. In case of an error, another message left channel shows the course of the air pressure during recording,
is output and the process is stopped using an endless loop. while the right channel shows the temperature.
That exhausts the space allocated to program discussion in this Weather Recorder
magazine article. Fortunately, the remainder of the program to run If we change the oversampling value to 3, only a good 32 (instead
the infrasound recorder is well documented just as well as Listings of 100) values per second will be recorded, which is still far more
1a trough 1h shown here. than enough than we need for weather recordings. We could also
So, you see, there are countless possibilities for what you can do,
and the individual book chapters offer — besides the concrete
projects — a lot of information and suggestions, which should
help you in implementing as many of your own ideas as possible.
Unfortunately, we have now reached the end of this article, and I wish
all readers a lot of fun in measuring, controlling, and hacking!
230393-01
Questions or Comments?
Do you have any questions or comments related to this
article? Email the author at [email protected] or Elektor at
[email protected].
Related Products
> Robert Sontheimer, Arduino & Co., Measure, Control,
and Hack, Elektor 2022
Book: https://elektor.com/20243
Ebook: https://elektor.com/20244
WEB LINK
[1] Software Archive for the Book: https://elektor.com/20243
Source: Shutterstock
Cloud-Based
Energy Meter
With ESP32 Module and PZEM-004T Voltage/Current Sensor
A project from Elettronica In consumption, sacrifice certain comforts, and closely monitor their
https://elettronicain.it energy usage to avoid unpleasant surprises on their electricity and
gas bills. The primary motivation for reducing energy consumption is
By Emanuele Signoretta (Italy) the fear of overspending, rather than concerns about climate change.
With the ever-increasing price of To assist those who are conscious of electricity usage, this article
electricity, wise use and savings introduces an energy consumption meter that utilizes an Espressif
ESP32 module and a PZEM-004T voltage/current sensor. The meter
have become a must. With an collects data and sends it to the cloud, specifically the servers of the
ESP32 module and a few other InfluxDB online service.
hardware components, it is The Hardware
possible to create an energy meter For the hardware component of the energy meter, we need an ESP32
that sends our energy data to the Wi-Fi module (Figure 1) and a PZEM-004T sensor (seen encapsulated
InfluxDb Cloud platform via a in its transparent plastic case in Figure 2). We also need a switching
power supply with a 5 V output (if you choose one with a Micro USB
connection on the Wi-Fi network. output, you can use it to power the ESP board and get power for the
PZME-004T from VIN), female-female jumpers for the Arduino, termi-
nals, some electrical cable, and a plastic box [2]. The sensor datasheet
Italy, like many other countries, relies heavily on foreign energy sources can be found at [3], while Figure 3 shows the circuit’s overall wiring
because its own renewable energy production is not enough to meet — we’ll go into more detail on that under Installation below.
national demand. This becomes a bigger problem when external factors
limit the availability of fossil fuel sources, leading to higher prices. The module comprises a circuit for sensing current and voltage,
As a result, people in Italy, just like us, have to cut down on energy housed in a plastic case with an open toroid. It incorporates minimal
+ F
5V POWER SUPPLY
N
̱
230VAC
TOROID
InfluxDB Configuration
Multiple software packages are available for receiving and analyzing
data transmitted by IoT devices. Notable options include Home Assis-
tant, Grafana, Blynk, Thingspeak, and more. In this context, we will
focus on InfluxDB, whose logo is shown in Figure 4.
To get started, please visit link [4] and proceed with registration. You
can choose to sign up using your Microsoft or Google credentials, or
manually fill in the required fields as shown in Figure 5. After completing
the registration process, you will be presented with a screen resem-
bling Figure 6, where you will be prompted to provide various details, Figure 6: Choice of provider and acceptance of terms of service.
To complete the setup, we need to generate an access token for the Now, let’s examine the subsequent code portions, starting with
bucket. To achieve this, access the left-hand sidebar and navigate to Listing 2, which contains the pre-processor section. By using #define
Load Data → API Tokens. REFRESH_TIME 5000, we set the interval (in milliseconds) for uploading
data to the cloud. We then define the device name, serial communi-
In the newly opened window, click on Generate API Token. After select- cation pins, and the desired serial port. Objects related to the Wi-Fi
ing the bucket, enable both read and write permissions, as depicted network and the sensor are instantiated. IP addresses are defined,
in Figure 12. Once the token is generated, copy it and keep it safe, as and if you wish to configure a connection to the access point with a
we will need it in the upcoming steps. static IP, you can adjust the parameters according to your network’s
subnet. Lastly, we define parameters for Wi-Fi connection and InfluxDB
The Sketch Cloud access. Replace these lines of code with the copied snippet
The sketch for our project is a combination of several sketches from and enter the missing data.
the libraries we used. You can download the sketch files from the
GitHub repository [5]. Now, let’s analyze our code, which is divided By using #define WIFI_SSID and #define WIFI_PASSWORD, we specify
into three sections that we will present with corresponding listings. the Wi-Fi network’s SSID and passphrase, respectively.
First, let’s discuss the inclusion of necessary libraries and dependen- Next, we set the parameters for connecting to InfluxDB Cloud. The only
cies, as shown in Listing 1. missing parameter is INFLUXDB_TOKEN, which can be retrieved from the
API key we created earlier. Insert the API key between the quotation
Regarding this, it’s important to note that the WiFiMulti library is marks. With #define TZ_INFO "CET-1CEST,M3.5.0,M10.5.0/3",
utilized for managing Wi-Fi communication between the ESP32 we specify the Central European Time zone for timestamps.
and the access point. The ESPmDNS, WiFiUDP, and ArduinoOTA [6]
To create the client object for connecting to the InfluxDB server, use
the following code:
/*************************
ESP32 initialization
---------------------
Listing 3: setup()
void setup() {
Serial.begin(115200);
// Uncomment in order to reset the internal energy counter
// pzem.resetEnergy()
// Setup wifi
WiFi.mode(WIFI_STA);
//Comment to use DHCP instead of static IP
if (!WiFi.config(local_IP, gateway, subnet, primaryDNS, secondaryDNS)) {
Serial.println("STA Failed to configure");
}
A connection to the AP is then attempted, and, if it fails, an error is Now, let’s move on to Listing 4, which contains the loop() code for
first printed to the serial port, and the board is restarted after a wait our sketch. Using ArduinoOTA.handle(), the ESP32 waits for OTA
of five seconds. to receive any compiled sketches.
The hostname is set with ArduinoOTA.setHostname("ESP32-Energy With EVERY(REFRESH_TIME) { … } the code within the brackets is
Meter"), which will be transmitted via mDNS and displayed on the executed at regular intervals and without using delays. The time inter-
Arduino IDE for loading the OTA sketch. There is commented code for val has been previously defined. Within the EVERY block, the address
restricting OTA sketch loading to users with a username and password. of the PZEM is first read and printed out in serial.
Uncomment these lines of code to add this security feature.
The code within the EVERY(REFRESH_TIME) { … } block is executed
The OTA mode settings are managed with the following code block: at the regular intervals defined earlier, without using delays. Within
this block, the PZEM’s address is read and printed to the serial port.
ArduinoOTA.onStart([]() {
String type; Next, sensor variables are created and initialized using functions from
// … the sensor library. These variables include voltage, current, active power
if (error == OTA_AUTH_ERROR) Serial.println("Auth (in Wh), active energy (in kWh), frequency, and power factor (a ratio
Failed"); between -1 and 1, representing the ratio between active power and
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin apparent power). If any of the variables are not a number, a read error
Failed"); is printed to the serial port. Otherwise, the sensor readings are printed.
else if (error == OTA_CONNECT_ERROR) Serial. After this, the initialized fields and timestamps are cleared, and the
println("Connect Failed"); variables are prepared for uploading to the cloud. Finally, the Wi-Fi
else if (error == OTA_RECEIVE_ERROR) Serial. connection and successful data upload are checked. If the upload
println("Receive Failed"); fails, the last error code is printed to the serial port.
else if (error == OTA_END_ERROR) Serial.println("End
Failed"); Installation
}); We planned to enclose the power supply, ESP32 and the main sensor
ArduinoOTA.begin(); module inside a plastic box, with only the wires for the power supply
and those going to the current sensor toroid going into the board.
The code block handles OTA start, end, sketch loading, and errors If you want to measure the overall energy consumption of your house,
in that order. ArduinoOTA.begin() starts the OTA loading process. the power input of our energy metering system must be connected
as close as possible to the AC line coming out of the house’s electri-
cal panel. Otherwise, as illustrated in Figure 3, it is always possible to
With sensor.addTag(“Device”, DEVICE); a tag is set, which in this measure the energy absorbed by a single electrical appliance of any
case corresponds to the device name. This feature could be useful to type. The hinged opening of the toroid makes it very convenient to clamp
distinguish one or more sensors within a fleet. the electrical cable under measurement down. In the case of three-
core power cables (Live, Neutral and Earth), the outer insulation sleeve
With timeSync(TZ_INFO, “pool.ntp.org”, “time.nis.gov”); must be carefully cut lengthwise (be sure to unplug it first, please!),
ArduinoOTA.handle();
EVERY(REFRESH_TIME) {
// Print the custom address of the PZEM
Serial.print("Custom Address:");
Serial.println(pzem.readAddress(), HEX);
// Read the data from the sensor
float voltage = pzem.voltage();
float current = pzem.current();
float power = pzem.power();
float energy = pzem.energy();
float frequency = pzem.frequency();
float pf = pzem.pf();
// Check if the data is valid
if (isnan(voltage)) {
Serial.println("Error reading voltage");
} else if (isnan(current)) {
Serial.println("Error reading current");
} else if (isnan(power)) {
Serial.println("Error reading power");
} else if (isnan(energy)) {
Serial.println("Error reading energy");
} else if (isnan(frequency)) {
Serial.println("Error reading frequency");
} else if (isnan(pf)) {
Serial.println("Error reading power factor");
} else {
// Print the values to the Serial console
Serial.print("Voltage: "); Serial.print(voltage); Serial.println("V");
Serial.print("Current: "); Serial.print(current); Serial.println("A");
Serial.print("Power: "); Serial.print(power); Serial.println("W");
Serial.print("Energy: "); Serial.print(energy, 3); Serial.println("kWh");
Serial.print("Frequency: "); Serial.print(frequency, 1); Serial.println("Hz");
Serial.print("PF: "); Serial.println(pf);
////UPLOAD DATA
// Clear fields for reusing the point. Tags will remain untouched
sensor.clearFields();
// Store measured value into point
sensor.addField("Tensione", voltage);
sensor.addField("Corrente", current);
sensor.addField("Potenza", power);
sensor.addField("Energia", energy);
sensor.addField("Frequenza", frequency);
sensor.addField("Fattore di potenza", pf);
// Print what are we exactly writing
Serial.print("Writing: ");
Serial.println(sensor.toLineProtocol());
// Check WiFi connection and reconnect if needed
if (wifiMulti.run() != WL_CONNECTED) {
Serial.println("Wifi connection lost");
}
// Write point
if (!client.writePoint(sensor)) {
Serial.print("InfluxDB write failed: ");
Serial.println(client.getLastErrorMessage());
}
}
Serial.println();
}
}
without affecting the insulation of the three inner cables. They will be we assign a name to our dashboard and click on Add Cell. In the new
separated and only the Live wire (normally black or brown) will be screen that will appear (Figure 14), we are going to select which param-
placed inside the measuring toroid. eters to include in each of the charts that make up the dashboard.
We select, in order, the bucket, the measurements, the device, and
To install the energy meter, simply follow the diagram already shown finally the values to be displayed. You can choose which graphics to
at the beginning of this article, in Figure 3. use for the values: heatmap, gauge, simple graph, table, etc., and also
which scaling values to utilize. We customize the cells to our liking
In particular, you must connect two wires in parallel to the input of and repeat the procedure for each value we wish to display until we
the power supply and between pins N and L of the PZEM-004T. obtain a result like the one visible in Figure 15, which illustrates our
Remember to always be very careful because you are working complete dashboard.
on the 230 V(AC) mains wires!
Next, we release the toroid safety catch and run one of the two wires
going to the electrical system, then connect the toroid wires to the CT
pins of the sensor. Additionally, we connect the sensor’s main module
to the ESP32, according to Table 1. To power the ESP, you can use a Table 1: Connections between the Energy Meter and the
power supply with a Micro USB output, taking the 5 V for the sensor ESP32 modules.
from VIN and GND. Once the sketch is loaded, we can close all the
electronics in the box and start the system. PZEM-004 pin ESP32 pin
VCC V5
Startup and Dashboard Setup GND GND
Once the board has started up, we go back to the InfluxDB website and,
RX 26
from our dashboard, we go to Dashboards → Create new dashboard.
Doing so will bring up a screen like the one shown in Figure 13, where TX 27
Related Products
> ESP32-C3-DevKitM-1
https://elektor.com/20324
WEB LINKS
[1] ESP32 board: https://futuranet.it/prodotto/esp32-scheda-di-sviluppo-32-gpio-con-wifi-e-bluetooth
[2] Plastic box: https://futuranet.it/prodotto/contenitore-plastico-ermetico-546x784x1182-mm
[3] PZEM-004 Datasheet on Github: https://bit.ly/3qTZdHf
[4] InfluxDB Account: https://cloud2.influxdata.com/signup
[5] The project’s GitHub repository: http://github.com/signorettae/ESP32-EnergyMeter
[6] ArduinoOTA Library: https://github.com/jandrassy/ArduinoOTA
[7] Arduino library for the Updated PZEM-004T: http://github.com/mandulaj/PZEM-004T-v30
A Bare-Metal
Programming Guide (Part 2)
Accurate Timing, the UART, and Debugging
By Sergey Lyubka (Ireland) The SysTick interrupt index in the vector table is 15, so we need
to set it. Upon boot, our STMicroelectronics Nucleo-F429ZI board
In the first part of the guide, runs at 16 MHz. We can configure the SysTick counter to trigger
we learned how to access an interrupt every millisecond.
microcontroller registers to control First, let’s define a SysTick peripheral. We know four registers, and,
pins. Additionally, we created from the Arm Reference Manual, we see that the SysTick address
minimal firmware and our first is 0xe000e010. So:
With a 16 MHz clock, we initialize the SysTick counter to trigger cmp r1, r3 // compare
an interrupt every 16,000 cycles: The SYSTICK->VAL initial value bcc.n 200000d2
is 15,999, then it decrements every cycle until it reaches 0, when bx lr
an interrupt is triggered. The firmware code execution gets inter-
rupted, and the SysTick_Handler() function is called to increment If there is no volatile, the delay() function will loop forever
the s_tick variable. Figure 1 shows how it looks on a timescale. and never return. That’s because it caches (optimizes) the value
of s_ticks in a register and never updates it. A compiler does that
The volatile qualifier is required here because s_ticks is modified because it doesn’t know that s_ticks will be updated elsewhere by
by the interrupt handler. volatile prevents the compiler from the interrupt handler! The code compiled using volatile, on the
optimizing/caching the s_ticks value in a CPU register; instead, other hand, loads the s_ticks value on each iteration. So, the rule
generated code always accesses memory. That is why the volatile of thumb: Values in memory that get updated by interrupt
qualifier is present in the peripheral struct definitions, too. Since handlers or by the hardware must be declared as volatile.
this is important to understand, let’s demonstrate that with a simple
function: Arduino’s delay(). Let us use our s_ticks variable: Now we should add the SysTick_Handler() interrupt handler to
the vector table:
// This function waits "ms" milliseconds
void delay(unsigned ms) { __attribute__((section(“.vectors”)))
// Time in the future when we need to stop void (*tab[16 + 91])(void) = {
uint32_t until = s_ticks + ms; / _estack, _reset, 0, 0, 0, 0, 0, 0, 0, 0, 0,
while (s_ticks < until) (void) 0; // Loop until then 0, 0, 0, 0, SysTick_Handler
} };
Now let’s compile this code both with and without the volatile Now we have a precise millisecond clock! Let’s create a helper
qualifier for s_ticks and compare the compiled assembly language function for arbitrary periodic timers:
code:
// t: expiration time, prd: period,
// NO VOLATILE: uint32_t s_ticks; // now: current time. Return true if expired
ldr r3, [pc, #8] // cache s_ticks bool timer_expired(uint32_t *t, uint32_t prd,
ldr r3, [r3, #0] // in r3 uint32_t now) {
adds r0, r3, r0 // r0 = r3 + ms if (now + prd < *t) *t = 0;
cmp r3, r0 // ALWAYS FALSE // Time wrapped? Reset timer
bcc.n 200000d2 if (*t == 0) *t = now + prd;
bx lr // First poll? Set expiration
if (*t > now) return false;
// VOLATILE: volatile uint32_t s_ticks; // Not expired yet,return
ldr r2, [pc, #12] *t = (now - *t) > prd ? now + prd : *t + prd;
ldr r3, [r2, #0] // r3 = s_ticks // Next expiration time
adds r3, r3, r0 // r3 = r3 + ms return true; // Expired, return true
ldr r1, [r2, #0] // RELOAD: r1 = s_ticks }
Now we’re ready to update our main loop and use a precise timer > Set alternate function pin mode for RX and TX pins. There can
for LED blinking. For example, let’s use a 250-millisecond blink- be several alternate functions (AF) for any given pin, depend-
ing interval: ing on the peripheral that is used. The AF list can be found in
the STM32F429ZI datasheet, Table 12 [7].
// Declare timer and 500ms period > Set the baud rate (receive/transmit clock frequency) via the
uint32_t timer, period = 500; BRR register.
for (;;) { > Enable the peripheral receive and transmit via the CR1
if (timer_expired(&timer, period, s_ticks)) { register.
static bool on; // This block is executed
gpio_write(led, on); // Every "period" milliseconds We already know how to set a GPIO pin to a specific mode. If a pin
on = !on; // Toggle LED state is in the AF mode, we also need to specify the “function number,”
} i.e. which exact peripheral takes control. This can be done via the
// Here we could perform other activities! Alternate Function Register, AFR, of the GPIO peripheral. Reading
} the AFR register description in the Reference Manual, we see that
the AF number occupies four bits, so the whole setup for 16 pins
Note that by using SysTick with a helper timer_expired() function, occupies two registers.
we made our main loop (also called the “superloop”) non-blocking.
That means that inside that loop we can perform many actions — static inline void gpio_set_af(uint16_t pin,
for example, have different timers with different periods, and they uint8_t af_num) {
all will be triggered on time. struct gpio *gpio = GPIO(PINBANK(pin)); // GPIO bank
int n = PINNO(pin); // Pin number
You can find the complete project source code in the step-2-sys- gpio->AFR[n >> 3] &= ~(15UL << ((n & 7) * 4));
tick folder [5]. gpio->AFR[n >> 3] |= ((uint32_t) af_num)
<< ((n & 7) * 4);
Add UART Debug Output }
Now it’s time to add a human-readable diagnostics to our firmware.
One of the MCU peripherals is a serial UART interface. Looking at In order to completely hide register-specific code from the GPIO
the memory map in section 2.3 of the microcontroller manual, we API, let’s move the GPIO clock init to the gpio_set_mode() function:
see that there are several UART/USART controllers — i.e. pieces of
circuitry inside the MCU that, properly configured, can exchange static inline void
data via certain pins. A minimal UART setup uses two pins: RX gpio_set_mode(uint16_t pin, uint8_t mode) {
(receive) and TX (transmit). struct gpio *gpio = GPIO(PINBANK(pin)); // GPIO bank
int n = PINNO(pin); // Pin number
In section 6.9 of the Nucleo board manual [6], we see that one of // Enable GPIO clock
the controllers, USART3, uses pins PD8 (TX) and PD9 (RX) and is RCC->AHB1ENR |= BIT(PINBANK(pin));
connected to the on-board ST-LINK debugger. That means that if ...
we configure USART3 and output data via the PD9 pin, we can see
it on our workstation via the ST-LINK USB connection. Now we’re ready to create a UART initialization API function —
see Listing 1.
So, let us create a handy API for the UART, like we did for GPIO.
Section 30.6 [4] summarizes the UART registers, and here is our Finally, we need functions for reading and writing to the UART.
corresponding UART struct: Reference Manual [4] section 30.6.1 tells us that the Status Regis-
ter, SR, shows whether data is ready:
struct uart {
volatile uint32_t SR, DR, BRR, CR1, CR2, CR3, GTPR; static inline int uart_read_ready(struct uart *uart) {
}; // If RXNE bit is set, data is ready
#define UART1 ((struct uart *) 0x40011000) return uart->SR & BIT(5);
#define UART2 ((struct uart *) 0x40004400) }
#define UART3 ((struct uart *) 0x40004800)
The data byte itself can be fetched from the Data Register, DR:
To configure a UART, we need to:
static inline uint8_t uart_read_byte(struct uart *uart) {
> Enable the UART clock by setting the appropriate bit in return (uint8_t) (uart->DR & 255);
RCC->APB2ENR. }
gpio_set_mode(tx, GPIO_MODE_AF);
gpio_set_af(tx, af);
gpio_set_mode(rx, GPIO_MODE_AF);
gpio_set_af(rx, af);
uart->CR1 = 0; // Disable this UART
uart->BRR = FREQ / baud; // FREQ is a UART bus frequency
uart->CR1 |= BIT(13) | BIT(2) | BIT(3); // Set UE, RE, TE
}
Transmitting a single byte can also be done via the Data register. Rebuild, reflash, and attach a terminal program to the ST-LINK port.
After setting a byte to write, we need to wait for the transmission On my Mac workstation, I use cu. It also can be used on Linux. In
to end, which will be indicated via Bit 7 in the Status register: Windows, using the PuTTY [8] utility works well. Run a terminal
and observe the messages:
static inline void uart_write_byte(struct uart *uart,
uint8_t byte) { $ cu -l /dev/cu.YOUR_SERIAL_PORT -s 115200
uart->DR = byte; hi
while ((uart->SR & BIT(7)) == 0) spin(1); hi
}
The complete project source code can be found in the step-3-uart
And writing a buffer: folder [9].
int main(void) {
uint16_t led = PIN(’B’, 7); // Blue LED
systick_init(16000000 / 1000); // Tick every 1 ms
gpio_set_mode(led, GPIO_MODE_OUTPUT); // Set blue LED to output mode
uart_init(UART3, 115200); // Initialise UART
uint32_t timer = 0, period = 500; // Declare timer and 500ms period
for (;;) {
if (timer_expired(&timer, period, s_ticks)) {
static bool on; // This block is executed
gpio_write(led, on); // Every ’period’ milliseconds
on = !on; // Toggle LED state
uart_write_buf(UART3, "hi\r\n", 4); // Write message
}
// Here we could perform other activities!
}
return 0;
}
For example: Great, now let’s retarget printf() to UART3. In the empty syscalls.c,
copy/paste the following code:
> fopen() eventually calls _open()
> fread() eventually calls a low level _read() #include "mcu.h"
> fwrite(), fprintf(), printf() eventually call a low level int _write(int fd, char *ptr, int len) {
_write() (void) fd, (void) ptr, (void) len;
> malloc() eventually calls _sbrk(), and so on. if (fd == 1) uart_write_buf(UART3, ptr, (size_t) len);
return -1;
Thus, by modifying a _write() syscall, we can redirect printf() }
to whatever we want. That mechanism is called “IO retargeting.”
Here, we say: If the file descriptor that we’re writing to, fd, is 1 (which
Note: The STM32 Cube IDE also uses ARM GCC with newlib, that’s is a standard output descriptor), then write the buffer to UART3.
why Cube projects typically include a syscalls.c file. Other toolchains, Otherwise, ignore. This is the essence of retargeting!
like TI’s CCS and Keil’s CC might use a different C library with a
slightly different retargeting mechanism. We use newlib, so let’s Rebuilding this firmware results in a bunch of linker errors, as
modify _write() syscall to print to UART3. shown in Listing 3.
Before that, let’s organize our source code in the following way: Since we’ve used a newlib stdio function, we need to supply newlib
with the rest of the syscalls. Let’s add just a simple stub that does
> Move all API definitions to mcu.h nothing (Listing 4).
> Move startup code to startup.c
> Create an empty file syscalls.c for newlib syscalls Now, a rebuild gives no errors. Last step: replace the uart_write_
> Modify the Makefile to add syscalls.c and startup.c to the build buf() call in the main() function with printf() call that prints
something useful, e.g. an LED status and the current value of
After moving all API definitions to mcu.h, our main.c file becomes systick:
quite compact. Note that it does not have any mention of the
low-level registers, just high-level API functions that are easy to // Write message
understand — see Listing 2. printf("LED: %d, tick: %lu\r\n", on, s_ticks);
> Choose our firmware.elf file (Figure 4). 1. We need to clock GPIOB first. Find Peripherals → RCC → AHB1ENR,
> Leave the defaults on the next screen, click Finish, and we’ve and enable the GPIOBEN bit — set it to 1 (Figure 8).
got our debugger loaded (note the mcu.h source code is picked 2. Find Peripherals → GPIO → GPIOB → MODER, set MODER0 to 1
up), see Figure 5. (output) (Figure 9).
> Click the green button to download, run the firmware, and 3. Find Peripherals → GPIO → GPIOB → ODR, set ODR0 to 1 (on)
we’re stopped here (Figure 6). (Figure 10).
Now we can single-step through code, set breakpoints, and do Now, a green LED should be on! Happy debugging!
the usual debugging stuff. One thing that should be noted is the
handy Ozone Peripherals view (Figure 7). Using it, we can directly In the third part of this series, we will implement a web server.
examine or set the state of the peripherals. For example, let’s turn Furthermore, we will show how a program can be tested automat-
on a green on-board LED (PB0): ically, and much more. Stay tuned!
220665-B-01
Figure 6: After we run the firmware, it halts on the SYSTICK->LOAD = ticks - 1; line.
Questions or Comments?
Do you have technical questions or comments about this article?
Email the author at [email protected] or contact Elektor
Figure 8: Enabling the running of the clock on Port B by setting the value of at [email protected].
GPIOBEN to 1.
Related Products
> Dogan Ibrahim, Nucleo Boards Programming with the
STM32CubeIDE (Elektor 2020)
https://elektor.com/19530
Figure 9: Set MODER0 to 1 (and thus, selecting output) in the GPIO
peripherals.
> Dogan Ibrahim, Programming with STM32 Nucleo Boards
(Elektor 2015)
https://elektor.com/18585
WEB LINKS
[1] GitHub Repository for this article: https://github.com/cpq/bare-metal-programming-guide
[2] Sergey Lyubka, “A Bare-Metal Programming Guide (Part 1),” Elektor 9-10/2023: https://elektormagazine.com/220665-01
[3] Arm v7-M Architecture Reference Manual: https://developer.arm.com/documentation/ddi0403/ee
[4] Reference Manual RM0090 for STM32F429: https://bit.ly/3neE7S7
[5] Step 2 SysTick folder: https://github.com/cpq/bare-metal-programming-guide/tree/main/steps/step-2-systick
[6] Nucleo-144 Board User Manual (UM1974): https://bit.ly/3oIBXKZ
[7] STM32F429ZI Datasheet: https://st.com/resource/en/datasheet/stm32f429zi.pdf
[8] PuTTY: https://putty.org
[9] Step 3 UART folder: https://github.com/cpq/bare-metal-programming-guide/tree/main/steps/step-3-uart
[10] newlib C library : https://sourceware.org/newlib
[11] Step 4 printf Folder: https://github.com/cpq/bare-metal-programming-guide/tree/main/steps/step-4-printf
[12] Ozone — The J-Link Debugger and Performance Analyzer:
https://segger.com/products/development-tools/ozone-j-link-debugger
[13] Converting ST-LINK On-Board Into a J-Link:
https://segger.com/products/debug-probes/j-link/models/other-j-links/st-link-on-board
Price: €23.95
Member Price: €21.56
www.elektor.com/20562
Price: €34.95
Member Price: €31.46
www.elektor.com/20553
Price: €799.00
Price: €104.95 Member Price: €719.10
www.elektor.com/20556 www.elektor.com/20530
www.elektor.com/20520 www.elektor.com/20526
Traditionally, the last page of Elektor The Hexadoku puzzle employs digits in the hexadecimal range 0
through F. In the diagram composed of 16×16 boxes, enter digits
Magazine is reserved for our puzzle with an such that all hexadecimal digits (that’s 0–9 and A–F) occur once
electronics slant: Welcome to Hexadoku! only in each row, once in each column, and in each of the 4×4 boxes
Find the solution in the gray boxes, submit it (marked by the thicker black lines). A number of clues are given in
the puzzle, and these determine the starting situation.
to us by email, and you automatically enter
the prize draw for one of five Elektor Store Correct entries received enter a prize draw. All you need to do is
vouchers. send us the digits in the gray boxes.
PRIZE WINNERS
The solution to the Hexadoku in our July/August edition is: 23BDF.
Solutions submitted to us before August 15th were entered in a prize draw for 5 Elektor Store vouchers.
The winners are posted at elektormagazine.com/hexadoku.
Congratulations, everyone!
The competition is not open to employees of Elektor International Media, its subsidiaries, licensees and/or associated publishing houses.
[email protected]
lektor September & October 2023 123
Imagine if the Wright brothers had
partnered with Mouser
mouser.co.uk/new
+44 (0) 1494-427500