100% found this document useful (1 vote)
525 views

Elektor 09 10 2023

Uploaded by

aluisio xavier
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
525 views

Elektor 09 10 2023

Uploaded by

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

£9.95 | €10.95 | $12.

95

524 SEPTEMBER & OCTOBER 2023


ELEKTORMAGAZINE.COM
S

*
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

Elektor Magazine is published 8 times a year by


Elektor International Media b.v.
PO Box 11, 6114 ZG Susteren, The Netherlands
Phone: +31 46 4389444
www.elektor.com | www.elektormagazine.com From Simple to Modern
For all your questions
[email protected] Our future will largely be wireless: At present, various companies and universities are already
researching 6G, which is expected to achieve data rates of up to 400 Gb/s and operate at
Become a Member frequencies up to 3 THz, and all this is aimed to start in around 2030. The spectrum of wireless
www.elektormagazine.com/membership applications is already vast today. It ranges from position-determination to energy-saving
long-distance data transmission to using a smartphone as a remote control. In any case, we
Advertising & Sponsoring
had so many articles and ideas for this magazine issue that it was impossible to fit everything
Büsra Kas
Tel. +49 (0)241 95509178
into one edition. The diversity of electronic topics, for which we are particularly appreciated
[email protected] by our varied-interest readers, would otherwise have been compromised. Some of our wireless
www.elektormagazine.com/advertising articles — including an interesting report on centimeter-accurate position determination at
maker-friendly costs — can be found in the upcoming issues.
Cover Design
Midjourney, created by Harmen Heida And for those particularly interested in specific areas such as “Power Electronics,” “Wireless,”
“Measurement and Testing,” or “Electronics Production,” we will soon be offering special theme
Copyright Notice
© Elektor International Media b.v. 2023
pages on our website, elektormagazine.com. There, you will find not only articles from our
magazines but also exclusive online content. Background reports and (video) tutorials for
The circuits described in this magazine are beginners are complemented by additional projects from our global community.
for domestic and educational use only. All
drawings, photographs, printed circuit board Perhaps I will also introduce my very personal wireless project there, a wirelessly controlled
layouts, programmed integrated circuits, speaker system for outdoor use, powered by individual lithium batteries. Although everything
digital data carriers, and article texts published
is (still) composed of purchased components, considerable development work has already gone
in our books and magazines (other than
third-party advertisements) are copyright
into it. Now, you might want to know which hypermodern wireless standard I use? Well, it’s
Elektor International Media b.v. and may not good old FM radio, but at 863…865 MHz, which is also used at “Silent Disco” parties. When it
be reproduced or transmitted in any form comes to straightforward setup and the lowest latencies, simplicity is still key!
or by any means, including photocopying,
scanning and recording, in whole or in part
without prior written permission from the
Publisher. Such written permission must also
be obtained before any part of this publication
is stored in a retrieval system of any nature.
Patent protection may exist in respect of
circuits, devices, components etc. described
in this magazine. The Publisher does not
accept responsibility for failing to identify such
patent(s) or other protection. The Publisher Submit to Elektor! ElektorLabs
disclaims any responsibility for the safe and Your electronics expertise is welcome! Ideas & Projects
proper function of reader-assembled projects
Want to submit an article proposal, an The Elektor Labs platform is open to
based upon or from schematics, descriptions
electronics tutorial on video, or an idea everyone. Post electronics ideas and
or information published in or in relation with
Elektor magazine.
for a book? Check out Elektor’s Author’s projects, discuss technical challenges and
Guide and Submissions page: collaborate with others.
Print www.elektormagazine.com/submissions www.elektormagazine.com/labs
Senefelder Misset, Mercuriusstraat 35,
7006 RK Doetinchem, The Netherlands

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]

lektor September & October 2023 3


THIS EDITION
Volume 49, No. 524
September & October 2023

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

122 Hexadoku FOCUS


The Original Elektorized Sudoku 67 Wireless Communication in IoT Systems — Using Arduino
MKR Modules
The Right Board for Wi-Fi, LoRa, and Many More Standards
70 AC Losses in Magnetic Components
Avoid Hot Inductors!
73 Measurement for Optimal Cloud Deployment

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

Projects Next Edition


FOCUS
Elektor Magazine November & December 2023
6 Raspberry Pi Pico as Spectrum Analyzer
Our next edition covers Prototyping and Production, so you’ll have
FFTs on a Low-Cost Hardware Basis
all the information you need to get that project idea from concept to
18 ±40 V Linear Voltage Regulator schematic to PCB to product!
An Alternative Power Supply for the Fortissimo-100 Power
From the contents:
Amplifier… and Others!
> PCB Services
FOCUS > AI Tools for Developers
24 MCU Wireless Communication Made Flexible > BLE in Practice
EEPROM Opens Networking Prospects for Wireless MCUs > Low-Cost GNSS RTK Systems
42 Adjustable Current Sink with Integrated Clock Generator
> DIY Heating Plate
Test Power Supplies, Voltage Converters, and Batteries
> ChatGPT Improves Firmware
> Open-Source Tools
56 Motor Driver Breakout Board > CNCing a Simple Enclosure
A BoB for a 5 A DC Motor Driver with a 3×3 mm Size > Introduction to KiCad 7
FOCUS
> Solar Xmas Garland
82 PIC O’Clock — In Touch with Time
Designing an SDR Time Signal Receiver And much more!
97 Infrasound Recorder with the Arduino Pro Mini
Elektor Magazine November / December 2023 edition will be
A Sample Project from Elektor’s “Arduino & Co.” Book
published around November 15th, 2023. Arrival of printed copies
FOCUS with Elektor Gold Members is subject to transport. Contents and
102 Cloud-Based Energy Meter article titles subject to change.
With ESP32 Module and PZEM-004T Voltage/Current Sensor

FOCUS ON

Wireless &
Communication
lektor September & October 2023 5
PROJECT

Raspberry Pi Pico
as Spectrum Analyzer
FFTs on a Low-Cost Hardware Basis

By Prof. Dr. Martin Ossmann (Germany)


When using the Raspberry Pi RP2040 microcontroller’s integrated
This article shows how to build a ADC, analog signals are sampled with up to 500 kS/s and resolved
software-based spectrum analyzer at 12 bits. In the simplest case, a PC is used for the actual frequency
analysis and display of the results. As the first expansion stage,
with a simple Raspberry Pi Pico. an LCD can be connected, which already gives you a stand-alone
A basic version with a 12-bit analyzer. With an external ADC, up to 50 MS/s can be achieved in
resolution and a sampling rate the next step, making the analyzer suitable for signals up to 25 MHz.

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

signal to calculate N spectrum values Zk (with k = 0 to N-1). The


GP2 3V3_EN
5 36
BOOTSEL

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

So only the first N/2 values are relevant. This is in accordance


Figure 1: Minimal wiring of the Pico board for data transfer to the PC. with the sampling theorem, according to which unique values are

6 September & October 2023 www.elektormagazine.com


Table 1: Computing times for different N.

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

fast Fourier transform (FFT) instead of the DFT, since it calculates


Figure 2: My breadboard design of the circuit from Figure 1. the same values much faster. On the Pico board, the computing
time is TFFT ≈ 4 N log2(N). Table 1 shows the computing times for
some practicable values of N.
obtained only up to half the sampling rate. Consequently, only the
first N/2 spectral values are used in the following. The calculated For a simple spectrum analysis, N = 1024 is often used. The calcula-
spectrum is that of the input signal S continued with the period N. tion time of the DFT would still be acceptable here with approx. 9 s,
In order to understand why the DFT actually performs a spectral but the FFT is much faster with 40 ms. Occasionally, N = 16,384 is
analysis, we first consider how the input signal sn = cos(2 π m n / N) used, too, for which the DFT would already take a good 40 minutes
is transformed with, for example, m = 5 and N = 16. This input signal — unacceptably slow. The FFT, however, needs less than one second
is a cosine oscillation with the frequency f = fs m / N. for this! N is therefore always selected as a power of two in favor
of the FFT.
The resulting transformed values are Zm = Z5 = N/2 = 8, and the other
values, Zk, are all zero. Thus, an oscillation of frequency m becomes RMS Value and dBm
noticeable exactly in the mth transformed value. If, instead of the In communications engineering, quantities are often specified
cosine signal, a sine signal would be transformed, the imaginary as effective values. Since for this the time-dependent quantity is
part of Zm would not be zero. But what happens when we trans- squared, averaged and then the root is taken, the term root mean
form a signal that is composed of oscillations of different frequen- square (RMS) has become common for this. For a discrete, periodic
cies? This is simple, too: The DFT is a linear transformation, which signal with the period length N as with our DFT signals, the RMS
means that the DFT of a sum is also equal to the sum of the DFTs value is calculated as follows:
of the individual signals. The resulting formula is

DFT(u Un + v Vn) = u DFT(Un) + v DFT(Vn)

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

lektor September & October 2023 7


P0 = 1 mW is common. We then get PdBm = 10 log10(P / 1 mW). If we
want to specify voltages U in dBm, we use the power P at a resistor
of R = 50 Ω, at which the voltage URMS is applied. Since the power
dissipated by the resistor is P = U2 / R, we get UdBm = 10 log10(U2R
Figure 3: Poor spectral representation at half-integer frequency. MS / (R 1 mW).

For the spectrum analyzer described here, the Y axis is scaled in


dBm, the usual logarithmic representation for spectrum analyz-
ers, but note: In audio engineering, dBm often refers to a resis-
tance of 600 Ω.

Signals and Windows


So far, we have considered input signals that fit exactly
into a window of N values. The frequency m of the signal
sn = A cos(2 π m n / N) was therefore an integer. Figure 3 shows
Figure 4: At sample N, an amplitude jump occurs if the signal is continued the spectrum at m = 5.5 und N = 256.
periodically.
Actually, one would expect a line-like spectrum because the signal
contains only one frequency. Instead, you get a spectrum that falls
off slowly on both sides of the maximum values. This is, of course,
useless for a spectrum analyzer. The reason is that the periodically
continued signal (period length N) contains a jump at the edges.
This can be seen clearly in the amplitude/time diagram of two
periods in Figure 4: At sample N, the signal jumps from +1 V to
-1 V. This jump generates spectrally high-frequency components
beyond the signal frequency. To avoid these effects, one applies
the window technique, which in principle is equivalent to a super-
imposed envelope. This involves multiplying the input signal by
a window function, which gently reduces it to amplitude 0 at the
Figure 5: Blackman window function. window boundaries, but otherwise does not change the signal
much. Figure 5 shows the window function used.

Figure 6 shows two periods of the signal multiplied by the window


function. It can be seen clearly how the signal is amplitude-modu-
lated so that it does not jump at the period boundaries (0, N, 2N…)
but runs continuously. There are different window functions in use,
each having different advantages and disadvantages. The follow-
ing C listing shows how the Blackman window (three-term) used
here is calculated:

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));
}

The window function is composed of two cosine functions. After


applying the window, the FFT yields the spectrum of Figure 7.
The spectral maximum is four bins wide around m = 5.5 and then
drops significantly. With larger values for N, the spectral broad-
ening is well acceptable and good, line-like spectra are obtained.
However, we must consider that the window function reduces
Figure 7: Spectrum after applying the window function. the signal amplitude. As window factor, we can approximate by

8 September & October 2023 www.elektormagazine.com


using the arithmetic mean value of the window function values,
as in the following listing.

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 ;
}

To compensate for the amplitude reduction, we divide the spectrum


by the window factor after calculating the FFT. When using a
window function, Parseval’s identity no longer applies.

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.

When analyzing signals with noise components, the individual


spectra are often very ragged. This can be improved by averaging Figure 10: Amplitude over time of the DCF77 signal.
over successive spectra. This procedure is activated by the analyzer
software’s “MEAN” option, which, by the way, can be downloaded
free of charge from the Elektor website for this article at [2]. The The thin white line is a single spectrum. Since no message is
spectrum of the DCF77 time signal transmitter can be used to currently being sent, only the peak at 128.93 kHz is visible. The
see how beneficial averaging is. Here, the sampling frequency is MAXHOLD spectrum is represented by the thicker green curve.
250 kHz, and N is 16,384. Figure 8 shows the resulting spectrum The two peaks at 129.1 kHz ±170 Hz (at the dotted vertical lines)
in the range of ±5 kHz around the center frequency of 77.5 kHz. are clearly visible. To obtain such a finely resolved spectrum, many
samples are required with N = 16,384. The sample rate is 500 kHz
The thin white line shows a single spectrum that is clearly noisy. and the resolution, accordingly, is Δ = 500 kHz / 16,384 ≈ 30.5 Hz.
The averaging (thick green curve) clearly shows that DCF77 has Thus, the two spectral lines are just 340 Hz / 30.5 Hz ≈ 11 frequency
a noise spectrum. This is because DCF77 transmits the data with samples away from each other.
pseudo-random noise at a bit rate of 77.5 kHz / 120 ≈ 645.8 Hz,
in addition to amplitude modulation (very narrow-band). The Time Domain (Oscilloscope Function)
bandwidth of ±645.8 Hz is represented by the two vertical lines. Of course, the signal in the time domain is also informative, if only
to control how far the ADC acquisition range is utilized. The software
Next, the spectrum of the EFR transmitter (129.1 kHz) is analyzed. can do this, too, by simply displaying the sampled signal. Figure 10
EFR transmits RTTY data with a shift of ±170 Hz and a data rate of shows a kind of oscillogram of the DCF77 signal at 77.5 kHz.
200 Bd. Thus, two spectral lines should be seen in the spectrum
at 128.93 kHz and 129.27 kHz. However, since only short messages Since the carrier drops occurring every second are of particular
are sent with long pauses between them, the frequency of +170 Hz interest here, it is advisable to select a lower sampling rate and a
occurs only rarely and is therefore difficult to detect. For this higher number of samples. For the representation in Figure 10,
purpose, the software offers the MAXHOLD function, where the fs = 4 kHz and N = 16,384 were chosen. The time window thus has a
maximum of the spectra is calculated over many spectra. That way, size of Ts = N/fs ≈ 4 s, resulting in four carrier drops in Figure 10. The
the spectral components occurring briefly at 129.27 kHz show up 77.5 kHz signal is heavily undersampled, but this is not a problem,
more prominently (see Figure 9). since only the amplitude is relevant here.

lektor September & October 2023 9


+2V5
+2V5

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.

10 September & October 2023 www.elektormagazine.com


after all. Since each sample has the absolute value A, we get the
simple equation RMSn = A. In the test setup, A = 750 mV applies.
Figure 14 shows an example of this signal, and Figure 15 shows
the associated spectrum. The red thin line is a single spectrum. Figure 14: Binary noise as a time-domain signal with an amplitude of
It is very jagged because it is only a single function specimen of ±750 mV.
the spectrum. The thick green line is the result of averaging over
many spectra (MEAN function), and makes it more obvious that
this is white noise at a certain level.

If we look at noise spectra with different signal lengths N, we can see


that the displayed level also depends on N. The following relation-
ship exists between the RMS value, the displayed level, and N: For
a large N, the following applies: RMSs ≈ RMSn. Due to Parseval’s
identity (see above), the following also applies:

Figure 15: Spectrum of the binary noise in Figure 14.

Now the energy in

will be distributed evenly over wk. For simplicity, it is assumed that


all wk are equal in size and equal to w. Putting all this together, we
get: w2 = 4 RMS2n / N. Here, w is exactly the sought strength of the
noise signal in the spectrum. In Figure 15, this level can be seen
as a thick purple line. It is actually quite a good prediction of the
real noise level. It also becomes clear why this level decreases with
larger N: It is because the energy of the noise is distributed over
more spectral lines. Figure 16: Spectrum of the noise at a bit rate of 25 kHz.

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.

The thin red line again shows a single-specimen function. The


averaged spectrum is shown in green. The first zero point of
the spectrum is at 25 kHz. The spectrum is proportional to
H(f) = si(π f / fN); where si(x) = sin(x) / x is what is known as the
gap function. Simplifying, one can calculate the level around 0 as
follows: The bandwidth is approx. fBW = 12,5 kHz, which is equiva-
lent to kBW = N fBW /fs = 25 spectral lines.
Figure 17: Spectrum of a sinusoidal signal with 48,828 kHz at a sampling
If the spectrum has a constant bandwidth of w, the equation rate of 500 kHz.
RMS2w = 2 kBW w2 / N is obtained for the RMS values by summing
the spectral lines within the bandwidth. The factor of 2 is necessary
because the FFT provides a symmetrical spectrum with the spectral corresponds exactly to the 100th spectral line. Figure 17 shows
lines N - kBW to N. Using Parseval’s identity, spectral power w is the resultant spectrum.
calculated as follows: w2 = 2 RMS2n / kBW. It is shown in Figure 16 by
the thick purple line and matches the current spectrum quite well. The spectral line at fs can be seen well and also has the correct size.
At 2 fs, we can see the first harmonic caused by the signal genera-
The next example is somewhat more practical: The ADC is tor with a level of approx. 45 dB below the signal. Numerous small
now offered the signal of a sine generator with an amplitude of spectral lines can also be seen, since the components are not ideal
3 VSS (approx. 14 dBm). The signal frequency of fs = 48.828 kHz and have small nonlinearities, for example. The noise level is also

lektor September & October 2023 11


+1V6

R7 IC1 = OPA2350 +1V6

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

Figure 19: Analyzer consisting of a Pico board with LCD and a 1 MΩ


13 28
GND GND R3
8 C2 14 27 C1
preamplifier, showing a VHF multiplex signal.
GP10 GP21
10k

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

12 September & October 2023 www.elektormagazine.com


+5V
Raspberry Pi PICO
1 USB 40
GP0 VBUS
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
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

appears. At 38 kHz, the spectrum of the stereo difference signal 11 12 13 14 15 16 9 10 17 18 19 20

(L - R) is visible. At 57 kHz, the spectrum of the RDS signal is visible, J2 J1

which consists of two sidebands around 57 kHz.

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

ADC, up to 53 MS/s is possible. For the spectra, you need a lot of


computing power and therefore some tricks to achieve this high
230078-024
+5V

sampling rate. Conveniently, the ADS807E provides a built-in refer-


ence voltage. The ADC is connected to the Pico Board as shown Figure 21: Parallel connection of a 3.5″ 480×320-pixel LCD to the Pico
in Figure 22. board.

Due to the parallel connection, many GPIO


pins are occupied, so you unfortunately can’t +3V3 +5V

connect the LCD at the same time. For this RS232 R2 R1

reason, the ADS807 gets a second Pico board. 115200 Bd


2k2

2k2

1
During the first experiments with it, the data 6

is processed and displayed using the PC as 2


7 D
in the beginning. Various analog front-ends 3
R3
2k2
T2 T1
G
can be connected to K2, which are presented 8
4 S
below. Figure 23 shows the test setup of a
BC550 BS170
9

Pico board with an ADS807 and a 50 Ω trans-


5

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

use an inexpensive 8-bit ADC such as the +5V


1
2
15 27 28
3
4
GND LED GND
38
37 100µ

ADS830E, instead. It offers sample rates of NC VS VS VDRV


13 5
GP2 3V3_EN
36
BOOTSEL

LSB BIT12 GP3 3V3_OUT

up to 60 MS/s and only requires an adapted +IN


4
5
25
24
+IN BIT11
12
11
6
7
GP4 ADC_VREF
35
34

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

minimal loop to acquire N data values with it: ADS807E


14
17
18
GP13 GP18
24
23
CLK GND GND
19 22
GND GND GND GP14 GP17
SWCLK

SWDIO

C3 C2 20 21
for (k = 0; k < N; k++) {
GND

1 20 26 GP15 GP16

sampleBuffer[k] = gpio_get_all(); 100n 100n

gpio_put(ADCclock,0); 230078-025

gpio_put(ADCclock,1);
} Figure 22: Connection of the external ADC ADS807 to the Pico board.

lektor September & October 2023 13


Figure 24: Spectrum of a 500 kHz square-wave signal with a duty cycle of
10%.

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

The keywords .wrap_target and .wrap cause the two instructions


+5V
between them to be executed endlessly one after the other. The loop
itself does not cost any overhead in the process. The in command K2 C1 R1
1
K1

causes 12 bits to be moved from the ADC into the ISR (input shift 50Ω
R2 2
+5V

register). As we know, the nop instruction does nothing. Following


10µ NC
2k2

each instruction, the side option is used. With this, GPIO pins can 4
+IN

be influenced in parallel to the actual PIO command. This way, the


5
–IN
6
ADC clock is generated at GPIO14. Since each instruction requires C3 C2
7
CM
REFT
one cycle, this program can, in principle, process 125 / 2 MS/s. This 100n 10µ 8
REFB
is sufficient for the ADS807. Besides the actual program, the config- 9
GND
uration of the state machine plays an important role. It defines, 230078-028

for example, which pins are influenced by side-set. In addition, it


was configured so that, after every two samples (when 24 bits have Figure 25: Single-ended frontend.

14 September & October 2023 www.elektormagazine.com


Front-end 1: single-ended phase difference between +IN and -IN remains as small as possible.
In the most simple case, you ignore the differential input, set -IN R2 and R4 are used for the stability of these opamps. IC1B buffers
to CM (Common Mode) and simply feed the signal to +IN. You then the offset voltage of 2.5 V. Figure 28 shows, among other things,
work with AC coupling, and the DC offset of 2.5 V is supplied by the setup of the frontend on a breadboard.
CM (Figure 25). If you want to have a 50 Ω input impedance, you
can simply connect a 50 Ω resistor in parallel to input K2. Noise
Certain noise sources make life difficult for a circuit designer. At R5,
Front-end 2: transformer coupling with 50 Ω for example, a thermal noise voltage of UN, RMS = √(4 kB T B R) occurs,
Using an RF transformer with three closely coupled windings with where kB is the Boltzmann constant, T is the absolute temperature (in
the same number of turns, a simple use of the differential input can Kelvin), B is the bandwidth (here 25 MHz) and R is the value of R5
be achieved. The prototype used a 4.7 mH common-mode choke (1 MΩ). This results in an effective noise voltage of 6.3 mV.
with four windings, of which only three are used (Figure 26). The
blue choke from Siemens can be seen clearly in Figure 23. This is several times the ADC resolution, and this noise level is
strongly noticeable with broadband, high-impedance measure-
One winding each feeds the +IN and -IN inputs with opposite ments. This also explains why a low-impedance system of e.g. 50 Ω
phases. The windings each have a parallel resistance of 100 Ω.
The 1:1 coupling transforms these resistors into two parallel-con-
nected 100 Ω resistors on the primary side, resulting in an input
impedance of 50 Ω. Since the ADC sees twice the input voltage, this
+2V5
results in an amplification factor of 2. At the same time, the input
is electrically isolated from the ADC, which avoids common-mode R5

interference. The circuit is well suited for measurements on 50 Ω

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

high frequencies. The core should have a high permeability even 1k


R4

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

a high-impedance input. This then allows the usual 10:1 oscillo-


1 5
IC2A –IN
2 6

scope probes to be used. Figure 27 shows the circuit of a suitable


CM
7
R2 REFT
+5V
preamplifier.
8
1k REFB
+2V5 9
GND
5
R1
Opamp IC1A serves as an impedance converter with an input resis- C4 8 8 C2 100Ω
7
IC1B
6
C1

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

into a differential signal, the result is an amplification factor of two.


IC2 has been selected considering the high bandwidth so that the Figure 27: RF preamplifier with an input impedance of 1 MΩ.

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.

lektor September & October 2023 15


is more advantageous for RF. The input current of an OPA2350 Figure 28 shows how this solution with two Pico boards might look.
has a noise density of 4 fA / √Hz. This results in a negligible effec- The display shows the spectrum of a 1 MHz square wave signal at
tive noise voltage of 20 µV at R5 at a bandwidth of 25 MHz. For a sample rate of 50 MS/s. The harmonics quickly become smaller
the input voltage noise, a density of 7 V / √Hz is specified. This with increasing order.
results in a noise voltage of 30 µV at 25 MHz, which is also negli- Translated from German by Jörg Starkmuth — 230078-01
gible. However, it becomes clear how the noise parameters of the
opamp influence the design. For example, the AD8042 has a current
noise of 500 fA / √Hz and is therefore unsuitable as an impedance Questions or Comments?
converter at the input. Do you have questions or comments about this article? Email
the author at [email protected] or contact Elektor at
Graphic Display [email protected].
As already mentioned, it is not possible to connect the external
ADC and the LCD at the same time due to the lack of GPIO pins.
For a standalone device, this shortcoming is compensated for by About the Author
using two separate Pico boards: One for data acquisition from the Martin Ossmann started reading Elektor at the age of 12 — and
external ADC, and one for the LCD. The latter serves as a graphics tinkering, of course. After studying electrical engineering and
terminal that can independently perform various basic functions working for several years as a development engineer, he was a
such as drawing lines and rectangles, as well as text output. On the professor at the Department of Electrical Engineering and Informa-
Pico board with the ADS807, the spectrum analyzer functions are tion Technology at the FH Aachen University of Applied Sciences.
implemented. For graphics output, this part sends corresponding He is not only the author of scientific publications, but has also
commands to the graphics terminal via the serial interface. At a been regularly publishing circuits and software projects with a
price of a few dollars for a Pico board, this dual-board design is lot of technical know-how in Elektor for more than three decades.
economically justifiable.

Related Products
> Joy-IT JDS6600 Signal Generator & Frequency Counter
https://elektor.com/18714

> OWON HDS242 2-channel Oscilloscope (40 MHz) +


Multimeter
https://elektor.com/20415

> Raspberry Pi Pico RP2040


https://elektor.com/19562

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

16 September & October 2023 www.elektormagazine.com


Course Applied RF technology

Theory and practice of high-frequency systems


(in English language)

Date: 18 - 21 September 2023

Location: Dwingeloo, the Netherlands

More information on www.astrotec.nl/Courses/RF_Eng


or via email: [email protected] or
tel.: +31 (0)521 59 52 87.

Direct registration possible via


www.astrotec.nl/Courses/RF_Eng/registration

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.

Many technicians, including test and verification


engineers, work with radio frequency systems.
Understanding the coherence of system components is
extremely important in order to be able to see the
effects, causes and consequences of the influence
various RF system components have on one another.
Because high-frequency aspects play an increasingly
important role in the design of embedded electronics, a
course like this is also excellent as an introduction to
digital / analog engineers who are or will be involved in
the development of RF systems.

Good to know Objectives


The theoretical part of the course covers 75% of the • better understand systems based on their high-
course, with the remaining part spent in hands-on frequency behavior
sessions. Part of the programme is a tour to the famous • recognize the importance of impedance matching in
14-dish Westerbork Synthesis Radio Telescope (WSRT). high-frequency systems
• describe the principles of modern communication
systems
• understand specifications in data sheets
• describe various modulation techniques
• know the effects of non-linear systems
• understand the operation of various antennas
• be able to perform practical microwave
measurements
The course will be held at ASTRON, which is located in • know the principles of RF measurement techniques
the beautiful National Park Dwingelderveld, Europe's and their limitations.
largest wet moorland area. ASTRON has price
arrangements with several local accommodations, we
All RF courses incl.hands-on training are organized by
can help you out finding the right place to stay. ASTRON, Netherlands Institute for Radio Astronomy.

This course is also taught in Dutch from 6-9 November


2023, check www.astrotec.nl/Courses/RF
lektor September & October 2023 17
PROJECT

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!

By Ton Giesberts (Elektor Labs)

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

18 September & October 2023 www.elektormagazine.com


directly, a transformer rated at 2× 30 V is the ripple should not go beyond the dropout accordingly to counteract any changes.
the most likely choice. The resulting no-load voltage (43 V at 10 A). In a lab test, a 2× 35 V, Although the present regulator circuit follows
DC voltage is usually around 42 VDC, largely 300 VA toroid (ring core) transformer with that concept, one dissimilarity that is marked is
depending on internal regulation of the trans- 20,000 µF worth of smoothing capacitance its much higher secondary reference voltage,
former and voltage drop across the rectifier appeared sturdy enough to feed the regula- which, at a little over 33 V, is relatively close to
diodes. In practice, the no-load output voltage tor. The maximum (near-clipping) sine wave the 40 V target output voltage. The higher the
of a power transformer is always a few percent power at 20 Hz and 0.1% THD+N into a 3 Ω reference voltage — 33.6 V here — the more
higher than loaded. The next higher standard load caused a mere 1.8 Vpeak of dropout at gain left to a (simple) circuit to increase both
secondary voltage is 35 V, which results in the supply output. Mind you, the continuous the ripple rejection of the input voltage and
approximately 49 to 50 VDC or more at low output power then is 227 watts into the 3-ohm the output voltage regulation.
output power — close to 52 V was measured load and the 300 VA transformer is slightly
in a Labs test setup. overloaded. This, however, was not enough Simply put, the circuit consists of a reference
to trip the Fortissimo-100’s protection. voltage, a differential amplifier, and an output
With an 8 Ω load on the power amplifier, the buffer. Additionally, a safe operating area
regulator requires a small smoothing capaci- Theory of Operation (SOA) protection is added to both regulators.
tance only. The advantage of the larger ripple The basis of any voltage regulator is measur- Let’s look at Figure 1 to explore the operation
voltage is a somewhat lower power loss in the ing the output voltage, comparing it to a refer- of the positive regulator.
supply regulator(s). But, at lower impedances, ence level, and controlling the output stage

Figure 1: Schematic of the ±40 V linear voltage regulator, principally, but not exclusively, intended for the Elektor Fortissimo-100 audio power amplifier.

lektor September & October 2023 19


Reference Voltage Quick Specifications
The reference voltage is not created by a Input voltage range 52 VDC (low-power usage) to 43 VDC
Zener diode, as standard Zeners typically
Output voltage range approx. 38.9 VDC to 41.4 VDC (theoretically)
have considerable temperature coefficients.
38.6 VDC to 41.1 VDC (measured)
Special temperature-compensated versions
are hard to come by these days, especially Dropout voltage at 6 A 42 V
33 V versions. Instead of a Zener diode, a Dropout voltage at 9.5 A 43 V
type TL431 adjustable-precision shunt voltage Dropout voltage at 13.5 A 44 V
reference is used with a maximum working Max. current 15 A peak (half sinewave)
voltage of 36 V. Its internal reference voltage 4.8 A average
(i.e., the primary reference voltage of the 40 V
SOAR protection 15 A at 45 VDC in
regulator) is typically 2.495 V. The cathode
current through the TL431 is set by resistor R1. Ripple rejection >60 dB (@ 5 ADC load)
If the input voltage is between 43 and 50 V, the No-load input current 27 mA (@ 52 VDC input)
current is set between 1.9 and 3.4 mA, which Assembly from Elektor kit of parts; add power transformer,
turned out to be adequate for a stable 33.9 V (bridge) rectifier, reservoir, capacitors
reference voltage to be created. The 33.9 V is
set by resistors R2 and R3, as follows:

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,

20 September & October 2023 www.elektormagazine.com


Figure 2: Some shots from the Construction Manual written for the ±40 V linear voltage regulator project. The manual complements this article and is
available for free download from [2].

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.

The regulator input is protected by a 15 A fuse.


The maximum RMS (root-mean-square)
current must be considered, and at maximum
half-wave sine current, the RMS value is
Ipeak/2, i.e., 6.5 A. However, at very low frequen-
cies like 16.4 Hz (if you like organ music), the
peak current may last several milliseconds. To
make sure the fuse doesn’t blow under such
conditions, a 15 A type is used here, which,
as a bonus, also reduces the voltage drop. If
much more power is taken by the amplifier
and/or the regulator, the primary fuse linked
to the power transformer blows. The 15 A fuse
will reliably blow should there be a sudden
short circuit “behind” it.

Kit, Construction Manual, and


Bill of Materials
The Elektor Store offers a comprehensive kit
for the Linear Voltage Regulator project [2],
containing the printed circuit board (PCB) and Figure 3: Suggested schematic for the unregulated power supply circuitry (top) and wiring diagram of
all parts listed in the bill of materials (BoM, the ±40 V linear voltage regulator / Fortissimo-100 combo (bottom).

lektor September & October 2023 21


Component List
(Elektor kit contents listed)

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

22 September & October 2023 www.elektormagazine.com


power transformer, a rectifier, and smoothing in combination with the ±40 V Linear Voltage gone, but the rest of the spectrum is essen-
capacitors added, a suggested schematic — Regulator described here. Both units were tially the same. The overall performance of the
tuned to the Fortissimo-100 amp — is given built from their respective Elektor kits. The combo is impressive, with harmonic distortion
in Figure 3. The parts for this section are not following key ingredients went into the unreg- plus noise as low as:
included in the ±40 V Linear Voltage Regula- ulated supply section:
tor kit and must be purchased locally. > 0.0007% (1 kHz, 1 W, 8 Ω, B = 22 kHz)
> 1 pc. TX-146-300-235 power transformer > 0.0013% (1 kHz, 1 W, 8 Ω, B = 80 kHz)
Safety Consideration (300 VA, 2× 35 VAC secondary).
Although the construction of the project and > 2 pcs. 10,000 µF electrolytic capacitor per The ±40 V linear voltage regulator described
its practical use are detailed in the Construc- supply voltage rail (i.e., 20 mF on each here and available as a kit from Elektor is a
tion Manual, we feel obliged to print the follow- rail). good alternative to the best, yet affordable,
ing safety notice in this article as well: > 1 pc. SB352SBPC-style bridge rectifier, switch-mode power supplies on the market
35 A/200 V (25 A/100 V satisfactory). today, and should satisfy those of you object-
The large heatsinks are connected to the ing, however lightly, to the concept or perfor-
±40 V output voltage, not to GND. Always At low output levels from the Fortissimo-100, mance of “them @#!%^ switchers”. Feel free
remove the input voltage before touching or the frequency spectrum shows that very to join the technical discussions on the ±40 V
working on the regulator! small improvements can be achieved when linear voltage regulator on the Elektor Labs
compared with the SMPS800RE switched- page created for the project [3].
Results Achieved mode power supply (Figure 4). The graph 220581-01
At Elektor Labs, a test setup was built to verify shows the frequency spectrum at 1 W into
the operation of the Fortissimo-100 amplifier 8 Ω. The SMPS800RE’s switching artifacts are
Questions or Comments?
If you have any technical questions, you
can contact the Elektor editorial team by
email at [email protected].

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

lektor September & October 2023 23


PROJECT

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.

24 September & October 2023 www.elektormagazine.com


Figure 1: Implemented project with screenshots of WeMos actions
(from upper-left): Power-on logo, setup() call, Mode 2 WLAN scan
result, successful connection to a WLAN, logo of Mode 4 for dumping
EEPROM entries, and the listing of EEPROM entries.

Table 1: DIP switch configuration of the relevant WeMos modes.

Mode DIP 1 DIP 2 DIP 3 WeMos Action


1 0 0 0 Default WLAN selected
2 0 0 1 Scan available WLANs
3 0 1 0 Clear internal EEPROM
4 0 1 1 Dump internal EEPROM
5 1 0 0 Initialize internal EEPROM
6 1 0 1 Check external EEPROM
7 1 1 0 WPS
8 1 1 1 Interactive WLAN setup

Figure 2: Project wiring using Fritzing breadboard tools and showing an extra fourth DIP switch for extended networking options.

lektor September & October 2023 25


Table 2: Breakdown of Arduino code files and their functions.

.ino file Description Line Count


wemos-d1- Global variables, setting up 240
mini-network network mode
wlan-utils Manipulate WLAN connections: 110
Software WPS setup, scan/list WLANs,
The project emphasizes software development best practices, such check connectivity
as well-structured and reusable code. To achieve this, I divided the
tft-utils Manipulate TFT display 130
800-line sketch into six separate files, each handling a specific
internal- Initialize EEPROM with five 180
piece of hardware or functionality (see Table 2). This approach
eeprom-utils preset WLAN credentials, reset
makes the code more manageable and helps readers understand
EEPROM, read/write entries
the complex code involved. The main sketch file focuses on the
WeMos networking modes within the setup() function, while external- Check external EEPROM 40
leaving the loop() function free for the WeMos application code. eeprom-utils connectivity and size
During the development phase, I used loop() to manipulate the ap-web-setup Interactive WLAN setup: Initiate 100
onboard LED blinking and ensure that the WeMos was function- web server, display detected
ing correctly. WLAN SSIDs, save selected
WLAN to EEPROM
Utilizing EEPROM for WLAN Networking
The ESP8266 module has 4 MB of flash memory, out of which 4 KB
is set aside to emulate an EEPROM that is normally built-in on Table 3: EEPROM housekeeping table for multiple AP settings.
Arduino devices. Our example sketch stores the latest workable
AP credentials in the internal EEPROM by default. With internal Entry Size (Bytes) Description Type
(or external) nonvolatile storage in use, our sketch can recall the 2 AP entry count integer
AP credentials each time it boots after power-up. The EEPROM
32 AP1 SSID string
is also accessible by means of function calls from the Arduino’s
EEPROM library, and I’ll follow this direction to save our network 64 AP1 Passphrase string
data that must be non-volatile for when the module is powered off. . . .
The main concept is to maintain the proposed structure shown . . .
in Table 3 for holding WLAN AP credentials — as many as the
. . .
internal or external EEPROM can hold. Each subsequent entry
in the structure holds either the AP’s SSID or its passphrase in 32 32 APn SSID string
and 64 bytes of storage, respectively. That’s 96 bytes in total per 64 APn passphrase string
AP. Whenever the user adds a new WLAN to the list of preferred
networks, the code appends this structure with the credentials of
the new network’s SSID and passphrase. The user needs to clear
the EEPROM in the first run of the project code, using Mode 3, Mode 2: WLAN Scanning
thus marking the end of the list with blank entries. The user will In this mode, the WeMos disconnects from any connected WLAN
have the choice of applying the hard-coded WLAN credentials, in order to be able to scan for other accessible networks. Detected
using Mode 1, or checking the connectivity using the credentials in WLANs are listed by their SSIDs and signal strengths in decibels
EEPROM, which is done using Mode 8. My implementation for this (dB). This mode gives the reader an insight into the prospects of
project is confined to this mechanism for up to 10 WLANs, limited networking the WeMos board and which mode to choose for joining
by defined constant MEMCNT in the code, in addition to clearing the a WLAN. Figure 3 shows the outcome of booting the WeMos in
structure and initializing it with a preset list of AP credentials of this mode, where only one WLAN was detected and later on was
the user’s choice. The reader may increase or decrease the size of joined, as shown in Figure 1d.
MEMCNT as necessary.
Mode 3: Clear Internal EEPROM
Background knowledge for accessing the EEPROM can be found This mode causes the WeMos to erase its internal EEPROM in prepa-
at [2]. Now, I elaborate on the modes of operation for the WeMos, ration for building a new list of preferred WLANs. All bytes in the
each of which requires the setting of the DIP switches (as per Table 1) EEPROM are cleared to 0×00 in this mode.
then rebooting the WeMos to apply the setting.

Mode 1: Default WLAN Settings (Hard-Coded)


An MCU requires WLAN credentials, composed of an SSID and a
passphrase for the relevant access point. Passing WLAN creden-
tials can either be hard-coded in the flashed sketch or interac-
tively passed to the MCU when the user is equipped with either a
keyboard and a display or Serial Monitor in the IDE linked via the
serial port. In this project, I’m using the conventional way of fixing Figure 3: Arduino IDE’s Serial Monitor messages — Mode 2 wireless
AP credentials right in the sketch. network scan.

26 September & October 2023 www.elektormagazine.com


Figure 4: Serial Monitor messages — Mode 6 checking external EEPROM
sanity.

Mode 4: Dump Internal EEPROM


This mode causes the WeMos to dump the WLAN credentials struc-
ture, as explained in Table 3, from the internal EEPROM. Figure 1e
and f show screenshots of the displayed EEPROM entries currently
stored. A series of formatted SSIDs and passphrases is printed for
the stored APs’ credentials in this mode.

Mode 5: Initialize Internal EEPROM


This mode enables the reader to preset the credentials of
10 preferred WLANs into the internal EEPROM. This action is an
exaggeration of the traditional hard-coded single WLAN creden-
tials. Upon rebooting in Mode 8, the WeMos will inspect the list of
credentials for WLAN connections. If its attempts fail to connect
to any of preferred WLANs, then the reader would have to resort
to either interactive or WPS modes.

Mode 6: Checking External EEPROM Status


In this mode, the WeMos checks the sanity of the external EEPROM,
in my case a 24LC64 with 8 KB on board. Figure 4 shows the output
of this check in Serial Monitor. I didn’t involve this external device
any further in the project since utilization of the internal EEPROM
is minimal. The reader may refer to the I2C EEPROM code [3] and
library [4] for integration in the project. Figure 5: AP configurations for WPS alternatives.

Mode 7: Direct Connection to WLAN (WPS)


WPS is a feature supported by modern APs that simplifies the
process of connecting wireless devices to a WLAN. Rather than
providing an MCU with the AP credentials, e.g. SSID and passphrase/
pre-shared key, the MCU may provide the AP security pin or its
own preset pin (see Figure 5). Alternatively, a WPS push button
may be pressed on the AP for direct connection to the requesting
MCU (see Figure 6). Figure 7 shows the outcome of establishing
a connection using WPS.
Figure 6: WPS button and indicator of a typical AP.
In this project, I confine the WPS connection to the AP push button
alternative as it makes coding simpler and more generic to accom-
modate any AP within reach, as follows:

bool wpsSuccess = WiFi.beginWPSConfig();


if (wpsSuccess) {
String newSSID = WiFi.SSID();
if (newSSID.length() == 0) { wpsSuccess = false; }
} Figure 7: Serial Monitor messages — Mode 7 WPS setup.

lektor September & October 2023 27


The WeMos board needs to be in close vicinity to the AP of choice EEPROMs can make a difference when networking wireless MCUs.
for registering the AP parameters in the module’s EEPROM. Recon- Rather than hard-coding WLAN credentials in the MCU code, acces-
necting the module to the same AP no longer requires pressing sibility to either an external or an internal MCU’s EEPROM has been
the WPS button anymore, as we enable the module to retrieve the used in this article to dynamically keep and update the creden-
stored AP parameters for reuse, like this: tials of multiple APs for feasible connections. The source code
accompanying the article is modular and well-structured, easy to
WiFi.mode(WIFI_STA); understand, and provides reusable code for handling EEPROMs,
WiFi.begin(WiFi.SSID().c_str(),WiFi.psk().c_str()); WLANs, and for communicating with MCU through the web.

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

> 0.96″ OLED Display (Blue, I2C, 4-Pin)


https://elektor.com/18747

> Hans Henrik Skovgaard, Home Appliance Hack-and-IoT


Guidebook (+ FREE ESP8266 Board), Elektor 2022
https://elektor.com/20370

Figure 8: Mode 8, the interactive WLAN selection.

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

28 September & October 2023 www.elektormagazine.com


Genius by
Enable peak efficiency in intralogistics with wheel.me's Genius:
Four adaptable robot wheels enabling autonomous transporta-
tion of goods at a competitive price.

Smart navigation Omnidirectional movement

State of the art


Remote access via App
sensor technology

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

By Clemens Valens (Elektor)

STM32 Wireless Innovation Design Contest gives you the


opportunity to create and develop exciting wireless applications
with powerful products supported by a rich ecosystem including
development and evaluation boards from STMicroelectronics.
Use them for whatever you think is interesting — and in any
way you like! IoT, robotics, gaming, home automation, test and
measurement, and AI are just a few of the possible application
fields. It’s all up to you. Release your creativity, have fun and win!
A total of €5,000 is up for grabs!

NUCLEO-WBA52CG keeps evolving, and version 5 introduced IoT support.


Bluetooth applications have gained a lot of popularity Currently, the Bluetooth Core Specification is at version 5.4.
over the past years. At the time of writing, the Bluetooth
SIG website expects that 7.6 billion Bluetooth-enabled The STM32WBA52CG is an RF/SoC microcontroller
devices will ship annually by 2027. The standard itself supporting Bluetooth LE 5.3. This is an ultra-low-power
ARM Cortex-M33 device running at up to 100 MHz. It has
1 MB of Flash memory and 128 KB of SRAM. The MCU
implements a single-precision floating-point unit (FPU),
plus a full set of DSP instructions. It has a memory protec-
tion unit (MPU) and it features Trust Zone. The device
integrates a 2.4 GHz transceiver supporting Bluetooth
Low Energy and proprietary protocols. The microcon-
Figure 1: The NUCLEO- troller is mounted inside a metal can, so you can’t see it.
WBA52CG features an
Arm Cortex-M33 with The STM32WBA52CG is soldered to a breakout board
Trust Zone and Bluetooth
LE 5.3. that, in turn, is plugged onto another breakout board. This
board is equipped with Arduino and ST Morpho-com-
 patible extension headers, configuration jumpers, push

30 September & October 2023 www.elektormagazine.com


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.

More information: https://st.com/en/evaluation-tools/


stm32wb5mm-dk.html

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

lektor September & October 2023 31


Figure 3: The NUCLEO-
WL55JC is compatible
with standardized as well The board has, of course, many more application possibil-
as proprietary protocols ities. One that immediately springs to mind is a LoRaWAN
such as LoRaWAN, end node. Instructions explaining how to do this can be
Sigfox, wM-Bus and
found by searching the ST website.
more.

 The NUCLEO-WL55JC board comes in two versions: the


WL55JC1 is for use in the 865-928 MHz band, whereas
the WL55JC2 is for the 433-510 MHz band.

More information: https://st.com/en/evaluation-tools/


nucleo-wl55jc.html

debugger/programmer to facilitate application develop-


ment. An SMA antenna is also included.

The NUCLEO-WL55JC board comes preprogrammed


with a sensor data concentrator demo application. The 230442-01
WL55JC board can be turned into a compatible sensor
node too, if you upload another firmware example from
the STM32CubeWL library package. This is available
from the product page on ST’s website.

!
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:

STM32Cube includes STM32CubeMX, a graphical software configuration 1st prize: €2,500


tool that uses graphical wizards to help the developer generate C initializa-
2nd prize: €1,500
tion code.
3rd prize: €1,000
A suitable toolchain for developing applications for the three boards presented
in this article (and many more) is, of course, STM32CubeIDE from STMicro- For details on how to participate in the STM32
electronics themselves, which is free of charge. Keil’s MDK-ARM and IAR’s Wireless Innovation Design Contest, the timeline,
Embedded Workbench can be used too, but at the developer’s expense. and the exact terms and conditions, please refer
https://st.com/en/development-tools/stm32cubeide.html to the contest entry webpage at

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/

32 September & October 2023 www.elektormagazine.com


AI

2023:
An AI Odyssey
Getting Started with ChatGPT’s Code Interpreter

By Brian Tristam Williams (Elektor)


Code Interpreter is a game-changer. It goes beyond just execut-
ChatGPT’s capabilities have reached ing Python code — it interprets, debugs, and even converts files
new heights with the release of the between formats. Users can input mathematical problems, and
Interpreter will solve them. It can also take data in various file
ChatGPT Code interpreter plugin. formats, analyze it, and visualize it, meaning that it isn’t just limited
Code Interpreter is now available for to straightforward code execution. It can generate data visualiza-
all ChatGPT Plus users. But, what is tions at a speed that has left long-time data analysts astounded.

it, and what does it do? Let’s take a Use Cases


closer look at this unique and useful Code Interpreter’s applications are myriad, and many are still to be
ChatGPT plugin. discovered. Some of what we’ve already been trying:

> Code testing: Users can test code snippets in real-time,


ensuring they work as intended.
OpenAI’s ChatGPT is revolutionizing our interaction with artificial > Collaboration: Teams can collaborate on coding projects
intelligence. With the recent addition of the Code Interpreter, it has directly within the chat.
transformed into more than just a chatbot — it’s now a powerful > Learning tool: It’s an excellent resource for students learn-
assistant for developers, data scientists, and coding enthusiasts. ing Python, offering interactive coding sessions. This is huge
for me — it’s like having your own private tutor on the other
OpenAI’s mission to push the boundaries of AI capabilities has led side of a chat window.
to groundbreaking developments, such as the various ChatGPT > Experimentation: Developers can try out different program-
[1] models, significant leaps in natural language processing. The ming approaches without leaving the chat.
recent upgrade, GPT-4, builds upon this impressive foundation, > Solving mathematical problems: Whether it’s high school
but it’s the introduction of the Code Interpreter plugin [2] that truly algebra or differential calculus, the right prompts will get you
sets it apart. your solution and walk you through how to get there.
> Format conversion: Take data in various file formats and
Code Interpreter analyze it, clean it up, and visualize it.
We have to note that the term “interpreter” is ambiguous here. Even
the free version, GPT-3.5, is capable of interpreting code (meaning Getting Started
figuring out what code does) and providing meaningful feedback While there is a free version of ChatGPT, you need to be a Plus
in natural language. That’s not what they mean here. This is an subscriber to use plugins such as Code Interpreter. At the time
interpreter in the sense that it can actually run our Python code of writing, it’s in Beta, so you’ll have to enable the feature. On a
as an interpreted language, in its own sandboxed and firewalled desktop browser, get there by clicking on your profile image on
environment, along with its own virtual disk space. Just as when you the bottom-left, followed by the Settings cog (Figure 1). Then, in
used “immediate mode” in gold old-fashioned traditional BASIC, the dialog that follows, click on Beta features, and make sure that
your Python session remains persistent for the chat session. both the Plugins and the Code interpreter toggles are on (Figure 2).

lektor September & October 2023 33


Figure 1: How to get to Settings in ChatGPT. Figure 2: Make sure that Plugins and Code interpreter are enabled.

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:

34 September & October 2023 www.elektormagazine.com


of a problem newly-broken links are once an item
is published, an automated script could pass the
data to Code Interpreter in a CSV file for automated
analysis, and we could gain a far better idea of how
often links become invalid versus their age, for
example.
> If links change so often that it is a concern, consider
using a branded link shortener, which can be
updated whenever manufacturer X or software
publisher Y decides to move their page somewhere
else, or a smaller website gets switched off and
we have to rely on a third-party archive such as
archive.org.

The Sky Is the Limit


The basic exploration above barely scratches the surface
Figure 5: The file is uploaded. Let’s get cracking on the analysis, even if we have to of what’s possible and the potential it has. In demos
remind the computer of its capabilities. shown on OpenAI’s blog posts [3], we’ve seen the plugin
performing a wide range of tasks excellently, inter-
preting large datasets, identifying trends, comparing
> The three most-mentioned accessory/microcontroller boards variables, and creating plots. The plugin can even be used to create
were the nRF52, the ESP32, and the Raspberry Pi, with 149, 136, GIF animations from a short prompt.
and 30 mentions, respectively.
> Helpful subjects to have a grasp of before beginning this I have gone on many meandering tours of many subjects, including
book: A basic understanding of the C and Python languages; a conversation about discrete mathematics, Amida-kuji, Hamil-
some experience interacting with microcontrollers; general tonian cycles, the Towers of Hanoi, and gray code, with my trusty
understanding of wireless communication protocols; using and patient guide, and it has even generated Python code to, in
the Linux command line; basic networking concepts. turn, generate visualizations of ideas I wanted to test [4].
> The book contains 121 URLs, and Code Interpreter was able to
output the entire list for me. This a boon for both editor and Now that the internet has had more time to use the Code Inter-
publisher, who need to check if links work, or have expired, or preter plugin, we’ve seen even more uses come to light. Have you
had typos. So, I had Code Interpreter write me a Python script tried it? If so, let us know how it’s helped make your life easier!
to check all of these links and return the HTTP status codes. 230181-B-01

It turns out that a couple of websites, including big ones, have


restructured already (this book is only a year old), breaking some Questions or Comments?
of those links. Furthermore, some of the links in the ebook are Have you found any amazing uses for AI in your field? Do you
misinterpreted by Adobe PDF due to formatting (line breaks, etc.), have questions or comments about this article? Let me know at
which does not affect the print edition that we poured over. This [email protected] or contact [email protected].
leads me to useful, actionable, ideas:

> For each book or magazine publication, an automated script


could run daily, validating all the links, checking for “404 not
Related Products
found” errors or suspicious new redirects (as may happen if a
domain expires and is snapped up by a third party). Alert the > Koen Vervloesem, Develop your own Bluetooth Low
publisher where necessary. Energy Applications (E-book), Elektor 2022
> While it was never previously easy to determine how much https://elektor.com/20201

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

lektor September & October 2023 35


PROJECT

oRa, The LoRa Protocol and Its Advantages


a Swiss
Army Knife (1)

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.

36 September & October 2023 www.elektormagazine.com


easily be purchased from major distributors for between 3 and 10 euro,
depending on model, power and supplier.
Figure 4: Modules ending in ‘S’ offer IPEX / U.FL
antenna output. We’re combining this module, along with a few peripheral compo-
nents, with a microcontroller whose programming we’ve mastered
and for which we can create applications. In this way, we’ll be able to
a regulator, and an RX/TX RF output switcher. All other components make all kinds of LoRa connections and interesting applications. This
are resistors or capacitors and HF chokes, as well as a 32 MHz oscil- module will become your LoRa “Swiss Army knife.”
lator, controlled by a crystal.
A Little More About LoRa
Modules with the ‘30’ radical also incorporate an 8 dB power ampli- The LoRa protocol enables links over relatively long distances (several
fier, raising the transmitting power to 30 dBm or 1 W. They are slightly kilometers) at very low power levels (tens to hundreds of milliwatts),
larger in size, and consume considerably more power at full output but with the drawback that it‘s only at low data rates. As soon as you
(750 mA instead of 150 mA for Model 22). This power reserve can be increase the (configurable) data rate, the range is reduced. This means
invaluable in compensating for losses of all kinds caused by HF cables that LoRa is very effective for low-bitrate applications such as gate
and connections in the gigahertz range. control transmission, very long-range remote control, and reception
of remote sensors that don’t require frequent updating.
The two aforementioned models have an antenna output with a female
SMA connector, but these modules are also available with an IPEX / U. We chose the 868 MHz frequency because it’s available in Europe
FL antenna output; the reference ends with ‘S’ instead of ‘D’ (Figure 4). without the congestion of the 433 MHz band. In addition, it’s the
frequency chosen for the LoRaWAN protocol. It’s also regulated, just
Without Integrated Microcontroller like all ISM bands (Industrial, Scientific and Medical). The advantage
The module we’re going to use, the E220-900M30S, is of particular of ISM bands is that as long as you comply with European regulations,
interest to us, as it has no microcontroller on the control lines. In fact, you can transmit radio signals without any prior declaration.
the LLCC68 is directly accessible via an SPI connection (the model is
identified by the letter “M”). This means that all LLCC68 parameters Radio Spectrum Sharing
can be accessed without restriction, which is essential if we are to Radio spectrum is a common resource, so we need to share it so that
exploit the full benefits of LoRa. we don’t disturb others with our transmissions, and aren’t disturbed
by theirs. LoRa uses three ways of sharing a frequency band:
This model, like its predecessors, is available for different frequency
bands, from 150 to 930 MHz. We have chosen the 900 model, which Frequency sharing: The available frequency band is divided into
covers the 868 MHz band authorized in France. This module can contiguous channels more or less evenly spaced (Figure 5).

868 Mhz 868.3 Mhz 868.6 Mhz 868.9 Mhz

Figure 5: LoRa modulation uses a


ƒ configurable bandwidth. This example
shows a BW bandwidth of 250 kHz,
50 khz

i.e. 125 kHz on either side of the center


125 khz

125 khz

frequency. The frequency deviation will


therefore range from 868.175 MHz to
868.425 MHz for the second frequency
of 868.3 MHz.

lektor September & October 2023 37


9.226
E (mJ)

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.

38 September & October 2023 www.elektormagazine.com


A LoRa specificity: the Spreading Factor (SF)

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:

Figure 7: LoRa modulation can be viewed directly with SDR software


and an associated SDR key. Here we see the modulation for a frequency
of 868 MHz with a bandwidth of 250 kHz. The slowness of the LoRa
transmission allows us to see the modulation of the symbol coding. At the
Link budget is the link budget of the module used for our example, in
top of the image, the vertical axis is graduated in average signal power
compliance with the European standard is 143 dBm. (dBm) and the horizontal axis in frequency. In the lower part of the image,
Frequency is the frequency of the module: 868 MHz. you can see the transmission sequence as a function of time, with the
Distance is the range in kilometers (excluding HF noise). frequency variations characteristic of LoRa modulation.

lektor September & October 2023 39


for SF = 11, there would be 2048. The duration of each increment Tc
N depends on the bandwidth. For BW = 250 kHz, they last 4 µs, for
t

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

Ts The LoRa Package


A The transmitted message is integrated into a physical frame called a
packet. It consists of four parts (Figure 9), some of which are optional
867,875 Mhz 868 Mhz 868,125 Mhz and/or configurable:
F - BW /2 F F + BW /2
1. A preamble, always mandatory, but customizable. It’s a succession
Figure 8: This chronogram shows the transmission of four symbols with of several (usually eight) increasing chirps and two decreasing
SF = 8 and BW = 250 kHz. Warning: Time is represented by the vertical chirps. This preamble is essential for the receiver to synchronize.
axis, frequency by the horizontal axis.
2. Header, optional. It is present by default if explicit mode is chosen
(absent with implicit mode). It is always transmitted with a CR
Figure 8 is a timeline showing the transmission of four LoRa symbols (code rate) of 4/8 to have the maximum chance of being received.
with SF = 8 and BW = 250 kHz. If our center frequency is 868 MHz, It indicates:
the frequency deviation comprises 28 = 256 increments to transit from
the minimum frequency of 867.875 MHz to the maximum frequency > Data size (payload).
of 868.125 MHz. > Code rate (CR) used for the rest of the frame, between 4/5 and
4/8, but 4/5 is the most widely used. A code rate of m/n means
The coding of each symbol’s information lies in the initial frequency that for every m bits of useful information, the encoder gener-
value of the linear sweep of this frequency. For example, for symbol 1, ates a total of n bits of data, of which m-n bits are redundant.
the start frequency A, starts at 32/256 of the total frequency sweep, Redundant bits enable the detection of transmission errors.
so the transmitted symbol encoding will be 32. For symbol 2, the start > It specifies whether a CRC (error code) is present or not.
frequency E, starts at 128/256, so the symbol encoding will be 128. For
symbol 3, the start frequency I, starts at 64/256, the symbol coding 3. Data (payload). The maximum data packet size is 256 bytes. It
will be 64 and so on. For symbol 4, the start frequency M starts at depends on the value of the spreading factor and the buffer settings.
0/256 and the symbol encoding is 0. The values of the 4 transmitted The higher the SF value, the smaller the packet size. Maximum
symbols are therefore successively 32, 128, 64, and 0. message duration is limited.

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.

Header Payload CRC


Preamble Payload
(optional) (optional)

CR = 4/8 CR = 4/(4+n)

Figure 9: The LoRa package consists of four parts, some of which are optional and/or configurable.

40 September & October 2023 www.elektormagazine.com


In the rest of this article, we’ll present the printed circuit board integrat-
ing the LoRa E220-900M30S module, controlled by an Arduino Nano.
A C++ program allows the complete configuration of the LLCC68, and
above all, to be used for transmitting and receiving messages. Range
and autonomy settings are also detailed, with SF, BW, CR, LDRO, as
well as the values returned by the receiver, RSSI, measured sensitivity,
signal-to-noise ratio and reception statistics (error rate).
230140-01

Related Products
> Great Scott Gadgets HackRF One Software Defined
Radio (1 MHz to 6 GHz)
https://elektor.com/18306

> CircuitMess Chatter – DIY LoRa Communicator


https://elektor.com/20407

> Claus Kühnel, Develop and Operate Your LoRaWAN IoT


Nodes, Elektor 2023
https://elektor.com/20147

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

YOUR KEY TO WE are here for you!

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

• Small form factor • Long range/wordwide coverage


• Security and encryption • Multi-band support #GOCELLULAR

lektor September & October 2023 41


PROJECT

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

fast load changes. This is actually essential


F
BEST O
for a complete assessment of a power supply.
Power supplies often respond to sudden load
m

ek changes with strong overshoots in the output


co
El

.
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.

This means that a practical current sink


must be able to generate fast load changes
in addition to providing a static load. This is
exactly the task performed by the current
Figure 1: The current sink without the booster and with a large heatsink plate (left). The plastic screw sink described here. Two versions of this
for the LM317 was not a good idea. The fully populated board with the booster is shown on the right. current sink are shown in Figure 1. The circuit

42 September & October 2023 www.elektormagazine.com


T10*
BD910/912

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

1µ 220µ 100n 10n 1µ 100n


BZV55-C5V6 25V 10V 25V

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

25V

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

lektor September & October 2023 43


and, as a result, acts as a load on the power voltage that is stabilized at -1.25 V by IC4 The undervoltage shutdown is implemented
supply under test. This remains true even — a type LM4041 precision shunt regulator. with the shunt regulator, IC5 (also an LM4041),
when the voltage at the input of the circuit The negative voltage at the Adjust terminal which is configured so that no current flows
changes, so we effectively have a load that of voltage regulator IC1 is applied through through it at a voltage less than 3 V, causing
draws a constant current under all conditions. trimpot R7 to set the adjustable reference the timer to be persistently reset via T6 and T7.
If the voltage on the load resistance is adjust- point. Resistors R1 and R7 form a voltage When the supply voltage rises above approx-
able, the current drawn by the current sink can divider, with a constant voltage of +1.25 V over imately 3.1 V, IC5 starts conducting, causing
also be adjusted. An obvious solution is to use R1 and a voltage of -1.25 V at the bottom end of T6 to switch on and via T7 withdraw the reset
an integrated voltage regulator to implement R7. This way, the reference point of IC1 can be of IC3.
this circuit. Along with low complexity, this has adjusted over the range of -1.25 V to -0.2 V. As
the advantage that many voltage regulators a result, the voltage regulator’s output voltage A voltage signal proportional to the load
have built-in protection functions. ranges from 0 V to approximately 1 V. This current is available at JP1 for measurement
voltage is applied to the parallel group of load with a voltmeter. The proportionality factor is
The lowest output voltage possible with these resistors, R3–R6, which determine the amount 0.1 V/A. A signal with a peak value of around
voltage regulators is always the bandgap of current drawn by the circuit. The switch 6 V is available at JP2. In clocked mode, it can
reference voltage, which is usually 1.25 V. This transistor, T2, which handles clocking of the be used to trigger an oscilloscope.
means that additional means are necessary to current, is connected in series with the load
allow the current to be set to zero. However, if resistors. The circuit input is protected against
the regulator’s feedback terminal (the refer- reverse-polarity connection by the MOSFET,
ence point used by the voltage regulator To keep the power dissipation of shunt regula- T1. When the input voltage polarity is correct,
to set the output voltage) is tied to -1.25 V, tor IC4 low, charge pump IC2 is operated a current flows through the body diode of T1
the output voltage with reference to circuit at only 3 V. This voltage is generated by to allow the internal power supply to start up.
ground can be adjusted all the way down to emitter-follower T3. The reference voltage As a result, T1 is fully switched on. In the event
0 V. This means the current adjustment range is provided by two green LEDs connected of a short circuit in the current sink, the slow
also extends to zero. The required negative in series, which have a significantly more fuse, F1, will blow to prevent a fire.
voltage can be implemented relatively easily pronounced knee voltage than a Zener diode
using a charge pump followed by a voltage with the same Zener voltage. Higher Power
stabilization stage. If you want to increase the power capacity of
The rest of the circuit is powered by a simple the current sink, you can connect a booster
The easiest way to clock the load current is to voltage regulator circuit consisting of T4, T5, circuit ahead of the voltage regulator. This will
use a MOSFET that switches the load resis- and Zener diode D1, which provides the refer- increase the permissible power dissipation to
tor at the output of the voltage regulator. The ence voltage. This circuit has the advantage as much as 50 W, depending on the heatsink.
clock frequency should be chosen to be close that it has a low voltage drop (LDO) and can However, the maximum current is still the
to the line (mains) frequency. This way, the thus provide the required gate voltage for T1 same. Unfortunately, the LM317’s protection
power supply under test is loaded over a full and T2 even with a low input voltage. The drive functions do not apply to the booster, so it’s
half wave of the line voltage, which allows signal for transistor T2 comes from another important to provide an adequately dimen-
correct dimensioning of the power supply filter good friend, a classical 555 timer (IC3). As sioned heatsink. The booster circuit uses
capacitors to be checked. long as capacitor C14, which is responsible around 1.2 V of the applied voltage, so the
for timer oscillation, is shorted out by fitting minimum input voltage is increased to 5 V. For
The Circuit jumper JP3 (ClkDis), the output of IC3 is high this reason, the booster circuit should always
The circuit of the adjustable current sink is and T2 is constantly switched on. This corre- be disabled for voltages under 8 V by fitting
shown in Figure 2. The components marked sponds to the static operating mode. If the a jumper on JP5 (BstDis).
with an asterisk (*) are only required for the jumper is removed, the current is clocked. On
booster circuit. The tried-and-true LM317 is power-up, if the input voltage is less than the The booster circuit’s working principle is fairly
used as the voltage regulator, IC1. This voltage minimum operating voltage, IC3 is reset via its straightforward. Part of the input current flows
regulator has optimal thermal properties and Reset input. In this situation, the timer output through the series resistors, R41 and R42.
a maximum power dissipation of 20 W at is low, and no load current can flow. The timing Trimpot R40 taps off a portion of the voltage
reasonable ambient temperatures, a maximum element, R19/C15, delays the output-enable. drop over the series resistors and applies it
input voltage of 37 V, and overtemperature The current sink can be disabled by apply- to the base-emitter junction of PNP transis-
and overcurrent protection. ing an external low signal to JP4 (/CurDis). tor T10. R40 is set so that T10 starts conduct-
Among other things, this allows a time-driven ing at a current of approximately 0.6 A. As a
IC2 is a type LM2662 voltage inverter based discharge of a rechargeable battery to be result, T10 supplies any current above 0.6 A
on a charge pump. It generates a negative implemented using an Arduino board. directly to load resistors R3–R6, while the

44 September & October 2023 www.elektormagazine.com


LM317 continues to regulate the voltage as
usual. RC network R43/C20 prevents the
circuit from oscillating.

Test Procedure and


Interpretation of the Results
To measure the static parameters of a power
source, disable clocking by connecting a
jumper at JP3. Measure the output voltage
with a voltmeter connected to the output of
Figure 3: Dynamic behavior of a linear lab power supply at 12 V / 1 A. the device under test. Measuring directly at the
current sink would lead to an incorrect result
due to the voltage drop over the connecting
wires. Also, connect an oscilloscope config-
ured for AC input in parallel with the voltme-
ter. Then, increase the current in steps while
measuring the source voltage. This gives you a
series of measurements that show the control
deviation of the device under test. In addition,
the oscilloscope gives you an indication of any
oscillation tendency from the device under
test. When increasing the current, you should
always keep an eye on the current sink’s
maximum power dissipation. Up to 18 W is
possible with a good heatsink for the LM317,
but this is quickly reached at relatively high
input voltages. Fortunately, the LM317’s inter-
nal protection functions (safe operating area,
SOA) protect against damage.

The next step is to measure the dynamic


Figure 4: Step response of the lab power supply from Figure 3 to switching on the load. characteristics of the device under test using
the oscilloscope. For this, clocking of the
current sink must be activated. It’s especially
important to connect the oscilloscope directly
to the power source, as otherwise the results
will be falsified by voltage spikes caused by
the inductance of the connecting wires. The
basic measurement procedure is the same
as for static measurements. The power dissi-
pation is cut in half by the 50% duty cycle
clocking, so you can use higher voltages and/
or currents now. Each of the following oscil-
lograms shows the trigger signal at the top
(CH4, violet trace), the current in the middle
(black trace, measured differentially at JP1
with 0.1 V/A), and the output voltage at the
bottom (CH2, green trace). Also note the
different horizontal and vertical resolutions
in the oscillograms.

Figure 3 shows the dynamic behavior of a


Figure 5: Step response of the lab power supply from Figure 3 to switching off the load. linear lab power supply; Figure 4 and Figure 5

lektor September & October 2023 45


Figure 6: Dynamic behavior of a switch-mode power supply at 12 V / 1 A.

Figure 7: Step response of a flyback voltage converter to load shedding at 13 V / 1 A.

Figure 8: Dynamic behavior of a USB charger at 1 A.

46 September & October 2023 www.elektormagazine.com


show the response to step changes when the
load is switched on and off, respectively. The
amplitude and duration of the overshoots are
the main items of interest here. Figure 6 is
the counterpart to Figure 3, but measured at
a switching lab power supply. Figure 7 shows
the step response of a flyback converter to
load shedding. Figure 8 and Figure 9 show
the dynamic behavior of two USB chargers;
the key item of interest here is the persistent
offset of the output voltage. The control devia- Figure 9: Dynamic behavior of another USB charger at 1 A.
tion, also known as the voltage drop under
load, and the associated current correspond
to the internal resistance of the power source.

You can also see whether the internal filter-


ing and output damping are correctly dimen-
sioned. If the power source has a tendency
toward high-frequency oscillation, it will be
reliably revealed by this measurement. If you
design a power supply yourself, this current
sink is an invaluable tool for optimizing the
control loop’s timing parameters and stability.

A dynamic measurement from a recharge-


able battery provides information on its inter-
nal resistance, which is a good indication of
its state of health. For this, the measurement
current should not exceed a factor of 1 or 2
of the nominal capacity. The internal resis-
tance of a cell from a lithium-ion battery with a
1500 mAh capacity is usually less than 30 mΩ, Figure 10: Measuring the internal resistance of a healthy three-cell LiPo battery at 2 A.
and, with larger capacities, it is usually even
less (in the single-figure range). It’s a good
idea to measure the internal resistance of a
new battery so that you can use this value
later on for comparison purposes. In the
oscillogram in Figure 10, you can see that,
with an internal resistance of 5.9 mΩ per cell
(Ri = 35.2 mV/(2 A × 3)), the battery is in
healthy condition. Looking at Figure 11, on the
other hand, you can see that, with an internal
resistance of 53 mΩ per cell (Ri = 316 mV/
(2 A × 3)), the battery is rapidly approaching
the end of its useful service life.

Figure 11: Measuring the internal resistance of a used three-cell LiPo battery at 2 A.

lektor September & October 2023 47


Figure 12: Board layout for the adjustable current sink with booster.

Construction sink to minimum current while connected to About the Author


A PCB layout has been designed that also an adjustable power supply with the output Roland Stiglmayr studied computer science
supports the addition of the booster circuit. voltage set to 3 V and current-limiting set to in the 1970s and has 40 years’ experience
The layout in Figure 12, as well as the 100 mA. The current sink should draw a quies- in R&D. His main focuses were devel-
schematic diagram, can be downloaded as a cent current of approximately 10 mA. Next, oping computer mainframes, fiber-optic
PDF from [1]. The Eagle files are also included increase the voltage to 3.3 V. Using trimpot R7, data transmission systems, remote radio
in the download. set the current to around 80 mA. Then, reduce heads for wireless networks, and contact-
the voltage again. At around 3.1 V, the current less energy transmission systems. He is
The footprints for T1 and T2 allow placement of should drop back to the quiescent level. This currently active as a consultant, with a
both DPAK and D2PAK components. For IC2, indicates that the undervoltage shutdown is particular passion for knowledge transfer.
you can use either an LM2662 or an LM2663, working properly. With an input voltage of 5 V
so there shouldn’t be any problems procuring and trimpot R7 set to its minimum value, the
the components. If you don’t need the booster, current should be less than 30 mA. Other- Questions or Comments?
you can omit the components marked with wise, the current can be reduced by closing If you have technical questions or
an asterisk (*). In any case, you should pay solder bridge SJ2. comments about this article, feel free
careful attention to the heatsinks for IC1 and to contact the Elektor editorial team at
T10, because the reliability of the current sink To put the booster into operation, turn trimpot [email protected].
essentially depends on them. The heatsinks’ R40 counter-clockwise to prevent any base
thermal resistance must be less than 2 K/W, current flowing into T10, then remove the
and the semiconductor devices must be jumper on JP5. With an input voltage of 15 V
mounted using high-quality thermal pads and a current of 1 A, adjust trimpot R40 so
Related Products
and metallic screws with suitable washers, that the voltage regulator’s input current is
with proper attention to insulation. 0.6 A. You can measure the voltage regula- > Siglent SDL1020X-E
tor’s input current from the voltage drop over Programmable DC Electronic Load
Getting Started with the Current R41 or R42 at JP5. There, 1.0 V corresponds (200 W)
Sink https://elektor.com/19254
to 0.6 A. Next, increase the input voltage to
If you use an LM2663 for IC2, solder bridge 25 V and the current to 2 A. If necessary, you > PicoScope 2204A USB
SJ1 must be closed. Fit a jumper on JP5 can adjust the setting after the current sink Oscilloscope (10 MHz)
(BstDis). Using trimpot R7, adjust the current has warmed up. https://elektor.com/17303
RG, Translated by Kenneth Cox — 220388-01

WEB LINK
[1] Project downloads at Elektor Labs: www.elektormagazine.com/labs/adjustable-current-sink-with-integrated-clock-generator

48 September & October 2023 www.elektormagazine.com


lektor September & October 2023 49
REVIEW

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.

More Peripherals on the UNO R4


Replacing an old 8-bit, 28-pin controller with a modern 32-bit 64-pin
device has, as you may expect, an impact on the complexity of
the product. However, this touches mainly the software part, as
indicated by the MCU’s ±1,400-page-long datasheet (versus fewer
than 300 for the ATmega328). The UNO R4 Minima board is of
similar design complexity as the R3. The UNO R4 WiFi is a denser
board, as it uses the Minima’s empty board space for an 8×12 LED
matrix and an ESP32-S3-MINI-1 module.

The datasheet is so long because the Renesas MCU features many


Figure 1: The UNO R4 boards are powered by a Renesas R(7F)A4M1 more peripherals than the Microchip ATmega328. Not all of these
microcontroller. are supported by the R4s because not all the pins of the MCU are

50 September & October 2023 www.elektormagazine.com


Figure 2: The SWD connector on the UNO R4 Minima. Figure 3: The Arduino UNO R4 WiFi has an 8×12 matrix of red LEDs.

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.

lektor September & October 2023 51


about the
Video: Learn R4 from Arduino
Arduino UNO s engineers
and Renesa u.be/vrZ_aJnFd-Q
https://yout

Figure 4: The boards’ input voltage range is 6 V to 24 V.

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

52 September & October 2023 www.elektormagazine.com


developer’s zone
Tips & Tricks, Best Practices and
Other Useful Information

Logarithmic
Potentiometers They ’re Exponential!

By Joseph Kreutz (Germany)


The Ideal Volume Potentiometer
Ideally, when you turn a volume In order for the sensation to be as proportional as possible to the
control on an amplifier or a position (rotation or translation) of the control device, the law respected
by a potentiometer should be complementary to a logarithmic function.
mixer desk, you want there to An exponential function suits this requirement best. We can define a
be a linear relationship between parameter to represent the position of a potentiometer:
the angle of the control and the
amount of sensation that your ear Effective Rotation Effective Translation
α= = (I)
perceives. A result that is close Maximum Rotation Maximum Translation
to this ideal is obtained thanks
As this control has a minimum (in principle, 0) and a maximum (in
to “logarithmic” potentiometers, principle, 1), if follows that 0 α 1. The ideal potentiometer should
which are actually exponential. thus have a characteristic corresponding to
Let’s look at this a bit more closely.
S = Sref • 10α Fp = 20•10−6•105α

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)

lektor September & October 2023 53


IN OUT

Rp

R1

210082-004

Figure 1: By adding a resistor to a linear potentiometer as shown here, it is


possible to approximate an exponential response.

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

54 September & October 2023 www.elektormagazine.com


because at low levels the attenuation is reasonably close to an ideal
exponential and tends towards an effectively zero value. For this, consult Related Products
the manufacturers’ characteristic curves.
> Douglas Self, Small Signal Audio Design (2nd
For a volume control for use in a mixing desk or at the input of an ampli- Edition) (Routledge 2014)
https://elektor.com/18046
fier, a linear potentiometer loaded with a resistor will give complete
satisfaction. Even though the control shows some anomalies at low > Elektor Fortissimo-100 Power Amplifier Kit
levels, the use of a resistor with a linear potentiometer also allows a https://elektor.com/20273
substantial reduction in the level of thermal noise. This is a signif-
icant advantage in many applications, particularly for professional
equipment.
210082-01

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

lektor September & October 2023 55


PROJECT

Motor Driver
Breakout Board
A BoB for a 5 A DC Motor Driver with a 3×3 mm Size

By Edwin van den Oetelaar (The Netherlands)

Today’s makers and students are often in a hurry and lack


the skills to design and solder electronic circuits. They
are more into “shields,” and handling a soldering iron is
Figure 1: Functional a challenge. So, I’ve developed a breakout board for the
block diagram.
(Source: Monolithic
Monolithic Power Systems MP6619 motor driver, which
Power Systems [1]) can be used well for one’s own motor-based projects.

56 September & October 2023 www.elektormagazine.com


Chip Features

> 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, my curiosity was piqued, and I wanted to know


if this was true and whether it would be useful for my
projects. So, I ordered a few. After just two days, they The OCP (Over-Current Protection) is adjustable with
were on my desk: Wow, they were tiny! Only 3×3 mm an external resistor. Without that, the chip switches
with 0.2 mm between the contacts and no legs. What off when the voltage across the shunt resistor reaches
have I gotten myself into? 200 mV. The datasheet suggests a shunt of 0.04 Ω,
which limits the maximum current to 5 A (V = I × R).
I dive headfirst into this subject. Despite the low price By adding an R(i-set) of 80 kΩ, the limit is set to 100 mV,
of around €2.50, the small dimensions and unusual allowing you to reduce the current limit when using
footprint of the MP6619 turned out not to be directly the same shunt resistor. Other resistor values are also
applicable to my projects. A BoB was needed that possible. I chose a shunt of 0.05 Ω for my first test
would make the MP6619 more manageable and because I had it in my drawer. This results in an output
suitable for testing and integration. current limit of 4 A.

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,

lektor September & October 2023 57


starts operating. At that moment, the MP6619’s VCC
output provides a voltage of 5 V. I used a small 100 nF
decoupling capacitor to stabilize this voltage. If the
5 V is up, the N-channel MOSFETs also become active.
Depending on the input levels at IN1 and IN2, either
the high-side or low-side MOSFETs are switched.

It is safe to have 3.3 V to 5 V logic levels at the inputs.


So it is no problem to connect the BoB to an ESP32

or an Arduino. For my initial tests, I used switches to
apply 3.3 V to the inputs, and connected the motor to
Figure 2: 3D model of the those other “normal” SMD components were child’s the BoB’s outputs.
first PCB. play; they seemed gigantic compared to the QFN.
The solder island for the PCB terminal block is larger Partial Success
than the entire QFN chip (Figure 2)! I posted this first My motor didn’t want to spin, the nFault output
version on the Elektor Labs website [2]. immediately went low (error indication LED turned
on), but I didn’t have a short circuit at the output.
First Tests Significantly reducing the input voltage eventually
The first tests were done with a small DC motor [3] allowed me to slowly rotate the motor counterclock-
that was on my workbench. It was a simple 12 V model wise and clockwise. It’s important to note that I didn’t
with a stall current of under 5 A (Figure 3). provide any PWM speed control yet.

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.

Removing these capacitors partially helps to control


the motor at somewhat higher voltages. Meanwhile,
after studying the datasheet more carefully, I also had
improvement plans for my BoB design and decided
to create a new version.

New Design and Layout
Figure 3: The first tests For my second version, the design and the layout had
were done with a DC to be adjusted. I made the following changes:
planetary geared motor.
(Source: E-S Motor /
RobotShop [3])
> Only one MP6619 chip.
> The position of the shunt was revised.
> A 0.1" pin header instead of terminal blocks; no
mounting holes.

58 September & October 2023 www.elektormagazine.com


VIN

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

> A clear silkscreen; only the minimal number of


components.

This resulted in a new schematic (Figure 4) and subse-
Figure 5: 3D model of
quently also a new PCB (Figures 5 and 6) with four the 25×25 mm BoB (top
layers and an outline of only about one square inch side) consisting of four
(25×25 mm) produced in a production panel with layers and ENIG finish.
ENIG finish (electroless nickel immersion gold). After
populating the BoB, I got a really compact module,
which, I believe, can be controlled by nearly every
microcontroller.

More Tests and Experiments


I used the same motor as in the first test. OVP and
ULVO behaved well. Now I tried it with PWM control
to realize speed control. Testing with frequencies from
1 kHz to 50 kHz yielded the expected behavior: The
motor was nicely controllable. The example from the
datasheet uses 20 kHz, and that worked fine at low
voltages.

But, at higher voltages, again the OCP kicked in and the


motor stopped. By adding an extra 220 µH inductor
(from the workbench, like the one from Figure 7) in
series with the motor, the control behavior was signifi-

cantly improved, and the speed range was increased.
Figure 6: 3D model of
As a result, the motor delivered more power, and the BoB (bottom side)
the OCP kicked in less frequently. With these extra with pin headers.

lektor September & October 2023 59


Resistors
(SMD 0805)
R1, R3 = 10 Ω
R5 = 100 kΩ
R8 = 0Ω04, 2 W, SMD 2512
R9, R10 = 1 kΩ

R13 = 80 kΩ
Figure 7: A toroidal-core
inductor in series with Capacitors
the motor improves the C1, C3, C5 = 100 nF, 50 V, SMD 0805
BoB’s behavior.
C7, C10 = 4.7 µF, 35 V, SMD 1210
C8 = 100 µF, 35 V, electrolytic, ø 8 mm

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

MCU via an optocoupler in the same manner as the


1µ 1µ
other way around. In such a case, the connected micro-
R6
VCC 35V 10V
VCC
470Ω

controller’s GPIO will need a pull-down resistor.


4 1
+V
U6 QFN Packages
The FCQFN packages (Figure 9) can have irregu-
PC817 12 11 10
NC

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

2 3 Small vias can be placed within the pad areas (via in


GPIO OUT 1 2 3
PAD). On multilayer PCBs with power and ground
210657-016
planes, vias can directly connect these pads to the
planes. In other cases, copper must be directly attached

60 September & October 2023 www.elektormagazine.com


 Figure 9: MP6619 QFN-19 package pinout.
(Source: Monolithic Power Systems [1])

are building small robots and other creative projects.


All design files and production files are open-source
and can be found on my GitHub page [5]. The MP6619
is widely available in small quantities from distributors
such as Farnell, Mouser, and directly from Monolithic
Power Systems.
210657-01

About the Author


Edwin van den Oetelaar works as an engineer for
Fontys ICT, the Netherlands. He is a member of the
High Tech Embedded Software Research Group, led
to the pads to dissipate heat from the IC to larger copper by Prof. Teade Punter. As a specialist in hardware and
areas. A layout guideline is available at [4]. software development, Edwin relishes the opportunity
to tackle diverse technical projects. His proficiencies
The greatest obstacle I encountered during this project span a broad array of domains, such as streaming
was soldering the MP6619 chip. To overcome this data, smart devices, healthcare, IoT, image process-
problem, I experimented with various techniques, and ing, and applied AI.
eventually succeeded with lots of flux, leaded solder
and hot air, but it remained a challenge to place the
chip precisely. Questions or Comments?
If you have any technical questions, you can
Once in place, the molten solder’s surface tension contact the Elektor editorial team by email at
ensures that the chip is properly aligned with the [email protected].
pads. A lot of practice turned out to be necessary. My
conclusion is to purchase a hotplate to simplify the
soldering process.

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

lektor September & October 2023 61


developer’s zone
Tips & Tricks, Best Practices and
Other Useful Information

From Life’s Source: Shutterstock / wk1003mike

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,

62 September & October 2023 www.elektormagazine.com


Finally, the phosphors in today’s LED lamps
contain a diverse range of exotic elements, Figure 3: A Urdox PTC resistor.
including the rare earth metals yttrium, cerium, Photo: Ilse Joostens.
and europium. Although these do not look very
poisonous according to their data sheets, the Industrial sensors such as thickness gauges,
lack of extensive toxicological data is a cause concentration gauges, or sensors for measur-
for concern. ing the moisture content of materials also
sometimes contain radioactive substances.
Patriotism There’s not a big chance you’ll come in contact
Along with the previously mentioned poison- with these devices, but that’s not true with the
ous substances, older components in particu- (now-prohibited) ionization smoke detectors.
Figure 1: A selenium rectifier. Source: Wikimedia lar sometimes contain radioactive substances. In the early days, there were some types with
/ Binarysequence / https://creativecommons. For example, some tube filaments are coated radium-226, but more recent devices contain
org/licenses/by-sa/3.0.
with materials such as thorium oxide or made americium-241. That reminds me of the man
of a thorium-tungsten alloy — including the who accidentally smoked the radioactive
as long as things go well, but the smell of an filament of the magnetron in your microwave source from that sort of smoke detector in a
overheated selenium rectifier is something you oven. Uranium can be found in the form of cannabis vaporizer. He didn’t get high from
never forget. The hydrogen selenide released uranium dioxide in the former Urdox PTC it, but, according to the story, it had a strange
in that situation not only has an obnoxious resistors (Figure 3) and as uranium glass in taste [7].
odor, but is also highly poisonous [4]. Not that certain tubes. And then there’s a whole list
anyone has ever died from it — a small mercy. of radioactive vacuum tubes, radar tubes, The former Soviet Union also had their own
surge protectors, and gas-filled spark gaps smoke detectors, but, for patriotic reasons,
Another substance in the rogue’s gallery is [6]. Just about anything you can imagine — americium-241 was a no-go, so they used
cadmium, best known from nickel-cadmium fluorescent lamps, fluorescent lamp starters, reactor-grade plutonium instead, and quite
rechargeable batteries, but also present in metal-hydride lamps, and even Nixie tubes a bit of it — as much as 18.5 MBq in the KI-1
LDRs, cadmium-telluride solar panels, sensors, — can contain radioactive material. smoke detector [8]. At the time, electronic
transparent conductors, sometimes in SMD components were not very sensitive, so a
resistors, and even in PVC wire insulation. That strong source was necessary. Still, it’s a strange
means that it’s almost everywhere. realization that something like that hung over
your head in many government buildings.
Mercury, previously used in batteries, mercury
switches, Nixie tubes, energy-efficient lamps, After all this, I hope you will still be able to get
fluorescent lamps, mercury lamps, and mercu- a good night’s sleep. In practice, things are
ry-arc rectifiers, is a well-known hazardous not so bad as long as you don’t do something
substance. Fluorescent lamps are still on the crazy and don’t inhale too much magic smoke.
market, and Uncle Ali is your friend if you’re However, there is a problem for workers who
looking for mercury switches. Antique octopus- recycle electronic waste, so let this be a plea
style mercury-arc rectifiers are especially fasci- for more sustainable electronic products.
nating, even a bit unworldly, with their spooky
blue glow (Figure 2) [5]. If you break one of Figure 2: A mercury-arc rectifier. Source: Translated by Kenneth Cox — 230411-01
them, it’s time to call in a HazMat team. Wikipedia / Timberwind / Public Domain.

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/

lektor September & October 2023 63


INDUSTRY

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

64 September & October 2023 www.elektormagazine.com


LTE-M NB-IoT
LTE Cat M1 LTE Cat M2 LTE Cat NB1 LTE Cat NB2
3GPP Release Release 13 Release 14 Release 13 Release 14
Peak Uplink Rate 1 Mb/s 7 Mb/s 66 kb/s 160 kb/s
Peak Downlink Rate 1 Mb/s 4 Mb/s 26 kb/s 127 kb/s
Voice over LTE yes yes no no Figure 1: LTE-M offers
mobile IoT with higher
Duplex full / half full / half half half data rates and VoLTE,
while NB-IoT targets static
Latency <15 ms <15 ms <10 s <10 s applications.

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].

Achieving Low-Power IoT with Cellular


Power is one of the core requirements for an IoT
application, as it will use primarily either batter-
ies or some other renewable energy source, such
as a solar panel. Both of these wireless technol-
ogies support various low-power modes to give
developers options for improving battery life. The
first of these is PSM, or Power Saving Mode. This
allows the application to place the cellular radio
module in a deep sleep state, resulting in a power
draw of a few microamps in most cases. The device
notifies its cell tower of its intention and can then sleep
for up to 413 days. During this time, there is no way to
pass data to the device. However, when it wakes up, there
is no need to register with the cell tower. Figure 2: Mobile applications, like e-scooter sharing, are better served with
LTE-M. A static application, such as a weather station, benefits from the lower
power demands of NB-IoT. (Source: Shutterstock)

lektor September & October 2023 65


LoRa, on the other hand, provides the developer with more control However, designers often only work on the end node, relying on
over the transmission configuration by setting a spreading factor others for the infrastructure they’ll connect to. Despite LTE cellular
(SF). At SF7, the bit rate is higher, meaning less air time, while at SF12, networks’ ubiquitousness and ease of use for smartphone users, the
the lowest setting, the air time is the longest when transferring the same cannot be said for those hoping to rely upon it for IoT.
same number of bytes. The risk, however, is that SF7 reduces the
range too much for a successful transfer, meaning the exchange of Not for the Faint-Hearted
data must be repeated. During testing, SF7 required just 100 mJ per For the uninitiated, it’s challenging finding reliable guidance on
transaction. However, increasing to SF12 required 250 mJ. what cellular IoT can and can’t do, whether important power-sav-
ing features are available globally, or how to determine their avail-
The conclusion is that, for a 3,000 mAh battery, LoRa using SF7 could ability. As such, it makes cellular IoT look like the poor sibling of
power this configuration for over 32 years, but using SF12 reduces the smartphone industry. Recent news that Vodafone wants to sell
this to just under 13 years. By comparison, using NB-IoT could deliver its business focused on IoT services doesn’t help shake this image.
just under 20 years of operation. Considering that, under real-life Although they sold 150m IoT SIM connections last year [11], that
conditions, LoRa would need to adapt its SF and other transceiver division only makes up 2% of their service revenue.
configuration (bandwidth) to maintain successful data transfers,
such a variation in battery life may be considered too risky. Although research shows cellular IoT to be competitive in power
consumption and battery life compared to alternative LPWAN
Comparing with LoRaWAN solutions, it still has its foibles. With network infrastructure
This risk is also highlighted in research from a team at the Univer- from some providers and in some countries failing to imple-
sity of Antwerp [9]. In their conclusion, they also state that, while ment power-saving support universally, engineers will clearly be
LoRaWAN consumed the lowest power under controlled laboratory uncomfortable committing to battery life values that are attrac-
conditions indicating an application life of years, “with the real time tive to customers. What is clear is that each LPWAN approach has
[sic] deployment it narrowed down to a few months.” They also tested disadvantages, and design teams need to weigh them all up based
NB-IoT alongside Sigfox and DASH7 [10]. While DASH7 offered even on each use case. And, it would seem a healthy portion of research
better power consumption than LoRaWAN under the same condi- time is also needed to achieve, as far as possible, an apples-to-apples
tions, the team surmised that NB-IoT may still be the better option comparison of the LPWAN solutions that fit the bill most closely.
despite the slightly higher power consumption. NB-IoT may simply
tick more boxes when factoring in everything an IoT application 230376-01
requires, such as availability, latency, coverage, security, robustness,
and throughput.
Questions or Comments?
Wireless technology has been democratized over the past two decades Do you have technical questions or comments about this article?
thanks to CMOS radio transceivers, highly integrated radio modules, Email the author at [email protected] or contact Elektor
and tiny antennas. Even the software stacks are often freely available. at [email protected].

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

66 September & October 2023 www.elektormagazine.com


FEATURE

Wireless Communication
in IoT Systems
Using Arduino MKR Modules
The Right Board for Wi-Fi, LoRa, and Many More Standards

Contributed by Transfer Multisort Elektronik Sp. z o.o.

In this article, we present a brief overview of selected Arduino development


kits from the MKR family for rapid prototyping of IoT devices using wireless
communication in standards such as WiFi/Bluetooth, LoRaWAN/Sigfox,
GSM/3G, or NB-IoT.

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

Partner Content lektor September & October 2023 67


the ATSAMW25 module [5], containing the subject of smart cities. Unfortunately, Wi-Fi/ Arduino MKR WAN 13x0 modules work
SAMD21 microcontroller, WINC1500 [6] radio Bluetooth/BLE standards are used over short with Arduino IoT Cloud, which is provided
path and the ECC508 [7] authentication chip. distances and do not meet all the requirements by the manufacturer. The complexity of the
The MKR 1010 kit is fitted with the NINA-W102 set for “Smart City” projects (which include, solutions provided is complemented by the
radio module from u-blox [8], which offers among others, extensive networks of pollu- Arduino Pro Gateway LoRa Connectivity [12],
Bluetooth/BLE communication. tion sensors, water level monitoring sensors, optimized for MKR WAN 1310 modules.
and parking lot sensors). The solution to these
On the software side, Arduino provides the problems may be the use of one of the two An interesting alternative to LoRa/LoRaWAN
WiFi101 library, supporting WEP and WPA2 most popular communication standards in is the Sigfox standard, which places particular
personal encryption for the MKR WiFi 1000 the LPWAN (Low-Power Wide Area Network) emphasis on communication from nodes to the
modules. For the MKR WiFi 1010 module area — LoRaWAN or Sigfox, which enable access gateway. The Arduino MKR FOX 1200
(and other kit s based on the u-blox small amounts of data to be transmitted over [13] module, based on the Atmel SAMD21
NINA-W102 module, including the Arduino long distances. For the rapid prototyping of microcontroller, was made available to design-
NANO 33 IoT [9]) the manufacturer has devices using LoRa/LoRaWAN, communi- ers. The Microchip Smart RF ATA8520, tuned
prepared the WiFiNINA library, as well as a cation, Arduino designers have prepared the to ISM 868 MHz band assigned for Europe, is
number of sample applications demonstrating MKR WAN 1300 [10] development kit, and responsible for radio communication.
integration with Android IoT Cloud and Azure, its successor, the MKR WAN 1310 [11]. Both
AWS IoT Core, Google Firebase, or Blynk. modules are based on the Atmel SAMD21 GSM/3G:
microcontroller, used in other Arduino MKR Arduino MKR GSM 1400 module
LoRaWAN and Sigfox: Arduino series modules, and the Murata CMWX1ZZABZ Even an extended mesh network operat-
MKR WAN 13x0 and FOX 1200 radio module. The newer version of the module ing in the LoRa/LoRaWAN technologies is
modules is additionally equipped with 2 MB of flash currently unable to provide global coverage.
The rapid development of IoT systems memory, a new battery-charging circuit, and In the case of IoT projects requiring almost
has resulted in an increased interest in the low-power optimized power supply circuits. unlimited communication range, the best

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.

68 September & October 2023 www.elektormagazine.com Partner Content


solution is to use the GSM/3G standard. (NB-IoT) standard, which use the licensed
Arduino has prepared the MKR GSM 1400 [14] LTE 800 MHz band for communication.
module for GSM/3G communication, featur- Similarly to LoRaWAN and Sigfox solutions,
ing a SARA-U210 modem from u-blox and NB-IoT belongs to LPWAN networks, thus
a Microchip ECC508 secure authentication ensuring stable communication over large
module for the implementation of communi- areas with the use of energy-saving radio
cation security mechanisms. The built-in GSM modules that ensure many years of battery
modem operates in the following frequency operation. Thus, it provides another alterna-
bands: GSM 850 MHz, E-GSM 1900 MHz, tive to LoRaWAN and Sigfox communication
DCS 1800 MHz, and PCS 1900 MHz. in “Smart City” solutions.

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.

Narrowband IoT: Arduino Transfer Multisort Elektronik Sp. z o.o.


MKR NB 1500 module: Headquarters
When briefly characterizing selected ul. Ustronna 41
communication standards for Internet of 93-350 Łódź, Poland
Things devices, it is impossible to ignore [email protected]
solutions based on the Narrowband IoT www.tme.eu/en

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

Partner Content lektor September & October 2023 69


BACKGROUND

AC Losses in
Magnetic Components
Avoid Hot Inductors!

By George Slama (Würth Elektronik eiSos)

One of many problems a power supply designer


faces is the unexpected overheating of magnetic
components that were previously selected with
great care. This unexplained behavior can leave the outside influence is removed, the magnetic
designer confused and frustrated, all of which add dipoles in the domains reorient and domain
walls jump back, but not completely. When
pressure to completing their project successfully on the direction of current changes, the magnetic
time and within budget. Accurate AC loss estimation poles in the domains again reverse direction,
is a complicated topic and not for the faint of heart. but not completely. The energy resulting from
the spring back is returned to the system, but
Fortunately, an easy-to-use solution is available. the rest is expended as work done against
the friction of other domains and is converted
to heat. The higher the frequency, the more
times per second the elementary magnets
Despite often looking like simple devices, components such as inductors and capacitors in the domains and domain areas are moved
power supplies are complex projects to to be smaller because the energy storage per and shifted, and the more energy is required
design, with many conflicting requirements cycle is lower. Their size is proportional to their — exponentially more. The movement of the
pressed on by the end user and a multitude of energy storage capacity. However, reducing magnetic dipoles is also proportional to the
regulatory agencies. The end user wants the the size reduces the surface area available to flux change. Greater flux swing equals more
least-expensive solution, often in the small- dissipate heat from losses, making the thermal movement equals more energy required, not
est package, with the highest reliability. The design more critical. all of which is recovered. The area within the
regulatory agencies want minimum thickness BH curve represents the energy loss through
insulation and creepage distances, which In a magnetic device, there are two sources one cycle.
result in larger components. The designer of losses: the windings and the core. Both
must have a broad knowledge in many areas can be further divided into subtypes (Table 1). Eddy current losses stem from the fact that,
besides electrical, mechanical, and control when alternating currents flow through a
theory. Add to this the mystery of magnetics What Are Core Losses? conductor, a voltage is induced, per Faraday’s
— where invisible forces act on materials to The root of hysteresis core losses lies in the law, proportional to the magnetic field’s rate
store or transform energy based on age-old movement of the magnetic dipoles and, at of change. The core itself is like a winding,
cryptic formulas from the past — and it’s no high saturation currents, in the displace- and, although the ferrite material used in
wonder the designer seeks a simpler solution ment of the core material’s domain walls. high-frequency technology has a high resis-
to select the proper magnetic device. When a soft magnetic material is influenced tance, the small particles conduct. This resis-
by an external magnetic field, caused by a tivity characteristic changes exponentially
Take the buck regulator as an example, simply current in a coil or a nearby magnetic field, downward as temperature increases. Faster
because it is the most widely used topology for the magnetic dipoles in the domains (tiny rise times induce higher voltages, and pulses
reducing voltage in non-isolated circuits. The magnetic regions with elementary magnets of higher voltage have exponentially greater
goal of size reduction is realized by increasing in the material), align themselves with the losses, according to P = (V2 × D) / R (where
the switching frequency. This allows passive field. This takes energy and time. When the D = duty cycle and R = resistance).

70 September & October 2023 www.elektormagazine.com Partner Content


Figure 1: Minor loops are shown at various positions along the major loop. Figure 2: Alternating currents induce a magnetic field, which introduces
They all have the same peak-to-peak flux swing. The loop area is hysteresis eddy currents in the opposite direction, cancelling current flow in the center
core loss per cycle. region and reinforcing it in the outer region.

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)

Partner Content lektor September & October 2023 71


to check the extremes of your design. Charts
immediately give the full performance range,
Figure 3: Currents in adjacent wires. Left: with current in the same direction. Right: with current in the including temperature effects. This allows the
opposite direction. Red is high current density; blue is low density. user to compare the merits of each inductor to
their own satisfaction. Then download only the
most suitable inductor’s file, and, at the same
increases and is not cancelled by a secondary DC bias, ripple current, and temperature. This time, you can order free samples.
winding. With each additional layer, the losses rich data set of total AC losses includes all the
increase exponentially, since the magneto effects of construction methods, wire types, REDEXPERT will save your work automati-
motive force is the product of the magnetic core material, and excitation waveform. No cally when you click on the share icon in the
flux and the magnetic resistance (reluctance). need to do tedious and complicated calcu- top menu bar, where a unique URL will be
lations, often with missing information, or presented. Save it to your design book, or
It’s clear to see why single-layer, edge-wound to try modelling losses with arrays of resis- email it to yourself or a colleague to share.
flat wire inductors (aka helical wound coils) tors, inductors, and capacitors in order to run The exact display you see will be reproduced
have become so popular in high-current simulations for each possible choice. when you need it again.
inductors. The current, whether AC or DC, will 230470-01
still crowd around the path of least resistance, The Würth Elektronik eiSos online induc-
which is the inside diameter, but the added tor selection tool, REDEXPERT (Figure 4)
proximity losses from multiple layers is gone. provides convenient access to this data with
the ability to compare multiple inductors
Inductor Selection With instantly. Simply select the converter type,
REDEXPERT enter the basic operating conditions, and all
Over the years, Würth Elektronik eiSos has usable inductors are presented. From these,
taken thousands of loss measurements of sort and select down to a list of inductors that
inductors in its portfolio under real-use condi- meet your requirements, including size, height
tions — rectangular waveforms, duty cycle, and shape. Easily adjust operating conditions About the Author
George Slama has been designing and
working with transformers over his entire
40+ year career. His design experience
extends from milliwatt audio and telecom
transformers to ferro-resonant, radar,
high voltage, small three-phase, high-fre-
quency switching and LTCC transform-
ers and inductors. His work has included
quality control, automated testing and
manufacturing engineering as well as all
aspects of custom switch mode power
supply design and development. George
has given numerous magnetics design
seminars at conferences in the US and
Europe. Currently, he is working as a senior
application and content engineer at Würth
Elektronik, developing application notes
and tools to help power supply designers
Figure 4: Tables and charts in REDEXPERT allow for quick and accurate comparison of inductors. solve their magnetics challenges.

WEB LINKS AND LITERATURE


[1] Baguley, C., Carsten, B. Madawala, “The Effect of DC Bias Conditions on Ferrite Core Losses,” IEEE Transactions on Magnetics,
Vol. 44, No. 2, February 2008.
[2] Barbisio, E., Fiorillo, F., Ragusa, C., “Predicting Loss on Magnetic Steels Under Arbitrary Induction Waveform and With Minor
Hysteresis Loops,” IEEE Transactions on Magnetics, Vol. 40, No. 4, July 2004.
[3] Online simulation platform REDEXPERT: https://redexpert.we-online.com

72 September & October 2023 www.elektormagazine.com Partner Content


BACKGROUND

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.

Partner Content lektor September & October 2023 73


Figure 2: The RFX-8440 provides a highly configurable L-Band capture card
suitable for RF test and measurement or volume deployment applications.

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.

Figure 3: The Teledyne T3SP-D4MX provides


a two-channel, DC to 10 GHz 1:4 multiplexer
controllable via a DLL or the WinD4MX.exe GUI.

74 September & October 2023 www.elektormagazine.com Partner Content


Figure 4: Designed for remote operation and
collaboration, Keysight’s Smart Bench Essentials
test and measurement equipment unites
traditional operation with cloud connectivity.

The Smarter Bench


While laptop-connected test equipment can
offer a lot in a small package, it clutters the
bench. It also makes it more challenging to
use the computer for email, report writing, and
the inevitable video call. Keysight Technolo-
gies’ Smart Bench Essentials [8] is a family landscape, advanced and configurable RF test cloud-based control. It seems that, which-
of traditional, stackable, test and measure- approaches, or solutions that can cloud-enable ever way you look, there is a cloud approach
ment tools with industry-grade connectivity, older, still-useful manufacturing equipment. available for test and measurement.
well-dimensioned 7-inch (18 cm) displays, and Display-less oscilloscopes, thanks to their 230458-01
measurement-sharing capabilities. programmability, can be repurposed as highly
versatile, remote test and data logging tools. Mouser Electronics
The family consists of two- and four-chan- These, too, are capable of streaming their Hillbottom Road
nel oscilloscopes, a 5½ digit multimeter, one measurements to cloud platforms for further High Wycombe
and two-channel arbitrary waveform genera- analysis. Finally, even traditional, one-instru- HP12 4HJ
tors, and a triple-output programmable power ment-per-box test equipment offers advanced United Kingdom
supply (Figure 4). The required bench real and robust connectivity, enabling efficient lab +44 (0) 1494-427500
estate can be minimized using the instrument management, measurement sharing, and [email protected]
stacking kit. The BenchVue software provides
data logging and analysis. However, the main
attraction is the PathWave Lab Management
software. Managers and educators can keep
track of equipment connected via wired Ether-
net or Wi-Fi, roll out firmware updates, or make
the measurement tools available remotely via About the Author
the cloud. Stuart Cording is a freelance journalist who writes for, amongst others,
Mouser Electronics. He specializes in video content and is focused on
Test and Measurement for technical deep-dives and insight. This makes him particularly interested in the technology
Cloud Deployment itself, how it fits into end applications, and predictions on future advancements.
Cloud connectivity continues to increase
in the markets engineers address, requir- Mouser Electronics is an authorized semiconductor and electronic component distributor
ing an on-site understanding of the wireless focused on new product introductions from its leading manufacturer partners.

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

Partner Content lektor September & October 2023 75


BACKGROUND

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.

Once these requirements are mapped out, it’s time to


determine the system architecture (Figure 2):

76 September & October 2023 www.elektormagazine.com Partner Content


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

Partner Content lektor September & October 2023 77


REVIEW

YARD Stick One A Sub-1 GHz Wireless Test Tool

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

78 September & October 2023 www.elektormagazine.com


The controller used in the CC1111 is a MCS51 variant and needs
SDCC (Small Device C Compiler) [7] version 3.5 or lower. It requires
some manual work during installation, as the current version is
4.x. However, many users will just be using the rfcat firmware.

Using the YARD Stick One


The CC1111 radio does all the low-level work, adding and remov-
ing pre- and post-ambles, sync words, CRC, plus modulation and
demodulation. The radio must be fully configured before use, as
Figure 1: Rfcat spectrum display. the reset configuration is useless. Writing a small Python program
as outlined in [8] saves a lot of typing and errors.

Rfcat comes with a spectrum display as well. Calling it an “analyzer”


If you receive an Error in resetup(), unplug and reinsert the is a bit of a stretch — most of the simpler devices have a limited
device. bandwidth and dynamic range, unlike the boat anchors such as
the HP141 or HP181 that can display 1 GHz bandwidth at an 80 dB
Windows 10: Do not install Python via Microsoft Store, as it messes dynamic range.
up the file permissions; install manually for all users. Additionally,
you should enter: To use the YARD Stick One as a receiver, the Layer 1 and Layer 2
properties must be configured correctly, or the radio will ignore
pip install Cython the packet. To analyze an unknown signal, an additional SDR is
needed; the cheapest hardware for this are the RTL dongles. Besides
In any case, install with admin privileges (see where the Linux using GNU Radio and Audacity as shown in [9], the Universal Radio
instructions require sudo). And have a VC > 14 installed. Hacker [10] provides a more integrated workflow for signal analysis
and replay. Alternatively, the setting of the peer’s radio chip can be
Required tweak if you get an error message about “collections not sniffed from the hardware interface if the type of chip is known,
callable:” add .abc in C:\Program Files\Python310\Lib\site-packages\ as shown in [11].
pyreadline\py3k_compat.py on line 8:
Using the YARD Stick One as a generic receiver is rather awkward:
return isinstance(x, collections.abc.Callable) when using too generic settings a lot of noise is received; with
too tight settings everything is filtered out. It might work with a
The pyreadline package is said to be only required for Windows. variable attenuator at the input, but I did not have one at hand.

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

Figure 2: Symbol view.

lektor September & October 2023 79


is a much better choice. For transmitting, you have a generic SDR
transceiver for €150 more (e.g., HackRF One or Adalm Pluto).

The YARD Stick One might be of use when you concentrate on


the specific protocols supported by this family of radio SoCs. (See
IM-Me [14] as mentioned on the Elektor site.) For dedicated applica-
tions, one could consider a CC111x breakout board [15] from China
Figure 3: Data view. connected to an Arduino, which avoids the awkward USB commu-
nication.
230388-01
interface. After a Python exception, the YARD Stick One must be
unplugged and reinserted; otherwise, rflib does not find it anymore.
The following example shows a PWM signal with ASK modula- Questions or Comments?
tion, which is very common for simple remotes. The screenshots If you have technical questions or comments about this article,
are from URH. feel free to contact the Elektor editorial team by email at
[email protected].
Each data bit consists of four symbols, a 0 is transmitted as 1000
and a 1 is transmitted as 1110, so this must be sent to the YARD Stick
One as 8e88888888888888888e8e8e8. One symbol is 0.484 ms, so
the baud rate must be set to 2744.
Related Products
Documentation > Great Scott Gadgets YARD Stick One – Sub-1 GHz
The documentation [4] pointed to by the Elektor Store is very Wireless Test Tool
sparse. The forum indicated by Great Scott Gadgets is of limited https://elektor.com/20088
use. The rfcat git repository gives a lot of information on building
> Great Scott Gadgets HackRF One Software Defined
and downloading the YARD Stick One firmware.There are some Radio (1 MHz to 6 GHz)
tutorials on the Internet, see for example [13]. Please adapt to the https://elektor.com/18306
local rules for the ISM band.
> Great Scott Gadgets GreatFET One Universal USB
Verdict https://elektor.com/19114
The YARD Stick One is not cheap for what it offers and has a rather > Elektor Raspberry Pi RTL-SDR Bundle
steep learning curve. The software isn’t perfect, and the documen- https://elektor.com/19518
tation is on the lighter side. For analysis only, a simple SDR receiver

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

80 September & October 2023 www.elektormagazine.com


COMPONENTS

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.

I have come across various types of latching relays in frequency-in-


jection devices. These are basically devices on the electricity network
that switch power to streetlights or hot water systems and the like; they
can be remotely controlled using a special coded frequency injected
onto the power wires (hence the name). Because latching relays are
used, these devices consume almost no power in either state, and
require only a short pulse of power to change it.

Latching relays would also be useful in other applications where power


needs to be switched without consuming much of it. For example, in
solar charge controllers where you want the maximum power from
a solar panel to go towards charging a battery, but also to be able to
switch the solar panel out of circuit during the hours of darkness — or Figure 2: 2-coil latching relays from Panasonic with 4 changeover contacts.

lektor September & October 2023 81


PROJECT

PIC O’Clock
In Touch with Time
Designing an SDR Time Signal Receiver

By Marco Rohleder (Germany)

When you’re designing a time signal


receiver, there’s no getting around the
concept of software-defined radio (SDR).
Elektor has published many articles
about software for decoding these
signals, and here we focus on
the required hardware. In this
connection, the aim was to manage
with a minimum of processing power
by using a simple 8-bit microcontroller
equipped with peripheral functions that work
control transmitters, such as DCF49 at
independently of the CPU. Remarkably enough, 129.1 kHz (also in Mainflingen) and DCF39
at the end of the development process described at 139 kHz in Burg near Magdeburg, that
here, the PIC MCU used was even able to receive and transmit the current time of day. As a bonus,
DCF39 and DCF49 have a transmit power
decode two different time signals at the same time. of 100 kW, significantly more than the 50 kW
transmit power of DCF77. Various meteoro-
logical services, such as maritime weather
reports, are also still active on these frequen-
How can one construct a time signal receiver Capacitors and resistors in 0805 packages cies. Wouldn’t it be nice to be able to receive
using readily available resources? The key can be easily soldered by hand, saving space all these stations (and even more) in the
component required for extracting the on the circuit board. However, soldering a longwave band as desired?
time signal is a microcontroller (MCU), so four-lead IC with very small lead spacing is
an obvious approach is to utilize the exist- more challenging. Getting Started Is Always
ing resources within the microcontroller as Difficult
much as possible. This means that the receiver Along with the DCF77 signal at 77.5 kHz from My first attempts to amplify the DCF77 signal
should rely heavily on software and minimize Mainflingen near Frankfurt, there are many from a ferrite rod antenna tuned to 77.5 kHz
the use of additional hardware. other transmitters in Europe and elsewhere and view the carrier frequency on an oscil-
in the world that broadcast the current time, loscope to see how its amplitude varied at a
Moreover, the objective is to avoid using exotic including MSF60 at 60 kHz in Great Britain, 1 Hz rate were bitterly disappointing. Unfor-
and hard-to-find components, instead favor- TDF162 at 162 kHz in France, and WWVB at tunately, there is a lot of noise present in the
ing standard components whenever possible. 60 kHz in the USA. In addition to dedicated longwave band. Switching power supplies
This is especially true for SMD components. time signal transmitters, there are also ripple and LED lighting systems in all shapes and

82 September & October 2023 www.elektormagazine.com


sizes, mainly of Asian origin, create a noise We’ll go through these blocks one by one and
level that in some cases is considerably higher fill them with content.
than the desired signal. When you look at the
mishmash of all possible signals, it’s difficult to Preselector with MOSFET
believe that the DCF77 signal can be extracted Variable Capacitance
from this. Even the most effective and steep-edged
filters implemented in software and the best
The commercial modules are apparently and fastest A/D converters are of no use if
designed as simple straight-through receiv- they are swamped by interference and the Presector
ers using a 77.5 kHz crystal as a very narrow desired signal is lost in the noise. There’s no
210244-002

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

To allow the tuning range of the MOSFETs


to be used as well as possible, they must
LPF be driven by a higher voltage than can be
provided by the DAC in the microcontroller.
Booster
Accordingly, an LM358 opamp is used to
Backlight Display Amplifier
LM386
boost the signal from around 0…4.2 V to the
required voltage range of 0…30 V.

210244-019

Figure 1: Time signal receiver block diagram.

lektor September & October 2023 83


DAC1 IC132B +4V3
5
7
LM358 R35
6 VCCA1

2k2
R133 OSC1 ST31
VCC 5
33k ANT1
4

Alternative Resonant Circuits


R34 OSC VCC1
R134 C36 3
OSC GND1
5k6

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.

The feedback turns the preselector into a


C34 C33 C32 C31 C30
resonant circuit whose oscillation frequency
10n 4n7 2n2 1n 470p is approximately the same as the resonant
frequency, but in the longwave band. There’s
T34 T33 T32 T31 T30

T30...T34 = BC817-40 a small difficulty: At the envisaged receive


frequency, the phase shift from the input
to the feedback changes, unfortunately, so
210244-003
the circuit does not always resonate at the
TUNE 1E TUNE 1D TUNE 1C TUNE 1B TUNE 1A
expected resonant frequency.

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

least if you want to avoid routing the sensi-


2µ2

tive antenna signal crisscross over the board


210244-005 layout. For this reason, I opted for an external
comparator (IC70) to keep the signal paths as
Figure 5: An oscillator based on an opamp. short as possible.

84 September & October 2023 www.elektormagazine.com


CHECKING TUNER ...

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.

lektor September & October 2023 85


100
90
80
Capacitance (pF)
70
60
50 and not too low. For this, I used the opamp
40 integrated into the PIC18F46Q71 microcon-
troller, configured as an inverting amplifier
30
and connected in series with the input. A
20 nice feature here is that a resistor network
10 is also available to set the gain, and in this
configuration it enables gain factors as high
0
0 5 10 15 20 25 30 as 15. Like the DAC, the reference voltage of
the ADC can be selected between 1.024 V and
Reverse Voltage (V) 4.096 V, representing an additional fourfold
gain factor. And, if you use only eight of the
Figure 8: Junction capacitance nonlinear curve. (Source: Digikey — A/D converter’s available twelve bits, you get
https://tinyurl.com/3js37yjn) an additional adjustable 16-fold gain. Overall,
this means that the gain can be adjusted over
a range of 1:14,400 (14,400 = 15 × 15 × 16 × 4),
as illustrated in Figure 10.
+4V3

R20
As six bits are actually enough to reliably
MIX decode the signal (as demonstrated below),
100Ω

the dynamic range can be increased to


MCLK
C20 1:57,600 (four times the above value) — more
than 95 dB. That should be enough, no matter
HFSEL 10µ
8 7 4
IC20
MCP2036 R21 whether you’re 2,000 km away from the trans-
mitter on only a few meters away.
1M
HFSEL CLK VDD VDET+ 14
C21
2 LREF
HF1 1 47p
10k MXOUT
12
C94
Now we just have to generate a variable local
NF
3 LBTN 10k 100n
oscillator frequency for the mixer. For this as
HF2
well, I used the microcontroller’s peripherals.
0 C22

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.

86 September & October 2023 www.elektormagazine.com


Figure 10: Adjustable overall gain.

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

shift), two fast comparators, and a hardware


1 2 5
100n 1µ
SPK CLK
3 4 4
DAT
5 6 3
VSS CRC unit, which are not used in this project.
7 8 2
VDD
9 10 1
MCLR

+5V PICICSP The microcontroller is also equipped with a


hardware multiplier, so it can provide the right
MCLR
1
RE3/MCLR RB7/IDAT
40
ICSP DAT processing power needed for complex compu-
tations, such as executing a Hilbert filter to
2 39
OSC2 VCC RA0 RB6/ICLK ICSP CLK
3 38
OP1 OUT RA1 RB5 MCU CS
DAC1
4
RA2 IC1 RB4
37
MCU SCI suppress the image frequency.
5 36
OSC2 OUT RA3 PIC18F46Q71 RB3 OSC1 VCC
6 35
NF RA4 RB2 DAC2
MCLK
7
8
RA5 RB1
34
33
OP2 OUT Figure 12 shows the microcontroller with
TUNE 2E MCU SI
all of its input and output signals. ST3 is the
RE0 RB0
9 32
MCU A0 RE1 VDD

ICSP programming port, and several I/Os


10 31
HF SEL RE2 VSS R9
11 30
VDD RD7 TEST
12 29 * are routed to connector ST1 for debugging
VSS RD6 LED
13 28
14
RA7
RA6
RD5
RD4
27
BOOST
TUNE 1E
purposes. This allows serial data to be trans-
TUNE 2D
15
16
RC0 RC7
26
25
TUNE 1D mitted using the UART, for example to display
TUNE 2C
OSC1 OUT 17
RC1
RC2
RC6
RC5
24
TUNE 1C
TUNE 1B
the operating range of the preselector or to
configure additional high-resolution PWM
18 23
TUNE 2B RC3 RC4 TUNE 1A
19 22
TUNE 2A DBG
signals to output analog values for debugging
RD0 RD3
20 21
BL RD1 RD2 AUDIO
Q81
the individual stages of the SDR demodulator.
C86 C87

A Suitable GUI
16MHz

33p 33p

Of course, the receiver should also have a


user interface in the form of a small graphic
210244-012

Figure 12: The brains of the time signal receiver: the PIC18F46. display and control buttons, along with a

lektor September & October 2023 87


+5V

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

Figure 14: Audio output with the old faithful LM386.


1µ 1µ
D1
10k

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.

88 September & October 2023 www.elektormagazine.com


As the voltage on the USB port is largely
unregulated, 3 V LDO voltage regulator IC2
first generates a clean operating voltage
from the USB voltage for the digital part of
the signal processing. The ground potential of
the voltage regulator is raised by two silicon Figure 17:
diodes, resulting in an output voltage (VDD) DIY loop antenna.
of 4.3 V. This is low enough to compensate for
voltage variations at the USB port and high
enough for the reference voltage sources used
in the microcontroller.

Now, let’s go back to the beginning: For the


tuning voltage, the 5 V USB voltage must be
raised to a much higher level. This is done
by an unregulated boost converter with a
refreshingly simple design (Figure 16). The
Figure 18: Good
PWM signal used to drive T70 is generated by
reception can be
the microcontroller with a suitable duty cycle. achieved using fixed
The Zener diode limits the output voltage to a inductors in an unusual
maximum of 33 V. Although this circuit is not configuration.
especially efficient, the current consumption
is low and is essentially determined only by
the opamp’s quiescent current, so efficiency
is not a significant issue in this case.

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

lektor September & October 2023 89


Two receivers are better than one #define FILTERDEPTH 25
Although the circuit was originally only designed to receive typedef struct {
data and time signal broadcasts in the longwave band, the int16_t Ihistory[FILTERDEPTH];
mixer has a second switchable input, so I decided to add int16_t Qhistory[FILTERDEPTH];
an additional preselector with its own antenna. This can be int32_t Iaverage;
fitted with components for either longwave or medium-wave int32_t Qaverage;
reception. As became apparent in the course of developing uint8_t index;
the software, this even allows signals at two different uint8_t lastQuadrant;
frequencies to be received at the same time. int8_t phaseChange;
} IQ;
Unfortunately, the microcontroller I used here has only one IQ *iq;
NCO, so I had to resort to a trick to generate the second void IQcallback( int16_t I, int16_t Q ) {
local oscillator frequency. I used one of the two 16-bit
universal timers to generate the lower local oscillator uint8_t quadrant =0;
frequency. Although the timer is clocked by the 64 MHz
system clock, it is possible to come fairly close to the // moving average lowpass filter I
desired local oscillator frequency. At 77.5 kHz (DCF77), iq->Iaverage -= iq->Ihistory[iq->index];
for example, the error is only 200 Hz. If the second iq->Ihistory[iq->index] = I;
universal timer is used to generate the sampling rate for iq->Iaverage += I;
the intermediate frequency, it can be adjusted between
2,000 Hz and 2,200 Hz with a resolution of around 1 Hz, // moving average lowpass filter Q
making it possible to compensate for the previously iq->Qaverage -= iq->Qhistory[iq->index];
described error. The NCO of the other receiver circuit has iq->Qhistory[iq ->index] = Q;
to be adjusted according to the resulting new intermediate iq->Qaverage += Q;
frequency.
iq->index++;
Of course, the crystal used has only finite accuracy. If we if( iq->index >= FILTERDPTH ) {
assume the accuracy to be 50 ppm, the error at 77.5 kHz is iq->index =0;
4 Hz. This is too much for the very narrowband filter used }
for decoding. Nevertheless, the error can be determined // integrate phase shift > phase error >
by software. If the signal from the desired transmitter can estimate frequency offset of crystal
be received with an adequate signal level, the frequency if( iq->Qaverage<0 ) quadrant =1;
correction can also be performed automatically. For this if( iq->Iaverage<0 ) quadrant ^= 3;
purpose, the software must measure over an interval of if( iq->lastQuadrant == ( (quadrant+1) & 3 ) )
four periods whether the I/Q vector is rotating clockwise or iq->phaseChange--;
counterclockwise. If this is done over a defined time period, if( iq->lastQuadrant == ( (quadrant-1) & 3 ) )
it gives you an indication of how much the actual local iq->phaseChange++;
oscillator frequency differs from the desired frequency. A if( iq->phaseChange < -90 )
higher-level control function can then reduce or increase iq->phaseChange = 90;
the intermediate frequency to bring the difference close if( iq->phaseChange > 90 )
to zero. The following listing shows how this can be iq->phaseChange = -90;
implemented in C. iq->lastQuadrant = quadrant;
}

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

90 September & October 2023 www.elektormagazine.com


in three-way and four-way versions, so it someone out there will have the desire and
would even be possible to relocate part enthusiasm to help move this project forward?
of the circuit, such as the tuning capaci- Let us know! Related Products
tors, to the antenna assembly. Translated by Kenneth Cox — 210244-01
> Bert van Dam,
> Suitably modify the preselectors, so that PIC Microcontrollers (Elektor 2008 )
the receiver would be able to receive E-book, PDF:
signals in the medium-wave band (AM Questions or Comments? https://elektor.com/18093
broadcast band) or allow it to be used for If you have any technical questions
amateur radio purposes. Practical exper- or comments about this article,
> Tam Hanna, Microcontroller Basics
with PIC (Elektor 2020)
iments have shown that the mixer can feel free to contact the author at Book, paperback:
be operated up to the single-digit MHz [email protected] https://elektor.com/19188
range. or the Elektor editorial team at E-book, PDF:
[email protected]. https://elektor.com/19189
As you can see, SDR does not necessarily
have to be implemented with high-speed
32-bit microcontrollers, which are often only About the Author
available in packages that are hard to solder Marco was born in 1970 and was interested
by hand. With clever use of the peripherals of in electronics from a very early age. He
an 8-bit microcontroller, it is possible to substi- worked on electronics in his teens, studied
tute for one or more functions and ultimately electrical engineering at some point in time,
arrive at an easily implementable design. and has been active in R&D for around
35 years. He is presently employed by a
As always, this sort of project lives or dies US semiconductor manufacturer. Marco is
with the number of participants who contrib- also a radio amateur and answers to the
ute to the effort. In particular, implementing callsign DD9DD.
the software takes a lot of time. But perhaps

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.

lektor September & October 2023 91


ETHICS IN ELECTRONICS

Source: Midjourney AI-generated image.


Prompt: “/imagine prompt: Back of person with lots of papers
under his arm moving toward factory --ar 3:5”

Due
Diligence
Directive
Business as Usual Will Not Do

By Priscilla Haring-Kuipers (The Netherlands)

Currently rolling through the EU is the


Corporate Sustainability Due Diligence
countries under common EU legislation, the power
Directive or CSDDD [1]. The EU Parliament to effectively and sufficiently address environmen-
just voted generally to accept these new tal concerns and social inequality can be combined.
rules, and will continue to negotiate some Moving together is better.

of the finer points for another year. Things The Ask


are about to change. This directive concerns big EU companies with
hundreds of employees and millions in turnover, as
well as non-EU companies that make millions in the
EU market. At its core, the CSDDD [3] is a way to force
Our Sustainable Development Goals include the these big companies to take responsibility “by carry-
promotion of sustained, inclusive and sustain- ing out the following actions:
able economic growth. In the Paris Agreement, we
promised to keep global warming within 1.5°C, and (a) integrating due diligence into their policies
the private sector, with all their investments, must be (b) identifying actual or potential adverse impacts
in line with this if we are to keep our promises. Under (c) preventing and mitigating potential adverse
the European Climate Law, we are committed to being impacts, and bringing actual adverse impacts to
climate-neutral by 2050 and to reduce our emissions an end and minimizing their extent;
by at least 55% in 2030. All of this means that there (d) establishing and maintaining a complaint
must be a change in the way companies produce and procedure;
procure. Business as usual will not do. (e) monitoring the effectiveness of their due diligence
policy and measures;
Many issues in our global supply chains would be hard (f) publicly communicating on due diligence”
to tackle by any one company or even one country.
These new due diligence rules intend to even the Companies will need to investigate themselves and
playing field within the EU market and prevent their entire supply chain. When uncovering ‘adverse
fragmentation in law. Germany already has a Supply impacts,’ they must create corrective action plans with
Chain Act or “Lieferkettensorgfaltspflichtengesetz” clear timelines and qualitative as well as quantitative
[2], while other EU countries have limited require- metrics for improvement. Workers, unions and civil
ments. By connecting all the big companies of many society organizations must be able to make human

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).

The CSDD protects human and environmental rights


throughout the lifecycle of a product and throughout
the entire chain. This should mean that big digital
companies are going to have to include the manufac- 
turing of their hardware as part of their responsibility.
Source: Midjourney
AI-generated image.
Small and medium-sized enterprises (SMEs), which Prompt: “/imagine
make up 99% of all companies in the EU, are not prompt: EU Parliament
included in the CSDDD. However, big companies will with EU flags --ar 5:3”

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

September & October 2023 93


BASIC COURSE

Starting Out in
Electronics...
…Voltage Amplification

By Eric Bogers (Elektor)

So far, we have used the transistor


as a switch and as a current
amplifier. Of course, these are
both very important in electronics,
but it really gets fun when we can
amplify voltages. That’s precisely
what we’ll do in this installment.

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.

94 September & October 2023 www.elektormagazine.com


We take a default value of 560 kΩ for R1.

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.

The Constant-Current Source


If we use a LED for some occasion, then, in most cases, we already
have a constant supply voltage available, and it is easy to calculate
the required series resistance accordingly. Besides, it is hardly an
issue if the supply voltage varies (within certain limits): It doesn’t
make much difference whether the LED current flow is 5 mA or
20 mA (although, for reasons of economics, a low current flow is
always better). So, a supply voltage that varies by a factor of four
is still more-or-less acceptable. However, if the supply voltage has
larger variations, then it is recommended to use a constant-current
Figure 2: Catastrophic amplifier circuit — that’s not how it should be done! source.

lektor September & October 2023 95


R1
LED1 LED2

10k
I1 I2

T1

D1 T2
I [mA]
10
D2 I1
8
R2 R3
D3 6
100Ω

2k2
4
I2
230372-007 2

Figure 4: A (more-or-less) constant-current source. 5 10 15 20 25 U [V]

Figure 5: Current flow with and without constant-current source.


The designation “constant-current source” for the circuit in
Figure 4 is actually a bit of an exaggeration, as can be seen from
the graph in Figure 5. On the other hand, this circuit makes it I [mA]
possible to use an LED under conditions where the supply voltage 10
can vary by a factor of 40, and that’s a good thing, anyway.
8

Three diodes connected in series provide a more-or-less constant 6


voltage of about 2 V. This voltage is used to drive a Darlington
4
transistor that has an emitter resistance of 100 Ω. The voltage
across this resistor is about 0.7 V, resulting in a current flow of 2
about 0.7 mA (which is quite correct in practice). On a side note,
a Darlington transistor was not really needed in this example. We 10 100 1k 10 k RL
measured the current through the LED and plotted it in Figure 5.
For comparison, we also measured the current through an LED Figure 6: Constant-current source with varying load resistance.
with only a series resistor and plotted it on the same graph.

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.

Of course, you might wonder why we would need a constant current


with varying load resistance. Well, without such a current source,
the differential amplifier would be impossible — and the differen-
tial amplifier (perhaps the most important circuit in electronics)
will be discussed in the next installment of this series.

230372-01

96 September & October 2023 www.elektormagazine.com


ELEKTOR BOOKS

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

Arduino & Co – Measure


Measure, Control, and
Clever Tricks with
Hack
ATmega328 Pro Mini Board
Measure, Control, and
Let’s do something crazy: Let’s combine
s
With a simple Pro Mini board
20 or 30 years ago were
and a few other compone
unthinkable (or would have
nts, projects that Hack
cost a small fortune)
Clever Tricks with
an Arduino Pro Mini (or compatible)
are realized easily and aff
ordably in this book: From
to a full battery charging simple LED effects
and testing station that
#define me
ATm
will put a rechargeable
asurega
e_pin328
through its paces, there’s
ProMeas
Robert Sontheimer was

Min
something for everyone

All the projects are based


. immediately on board
when the
first home computers arrived A3 // i Boards
uring

with a BMP180 air pressure and an SD


on the ATmega328 microcon
endless measuring, switching troller, which offers our living rooms some
in
float r_nt input (A0
and A1 us
40 years
c2
float r_fi 5 = 50000; // re
, and control options with ago, with his ZX81 and
output lines. For example its 20 input and C64. Back
then, he converted a plotter ed for di
you can build a voltmete
, with a 7-segment display
and a few resistors, into a
xed = 4700 sistance splay)
, Control, and Hack •
r or an NTC-based thermom scanner, among other
platform offers the perfect eter. The Arduino
quirky and
original ideas, and today float r_fa 0; // fixe of the NT
C at 25 de
5°) NTC ve ctor[33] = // R-fa d resistor (exa
card module, and explore long-term
development environm he uses
this range of boards. ent for programming Arduino Pro Minis to control

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

infrasound level recording.


that’s
measure, and what? Which own ideas. How to been levitating for years
– controlled 6, 0.535, , 4.23, 3. of
transistor is suitable for
0.107, 0.
091, 0.07 0.438, 0.36, 0.3, 27, 2.54, 1.99, 1.
load? When is it better to switching a certain by a Pro Mini, of course.
use an IC? How do you Just a regular freak.
switch mains voltage?
Even LilyPad-based battery-o
0.0294}; 79, 0.0671 0. 57, 1.25,
, 0.0585, 25, 0.21, 0.176,
perated projects are discusse
0.148, 0. 1,
well as many different motors, d in detail, as
from simple DC motors
to stepper motors. 0.0507, 0. 126,
0441, 0.03
Sensors are another exciting
topic: For example, a simple byte digi 85, 0.0334
ts ,
boolean co = 4; // number
that can give disused remote infrared receiver
controls a new lease on
home, and a tiny compone life controlling your
nt that can actually measure
mmon_anode of digits
air pressure between floor
and table height!
the difference in
byte segm = false; //
ent_pin[8]
Robert Sontheimer

byte digi = {11,A1,6 fa ls e for comm


t_pin[6]
= {4,A0,13 ,8,9,12,5,7}; // on cathode
,10}; // a,
int freque last to fi b,c,d,e,f,g,poin
ncy = 200; rst digit t
Editor’s Note: This article is an excerpt from the 332-page Elektor Elektor International Media
float chan
byte segm
ge_frequen
// freque
cy = 0.
ncy of di
sp lay in
BV ents[20] 5; // refr Hz (about
www.elektor.com
= // bit es h display 10
book, Arduino & Co — Measure, Control, and Hack. The excerpt was B1111110,
pattern (a
to g) for every 2
0 to 300)
the differ seconds
B0110000, ent digits
B1011011, B1101101,
formatted and lightly edited to match Elektor Magazine’s conven- B1110111,
B1011111,
B0011111,
B1110000,
B1 11 10
B1111111,
01, B01100
11, // 0,
B1000111, B1 rt Sont 1,2,
B0000001,Robe00 1110 er111101 B1111011, // 5,6, 3,4
tions and page layout. Being an extract from a larger publication, this B1100011,
heim
, B0
B0000000,
, B1001111 7,
, // A,b, 8,9
B0000000 C,d,E
article may refer to discussions elsewhere in the book. The author // F,

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.

lektor September & October 2023 97


Figure 1: Graph progression for air pressure (above) and temperature Figure 2: Graph progression of air pressure (above) and temperature
(below), essentially unprocessed. (below), processed.

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 1b: Here, we have the recorder settings. The variable


oversampling also determines the number of pressure measure-
ments. To record 100 values per second, this setting must be 0.
audio_rate, on the other hand, specifies how many values per
second will be delivered when we later play back the recording as
an audio file. max_file_size determines the maximum record-
ing length. However, the 10 minutes refers to the playback time
— the corresponding recording time is several days. However, we
can adjust this value almost arbitrarily. When the maximum file
size is reached, the file is closed and a new recording is started.
Figure 3: Connection diagram for BMP180 sensor, SD card module, switch,
and Arduino. The duration variable determines the delay between measurements.

98 September & October 2023 www.elektormagazine.com


However, the times here are 500 μs longer because we do not work // low pin on output ...
with delays, but rather with a fixed clock here, during which the pinMode(low_pin, OUTPUT);
Wire instructions for temperature and pressure measurement // ... and LOW [...]
are also executed. digitalWrite(low_pin, LOW);

Listing 1b }
// 0 -> 1x, 1 -> 2x, 2 -> 4x, 3->8x
char oversampling = 0;
// sampling rate of the output audio file Listing 1e: In loop(), we now have only the alternating calls of
long audio_rate = 44100; temperature and pressure measurement because in order not to
// 10 minutes’ playback time (at 44,100 Hz) lose time, we do not wait there in each case with a delay for the data,
unsigned long max_file_size = 105840044; but use the waiting time for all further tasks. For the temperature
// time (µs) according to oversampling measurement, function calculate() is called while we wait for
int duration[4] = ; the result. For the pressure measurement, we call the recording()
// time for temperature measurement function.
int t_duration = 5000;

Listing 1e
void loop() {
get_t(); // read temperature
Listing 1c: After the special variables for temperature and pressure get_p(); // read pressure
calculation, which we skipped here again, these variables will be }
needed later for the recorder.

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() {

// if pressure has already been measured before


Listing 1d: setup() starts with the definition of the pins for the if (p) {
push button. Due to the active internal pull-up resistor, we do not …
need any further components. }

Listing 1d // if zero value has not been determined yet


void setup() { if (!zero_value) {
// switch pin on input with pull-up // cancel if no measurement has been taken yet
pinMode(record_pin, INPUT_PULLUP); if (!pressure) return;

lektor September & October 2023 99


// actual value as zero line
Listing 1h
zero_value = pressure; // search for the first not yet used
// actual value as zero line // recording number
zero_temp = b5; do {
} file_number++; // next number (starting with 1)
} // repeat with next number while
// pressure value for recording //file already exists
record_value = pressure - zero_value;
while (SD.exists("FILE_" + String(file_number)
// max value if clipping + ".wav"));
if (record_value > 32767) Serial.println("Recording no."
record_value = 32767; + String(file_number)
// negative clipping + " is started!");
else if (record_value < -32768) wave_file = SD.open("FILE_"
record_value = -32768; + String(file_number)
// temperature value for recording + ".wav", FILE_WRITE);
temp_value = b5 - zero_temp;
// max value if clipping if (!wave_file) { // if file could not be opened
if (temp_value > 32767) temp_value = 32767; Serial.println
// negative clipping ("Error: File could not be opened!");
else if (temp_value < -32768) temp_ // do not continue (infinite loop)
value = -32768; while (true);
} }

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

100 September & October 2023 www.elektormagazine.com


combine the altimeter (from section 13.8 in our book) with the
SD card functions so we can write a corresponding text line into
a file for each serial output as well. This way, we get the weather
recording as a text file.

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].

About the Author


Robert Sontheimer was immediately on board when the first
home computers arrived in our living rooms some 40 years ago,
with his ZX81 and C64. Back then, he converted a plotter into a
scanner, among other quirky and original ideas, and today he uses
Arduino Pro Minis to control entire CNC laser machines and has
even invented a matching suction system: his “self-changing toilet
paper filter.” In his office, he has a magnet that’s been levitating for
years – controlled by a Pro Mini, of course.

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

lektor September & October 2023 101


PROJECT

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

102 September & October 2023 www.elektormagazine.com


Figure 4: InfluxDB logo.

Figure 1: The ESP32 board. Figure 2: The PZEM-004T sensor


with transformer.

+ F

5V POWER SUPPLY
N
̱

230VAC

TOROID

Figure 3: The circuit’s wiring diagram.

electronics, isolated by optocouplers, and has a serial interface. The


module can accurately measure voltages ranging from 80 V to 260 V,
with a resolution of 0.1 V and an accuracy of 0.5%. Similarly, it can
measure currents from 0 A to 100 A with an accuracy of 0.5% and
a resolution of 0.001 A. Additionally, the sensor can determine the
phase angle (power factor) between voltage and current vectors with Figure 5: InfluxDB registration page.
1% accuracy, providing readings for active and reactive power. This
capability allows us to evalute the electrical efficiency of the device
being measured. The selection of circuit components was based on
cost-effectiveness, considering the ongoing semiconductor crisis, and
the ESP32’s impressive specifications.

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.

InfluxDB is versatile software that provides functionality such as creat-


ing dashboards, running queries, and sending alerts. It offers multiple
deployment options, including executable versions for various archi-
tectures, Docker containers, and cloud-based solutions. Although
initially we intended to install an instance on a Raspberry Pi for data
ownership reasons, the scarcity of components forced us to adopt the
InfluxDb Cloud v2 service instead.

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.

lektor September & October 2023 103


Figure 7: Choice of subscription plan. Figure 8: Creating a new bucket.

Figure 9: A newly created bucket.

Figure 10: Selection of data upload source.

Figure 11: Snippet of a demo sketch.

104 September & October 2023 www.elektormagazine.com


including the service provider name. For our project, we have selected
Amazon Web Services (AWS) as the provider. Listing 1: Including the libraries.
#include <WiFiMulti.h>
On the subsequent screen (depicted in Figure 7), you will need to
#include <ESPmDNS.h>
select a usage plan. In our case, we opted for the free plan, which
#include <WiFiUdp.h>
grants data storage for a duration of 30 days and the ability to receive
#include <ArduinoOTA.h>
notifications via Slack.
#include <InfluxDbClient.h>
#include <InfluxDbCloud.h>
After confirming our selection, the personal dashboard will be displayed.
#include <PZEM004Tv30.h>
To create a bucket, navigate to Load Data → Buckets → Create new
#include <Every.h>
bucket. This action will open a screen similar to the one depicted in
Figure 8. Fill in the Name field and click on the Create button. Once
the bucket is successfully created, it will appear among the available
data sources, as shown in Figure 9.
libraries are employed for OTA (over-the-air) uploading of sketches and
Next, click on Add data → Client library. A new screen will appear, host-name management. Please make sure to have Python version
offering various options for uploading data. From these alternatives, 2.7.x installed on your PC for this functionality. The InfluxDbClient
select Arduino (Figure 10). In the subsequent window (Figure 11), and InfluxDbCloud libraries are used for data upload to the InfluxDB
you will see a series of code snippets that constitute a demonstration Cloud. The PZEM004Tv30 library [7] facilitates serial communication
sketch. Copy the data provided for INFLUXDB_URL, INFLUXDB_ORG, with the sensor. Lastly, the Every library allows the execution of code
and INFLUXDB_BUCKET from the first snippet. blocks at regular intervals without relying on delay().

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:

InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG,


INFLUXDB_BUCKET, INFLUXDB_TOKEN,
InfluxDbCloud2CACert);

Finally, the sensor object is created with Point sensor("EnergyMeter").


This object, named EnergyMeter, will be associated with all the data
collected by the sensor. The code in Listing 3 represents the board
Figure 12: Creating an API key. setup and initializes the serial port at a baud rate of 115,200.

lektor September & October 2023 105


Listing 2: Definitions
#define REFRESH_TIME 5000 // Delay interval for data upload
#define DEVICE "ESP32"
#define PZEM_RX_PIN 27
#define PZEM_TX_PIN 26
#define PZEM_SERIAL Serial2

/*************************
ESP32 initialization
---------------------

The ESP32 HW Serial interface can be routed to any GPIO pin


Here we initialize the PZEM on Serial2 with RX/TX pins 26 and 27
*/
PZEM004Tv30 pzem(PZEM_SERIAL, PZEM_RX_PIN, PZEM_TX_PIN);
WiFiMulti wifiMulti;
IPAddress local_IP(192, 168, 178, 154);
IPAddress gateway(192, 168, 178, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress primaryDNS(192, 168, 178, 1); //optional
IPAddress secondaryDNS(1, 1, 1, 1); //optional
// WiFi AP SSID
#define WIFI_SSID ""
// WiFi password
#define WIFI_PASSWORD ""
// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com
// (Use: InfluxDB UI -> Load Data -> Client Libraries)
#define INFLUXDB_URL "https://eu-central-1-1.aws.cloud2.influxdata.com"
// InfluxDB v2 server or cloud API token
// (Use: InfluxDB UI -> Data -> API Tokens -> Generate API Token)
#define INFLUXDB_TOKEN ""
// InfluxDB v2 organization id (Use: InfluxDB UI -> User -> About -> Common Ids )
#define INFLUXDB_ORG ""
// InfluxDB v2 bucket name (Use: InfluxDB UI -> Data -> Buckets)
#define INFLUXDB_BUCKET "Energy Meter @ ElettronicaIN"
// Set timezone string according to
// https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html
#define TZ_INFO "CET-1CEST,M3.5.0,M10.5.0/3"
// InfluxDB client instance with preconfigured InfluxCloud certificate
InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG,
INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert);
// Data point
Point sensor("EnergyMeter");

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");
}

106 September & October 2023 www.elektormagazine.com


wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to wifi");
while (wifiMulti.run() != WL_CONNECTED) {
//Serial.print(".");
//delay(100);
Serial.println("Connection Failed! Rebooting...");
delay(5000);
ESP.restart();
}
Serial.println();
// Port defaults to 3232
// ArduinoOTA.setPort(3232);
// Hostname defaults to esp3232-[MAC]
ArduinoOTA.setHostname("ESP32-Energy Meter");
// No authentication by default
// ArduinoOTA.setPassword("admin");
// Password can be set with it’s md5 value as well
// MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
// ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");
ArduinoOTA
.onStart([]() {
String type;
if (ArduinoOTA.getCommand() == U_FLASH)
type = "sketch";
else // U_SPIFFS
type = "filesystem";
// NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end()
Serial.println("Start updating " + type);
})
.onEnd([]() {
Serial.println("\nEnd");
})
.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
})
.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
ArduinoOTA.begin();
// Add tags
sensor.addTag("Dispositivo", DEVICE);
// Accurate time is necessary for certificate validation and writing in batches
// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/
// Syncing progress and the time will be printed to Serial.
timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov");\
// Check server connection
if (client.validateConnection()) {
Serial.print("Connected to InfluxDB: ");
Serial.println(client.getServerUrl());
} else {
Serial.print("InfluxDB connection failed: ");
Serial.println(client.getLastErrorMessage());
}
}

lektor September & October 2023 107


The code block begins with WiFi.mode(WIFI_STA); which initializes the ESP connects to the two NTP (network time protocol) servers
Wi-Fi in station mode for connecting to an access point. The next pool.ntp.org and time.nis.gov to obtain the date and time.
block of code:
Finally, the code block attempts to connect to the InfluxDB servers:
if (!WiFi.config(local_IP, gateway, subnet,
primaryDNS, secondaryDNS)) { if (client.validateConnection()) {
Serial.println(“STA failed to configure”); Serial.print(“Connected to InfluxDB: ”);
} Serial.println(client.getServerUrl());
}
sets a static IP instead of using DHCP. If there is an error, a warning else {
message is printed to the serial port. If you want to use DHCP, you Serial.print(“InfluxDB connection failed: ”);
can comment out this part of the code. Serial.println(client.getLastErrorMessage());
}
The wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD) function call
attempts to connect to the access point using the specified SSID If the connection is successful, the server URL is printed to the serial
and passphrase. port. If not, the corresponding error message is printed, instead.

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!),

108 September & October 2023 www.elektormagazine.com


Listing 4: loop()
void loop() {

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();
}
}

lektor September & October 2023 109


Figure 13: Creating the dashboard.

Figure 14: Adding the dashboard graphics.

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

110 September & October 2023 www.elektormagazine.com


Figure 15: The completed dashboard.

Conclusion About the Author


This concludes the description of our simple but powerful energy Emanuele Signoretta was born in 2000 in Vibo Valentia, a small city
meter. The flexibility of the ESP32 board and the many features of in the south of Italy. He is passionate about all the stuff concerning
the supported network protocols and platforms allow us to expand ICT. While attending High School, he discovered Arduino and its
its fields of application according to our needs, perhaps by integrat- programming simplicity. Starting there, he wrote code for Arduino
ing the meter into a load-management system, and still be capable and Fishino boards. Now, he’s started with STM32- and ESP32-based
of autonomous actions. boards. He believes in the open-source ethos and uses Linux-based
230279-01 distros. Emanuele is currently completeing his Bachelor’s Degree in
Electronic and Communication Engineering at Politecnico di Torino.
Furthermore, he works for Rai, the Italian national broadcaster.
Questions or Comments?
Do you have technical questions or comments about this article?
Email Elektor at [email protected].

Related Products
> ESP32-C3-DevKitM-1
https://elektor.com/20324

> Koen Vervloesem, Getting Started with ESPHome,


Elektor 2021
https://elektor.com/19738

> Bundle: Getting Started with ESPHome + LILYGO TTGO


T-Display ESP32 (16 MB)
https://elektor.com/19896

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

lektor September & October 2023 111


SOFTWARE

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:

blinking LED demo with the help struct systick {


of a linker script and a Makefile. In volatile uint32_t CTRL, LOAD, VAL, CALIB;

this installment of the series, we };


#define SYSTICK ((struct systick *) 0xe000e010)
deal with accurate timing via system
clocks, the UART, and debugging. Next, add an API function that configures it. We need to enable
SysTick in the SYSTICK->CTRL register, and also clock it via
RCC->APB2ENR, as described in section 7.3.14 of the manual [4]:
Editor’s note: This guide is a living document on GitHub [1] and it grows.
So, we decided to extend this series by an additional installment, which #define BIT(x) (1UL << (x))
you will find in the next edition of Elektor (11-12/2023). static inline void systick_init(uint32_t ticks) {
// SysTick timer is 24 bits
if ((ticks - 1) > 0xffffff) return;
Blinky with Systick Interrupt SYSTICK->LOAD = ticks - 1;
For our first LED “Blinky” demo, we used a delay function called SYSTICK->VAL = 0;
spin() that just executed NOP instructions a given number of // Enable systick
times (see the first part of the series at [2]). SYSTICK->CTRL = BIT(0) | BIT(1) | BIT(2);
RCC->APB2ENR |= BIT(14); // Enable SYSCFG
In order to implement much more accurate timekeeping, we }
should enable ARM’s SysTick interrupt. SysTick is a 24-bit hardware
counter, and is part of the ARM core, therefore it is documented As mentioned, the Nucleo-F429ZI board runs at 16 MHz, which
by the Arm® v7-M Architecture Reference Manual [3]. Looking at means that if we call systick_init(16000000 / 1000), then a
this manual, we see that SysTick has four registers: SysTick interrupt will be generated every millisecond. We should
have an interrupt handler function defined — here’s one that simply
> CTRL — used to enable/disable SysTick increments a 32-bit millisecond counter:
> LOAD — an initial counter value
> VAL — a current counter value, decremented on each clock // "volatile" is important!!
cycle static volatile uint32_t s_ticks;
> CALIB — calibration register void SysTick_Handler(void) {
s_ticks++;
Every time VAL drops to zero, a SysTick interrupt is generated. }

112 September & October 2023 www.elektormagazine.com


Figure 1: Time scale representation of interrupted firmware execution with the SysTick_Handler() function.

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 }

lektor September & October 2023 113


000011000000

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. }

114 September & October 2023 www.elektormagazine.com


Listing 1. UART initialization API function.
#define FREQ 16000000 // CPU frequency, 16 Mhz
static inline void uart_init(struct uart *uart, unsigned long baud) {
// https://www.st.com/resource/en/datasheet/stm32f429zi.pdf
uint8_t af = 7; // Alternate function
uint16_t rx = 0, tx = 0; // pins

if (uart == UART1) RCC->APB2ENR |= BIT(4);


if (uart == UART2) RCC->APB1ENR |= BIT(17);
if (uart == UART3) RCC->APB1ENR |= BIT(18);
if (uart == UART1) tx = PIN(’A’, 9), rx = PIN(’A’, 10);
if (uart == UART2) tx = PIN(’A’, 2), rx = PIN(’A’, 3);
if (uart == UART3) tx = PIN(’D’, 8), rx = PIN(’D’, 9);

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].

static inline void Redirect printf() to UART


uart_write_buf(struct uart *uart, In this section, we replace the uart_write_buf() call with a
char *buf, size_t len) { printf() call, which gives us the ability to do formatted output
while (len-- > 0) — and increase our flexibility in printing diagnostic information,
uart_write_byte(uart, *(uint8_t *) buf++); by implementing so-called “printf()-style debugging”.
}
The GNU ARM toolchain that we’re using comes not only with a
Now, initialize the UART in our main() function: GCC compiler and other tools, but with a C library called newlib [10].
The newlib library was developed by RedHat for embedded systems.

uart_init(UART3, 115200); // Initialize UART If our firmware calls a standard C library function, for example
strcmp(), then a newlib code will be added to our firmware by
Now, we’re ready to print the message, “hi\r\n” every time the LED the GCC linker.
blinks!
Some of the standard C functions that newlib implements, specifi-
if (timer_expired(&timer, period, s_ticks)) { cally file input/output (IO) operations, are implemented by newlib in
… a special fashion: Those functions eventually call a set of low-level
uart_write_buf(UART3, “hi\r\n”, 4); // Write message IO functions called syscalls.
}

lektor September & October 2023 115


Listing 2. The main() function becomes quite compact.
#include "hal.h"

static volatile uint32_t s_ticks;


void SysTick_Handler(void) {
s_ticks++;
}

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);

116 September & October 2023 www.elektormagazine.com


Listing 3. Bunch of linker errors.
../../arm-none-eabi/lib/thumb/v7e-m+fp/hard/libc_nano.a(lib_a-sbrkr.o): in function `_sbrk_r’:
sbrkr.c:(.text._sbrk_r+0xc): undefined reference to `_sbrk’
closer.c:(.text._close_r+0xc): undefined reference to `_close’
lseekr.c:(.text._lseek_r+0x10): undefined reference to `_lseek’
readr.c:(.text._read_r+0x10): undefined reference to `_read’
fstatr.c:(.text._fstat_r+0xe): undefined reference to `_fstat’
isattyr.c:(.text._isatty_r+0xc): undefined reference to `_isatty’

Debug with Segger Ozone


Listing 4. Adding simple stubs. What if our firmware is stuck somewhere and printf() debug does
not work? What if even the startup code does not work? We would
int _fstat(int fd, struct stat *st) {
need a debugger. There are many options, but I’d recommend using
(void) fd, (void) st;
the Ozone debugger from Segger. Why? Because it’s standalone;
return -1;
it does not need any IDE set up. We can feed our firmware.elf file
}
directly to Ozone, and it’ll pick up our source files.
void *_sbrk(int incr) {
So, download Ozone from the Segger website [12]. Before we can use
(void) incr;
it with our Nucleo board, we need to convert the ST-LINK firmware
return NULL;
on the onboard debugger to the jlink firmware that Ozone under-
}
stands. Follow the instructions on the Segger site [13], then:
int _close(int fd) {
> Run Ozone. Choose our device in the wizard (Figure 2).
(void) fd;
> Select a debugger we’re going to use — that should be an
return -1;
ST-LINK (Figure 3).
}

int _isatty(int fd) {


(void) fd;
return 1;
}

int _read(int fd, char *ptr, int len) {


(void) fd, (void) ptr, (void) len;
return -1;
}

int _lseek(int fd, int ptr, int dir) {


(void) fd, (void) ptr, (void) dir;
return 0;
}
Figure 2: Select the device in the wizard.

The serial output looks like this:

LED: 1, tick: 250


LED: 0, tick: 500
LED: 1, tick: 750
LED: 0, tick: 1000

Congratulations! We learned how IO retargeting works, and can


now printf()-debug our firmware. You can find the complete project
source code the step-4-printf folder [11]. Figure 3: Select STLink as debugger.

lektor September & October 2023 117


000011000000

Figure 4: The program to be debugged will be our firmware.elf file.

> 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 5: The debugger is loaded, and soon mcu.h appears.

Figure 6: After we run the firmware, it halts on the SYSTICK->LOAD = ticks - 1; line.

118 September & October 2023 www.elektormagazine.com


Figure 7: Convenient Ozone Peripherals view for easy examination and
configuration of peripherals.

Figure 10: Turning ODR0 on by selecting value 1 in ODR (GPIO).

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.

About the Author


Sergey Lyubka is an engineer and entrepreneur. He holds an MSc
in Physics from Kyiv State University, Ukraine. Sergey is direc-
tor and co-founder of Cesanta, a technology company based in
Dublin, Ireland (Embedded Web Server for electronic devices:
https://mongoose.ws). His passion is bare-metal embedded network
programming.

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

lektor September & October 2023 119


lektor store
www.elektor.com

The Elektor Store


Never expensive, always surprising
The Elektor Store developed from the community electronics. We offer the products that we
store for Elektor’s own products, such as books, ourselves are enthusiastic about or that we simply
magazines, kits and modules, into a mature want to try out. If you have a nice suggestion, we
web store that offers great value for surprising are here: [email protected].

Arduino Nano ESP32


The Arduino Nano ESP32 (with and without headers)
is a Nano form factor board based on the ESP32-S3
(embedded in the NORA-W106-10B from u-blox). This is
the first Arduino board to be based fully on an ESP32,
and features Wi-Fi, Bluetooth LE, debugging via native
USB in the Arduino IDE as well as low power.

Price: €23.95
Member Price: €21.56

www.elektor.com/20562

Radio Builder’s Book


Radio frequency (RF) technology is one of the areas
which still allows putting your own ideas into practice.
Countless circuit variants with special objectives allow
space for meaningful experiments and projects. Many
things simply aren’t available off the shelf.

Price: €34.95
Member Price: €31.46

www.elektor.com/20553

120 September & October 2023 www.elektormagazine.com


Raspberry Pi 4 (4 GB) QuantAsylum QA403
Official Starter Kit 24-bit Audio Analyzer

Price: €799.00
Price: €104.95 Member Price: €719.10

www.elektor.com/20556 www.elektor.com/20530

FNIRSI DSO-TC3 (3-in-1) ESP Terminal (ESP32-S3 based


Oscilloscope, Component Dev Board with 3.5″ Display)
Tester & Signal Generator

Price: €74.95 Price: €44.95


Special Price: €59.95 Member Price: €40.46

www.elektor.com/20520 www.elektor.com/20526

lektor September & October 2023 121


Hexadoku
Puzzles with an Electronic Touch

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.

SOLVE HEXADOKU AND WIN! PARTICIPATE!


Correct solutions received from the By October 15th, 2023, supply
entire Elektor readership automati- your name, street address
cally enter a prize draw for five and the solution (the digits in the
Elektor store vouchers worth €50 gray boxes) by email to:
each, which should encourage all [email protected]
Elektor readers to participate.

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.

122 September & October 2023 www.elektormagazine.com


PROTEUS DESIGN
Driving SUITE
forward with Manual Routing

Push and Shove Routing


for dense layouts

Dedicated Differential Length Matching and


Pairs Routing mode Net Tuning Support

Visual DRC shows legal


paths for route placement

[email protected]
lektor September & October 2023 123
Imagine if the Wright brothers had
partnered with Mouser

With the widest selection of the newest products,™


the sky’s the limit on what engineers can design.

mouser.co.uk/new
+44 (0) 1494-427500

124 September & October 2023 www.elektormagazine.com

You might also like