100% found this document useful (1 vote)
429 views116 pages

Elektor En202405

Uploaded by

Indrek Aarelaid
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)
429 views116 pages

Elektor En202405

Uploaded by

Indrek Aarelaid
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/ 116

£9.95 | €10.95 (DE) | €13.50 (other EU countries) | $12.

95

529 MAY & JUNE 2024


ELEKTORMAGAZINE.COM
S

*
1

*
IN
CE 196

Repairing
Electronic
Equipment
Tools, Techniques, and Tips

FOCUS ON The AmpVolt


Test & Modular
DC Power Meter
Measurement Measure DC Power and
Energy Consumption up
to 50 V and 5 A

10 MHz Reference
Generator
Highly Accurate,
With Distributor and
Galvanic Isolation

Digital Bubble Level and Active In-Circuit LC Meter Measuring pH Value


Stroboscopic Disc for Turntables A Prototype Study with an Arduino UNO With the Arduino UNO R4
Fine-Tune Your Record Player Check the Quality of Your Water
Join the
Elektor C mmunity
Take out a G O L D membership

membership!

The Elektor web archive from 1974!


8x Elektor Magazine (print)
8x Elektor Magazine (digital)
10% discount in our web shop and exclusive offers
Access to more than 5000 Gerber files

Also available The Elektor web archive from 1974!


8x Elektor Magazine (digital)
The Digital G R E E N
membership
10% discount in our web shop and
exclusive offers
membership! Access to more than 5000 Gerber files

www.elektormagazine.com/Member
COLOPHON EDITORIAL

Jens Nickel
Volume 50, No. 529 International Editor-in-Chief, Elektor Magazine
May & June 2024
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 Quite Classic
For all your questions
[email protected] The focus of this issue is test and measurement, and we know from a wide range of feedback
that this is one of the most popular topics among our members. There are certainly several
Become a Member reasons for this. For one thing, it explicitly addresses classic electronics engineers (and I say
www.elektormagazine.com/membership “classic” here with great respect). Measurement and test circuits are very often largely analog
and built with many (discrete) components. There is a lot of knowledge involved in selecting
Advertising & Sponsoring
the right components and you can find clever circuit tricks, too. Knowledge that must not be
Büsra Kas
Tel. +49 (0)241 95509178
lost in times of ever faster prototyping.
[email protected]
www.elektormagazine.com/advertising In addition to their educational purposes (and perhaps a certain show effect), the projects
presented also have practical uses — and precisely where electronics enthusiasts like to spend
Copyright Notice their time the most: in their own labs! We have a long tradition of this. In 1978, Elektor published
© Elektor International Media b.v. 2024 a “TV Scope” with which you could turn a television into an oscilloscope. At the time, this was
a sensational application because you could save an incredible amount of money by taking
The circuits described in this magazine are
for domestic and educational use only. All
a DIY approach.
drawings, photographs, printed circuit board
layouts, programmed integrated circuits, Only very few readers would consider building an oscilloscope today. However, our authors
digital data carriers, and article texts published still find the odd gap in the market or at least an application where soldering actually pays
in our books and magazines (other than off. Take a look at the 10 MHz reference generator on page 96, for example, and there are even
third-party advertisements) are copyright more examples in this issue. I would also particularly like to recommend the article by my
Elektor International Media b.v. and may not
colleague Jean-François Simon, who worked at a repair service and can therefore report on
be reproduced or transmitted in any form
or by any means, including photocopying,
the practical side of component testing (page 26).
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
disclaims any responsibility for the safe and
proper function of reader-assembled projects
based upon or from schematics, descriptions Submit to Elektor! ElektorLabs
or information published in or in relation with Your electronics expertise is welcome! Ideas & Projects
Elektor magazine.
Want to submit an article proposal, an The Elektor Labs platform is open to
electronics tutorial on video, or an idea everyone. Post electronics ideas and
Print
Senefelder Misset, Mercuriusstraat 35,
for a book? Check out Elektor’s Author’s projects, discuss technical challenges and
7006 RK Doetinchem, The Netherlands Guide and Submissions page: collaborate with others.
www.elektormagazine.com/submissions www.elektormagazine.com/labs
Distribution
IPS Group, Carl-Zeiss-Straße 5
53340 Meckenheim, Germany
Phone: +49 2225 88010

The Team
International Editor-in-Chief: Jens Nickel | Content Director: C. J. Abate | International Editorial
Staff: Asma Adhimi, Roberto Armani, Eric Bogers, Jan Buiting, Stuart Cording, Rolf Gerstendorf (RG),
Ton Giesberts, Ouafae Hassani, Hedwig Hennekens, Saad Imtiaz, Alina Neacsu, Dr. Thomas Scherer,
PEFC Certified
Jean-Francois Simon, Clemens Valens, Brian Tristam Williams | Regular Contributors: David Ashton,
This product is from
sustainably managed
forests and controlled
Tam Hanna, Ilse Joostens, Prof. Dr. Martin Ossmann, Alfred Rosenkränzer | Graphic Design &
Prepress: Harmen Heida, Sylvia Sopamena, Patrick Wielders | Publisher: Erik Jansen | Technical
sources

PEFC/30-31-151 www.pefc.org

questions: [email protected]

May & June 2024 3


THIS EDITION
Volume 50, No. 529
May & June 2024

Repairing
Electronic
Equipment
Tools, Techniques, and Tips 26

Regulars Features
3 Colophon 23 embedded world 2024
New Products Presented at the Fair
6 STM32 Wireless Innovation Design Contest 2024
The Winners 26 Repairing Electronic Equipment
Tools, Techniques, and Tips
33 Starting Out in Electronics…
… Continues the Opamp Theory 40 Sparkplug at a Glance
A Specification for MQTT Data
48 Peculiar Parts
The CRTC 69 The Arduino-Inside Measurement Lab
An 8-in-1 Test-and-Measurement Instrument for the
86 From Life’s Experience
Electronics Workbench
Pangpong Butt Launcher
88 FNIRSI 1014D Digital Storage Oscilloscope
92 2024: An AI Odyssey
Good Performance for Tight Budgets
Getting Object Detection Up and Running
112 Raspberry Pi 5 and Beyond
106 Err-lectronics
An Interview with Eben Upton, CEO of Raspberry Pi
Corrections, Updates, and Readers’ Letters

Industry
62 Open Source and Its Significance for the
Electronics Industry (2)
66 M12 Circular Connector With A-coding
First Choice for Industrial Applications

FNIRSI 1014D
Digital Storage Oscilloscope
Good Performance for Tight Budgets 88
4 May & June 2024 www.elektormagazine.com
+3V3
Qwiic
I2C.
K3
1 Grove
2 3 I2C
4 K4
1 OLED
2 3 K11
-A
R2 4
1 OLE
2 3
R4 4 K9

6k7
1 2 3 4

Radar-Controlled

22k
1 2

Lighting RV1
100k
R1
The AmpVolt Modular
DC Power Meter (Part 1)
JP1
R3

100k
Automatic
K12

22k
BATT

Stairway Light Measure DC Power and


2
K5
1
K6
LOAD

With Human Energy Consumption


2

50 18
1
2
INA16 1
9-IN

Presence Detection up to 50 V and 5 A


1 2 3 4 NC_V
1 2 IN+
3 4
K7
RAW 1 2 NC_V
OUT K8 3 4 5 IN–
AG
K1
INA16
9-OUT
ab • Elek
or l t

Projects Next Edition


kt 24014
or
Ele

1
lab

O R IG IN A L
Ele

la b

or
kt

la b or
8 In-Circuit LC Meter • Elek t Elektor Magazine July & August 2024
A Prototype Study As usual, we’ll have an exciting mix of projects, circuits,
fundamentals, and tips and tricks for electronics engineers and
18 The AmpVolt Modular DC Power Meter (Part 1)
makers. We’ll focus on IoT & Sensors. Visit Elektor's IoT & Sensors
Measure DC Power and Energy Consumption up to
page for more content! www.elektormagazine.com/iot-sensors
50 V and 5 A
36 A Simple DDS Signal Generator
From the contents:
Direct Digital Synthesis in Its Purest Form
> DIY Thermal Imaging Camera
50 Radar-Controlled Lighting > Cloud Chamber for Radioactivity
Automatic Stairway Light With Human Presence Detection > Best Sensors for Weather Stations
54 Digital Bubble Level and Active Stroboscopic Disc for
> Airflow Detector With Arduino
Turntables
> GSM Alarm Interface
Fine-Tune Your Record Player With This All-in-One Tool
> Low-Cost I2C Tester
> Water Leak Detector
74 Sound Card Performs Gain/Phase and Impedance > AWS Cloud for Arduino and Co.
Analysis
and much more!
For Frequencies From 100 Hz to 90 kHz
80 Measuring pH Value With the Arduino UNO R4 Elektor Magazine July & August 2024 edition will be published
Check the Quality of Your Water around July 10th. Arrival of printed copies for Elektor Gold members
96 10 MHz Reference Generator is subject to transport.
Highly Accurate, With Distributor and Galvanic Isolation
102 Project Update #2: ESP32-Based Energy Meter
Some Enhancements

FOCUS ON

Test & Measurement


May & June 2024 5
CONTEST

STM32 Wireless
Innovation Design Contest

Winners By Jean-François Simon (Elektor)

After several exciting weeks of competition, the 2024 STM32


Wireless Innovation Design Contest has crowned its top
three prize recipients. Congratulations to the winners!

After several exciting months of competition, the STMicroelectronics [2] booth (4A-148)
during which dozens of innovative projects during the embedded world 2024 trade fair.
were submitted, the 2024 STM32 Wireless The top three winners emerged from the pool
Innovation Design Contest [1] (presented by of exceptional entries, each bringing a unique
STMicroelectronics and Elektor) has crowned perspective to the realm of wireless technol-
its top three winners after an intense period ogy (see Figure 1).
of evaluation. Congratulations to the following
STM32 winners for their hard work: Cédric Jiminez Claiming the prestigious First Prize (€2,500)
Wireless Innovation (First Prize), Alain Romaszewski (Second was Cédric Jiminez, with his Open-Vario
Design Contest Prize), and Balthazar Deliers (Third Prize). project [3]: an open-source, multi-functional
Want to learn about the connected variometer for paragliding and
STM32 Wireless Innovation Winning STM32-Based Projects hang gliding, equipped with features like
Design Contest and all the After meticulous scrutiny, the judges GNSS positioning, accelerometer, tempera-
participating projects? Visit the announced the winners on April 10, 2024, at ture sensing, glide ratio computation, and flight
Contest webpage for all the
details.

elektormagazine.com/st-contest

Figure 1: From left to


right: CJ Abate (Elektor),
Thibaut Dontail (Fourth),
Yvon Rannou (ST),
Balthazar Deliers (Third),
Erik Jansen (Elektor),
Cédric Jiminez (First),
Roman Ludin (ST).

6 May & June 2024 www.elektormagazine.com


Figure 2: Open-Vario Figure 3: ZigBee environmental measurement Figure 4: Electric Meter that Matters
center

data recording, all based on the STM32WB- the Matter over Thread protocol, enabling
5MM-DK discovery kit (Figure 2). The judges real-time monitoring of power consumption
were thoroughly impressed by the design, the via smartphone (Figure 4). The setup includes
features of the project, as well as the level custom hardware for data conversion and
of detail used by Cédric in the extensive connection to the STM32WB5MM-DK dev kit,
documentation he wrote. Congratulations, software development in C/C++ and Python, STM32 Solutions
Cédric for this well-deserved victory! and a smart home integration that visualizes Visit the STMicroelectronics
energy usage. All of this demonstrates an website (www.st.com) for
Alain Romaszewski wins the Second Prize innovative approach to home energy manage- more information about all the
(€1,500) with his ZigBee Environmental ment. Well done! company’s innovative STM32
Measurement Center [4] for indoor plants solutions, including the NUCLEO-
or greenhouses, using the STM32WB5MM-DK STM32 Wireless Innovation and WBA52CG, STM32WB5MM-DK, and
kit (Figure 3). It features sensors for monitor- Inspiration Nucleo-WL55JC.
ing soil humidity, temperature, ambient condi- The STM32 Wireless Innovation Design
tions, and CO2 levels, and includes automated Contest provided a platform for inventors
watering and lighting systems based on these and technology enthusiasts to unleash their
measurements, with data management via a creativity and explore many different paths in
server MQTT and Node-RED application. Well the realm of wireless applications [6]. From
done, Alain, for this very well documented and IoT [7] to home automation, the contest has
skillfully designed project, which uses numer- showcased the diverse ways in which wireless
ous external modules while sporting a neat technology can shape the future. Are you
3D-printed case. inspired? As you develop your own STM32-
based projects, we encourage you to share
The Third Prize (€1,000) went to Balthazar your innovations with the global electronics
Deliers for his Electric Meter that Matters community. You are welcome to post your
[5], which integrates a Linky smart electricity projects on the Elektor Labs online platform:
meter with a smart home ecosystem using www.elektormagazine.com/labs.
240241-01

WEB LINKS
[1] 2024 STM32 Wireless Innovation Design Contest: https://www.elektormagazine.com/st-contest
[2] STMicroelectronics: https://www.st.com/
[3] Open-Vario on Elektor labs: https://www.elektormagazine.com/labs/the-open-source-multifunction-variometer-for-paragliding
[4] ZigBee Environmental Measurement Center on Elektor labs:
https://www.elektormagazine.com/labs/zigbee-environmental-measurement-center-for-indoor-plants-or-greenhouse
[5] Electric Meter that Matters on Elektor labs: https://www.elektormagazine.com/labs/the-electric-meter-that-matters
[6] Wireless applications: https://www.elektormagazine.com/wireless-communication
[7] IoT: https://www.elektormagazine.com/iot-sensors

May & June 2024 7


PROJECT

In-Circuit
LC Meter A Prototype Study

By Michael Monkenbusch (Germany)

When troubleshooting a board, the ability to test provide estimates of the value of the paral-
passive components without desoldering them from lel resistor Rp, and also the assessment of
a potential series resistor in one run. And
the PCB is most useful but at the same time critical, further, if we exchange the capacitor C with
since interference from the rest of the circuit during an inductor L, the driving voltage U(t) with
testing must be minimized. This prototype circuit can a driving current I(t), and also exchange
the roles of parallel and series resistances,
measure in-circuit capacitance from 1 pF to 80 mF or a similar scheme can serve to measure
inductance from 1 mH to 40 H. It uses a low voltage inductors. The current measurement is
method that is robust against parasitic parallel or series exchanged with a voltage measurement
across the inductor (instead of the voltage
resistance. The signal processing is mainly analog; the over a current measurement shunt in capac-
computation to extract L, C, and “parasitic” resistance is itance mode).
performed by an Arduino UNO.
These features make it tempting to use
the method for in-circuit components as
well, without the need to desolder them. To
A while ago, I played with a function be proportional to the driving triangle make this viable, one may observe that — if
generator to assess a capacitor quickly by voltage U(t). If the driving voltage now runs not powered — basically all semiconduc-
measuring the current arising through it between negative and positive values, it will tor parts, in the worst-case, expose diode
from the applied voltage waveform with an be zero at some t0 times during the constant junctions, with the likelihood of creating
oscilloscope. The initial setup was primi- rising and falling slopes of the triangle. potential additional parasitic current paths.
tive, since I was using a small shunt resis- Then at these times the parasitic resis- If the driving voltage stays below some
tor in series with the capacitor to infer the tive current IR(t0) = 0 and the measured 100 mV, the diode currents are still negli-
current. There, a triangular voltage wave voltage at these times only represents C gible. In the case of inductors, the resulting
seems to offer the advantage that, during and is independent of Rp. In practice, the voltage must stay below that limit. Such low
the constant rising and falling slopes of measurement may be done by sampling voltages also allow for ignoring the polarity
the applied waveform (ideally), the current the current at times where U(t) = 0. In short, of electrolytic capacitors.
through the capacitor has a constant this was the initial idea to make a simple
(positive or negative) value, which is propor- C-metering circuit that supplies a voltage In the presented prototype circuit, the
tional to the capacitance, C (Refer to the that is proportional to C and independent shunt and inductor voltages stay below
Measurement Method text box). of leakage or other parallel resistors. 10 mV. Synchronous sampling and averag-
ing make the measurement robust against
An additional current IR(t) = U(t)/Rp due to A more in-depth analysis of the scheme the influences of internal and external noise
a parallel (leakage) resistor Rp would simply showed the possibility for its extensions, to sources.

8 May & June 2024 www.elektormagazine.com


drive generator attenuator buffer

x1 R-current-
feed

sampling pulse
generator feedback
x1/500+ Cx

amplifier
Uadc

x500
averaging
sampling Lx
oscilloscope R-shunt

Figure 1: Block diagram of the circuit.

Block Diagram > Triangle drive voltage generator current flows through the shunt resis-
The block diagram of the circuit is shown (U12A…D). tor, which is selected by SW2 respectively
in Figure 1. As functional elements, the > Sampling window generation (U2A, via the auto-ranging MOSFET bank Q2…
circuit contains a generator of a defined U2B, U3A, U3B, U13A, U13B). Q7. The resulting shunt voltage of a few
triangular voltage waveform, comparators, > Signal amplifier (U16A, U16B). millivolts is amplified (total factor ≈ 500)
and logic to generate the sampling inter- > Synchronous polarity reversal (Q8, by U16A and U16B. After the first ampli-
val pulses, the signal amplifier A and the U1B). fier stage, the positive feedback signal is
sampling stage(s) with buffer amplifiers > Sampling, averaging (U5B, U5C, U5D; extracted by R74 and fed into the drive
(not shown). The connection to the Arduino C2, C3, C4; U5A) and buffering (U1C, voltage attenuator (R3, R8) to raise the drive
includes a four-channel, 16-bit ADC ADS1115 U1D). voltage such that the shunt voltage drop is
by Texas Instruments. The analog inputs added. The amplified signal ICx(t) can be
Ax of the microcontroller itself are used to The triangle drive voltage is created by used for monitoring through an oscillo-
determine the positions of range switches, integration (U12A), i.e. by accumulat- scope. In the circuit, it is further processed
and digital outputs address a number ing into C1 a current set by the resistor by synchronous polarity switching, which
of MOS switches to support a partial connected by switch SW2 to the polari- is performed by (Q8, U1B).
auto-ranging. Thereby, the Arduino sketch ty-switched (Q1, U12C) reference voltage.
can evaluate the measurement and then U12B compares the triangle output to the For an ideal capacitor, the output of U1B
display C or L values and possible (effec- intended opamp’s voltage swing (±2.5 V) would then be a DC voltage proportional to
tive) parasitic resistances with some further to enact the polarity switching (Q1) of its capacitance value (see again Measure-
auxiliary information on a 4×20 LCD. the high-precision voltage reference that ment Method). Non-ideal components such
controls the value determining slope. as parallel resistance, etc., induce a slope
Schematic Diagram on the current through Rshunt and thus a
The circuit (analog part) is shown in U12D buffers the attenuated (R3, R8) trian- ripple in the output value of U1B. There-
Figure 2. It contains the following groups: gular voltage to drive the test item Cx with fore, the sawtooth-like ripple voltage has
> Reference voltages (U4, U11). low impedance. The induced capacitor to be sampled in proper time windows and

May & June 2024 9


+5V +9V
R18
10k

R9
100M 4 4 4
R7 C5 C6 C7
R19 R11 U1 U12 U17
100k

C1
10k

10M
11 1µ 11 1µ 11 1µ
R12
SW1B R20 1M SW1A 22n
2
–9V
10k

R14 R6 10
1 5
100k U12A 100k R17 8
3 7 Q1 U12C
R23 R21 R15 U12B 100k 9
1k

6
+9V
10k

10k
+2V5 R5
R16 J113
100k
R22 1k
R10 R13 8 8 8 8
R24
10k

C8 C9 C10 C11

100k

100k
U2 U3 U13 U16
1k

4 1µ 4 1µ 4 1µ 4 1µ
2
R29 1 –2V5
+5V U2A –9V
R48 3
U9B
10k

U7B
1k

5 U18A
4 1 6
6 =1 3 4
6 2 & 7 ≥1 +9V
R65 SW2A R59
R32 7
U2B
10k

1k
5
14 14 14 14
U7A

1k
C12 C13 C14 C15
R63 1
3 U5 U18 U7 U9
≥1
10k

2 2
7 1µ 7 1µ 7 1µ 7 1µ
R33 1
U3A
3

1k
U9A –9V
1
MOD1 SCL =1
3
R37 2
2k2 R38
ARDUINO UNO SDA R36
2k2 5
AREF R35

1k
2k2 7
GND R34 U3B U1, U12, U17 = TL084
2k2 6
RESERVED 13 1 16 9 8
R41
U2, U3, U13 = MC33172
IOREF 12 IN1 IN2 IN3 IN4
+5V R25 U5 = 4016
RESET 11 2 3 3
U7 = 4001

1k
1k
3.3V 10 D1 S1 1
R26 U13A U18B U7C U9 = 4070
5V 9 15 14 2 U9C 6 8
POWER

100k 8 4 10 U16 = OPA1282


GND 8 D2 S2 R42 10 7 & 9 ≥1 U18 = 4093
U10 R27 9 =1
GND 10 11
DIGITAL (PWM)

1M 5
VIN 7 D3 S3

1k
DG413xY R28 7
6 7 6 U13B
10k 6
A0 5 D4 S4
R43 +2V5
ANALOG IN

A1 4 V– GND V+ VL
ICSP Lx
A2 3 +5V
RESET

4 5 13 12 R1

1k
MISO
SCK

A3 2 4k7

3
3
U9D
A4 TX 1 1 12 U5A
U1A

1
A5 RX 0 –9V +9V =1
11
2 13
–2V5
R46

Figure 2: Schematic diagram of the analog section of the project.


GND
MOSI
5V

SW2B

2
100k
+5V MOD2
R55 R57
ADS1115 Module

10k
10k
R60 SW3B 9 1
ICx(t) R31 VDD
1k 5 8 2
R66 R30 U1C 10k GND
4 3 10 3
SW3A R71 100k 100k SCL
3 4
4k7 R73 C2 SDA
1 6 9 U5B 6 5
U16A 100k ADDR
2 7 8 8 9 6
U16B R72 U1B 1µ ALRT
5 10 13 7
+9V A0

10 May & June 2024 www.elektormagazine.com


R68 100k R40
R2 12 U5C 14 8
BT1 100k R70 R39 U1D 10k A1
11 10 12 9
2k2

R49 R50 R51 R52 R53 R54 100k 100k A2


10
D1 D2 A3

100Ω

100k
R67 R74 R69 R75

10Ω

10k

100k
U5D


R58

1k
+2V5

4k7

4k7
9V 2k5
U4 Q8 10k
1N4007 1N4007
Q7
J113 R62
C3 C4
TL431D

100k
R64
Q6 +2V5 10k
1µ 1µ
BT2 U11 R3
Q5

1k
R47 Cx
TL431D 12
9V –2V5 Q4
100Ω
14
R4 R56 U12D R8

100Ω
13
10Ω SW2C

2k2
Q3
R61

–9V
Q2
230581-006
A B
Measurement Method
The charge Q that is stored in a
capacitor is proportional to the voltage
U, increasing the voltage U(t) over a
capacitor increases the stored charge.
That implies that current has to flow
(I(t)). Mathematically, this is expressed
by I(t) = C(dU/dt). If U increases with a
constant slope, the current is constant.
A change from rising to falling slope
implies a change in current direction.
This is illustrated in Example A. sampling interval starts at this point, voltage. Driving the test item (L) with
there will be no residual influence of Rs a linear increasing current I(t) yields a
For a resistor, the current is proportional on the inferred C value. In the circuit constant induced constant voltage U(t)
to U (Example B), the current through presented in Example C, the time ∆t ≃ ts over the inductor U = L(dI/dt). The similar
a resistor parallel to C simply adds the is determined by conversion of the time effect of the parallel resistor in the case
capacitor current. At any time t0 with delay between slope sign change and of capacitors is now the extra voltage
U(t0) = 0 only, the capacitive current the zero crossing of I(t) to a voltage. caused by the (series) resistance of the
prevails. Sampling at these times (and inductor, while any parallel resistance to
multiplying with the sign of the slope) Note that the shunt used for the the inductor corresponds to the effect
yields current values that solely depend measurement of I(t) also adds to of the series resistance of the capacitor
on C. If the current I(t) increases linearly the effective series resistance Rs. To (see Example D).
around t0, the sampling time interval may compensate for this, the feedback
have a finite symmetric extension prior correction to U(t) is added to the circuit While, for “good” capacitors, the
and after t0, which helps to average out (see Feedback). parallel resistance is typically so large
contributions from various noise sources. that its effect is virtually invisible, the
To apply the scheme to inductors series resistance of inductors is nearly
Now, if we also have a series resistance L instead of capacitors, one has to always clearly visible as the slope of the
Rs, its effect is that the transition from exchange the roles of current and detected voltage across the inductor.
positive to negative current values
when the U(t) slope changes is no
longer abrupt, but follows a transient C D
with a finite time constant. This time
constant is τs = RC, where R is the
value of Rs ∥ Rp = RsRp/(Rs+Rp), which
for large Rp is very close to the series
resistance Rs. After a few cycles of τs the
transient effects are done. If the central

averaged, in order to single-out the proper supplied for the main sampling that yields R30×C2 and R39×C3; however, these times
and stable C and Rp values. the value of C and is supplied to MOSFET contain an additional factor 1/f — about 4
switch U5B, which then samples the ampli- for the main sample and 8 for the off-center
The sampling time windows are extracted fier output around the central part of the sampling — with f being the fraction of the
by the logic (U7, U18) driven by signal from slope and averages it in C2. Further off-cen- sloping period during which the sampling
comparators (U2, U3, U13; in the proto- ter sampling windows are selected such that window is open. The relative sampling
type I used audio MC33172 opamps from only the “late” windows of rising or falling window widths (f) are controlled by the
STMicroelectronics) that detect transi- slopes are selected by ANDing them with voltage divider levels seen by the row of
tions of the (non-attenuated) drive voltage Sync1 or NOT Sync1. By feeding these to U5C comparators (U2, U3, U13).
at levels supplied by the voltage divider and U5D, respectively, the amplifier voltage
between R24 and R43. XORing subsequent signal in both (rising and falling edges) Finally, to get a coarse estimate of the series
transitions yields a logic signal that is high selected off-center windows is averaged resistance, the time of zero crossing (=
when the drive voltage is within the window in C3. half of the voltage jump at slope reversal
between the pertaining levels. if Rp = ∞) of the signal is detected by U1A
The sampling average of the main signal (as comparator) and XORed (U9D) with the
Thus, a central window, symmetric to as well as that of the two off-center periods Sync1 signal, which ideally is High during
the zero-crossing of the drive voltage, is have time constants that are determined by the delay between sign reversal (“zero”) and

May & June 2024 11


Feedback
In capacitance mode, the shunt resistor voltage is added to the drive voltage U(t)
such that the net voltage applied to the capacitor under test matches the undistorted
triangular shape and value. The feedback uses the buffered and amplified (×20)
shunt voltage and injects this via R74 into the attenuating voltage divider R3/R8.
The output of the voltage divider is buffered by U12D to provide a very low source
impedance for the drive voltage. The feedback resistor R74 must be set to a value large series resistance, respectively, it may
such that the attenuation by R74/R8 matches the amplification to yield a feedback be advisable to adjust the accuracy by which
factor ≃ 1. the central sampling window is symmetric
to the zero crossing of U(t) and possibly the
For larger factors, the loop becomes unstable. In practice, R74 must be tuned to a length of the central sampling interval using
factor close to 1 using a high-quality capacitor in the range between 100…1,000 nF the resistors of voltage divider R33, R38.
as test capacitor. The feedback serves to eliminate the influence of the shunt resis-
tor to the series resistance effect. It has no influence on the accuracy of the C-value Additional Remarks
inferred from the central sampling, as long as the duration of the transient due to Rs The choice of using the BS170 MOSFET
is sufficiently shorter than the period of the triangular drive. for the shunt resistor switching was a
proof-of-principle for the prototype with
For inductance measurements no feedback is implemented, since the range imposed transistors that I had immediately available.
by the amplifier limits the useful voltage over the inductor to <10 mV at the low end Measurement of the ON resistance yielded
of the current setting resistor(s) R50, R55… which compares to the 2.5 V at the about 1.7 Ω, which was added to the shunt
“hot” end; the resulting current error is negligible (if we aim for about 1% accuracy). values in the sketch. This is a bit problem-
atic for the two lowest values (nominally
1 Ω and 10 Ω) — for the test the 1 Ω was
the time when the (ideally sudden) voltage The shunt resistors or the feed current replaced by just the MOSFET resistance
jump of the amplified shunt voltage is at 1/2 resistors are manually selected by SW1, alone. As an improvement, at least these
of its amplitude. This time delay pertains where, with the auto-ranging option, the two lowest shunt values should be switched
to the τs = RseriesC time constant. It is last position includes, respectively, the using, e.g., an Si4136DY (0.0025 Ω @ 4.5 V).
converted to a voltage by opening a switch MOSFETs (Q2…Q7 for Cx measurement or The backward body diode of the low resis-
(U5A) to the reference voltage during that U10 switched resistor banks for Lx). tance power MOSFETs does no harm for this
time and averaging with R57, C4, and R62. application, since the maximum applied
From that, the time delay — and subse- Accuracy Considerations voltage stays below 0.2 V.
quently the series resistance — may be The uncertainties of values for integration
estimated. capacitor C1, for integrating resistors R9, The switching of the inductance current
R11, R12, R14, R15, and R16, as well as those feed resistors exposes the switches to larger
Inductivity Mode of the shunt or current feed resistors, all voltages, but with a foreseen minimal value
SW3 is used to switch between capacitance affect the error of the final displayed values of 1 kΩ, switching is compatible with the
and inductance mode. In the latter, the of C or L. Furthermore, resistors R5, R10, 10…20 Ω on resistance of the DG411…13
inductance to be analyzed takes the place and R13, as well as R66, R72, and R73 in the series.
of the shunt resistor in capacitance mode. sign reversing stages must have exactly the
The imposed driving current is supplied via same value. Also, the attenuator R3, R8 as For the sampling and averaging CD4016
resistances R60, R55, and R46 in the range well as the amplification factor determined switches, despite their ON resistance of
of 1 kΩ to 1 MΩ, which are fed by the non-at- by R67, R68 and R69, R70 have an impact several hundreds of ohms is perfectly
tenuated triangular drive voltage. Since the on the result. suitable, and their voltage levels are
range of voltage drop across the inductor is compatible with the opamps.
limited to 10 mV and thus is much smaller The Arduino sketch allows for entering the
than the 2.5 V drive, we can consider this exact (measured values) of C1, the shunt and Warning: Resistors R31, R40, R58, and R64,
as a reasonably accurate current source current feed resistors as well as the atten- which connect the output of the averaged
without further corrections. uation and amplification factors. For the voltage buffer amplifiers to the 16-bit ADC,
prototype presented here, I measured these as well as R1 at the digital reference of the
Ranges and Switch Encoding resistors individually, using a 6-digit digital DG411…13 switch, may not be omitted.
Once the slope is set either manually multimeter, and entered their values in the They protect the chips from the excess of
or by the auto-ranging algorithm in the sketch. Concerning the resistors, a viable input current due to voltage range differ-
program, a shunt resistor (or feed current alternative would be to use 0.1% toler- ences between the 5 V Arduino rail and the
resistor) is selected such that the resulting ance types. For C1, measurement may be ±9 V opamp supply.
voltage is ideally in the window between the more accessible option. Again, for all of
400…4000 mV to ensure optimal accuracy. those, if they deviate from the schematics, Connection to the Components
The voltages are also shown on the LCD. For simply enter the proper values in the sketch! Under Test
auto-ranging, the raw voltage at the output Since the capacitance is measured via the
of the synchronous switching unit U1B is To maintain the measurement accuracy of current flowing through C, it is possible to
directly fed to the Arduino’s analog input C in the presence of a comparatively small connect the capacitor to be tested by two
A2, to avoid a time delay due to averaging. parallel resistance or L in the presence of a shielded cables: one for the drive voltage

12 May & June 2024 www.elektormagazine.com


Drive U(t)
Attenuator
Cx
Figure 3: Schematic diagram of the output front-end of the
LC meter, with the shielded 0.5 m probing leads.

Amplifier SW1A

and one for the amplifier/shunt input. R shunt

The residual parasitic capacitance is then R curr Lx


restricted to the unshielded ends of the
cables (a length of 0.5 m is perfectly fine). SW1B
Any internal stray capacitance is subtracted
through the Arduino program.
230581-007

The small inductors to be tested should


be connected by very short twisted wires.
Measurements of larger inductors may
benefit from shielded cable (which may
be longer) to reduce noise induction
(Figure 3).

Examples
As an illustration of the basic operation
of the circuit as capacitance meter, the
display with a 470 nF styroflex capacitor
is shown in Figure 4a and Figure 4b.
The two sides show the results obtained
with different slopes of drive voltage U(t). Figure 4: Readouts obtained with different slopes of drive voltage U(t), with the auto-range-determined
The slope is indicated by the value of the values of the shunt resistor R, a) with estimate of a series resistor Rs = 187 Ω (left), and b) without it
(right).
chosen integrator resistor RC in the last
display line, there also the (auto-range-de-
termined) actual value of the shunt resistor
R = Rshunt is shown. The primary result C is
displayed together with the raw voltage at
A0 of the ADS1115. The second line shows
the estimated value, Rp, of the parallel resis-
tor and the related voltage at A1 of ADS1115,
where it is too large to be detected and is
indicated by the display with “N.A”.

Finally, the third line gives an estimate of


the series resistance with the voltage at Figure 5: The raw
A3 of the ADS1115. The voltage range is sampled voltage.
0…4,096 mV, the larger the value within
the range interval is, the better is the resolu-
tion/accuracy will be. Rp is derived from
the difference A0−A1 voltage obtained
for an off-center and the central sampling
interval. A3 is a (non-linear) conversion of
the time delay between slope-change and
signal zero-crossing relative to the drive
voltage period. The raw sampled voltage is
shown in Figure 5. The red trace represents
U(t) and the blue trace the voltage at port
ICx(t). Besides the spikes, it conforms to
the ideal capacitor response. The visible
spikes probably result from spillover
of the sampling pulse generation with Figure 6: The author’s
the non-ideal (messy) prototype wiring project, in an absolutely
(Figure 6). Here, they nicely illustrate the prototypical version!

May & June 2024 13


Figure 8: The raw voltage
trace (blue) shows the
Figure 7: Readouts with a 1,000 µF electrolytic jump transient of finite
in-circuit capacitor in parallel with two diodes in time at slope reversals.
both directions and a 1 kΩ resistor, plus a 10 Ω
series resistor.

location of the sampling intervals. The large The second example simulates a large 1 s (RC = 10 MΩ). As visible in Figure 8,
gap in the center (around 25 ms) is the main 1,000 µF electrolytic in-circuit capacitor the raw voltage trace (blue) now shows the
sampling window, the marks around 38 ms parallel to two diodes in both directions and jump transient of finite time at slope rever-
indicate the sampling window where the a 1 kΩ resistor and a 10 Ω series resistor sal, as well as the sloped ICx(t) voltage at
voltage increase due to a parallel resistor (Figure 7). The large capacitance requires later times that indicate the presence of
is probed. the choice of a slope with a period of about the parallel resistor. The applied voltage

Arduino Sketch
The communication with the microcontroller comprises the use
of an ADS1115-based 4-channel 16 bit ADC shield and output on
a 4x20 LCD, both connected via I2C. Further auxiliary voltages
are read directly via the direct Arduino analog inputs A0…A2,
used to decode range switch positions and support for the respectively for inductors
(semi) auto-ranging function. Further digital GPIOs are used
to operate the MOSFET switches that select shunt or current
feed resistors. The actual values of the corresponding resistors
should be updated in the source code to obtain optimal
accuracy. The main function of the microcontroller is to interpret
the measured ADC voltages and convert them into the desired The analysis of the transient that contains information on the
information on C/L, Rp and Rs. series resistance of C or the parallel resistance of L (or other
losses) is more involved. In the first step, the time delay between
Uadc0 Rc ⋅ C1 slope change and zero crossing of the signal τESR must be
Cx = ⋅ − Coffset inferred from the voltage reading in the 3rd ADC channel Uadc2:
Uref R shunt ⋅ A

and similarly

where τoffset (a few μs) is a technical offset correcting for time


delays in the zero detections.

with A being the factor that combines the attenuation applied to In the case where the parallel resistance of C can be neglected
the drive voltage ≃ 1/10 with the amplification α ≃ 500, i.e. A ≃ 50; (i.e. no slope in the current signal) the series resistance can
for the actual values see the Arduino sketch! easily be obtained by Rs = τESR/(ln(2)Cx) in case of a substantial
parallel resistance effect, the extra slope has to be accounted
The parallel resistance (series resistance for inductors) the for, and the expression becomes slightly more complex. If the
difference of voltages from the “late” off-center sampling Rp related slope dominates the zero crossing, a reliable estimate
window Uadc1 and the central window Uadc0 is used, Ureffp of Rs is not possible and the display will show N.A. The actual
is the drive voltage difference between the centers of the two expressions can be seen in the source of the Arduino program.
sampling windows

14 May & June 2024 www.elektormagazine.com


Component List
Resistors (All 1%, metal film, ≥1/8W)
R1, R71 = 4.7 kΩ
R2, R4, R34, R35, R36, R37 = 2.2 kΩ
R3 = 1.0 kΩ (1)
R5, R6, R7, R10, R13, R66, R72, R73 = 100.0 kΩ (2)
R8 = 100.0 Ω (1)
R9 = 100.0 MΩ (3)
R11 = 10.0 MΩ (3)
R12, R27 = 1.0 MΩ (3)
R14, R26, R46, R54, R62 = 100.0 kΩ (3)
R15, R28, R53, R55, R57 = 10.0 kΩ (3)
R16, R25, R52, R60 = 1.0 kΩ (3)
R17, R30, R39, R75 = 100.0 kΩ
R18, R19, R20, R21, R22, R31, R40, R48, R58, R59, R63, R64 = 10.0 kΩ
R23, R45, R65 = 1.0 kΩ
R24, R29, R32, R33, R38, R41, R42, R43 = 1.0 kΩ (2)
R44 = 1.0 MΩ Figure 9: A typical inductor trace.
R47, R51 = 100.0 Ω (3)
R49 = 0.0 Ω (3)
R50, R56 10.0 Ω (3) is too small for the diodes to carry any
R61 = 1.0 Ω (3) sizeable current; thus, they stay “invisible”.
R67, R69 = 4.7 kΩ (1) This trace figure also shows that the inferred
R68, R70 = 100.0 kΩ (1) values for C and Rp may be hampered in the
R74 = 5 kΩ trimmer extreme situation if the transient due to Rs
prevails at times when the central sampling
Capacitors window starts.
C1 = 22 nF, low temp. coefficient
C2…C14 = 1 µF, ceramic, multilayer Inductors
A typical inductor trace is shown in
Semiconductors Figure 9, obtained with a ring core with
D1,D2 = 1N4007, protection diodes 29 turns, L = 3.45 mH (Al ≃ 4000 nH/n2),
Q1, Q8 = J113, n-j FET switch whilst Figure 10a and Figure 10b show
Q2, Q3, Q4…Q7 = BS170, MOSFET switch the measurements obtained using this
Q2,Q3 = Si4136DY, MOSFET (4)
U1, U12 = TL084, quad opamp
U2, U3, U13 = MC34072PG, dual opamp
U2, U3, U13 = LM393B+1k collector R, dual comparator (5)
U16 = OPA2182, fast zero-offset opamp
U4, U11 = TL431D, 2.5V reference
U10 = DG413Y, quad MOSFET switch (current drive)
U5 = CD4016B, quad MOSFET switch (sampling)
U7 = CD4001B, quad 2-input NOR
U9 = CD4070B, quad 2-input XOR
U18 = CD4093B, quad 2-input NAND

Miscellaneous
SW1 = rotary switch, 6×2
SW2 = rotary switch, 4×3
SW3 = toggle switch, 2×2 a) b)

Notes: Figure 10: a) Measurements obtained with


(1): Tolerances in these components can be compensated through the this project (left), and b) using a commercial
amplification and attenuation values inputs in the Arduino program. inductance meter (right).
(2): The equality of values among these resistors affects the accuracy.
(3): These resistors are critical for accuracy. Use precision (low-tolerance) resistors.
(4): More accurate alternative to BS170, with a lower Ron.
(5): Alternative to MC33172.

May & June 2024 15


design and a commercial inductance meter, accuracy. In any case, the transient derived
respectively. As with typical inductors, the series resistance (ESR) should be considered
traces show a sizeable slope due to the resis- as a coarse estimate only.
tance of the coil. The ratio of the L-depen-
dent constant part (size of the jump), Possible Modifications
which depends on the rate dI/dt of drive > To extend the range of allowed paral-
current change, and the resistant-depen- lel resistance, decrease the central About the Author
dent slope (independent on dI/dt) can sampling window (by decreasing R33 Michael Monkenbusch is a retired physi-
be optimized by choosing a proper rate. and R38). cist who worked in the fields of neutron
There are a couple of limits: too small a > This narrowing of the sampling scattering, instrumentation, and soft-matter
relative jump amplitude at low rates on window may require a reduction physics. Reviving an old electronics hobby
the one side and too long-lasting spurious of R30’s value to keep the value led to the project presented here.
oscillations after the jump (due to parasitic f × R30 constant.
capacitances) at too fast rates (i.e. too short > The C/L- and Rp voltages may also be
time between jump and sampling window). measured using the A2, A3 analog Questions or Comments?
Arduino inputs, if less accuracy is Do you have technical questions or
A collection of application examples for accepted. comments about this article? Please
different capacitors and inductors can be > The ±250 mV of U(t) may be still contact the author at
found on YouTube [2]. reduced to fully avoid errors in Rp in [email protected]
the presence of Schottky diodes by or the Elektor editorial team at
Measuring Strategy and reduction of R8. The actual attenuation [email protected].
Monitoring factor must be changed in the Arduino
The most comprehensive and fast infor- program.
mation on the item under test and the
relevance of the results can be obtained The analog part may also be designed such
Related Products
if the ICx(t) signal is monitored using an that only the 5 V supply (of the Arduino) is
oscilloscope. In that case, any violation of required. This implies the use of suitable > JYE Tech Capacitance Meter
the validity condition becomes immedi- opamps (e.g. OPAx388s for all), rail-split- DIY Kit
ately obvious and the choice of the best ting to create a virtual ground (e.g. using www.elektor.com/17472
slope value is easy. Additionally (or without a TLE2426). However, for the auto-range
> Peak Atlas LCR45 – LCR Meter
signal monitoring) consistency of readings switching of the inductor current resistor, with LCR Impedance
if the driving slope (Rc) is changed indicates a suitable replacement for DG411…13 must www.elektor.com/17563
reliable values and inspection of the raw be found.
ADC voltages allows assessment of the 230581-01

WEB LINKS
[1] Files for download: https://elektormagazine.com/230581-01
[2] This project on YouTube: https://youtu.be/hfbUxPfHmeg

16 May & June 2024 www.elektormagazine.com


e-zine
o u r d o s e o f e le c t r o n ic s
Y

Every week that you don’t subscribe to Elektor’s


Newsletter (e-zine) is a week with great electronics-
related articles and projects that you miss!

Stay Informed, Get Creative, and Win Prizes –


Subscribe Now to be Part of it!

www.elektor.com/ezine/en

What can you expect?


Editorial Store Partner mailing
Every Friday, you’ll receive the best Don’t miss our Elektor Store You want to stay informed about
articles and projects of the week. promotions. Every Tuesday the ongoing activities within the
We cover MCU-based projects, IoT, and Sunday (and occasionally industry? Then this e-mail will give
programming, AI, and more! Thursdays), we’ll have a special you the best insights. Non-regular
deal for you. but always Wednesdays.

May & June 2024 17


PROJECT
ab • Elek
or l
kt t

or
Ele

lab
ORIGINA
L

Ele

b
or

kt
or

la
la b
• Ele k t

The AmpVolt Modular


DC Power Meter (Part 1)
Measure DC Power and Energy Consumption Up to 50 V and 5 A

By Saad Imtiaz (Elektor)


When developing the AmpVolt module, my aim was to combine preci-
For a USB-based power supply, there are sion, flexibility, and modularity. The core components — a precision
cheap modules to monitor current and INA169 current sensor, a voltage divider, and an ADS1015 12-bit ADC
module — were selected with this in mind. These components work in
energy provided. And, on the other hand, combination to provide accurate current and voltage measurements
there are many devices for measuring AC across a wide range.
grid power consumption. However, for DC
The module presented here can be connected to any type of 3.3 V or
voltages beyond 12 V and especially beyond 5 V powered microcontroller with an I2C interface. To make the module
24 V, there are fewer solutions. When you even more multipurpose, we also put an OLED on it, controlled via
think about small solar systems and electric the same I2C bus. For easy connection of your choice, we placed
three connectors for the I2C signals on the PCB: a Grove and a Qwiic
bicycles, this voltage range is getting more connector with 2-mm pitch and an JST XH connector with 2.54-mm
interesting, and that is where this project pitch. Keeping the connectivity with common battery systems in mind,
comes in. To keep things versatile, we have XT60PW Connectors were used to for connecting to the load and
source.
chosen a modular approach. In this first part
of this AmpVolt series, we introduce a small Figure 1 is a block diagram of the entire AmpVolt project. You can see
board for measuring currents and voltages the measuring module as well as the microcontroller(s) connected.
The INA169 and ADS1015 both are from Texas Instruments [1][2]. For
up to 50 V and 5 A, which can be connected this project, we used Chinese breakout-boards (BoB) for both of these
to the microcontroller of your choice. chips [3][4]. Furthermore, there exist multiple BoBs that are available

SCL
Measurement
SDA
Microcontroller
Tx Rx
OLED
Display VIN + +
Rx Tx
ADS1015

VIN –
Module

Application INA 169


Source

Microcontroller Module
A0 Load

A1
Voltage Div. –

Figure 1: Block diagram of AmpVolt project.

18 May & June 2024 www.elektormagazine.com


Technical Features
> Input Voltage (for Modules): 3.3 V or 5 V,
depending on the microcontroller board.
for ADS1015 with identical pinouts and are also compatible with the
> Input Voltage (Source): 50 V DC max.
AmpVolt project. In contrast to the well-known hall effect current
> Max. Current Load: 5 A.
sensors, which are less accurate than shunt resistors at low current,
> Voltage divider for source voltage measurement.
the INA169 Module employs a shunt resistor current measuring method.
> INA169 module for current measurement
These modules are cost-effective and easily available.
> Voltage divider for INA169 Module for 3.3 V
based MCUs.
The choice of the ADS1015 ADC Module was pivotal. Its 12-bit preci-
> ADS1015 ADC module for 12-bit precision
sion and programmable gain allow for highly accurate readings, which
> OLED screen to display the real-time power
is why it got a place in this project. It’s important to note that not all
measurements.
microcontrollers offer internal ADCs with 12-bit precision, and some,
like the Espressif ESP32, may encounter reference voltage and linear-
ity issues. This inconsistency among MCUs underscores the need
for a reliable external ADC. Thus, the ADS1015 ADC was chosen for
its 12-bit precision, providing a sweet spot of accuracy, speed, and tors K6 and K12 for the battery and load connections reflected on the
power efficiency suitable for a wide range of applications. While a reliability and ease of use in high-power environments.
16-bit ADS1115 ADC could offer higher resolution, the decision to use
a 12-bit ADS1015 was mainly due to the higher sample rate. Connector K7 is placed, if the ADS1015 ADC is not used, a raw output
from sensors can be obtained, to be sampled with another ADC, for
The Schematic example an internal one in your microcontroller. Connector K8 is placed
In short, the schematic (Figure 2) covers the connections between the to use ADS1015 to its complete potential if any other analog voltage
INA169 and ADS1015 BoBs at K1 and K2, respectively, with connectors, needs to be measured.
voltage divider, and the OLED display. As the INA169 module outputs
1 V per 1 A, a voltage divider R3 and R4 are used to make it compat- For the OLED display, connectors K9 and K10 are used. You may ask:
ible with 3.3 V systems; but, if it has to be used with a 5 V controller Why two connectors? We also wanted to provide maximum flexibility
instead, the jumper JP1 can be shorted to bypass the voltage divider. here. Some OLED display modules have the 3.3 V pin as the pin 1 and
For voltage sensing, a voltage divider is used where R1 is 100 kΩ and others have it on the pin 2.
R2 is 6.7 kΩ. This setup can measure voltages up to 50 V, which is
more than enough for most DC applications. The input voltage of the battery or source at connector K12, for the
current setup of voltage divider, i.e., R1 100 kΩ and R2 6.7 kΩ, should
For connectivity, ensuring the module’s ease of integration into various not exceed 50 V. But keeping in mind the modularity of the setup, an
systems was a top priority. Thus, it includes a Qwiic Connector at option of a variable resistor RV1 is added to adjust the voltage divider
K3 for quick plug-and-play scenarios, a Grove Connector at K4 for to the application needs. Moreover, the maximum current load should
seamless integration with Seeed Studio’s ecosystem, and a 2.54-mm not exceed 5 A, as it’s the max limit of the INA169 breakout board. We
pitch header for custom setups. The inclusion of XT60PW connec- summarized the Technical Features in the text frame above.

Qwiic I2C. Grove I2C OLED-A OLED-B


+3V3
K3 K4 K11 K9 K10
K2 ADS1015
1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4 1 2 3 4
1
VDD
2
GND
3
R2 R4 SCL
4
SDA
6k7

22k

5
ADDR
6
ALRT
7
A0
8
A1
9
R1 JP1 R3 A2
RV1 10
A3
100k

22k

100k

K12 NC_VIN+
1
BATT

K5
2 1
NC_VIN–
2
K6 1 2 3 4 1 2 3 4 1 2 3 4 5
1
LOAD

INA169-IN K7 K8 K1
2
RAW OUT AG INA169-OUT 240141-001

Figure 2: AmpVolt module schematic.

May & June 2024 19


Figure 3: Overall wiring diagram of the AmpVolt module.

The Printed Circuit Board


The Elektor Lab team designed a PCB with KiCad 7 [5]. The basic
wiring diagram is illustrated in Figure 3. Please note that, in the illustra-
tion, the actual BoBs are not in place, but they are required, of course.

The design and layout of the printed circuit board, as illustrated in


Figure 4 and Figure 5, measures 96.5 × 40 mm and is designed for
simplicity and compactness, facilitating its use in series between the
source and the load. It segregates high-voltage and MCU interfaces
Figure 4: The PCB layout of the AmpVolt module. to opposite sides, enhancing electrical safety and integration flexibil-
ity. Designed for M3 screw mounting, it facilitates secure installation,
with provisions for a 3D-printed enclosure for specialized applications.

Critical to its design, voltage dividers are optimally positioned adjacent


to power terminals to mitigate parasitic resistances and electromag-
netic interference, crucial for maintaining signal fidelity. The OLED
display’s central placement allows for straightforward data monitor-
ing, while the ADS1015 ADC module’s proximity to MCU links ensures
reduced signal degradation through minimized trace lengths. Addition-
ally, the INA169 current sensor module is strategically located near the
load terminus, supported by 4 mm traces capable of sustaining high
current flow, underscoring the design’s focus on operational integrity
and user safety.

The Software
Figure 5: 3D Rendering of the PCB. We made a default firmware for an ESP32-C3 with the Arduino IDE. Our
sketch [5] measures voltage and current, displays these on an OLED
Display [6], and calculates power consumption and the state of charge
(SoC) of a battery connected. The firmware is designed to work with
various microcontrollers and includes setup for serial communication
and I2C for connecting the ADS1015 ADC module and OLED display.
Refer to Figure 6 to see the AmpVolt prototype in action.

Key functions in the code include readVoltage() and readCurrent(),


which use the ADS1015 to measure voltage across a voltage divider
and current through a current sensor. The energy consumed is calcu-
lated using the concept of power integration over time. Specifically, the
code accumulates energy consumed in small-time intervals, converting
instantaneous power (measured in Watts) into energy (Watt-hours,
Wh) over these periods. The calculation is based on the formula:

 Power [W] × Time [s] 


Energy consumed [Wh] = ∑  3600

Here, Power (W) is calculated as V × I (voltage times current), and the


Figure 6: AmpVolt module running in test setup. Time Interval is the duration between successive energy calculations

20 May & June 2024 www.elektormagazine.com


Component List
Resistors
R1 = 100 kΩ
R2 = 6.7 kΩ
in seconds, converted to hours by dividing by 3,600 (the number of RV1 = 100 kΩ multi-turn Trimmer or as required
seconds in an hour). This method effectively integrates power over R3,R4 = 22 kΩ
time to compute the total energy consumption.
Modules Used
The process in the loop function updates the energy consumed by INA169 Current Sensor Breakout Board [2]
adding the power calculated for each interval (every second, in this ADS1015 Breakout Board [3]
case) to a cumulative total. This ongoing summation provides a dynamic 128x64 0.96” OLED Display Module [4]
measure of energy used over time, allowing the system to track and
report energy consumption accurately as the module operates. Connectors
2× AMASS XT60 PW
The State of Charge (SoC) calculation is for monitoring battery life and Grove Connector
usage efficiency. It’s determined by the ratio of the energy consumed Qwiic Connector
to the total battery capacity, expressed as a percentage. The formula
used is:

 Energy Consumed 
State of Charge (SoC) =   × 100%
%
 Battery Capacity 

In this, “Energy Consumed” is the accumulated energy usage over Overview of the Arduino Sketch
time, measured in watt-hours (Wh), and “Battery Capacity” is the total
energy capacity of the battery, also in Wh. This calculation provides Setup and Global Variables
a real-time snapshot of how much energy has been used from the > Initializes serial communication and I2C with specific
battery, relative to its total capacity, offering valuable insight into the SDA and SCL pins.
remaining battery life and when recharging may be necessary. > Sets up the ADS1015 ADC module for reading analog
inputs and the OLED display for output.
Sample Rate > Defines constants for resistor values in the voltage
The ADS1015 ADC, as specified in its datasheet, boasts a maximum and current dividers, allowing for accurate voltage and
Sample Rate of 3,300 samples/s. However, when operated within current measurements.
the Arduino Framework, this rate experiences a notable adjust- > Establishes variables for calculating energy consumed
ment. Specifically, in single-shot test mode, the sample rate reduces over time and tracking the start time for elapsed time
to 312 samples/s, and in continuous mode, it can reach up to 1500 calculations.
samples/s. This reduction is attributed to the Hardware Abstraction
Layer (HAL) of Arduino, which, while facilitating code abstraction and Main Functions
simplicity, imposes a significant speed constraint on the ESP32. > readVoltage(): Reads and calculates the voltage based
on ADC values and the voltage divider ratio, accounting
During testing phases, efforts to enhance the sample rate were under- for any zero error offset.
taken by adjusting the I2C speed from the standard 10 kHz to 90 kHz. > readCurrent(): Similar to readVoltage(), but
This adjustment yielded a modest increase of approximately 20 to 30 calculates current using ADC values and the current
samples/s in single-shot test mode and 100 samples/s in continuous divider ratio.
mode. This outcome highlights the limitations imposed by the Arduino > sendData(): Sends data (voltage, current, or power)
Framework’s HAL on the ESP32’s performance capabilities. over serial communication based on the command
received.
It’s worth noting that operating the ESP32 in its native environment, > calculateAndSendAdditionalData(): Calculates
specifically the ESP-IDF, presents an opportunity for substantial additional data like power and state of charge, then
improvements in sample rate efficiency. The ESP-IDF allows for more sends it in JSON format over serial.
direct control over the hardware, potentially unlocking the ADS1015’s > readCommand(): Reads commands from the serial
full sampling capabilities. port, returning a complete command when a newline
character is detected.
Nonetheless, to accommodate a broader audience and ensure acces-
sibility, our first firmware implementation detailed here remains within Display and Utility Functions
the Arduino Framework. This approach aims to strike a balance > updateDisplay(): Updates the OLED display with
between performance and simplicity. However, there is an option to voltage, current, power, and other relevant data.
have highest measurement performance and additionally an easy > elapsedTimeAsString(): Calculates elapsed time since
application programming with Arduino and all its libraries: using two the module started and formats it as a string
microcontrollers.

May & June 2024 21


Serial Interface providing real-time updates to the user via an OLED display. In the
In the Elektor firmware, we already built in a simple interface to send text box, you can have a brief overview of the code.
the data to another “application controller” (or via a serial-USB bridge
to a PC). The application controller (for example, the main controller Future Improvements
of some IoT project) is freed up from any sampling and power/energy The roadmap for enhancing the AmpVolt module includes several
calculations. That is done in the “measurement microcontroller.” technical advancements aimed at increasing accuracy and usability.
A notable update will be the integration of a software calibration mode.
The sendData() handles serial communication by responding to This addition is expected to improve the precision of low voltage and
specific commands from the application controller received through current measurements through advanced curve fitting techniques,
the serial port. When a command is received, the function determines reducing measurement errors significantly.
the type of data requested — be it voltage (#v), current (#i), or power
(#p) — and then performs the necessary measurement by calling Furthermore, a feature that allows powering the microcontroller unit
either readVoltage(), readCurrent(), or calculating power directly directly through the source connector is under development. This
within the function. feature will simplify project setups by reducing the number of required
components, streamlining the integration process.
The function calculateAndSendAdditionalData() serves a more
comprehensive purpose by calculating additional metrics such as Additionally, work is underway to create a custom expansion board for
power and the state of charge (SoC) of a battery and then formatting compatibility with the XIAO controller board line from Seeed Studio,
this data into a JSON structure for transmission over serial. Here’s a expanding the module’s versatility and application range, which can be
step-by-step breakdown of its process: used for a measurement microcontroller or an application microcon-
troller for any setup. The upcoming V2 variant of this project promises
> Power Calculation: It calls both readVoltage() and to incorporate these enhancements, offering improved precision and
readCurrent() to get the current voltage and current measure- convenience in power monitoring solutions.
ments. Power is then calculated by multiplying these two values. 240141-01
> SoC Calculation: The state of charge is an estimation of the
battery’s remaining capacity. It’s calculated by integrating
the power over time to get energy consumed and then relat- Questions or Comments?
ing this to the total battery capacity predefined in the code If you have questions about this article, feel free to email the
(batteryCapacityWh). The SoC is expressed as a percentage of author at [email protected] or the Elektor editorial team
the total capacity. at [email protected].
> Data Formatting and Transmission: After computing these
metrics, the function formats them into a JSON string. This string
includes voltage, current, power, energy consumed, and SoC,
making it easy to parse on any device receiving the serial data.
Related Products
The code uses millis() to track and periodically update energy
consumption, adding a real-time element to monitor energy use over > Qoitech Otii Arc - Power Supply, Power Meter and Data
Acquisition
an extended period. It also includes a function, updateDisplay(), www.elektor.com/19270
to refresh the OLED screen with current readings and other relevant
information such as elapsed time since start, calculated using the > Renewable Energy at Home
elapsedTimeAsString() function. www.elektor.com/20747

> ESP Terminal


Overall, the code [5] is straightforward, focusing on accurately gather- www.elektor.com/20526
ing electrical measurements, enabling easy data communication, and

WEB LINKS
[1] INA169 Current Sense Amplifier | Datasheet: https://www.ti.com/product/INA169
[2] ADS1015 12-bit ADC | Datasheet: https://www.ti.com/product/ADS1015
[3] GY-169 - INA169 Current Module: https://s.click.aliexpress.com/e/_DFZSO21
[4] ADS1015 Module 12-bit ADC: https://s.click.aliexpress.com/e/_DnMmvRJ
[5] AmpVolt V1.0 | Source code and PCB files: https://github.com/ElektorLabs/AmpVolt
[6] 0.96” OLED Display (Blue, I2C, 4-Pin): https://elektor.com/products/0-96-oled-display-blue-i2c-4-pin

22 May & June 2024 www.elektormagazine.com


EVENT

EDITORs’
Picks
embedded world 2024
embedded world 2024 took place from April 9 to 11 in Nuremberg, Germany.
It was a must for everyone dealing with microcontrollers and tools. This year, there were
32,000 visitors, and more than 1,100 exhibitors in seven halls. Elektor editors
Brian Tristam Williams and Jens Nickel, plus Elektor Lab engineers Jean-François
Simon and Saad Imtiaz, took the chance to go around and find a lot of interesting new
products. As always, their personal selection can only be a small sampling of all the
innovations seen at the fair. You’ll find even more on our YouTube channel,
www.youtube.com/ElektorIM.

PTC
Java is a powerful language for multi-platform
programming with a gigantic ecosystem. But,
when it comes to real-time applications, Java is
not suitable because of unpredictable garbage
collector processes. The Perc Real-Time Java
platform from PTC fills this gap, with a virtual
machine and a tool set for realtime behavior. IoT
gateways are just one possible application.
www.ptc.com/en/products/developer-tools/perc

Seeed and
well-known for easy
Grove modules are me s int o play.
d now AI co
quick prototyping, an for an aly sis
e can be us ed
Artificial intelligenc Grov e se ns ors
m differe nt
of combined data fro sic) sp ee ch and
ll as for (ba
(sensor fusion) as we the Grove
Already available is
image recognition. ined with
, which can be comb
Vision AI Module V2 as host
act XIAO ESP32-S3
a camera and a comp ssible
models are also acce
controller. Pretrained there are
raft AI platform, and
on the public SenseC
more to come. 2
m/grove_vision_ai_v
wiki.seeedstudio.co
Arduino
Arduino displayed some new Pro solutions, for example new expansi
on
blocks for the Opta model, to allow more inputs/outputs. The Opta
Digital
Expansion block integrates 16 programmable inputs (0–24 V digital
or 0–10 V
analog) and 8 outputs, with a choice of 8 electromechanical or solid-sta
te
relays depending on the model. The Opta Analog Expansion block offers
6
programmable 0–10 V or 4–20 mA inputs and 6× 0-10 V, 4-20 mA or
PWM
outputs. These modules are designed in collaboration with Finder and
will
enable professionals to scale up their automation projects while integrat
ing
nicely with the Arduino ecosystem or Arduino PLC IDE.
An Arduino partner, SOLO Motor Controllers, was also present ,
demonstrating its various motor control modules, driven either by an
Arduino R4 or an Arduino Pro. The demonstration test bench (see photo)
used CANOpen to drive motors and linear actuators.
www.arduino.cc/pro/hardware-arduino-opta-expansions
www.solomotorcontrollers.com

May & June 2024 23


Nordic
Bluetooth LE Audio
can be a game Batronix
changer for wireless Batronix is now launching its own oscilloscope,
audio transmission. named Magnova. This model introduces a novel
It is now possible approach by reimagining the user interface. It
to send a left and has a large 15-inch full-HD touchscreen display,
a right channel four rotary encoders and… that’s pretty much it,
from a source to besides a power button, a run/stop button, and a
two different loudspeakers, independently of each single-shot button. This design results in a sleek
other, but in good synchronization for stereo. First, appearance, especially with the BNC connectors
we may think of battery-based loudspeakers and located on the side, as you see in the photo. While
music, but this is not the only application. Another its commercial success remains to be seen, it’s
can be hearing aids, which can get more compact very nice to see some innovation there. Batronix
because they don’t have to communicate with each emphasizes several key attributes: an entirely
other anymore. Nordic showed audio development new user interface, the large matte touchscreen,
kits named nRF5340 Audio DK for their nRF5340 silent operation due to passive cooling, advanced
Bluetooth LE 5.4 chip. Oftentimes when adopting software with a wide range of built-in decoders at
new technologies early, they have their price no additional charge, good analog capabilities, a
(around €180 at some big distributors), and you will 12-bit ADC, 4×1 GSa/s sampling rate, and three
need at least two, but better to have three of them. bandwidth options ranging from 100 to 350 MHz.
In the near future, we will most likely see cheaper www.batronix.com/magnova
and less-equipped dev boards and modules on the
market.
www.nordicsemi.com/Products/
Development-hardware/nRF5340-Audio-DK

Lattice
At the show, Lattice was mostly focused on
Cologne Chip showing their high-end, low-power products, such
We had a very nice chat with Cologne Chip, as the Lattice Avant-E. They had a very nice demo,
known for being one of the few EU-based FPGA which aggregated data from several sensors: a
manufacturers. Even the silicon die is made in a camera for on-board image recognition, a LiDAR, a
German “fab!” One of the interesting features of the RADAR, and so on. The demo setup is shown here.
GateMate family is scalability. The GateMate A1 and www.latticesemi.com/en/Products/FPGAandCPLD/
A2 are available now, and the A4 will be available Avant-E
shortly. They are all pin-compatible, which means
you can prototype your project with a GateMate A1
or A2 and then move to the A4 when it becomes
available, with no modifications to your layout.
They offer a good price-performance ratio and the
software toolchain is open-source too. There are
a few development boards available, including an
affordable one available from Olimex.
www.colognechip.com
www.olimex.com/Products/FPGA/GateMate/
GateMateA1-EVB/open-source-hardware

24 May & June 2024 www.elektormagazine.com


Espressif Systems
Espressif Systems recently showcased several
new products, including the ESP32-C5, -C6, and
-C61 models. Notably, the ESP32-C5 features dual-
band Wi-Fi connectivity, enabling simultaneous
operation on both 2.4 GHz and 5 GHz frequencies.
This improves the connectivity for a range of IoT
applications. The ESP32-H2 is currently available
for consumers, while the most powerful module in
Espressif’s range, the ESP32-P4, is scheduled to
launch in August. The ESP32-P4 is designed for
LabTalk live from the exhibition high-performance, secure applications and has
an integrated high-speed peripheral for improved
It goes without saying that we also had again a live
connection. Its dual-core RISC-V CPU can reach
show directly from the fair. Elektor editors Brian T.
up to 400 MHz. It is positioned as a leading
Williams and Jens Nickel were supported by Elektor
solution in embedded systems and IoT because
author and video creator Stuart Cording, who is a
of its ability to enable advanced human-machine
long-term expert in the field of Microcontrollers and
interfaces and effective edge computing.
Tools. In the one-hour show, Stuart, Brian and Jens
www.espressif.com/en/products/socs/esp32-p4
talked shop with Elektor Lab engineers Saad Imtiaz
and JF Simon about the most interesting things seen
on the embedded world 2024. Special guests: Pedro
Minatel and Anant Gupta from Espressif.

m,
is s e d t h e Live Strea t
If you m atch the video a
you can w u.be/eYugqSVYgY0
t
https://you

M5Stack
M5Stack is set to release several new products,
each utilizing Espressif’s ESP32 chips for diverse
applications. The ultra-compact NANO C6, about
the size of a fingertip and featuring the ESP32-C6
chip, offers advanced connectivity features
suitable for space-constrained environments. The
CORE MP135 focuses on long-range connectivity
with LoRaWAN and LTE, ideal for remote IoT
applications. The Cardputer, a unique, card-sized
Raspberry Pi computer with an OLED display, keyboard, and
Raspberry Pi was teasing brand- powered by the ESP32-S3, offers extensive I/O
new, unannounced products, capabilities, merging portability with functionality.
including the M.2 HAT+ for M5Stack also previewed the StamPLC, a
SSD applications and the new programmable power supply, and a digital
Raspberry Pi monitor. An exciting multimeter (DMM), all based on the ESP32-S3.
new product is a brand-new These tools are aimed at enhancing automation,
Raspberry Pi AI Camera module, measurement, and control systems.
which looks just like any other www.m5stack.com
camera module from the company. But, this one
has all the AI power on the module itself, meaning
that it will work for you while connected to as little
as a Raspberry Pi from the Zero range. The proof
was on display for all to see, with two demos,
one doing live object detection at 30 frames per
second, while another was able to do human-frame
detection and overlay wireframes in real time.
raspberrypi.com
240239-01

May & June 2024 25


TIPS

ab • Elek
or l t
kt

or
Ele

lab
ORIGINAL

Repairing

Ele

b
or

kt
or

la
la b
• Ele k t

Electronic Equipment
Tools, Techniques and Tips

By Jean-François Simon (Elektor)

The ability to repair and


troubleshoot your own
electronic devices not
only saves money but also
extends the life of your
equipment. Plus, it is a very
rewarding experience! From
mastering essential tools,
through troubleshooting
techniques, to explaining
common component faults,
this guide will help to boost
your confidence when you
repair and extend the lives of
your devices. Figure 1: Essential tools.

First, let’s take a look at the tools that will Let’s start with the essential tools useful at the same time, among other things
be useful for most electronic repairs. Of (Figure 1). You’ll need at least: a multime- for testing power supplies, by monitoring
course, everyone will have their list of ter, a soldering iron and solder, an oscillo- the output voltage while increasing output
favorite tools, according to personal prefer- scope, and an adjustable power supply. To current. As for the second soldering iron,
ence. Here’s my list. If you’re a beginner, check solder joints and inspect the PCB it will be almost irreplaceable as a comple-
it may give you a few pointers to get you for defects, a small magnifying glass with ment to the first, for desoldering all kinds
started. If you’ve only got one or two of a high enough magnification (10× in my of SMD components with one iron in each
these tools, and the list seems far too long case) will be a precious help. Even a very hand.
or far too expensive, don’t panic! On the inexpensive magnifier will be infinitely
one hand, it’s always possible to do without, better than no magnifier at all; personally, I Speaking of soldering, here are a few extra
until you’ve decided that it’s the right time use a €3 plastic model from RS (ref 136-8106) supplies. Desoldering braid (I recommend
to buy a new tool, and, on the other hand, which serves me well. the tinned variant) and gel flux. For cleaning
most of these things can be found either up after soldering, cotton swabs and 99% (or,
very cheaply in China, or at affordable It’s debatable, but, in my opinion, a second failing that, 90%) isopropyl alcohol work
prices on the second-hand market in any multimeter and a second soldering iron are well. I’d recommend putting the alcohol
country. also essential tools. Two multimeters are in small plastic bottles (50 or 100 ml,

26 May & June 2024 www.elektormagazine.com


for example), allowing small quantities to be
applied, and to devote one of these bottles
to a 50% isopropyl/50% acetone mixture —
very effective for hard-to-remove residue.
Of course, if you can afford it, a professional
cleaner such as Fluxclene is fine, but not
essential. To remove severe corrosion caused
by water ingress or electrolyte leakage from
a capacitor, a fiberglass pencil brush comes
in very handy.

Optional Tools to the Rescue


You can do without them, but once you’ve Figure 2: A home-made current limiter.
bought them, they turn out to be really
useful. I recommend an inexpensive desol-
dering station. It’s so effective for cleanly without one, especially with products as completely disappeared from store shelves
and quickly desoldering transistors, capac- affordable as the ZD-915 or ZD-8915 models in many countries.
itors, DIP ICs, connectors, relays, etc., that under €100. I would add to this category: an
I think it would be a pity to go too long ESR or LCR meter, as well as a very cheap For my part, I made a slightly more compli-
component tester such as the T4 model. cated setup than necessary (Figure 2),
using a rotary switch to connect a
A Dim Bulb Current Limiter? number of small halogen bulbs in paral-
Two Past Repairs In the category of small, home-made tools lel (20 W / 230 V, G9), enabling me to limit
Once, I troubleshot a Lithium battery-pow- that you build up over the course of your the current in five steps — from 80 mA to
ered remote control for industrial equip- life, I’d also mention a dim bulb current around 400 mA.
ment that refused to work. Everything on limiter. It’s especially useful when repair-
the board seemed to be inactive. No power, ing mains power supplies, particularly Now, let’s talk about repair methods. Here
no reaction to button presses, even when when these have faults such as short-cir- are a few things you might find helpful.
replacing the battery with a power supply. cuited diode bridges or shorted transistors
In fact, a simple visual check revealed the on the primary circuit, a blown fuse, etc. How to Tackle Electronic
solution: The central pin of the connector After repair, it’s a good idea to limit the Repairs: A Few Hints
used to charge the battery was broken. As maximum current, in case we’ve forgot- Start by taking stock of the situation. Do you
a result, the battery had discharged, and ten something, to prevent the same compo- know exactly what the fault is? If it’s a device
the battery charging/monitoring IC had nents from burning out again. you own, or one you were using yourself
put the whole board into deep sleep. To when the fault occurred, you probably
unlock this protection, you need to charge The principle is very simple: Put an incan- have a pretty good idea. But take the time
the battery, not with a lab power supply, descent bulb, with the appropriate voltage to make a note of it, noting anything that
but with the IC in question, which couldn’t for mains power wherever you are on the might be a clue. Does the unit have a display
happen with the pin missing. Keep your planet, in series with one of the two power that indicates an error message? Does it run
eyes open! supply wires. In the event of a problem when cold and stop after warming up? Or
(at worst, a short circuit between live and vice versa? Has the unit suffered a shock?
Another time, there was a rather complex neutral), there will be no more explosions; Does lightly tapping it affect its operation?
motor controller which displayed the lamp will simply light up, giving you All these clues will help you get started,
“emergency stop switch engaged,” time to disconnect without damage. so don’t overlook them. If possible, try to
although this was not the case. I identi- observe the fault yourself, if it’s a repair
fied the terminal block dedicated to the It’s a good idea to have several lamps of you’re doing for someone else.
emergency stop by consulting the manual, different wattages, so as to be able to limit
and followed the tracks back to one of the the current to a higher or lower value, Have a look on the internet to see if anyone
board’s microcontrollers, a good twenty depending on the device you wish to test. else, in any forum, might have had the same
centimeters away, checking numerous This can be done very simply with a few problem on the same device. See if a service
components along the way. I finally found spare bulbs and a bulb socket; you simply manual or schematics are available.
a short-circuited transistor, just before the screw in the bulb of your choice as needed.
signal reached the microcontroller. Victory! Note that you need an incandescent bulb, Next comes disassembly. Remember to
This €1,500-plus device was finally repaired not a CCFL or LED; to find one, you’ll maybe take photos to make reassembly easier, and
by replacing this 20-cent component. have to use the classified ads, as these have number the connectors on the cables with a

May & June 2024 27


fine-tipped permanent marker if necessary,
so you can reattach them unambiguously
on reassembly.

Visual Inspection Comes First


For diagnosis, start with a good visual
check: I’ve lost count of the number of
times this has been able to tell me immedi-
ately, if not the precise fault, then at least
its location on the PCB, thanks to burnt-out
components, signs of overheating, missing Figure 3: How to safely probe circuits for live testing.
components (component leads sometimes
snap on impact, after having been fatigued
by thermal cycling), cracked solder joints, lers. Datasheets and experience will tell you of creating faults. Rather than taking the
and so on. Use your other senses too: a which pin numbers to look out for. In the chance of slipping with the probe tip, I often
suspicious smell? A strange noise when event of zero voltage, use an ohmmeter to prefer to solder a small piece of wire to the
you shake the case? check that the rail is not short-circuited to node of interest, and hook the probe to it.
ground. If it is, look for the short circuit; if Another option is to use good quality, thin
Try to identify functional blocks. Power it isn’t, look upstream to find out why the mini-grabbers, like the ones from EZ-Hook
supplies, front panel PCBs, digital control power supply isn’t turned on. (see Figure 3). This leaves my hands free
section, analog section, output stages if any, to operate the on/off button and the oscil-
etc. Use deduction to locate possible sources Whenever possible, I try to desolder as few loscope controls.
of trouble. components as possible. Nevertheless, it
often happens that there’s a doubt, and you When I worked in an electronics repair
Choose a direction: Either in the direction have to desolder a component to confirm shop, I used my computer all the time to
of flow (energy flow or information flow), a measurement, especially when looking look for the datasheets and pinouts of the
or against the flow. From inputs to outputs, for short-circuits. Beware! I’ve often come countless new components I didn’t know
or vice versa. There are no hard and fast across PCBs without silk-screening, and it about when repairing a particular device.
rules; at the beginning, you can choose can happen to anyone to accidentally solder When working without schematics, which
arbitrarily, and alternate between the two a SO-8 or SO-14 integrated circuit rotated, are rarely available, and sometimes on PCBs
techniques as the diagnosis progresses. leading to anger and frustration on the next without a silkscreen, SMD marking catalogs
For a power supply that doesn’t light up at test. Refer to the photos taken beforehand. are invaluable tools to identify components.
all, it’s often convenient to start from the [1] and [2] are two well-known examples,
mains input, and check one after the other In this phase of troubleshooting, it’s likely and there are others too.
in the chain: fuse OK, diode bridge OK, PFC that you’ll have to alternate frequently
transistor OK, etc. On the other hand, if the between in-circuit component testing Finally, there comes the moment when
power supply powers on but there’s a fault (without power), desoldering, re-solder- you’ve found a faulty component. No
on just one of its multiple outputs, then it’s ing, possibly swapping components, testing doubt, your measurements are categorical:
more relevant to start looking at the output, with power on, and so on. In all cases, take It’s burnt out. Congratulations! Search the
working backwards. your time and keep a clear head. Above all, surrounding area, on all the tracks leading
never solder or desolder on a live circuit! from all the pads of that component for any
Is the Power On? And make sure it doesn’t happen either other damage.
As a general rule, start by checking the by accident. Apart from the safety issue,
power supply rails. Sometimes, there may there’s a very real risk of creating faults by Replacing Components
be test points; otherwise, you can measure short-circuiting two adjacent pads with the To replace the component, try as far as
the voltage across the electrolytic capaci- iron. possible to replace it with an identical
tors. Common voltages are 12 V, 5 V, 3.3 V, one, by searching all the usual suppliers:
etc. A fluctuating or absent voltage will alert Measuring Safely Farnell, RS, Mouser, Digikey, Distrelec, etc. If
you to a possible fault. Never take oscilloscope measurements possible, avoid eBay and Aliexpress, where
on the primary side (mains side, before the probability of receiving a counterfeit
If the power supplies seem to be working, the transformer) of a power supply, unless component is sometimes as high as 100%.
check that the functional blocks you come you are fully informed and fairly experi-
across are also powered, by measuring the enced with differential probes and isola- If the component is difficult to source or
voltages at the power supply terminals of tion transformers. On the secondary side, obsolete, there is no choice but to find an
the integrated circuits and microcontrol- there are fewer safety risks, but still a risk equivalent. Pay attention to the type of

28 May & June 2024 www.elektormagazine.com


package, its pinout, as well as the main the general case. Here’s a list of common for conventional diodes in the forward
characteristics: maximum voltage and failures, classified by component type. direction, and OL (infinity) in the reverse
current for transistors, switching speed, direction. For Schottky diodes, the voltage
and so on. If in doubt, don’t hesitate to ask Electrolytic capacitors: Sometimes is lower, down to around 0.3 V.
for help in a forum, where members are bulging, as shown in Figure 4, or having
generally very helpful and friendly. lost electrolyte, lost capacitance or having Power resistors: Often open. Typical case:
an ESR value too high. Test with a multime- resistors used to limit the start-up current
In the following section, let’s have a look at ter in capacitor mode, an ESR meter, or an of some switch-mode power supplies.
a few common faults that can happen for LCR meter. Those that are bulging or have
some of the more common components, as leaked need to be replaced without further Through-hole or SMD diodes, or Zener
well as a few tips about testing them. testing; for those with a normal appearance, diodes, and small bipolar or MOSFET
desolder one lead to prevent neighboring transistors: Short-circuited or open-cir-
Failure Modes of Common components from interfering with the cuited. Test them using the Diode mode.
Components measurement.
It can be useful to have an idea of the types Power ICs: Meaning those which can
of failure that can occur in a given type of Power transistors (bipolar or MOSFET): potentially dissipate some heat, such as
component so that you can search effec- Often short-circuited, sometimes open-cir- motor drivers: Supply pins short-circuited
tively. It’s common to hear that electrolytic cuited. Test with multimeter diode mode. to ground, or output pins short-circuited to
capacitors are always the culprits. This is Identify the pinout first. For a bipolar ground or VCC. This is often the case with
sometimes true of very inexpensive switch- transistor, check the base-emitter and switching-controller ICs, on the primary side
mode power supplies, which are built with base-collector junctions. Also check that of switching power supplies. In particular,
capacitors limited to 85°C instead of the there is no continuity between collector those incorporating the control logic and
slightly more expensive ones that can and emitter. For a MOSFET, check that the power transistor in the same package (such
withstand 105°C. Often, there is very little MOSFET’s internal diode is visible (junction as ST’s VIPER20 and others) are fragile.
margin, in terms of both voltage and capac- voltage around 0.5 or 0.6 V) between Drain
itance; this excessively strains the capaci- and Source (Figure 5), and that the gate is Plastic film capacitors: Loss of capaci-
tors, which will generally give up and fail isolated from the other two pins. tance. More rarely, short-circuited. Capac-
just after the expiry of the legal warranty. itance loss is frequent, especially when
Power diodes, rectifier diode bridges: these capacitors are used as capacitive
However, in better-designed devices, or in Often short-circuited, more rarely open-cir- droppers, i.e., to obtain a voltage of a few
test and measurement instruments and cuited. When tested in diode mode, you volts to supply a logic circuit from the
industrial equipment, this is far from being should find a voltage of around 0.6 or 0.7 V mains. In this case, a constant AC current

Figure 4: The infamous bulging electrolytic Figure 5: Using the diode mode to test a power MOSFET.
capacitors. (Source: Wikipedia [3])

May & June 2024 29


flows permanently through the capacitor,
which will age prematurely.

Transformers: Open-circuit, or short-cir-


cuit between turns (leading to overcurrent
and overheating).

Through-hole or SMD resistors:


Sometimes visibly burnt out, sometimes
open-circuited, not visible to the naked
eye. That can be checked easily with an
ohmmeter: Due to the various compo-
nents in parallel with the resistor under
test, the resistance measured must always
be lower than the value shown on the resis- A Power Supply That Wouldn’t Cooperate
tor marking. If this is not the case, the resis- That one gave me a hard time. I troubleshot an ATX PC power supply, a CX400 from Corsair,
tor is open-circuited or has drifted upwards dating from the 2010s. It was shutting down after some time. The first problem was that
considerably. the power supply was willing to switch on in the PC, but categorically refused to start up
on my workbench when I used the classic technique of shorting the green PS_ON wire
SMD ceramic capacitors: Sometimes to ground, which complicated my diagnosis. Being less experienced at the time, I didn’t
short-circuited. In this case, the entire immediately think of connecting an additional resistive load on the 5V_SB rail (standby
supply rail is shorted to ground. To locate supply) to remedy this.
it on the board, you can use a lab power
supply. Set the voltage to a low value, such Having done this, I noticed considerable instability in the 5V_SB voltage, with sawtooth
as 1 V or 2 V, and the maximum current fluctuations of several volts in amplitude. Yet all the infamous electrolytic capacitors were
to about 1 A. Connect it to the power rail, in good condition on the output (and on the other outputs too). To help me troubleshoot, I
while respecting the polarity. This will force made a hand-drawn snippet of schematic, as shown opposite. I highly recommend you do
current into the short-circuit. Then, use the the same when you get stuck; schematics, even incomplete and hand-drawn, are always
DMM in millivoltmeter mode to get closer helpful.
and closer to the short-circuit. The voltage is
lowest across the short-circuited capacitor. In fact, there was a small SMD ceramic capacitor, C107 on the previous figure, which was
Some people recommend using a beefier part of an RC low-pass filter, in the voltage feedback loop of this rail. This capacitor had gone
power supply and setting the current to a open, and was no longer filtering anything, causing the instability. A very rare failure! A few
higher value; this can make the short-cir- years later, while browsing a forum, I came across someone who’d had the same problem,
cuited component warm up, and it can then with the same component in the same power supply. That was probably a manufacturing
be seen with a thermal camera. If you use defect that caused the capacitor to crack due to thermal cycling.
this technique, be careful, a higher current
could also burn some tracks instead. In very
rare occasions, these caps can also go open
circuit — see the text frame about the power Push-buttons: Sometimes short-cir-
supply for an example. cuited (causing erratic device operation),
or sometimes no longer making any contact
Relays: Their contacts can become resis- (the device no longer responds), especially
tive after a large number of actuations. This when they have been in contact with water.
can be checked with the ohmmeter on the
contacts, by supplying the relay coil with Solder joints: Some lead-free alloys are
the appropriate voltage from a lab power prone to cracking with age, as a result of
supply. Take care to use the correct voltage repeated thermal cycling. These can be hard
for the coil, and the correct polarity, to avoid to see with the naked eye, but a hair-thin
damaging the rest of the circuit. The (+) crack can be enough to break continuity
can usually be found by looking at which completely. This shows the importance of
of the two coil terminals is connected to the inspecting the entire board with a magni-
cathode of the freewheeling diode, which is fying glass. An example of rather big cracks
often located nearby. If in doubt, unsolder is visible in Figure 6. Other, much thinner, Figure 6: These solder joints have seen better
the relay to test it safely outside the circuit. ones are much harder to find. days.

30 May & June 2024 www.elektormagazine.com


s and Tricks
A Few Additional Tip
on
e the oxidation layer
arp es t pro be tip s possible, to overcom wi tho ut having
> Use the sh components
an d ma ke rel iab le measurements on ete r pro be
solder joints . Cheap multim
ha rd. Th is red uc es the risk of slipping r my pa rt, I use
to press too ll quickly. Fo
en ma de of pla ted brass and tend to du , an d I reg ula rly
tips are oft are very sharp
n PR UE F 2 sta inl ess steel tips. They
Hirschman
a small whetstone.
re-sharpen them on
varnish,
read by a thick clear
on en t ma rki ng s are made difficult to e it an d see
> When comp used to remov
rm al co ati ng ,” ac etone can often be as a ch op stick to
called “confo tool such
y. Us e co tto n sw ab s and a hard wooden the co mp onent
more clearl rat ch the surface of
l, wh ich wi ll sc
metal too
scrape. Don’t use a marking.
it ev en mo re difficult to read the
and make
A
um load to operate.
h- mo de po we r su pplies require a minim PC B its elf.
> Some switc luded on the
we r res ist or wi ll do , but is not always inc n’t sta rt up or fails
suitable po ly yo u’r e tro ubleshooting ca
powe r su pp
Think about this if the
its ou tpu t vo ltage properly.
to regulate
ed with
D components are glu
es , be for e be ing wave-soldered, SM ey are tricky
> Sometim e-down. Th
glu e to ho ld the m when they’re upsid He at all the
a dot of red d the pads.
r wi tho ut da ma gin g the component an of so lde r. For
to desolde g tip and ple nty
at the sa me tim e with a large solderin at bo th sid es
terminals work well to he
erm ina l co mp on en ts, a “knife” tip can ns . Wh ile he ating,
small 2-t
r co mp on en ts, us e two soldering iro
bigge e.
simultaneously. For ent to detach the glu
ert an X-A CT O bla de under the compon
gently ins
primary
lk capacitors on the
of ch arg ed ca pa cit ors! In particular, bu 5 V DC . There is
> Beware charged to 32
itc h- mo de po we r supplies are often ma ins is switched
side of sw to dis ch arg e them when the
d res ist or ltimeter
sometimes a dedicate nt, check with a mu
t alw ay s. Be for e an y test or measureme ce ss ary .
off, but no charge them if ne
y are co mp let ely discharged, and dis kΩ /
that the ted together via a 2.7
eter probes connec
I use a pair of multim Don’t do this with a
sh ow n in the photo opposite.
5 W res ist or, as the solder joint and
ve r, as it wi ll da ma ge the screwdriver,
screwdri nt spike.
e to the sudden curre
also the capacitor du
ver, as
don’t use a screwdri
sn ap -o n en clo su res made of plastic, rs wh ich are
> To open dicated spudge
s de nts in the pla stic. You can buy de rin g kn ife from
it leave e an old pa
d thi n an d fle xib le, to avoid marking. I us sa nd pa pe r, to
wider, an completely wi th
en , wh ich I pu rpo sely de-sharpened
my kitch
less.
make it totally harm
and general DIY
r to us e to pro totype new circuits
> Leaded solder ca
n be ea sie buy due to RoHS
en ev er po ss ibl e. It can be difficult to
work, and I try to us
e it wh reworking a
t mi xin g lea de d and lead-free when
restrictions, though.
Note tha a roll of each,
ult s an d sh ou ld be avoided. Either buy
solder joint yields po
or res ldering with the
lea d- fre e so lde r residue before re-so
or carefully remove
all the Kester, Stannol,
ch oo se a go od bra nd, such as Loctite,
case , press.
leaded alloy. In any n brands from AliEx
a we ll-k no wn ret ailer; avoid unknow
etc. fro m

May & June 2024 31


Quartz crystals: They are generally marks, vaporized tracks/wires/connec-
reliable, but may stop oscillating after a tors, open NTC thermistors, short-cir-
shock. If the microcontroller to which a cuited MOVs, as well as severe oxidation About the Author
quartz is connected is active, with some on tracks, pads and components. Finally, Jean-François Simon has a longstand-
LEDs flashing or something showing on connectors were often oxidized, or caused ing passion for electronics and enjoys
the LCD, you know the crystal is working. poor contacts, having become loose due to topics as varied as circuit design, test and
If no such activity is visible, the easiest vibration. This frequently leads to arcing measurement, prototyping, playing with
way is to probe one of its terminals with between adjacent pins. SDRs, and more. He likes to create, modify
an oscilloscope, relative to ground. Then and improve his tools and other systems.
move the probe to the second terminal. You Looking Ahead He has an engineering background and
should find a stable oscillation, at least a Now you should be able to approach also enjoys mechanics, machining, and
few hundred millivolts in amplitude, at the repairs with more confidence and seren- all things technical. Jean-François recently
frequency marked on the quartz. One of the ity. I strongly encourage you to give it a go joined Elektor’s Lab and Content team.
signals will have a larger amplitude than — the results and the satisfaction you’ll
the other — this is normal. derive from them are well worth the effort.
Also, don’t hesitate to check out the forums
Note: An 10× probe should be used for and YouTube, where you’ll find some very
this to avoid disturbing the oscillation too interesting content. Each of the electron-
Related Products
much. Sometimes, the input capacitance of ics specialists on YouTube has their own
the oscilloscope probe stops the oscillation personality and their own, often different, > PeakTech 3350 Multimeter
of a quartz crystal, even though the quartz methods — that’s what makes it so rich. www.elektor.com/19986
is fine. In this case, try again on the second For example, when it comes to repairing
terminal: This time, you should see an test and measurement instruments, some
> UNI-T UPO1102CS 2-ch
Oscilloscope (100 MHz)
oscillation. Oscillators often have an input videos from The Signal Path, or Feedback www.elektor.com/20495
side with a high impedance, on which this Loop, are inspiring; when it comes to
can occur. The output side, with its lower switching power supplies, DiodeGoneWild > DER EE DE-5000 LCR Meter
impedance, is less easily disturbed. If you produces videos packed with information; (100 kHz)
www.elektor.com/20675
don’t see anything on any of the terminals, and finally, for retro computing enthusiasts,
either the microcontroller is not powered take a look at Tony359’s videos. Good luck
on or the quartz is defective. with your repairs, and have fun!
240069-01
Other faults: In an industrial electronics
repair shop, we come across failures that
are a little different from those encoun-
tered in consumer electronics. For example, Questions or Comments?
liquid damage is very common, due to water Do you have technical questions
penetration when machines are washed. or comments about this article?
As the equipment is often live, with high Feel free to contact the author at
voltages (400 V AC) and circuit breakers [email protected]
rated for substantial currents, the damage or the Elektor editorial team at
can be severe. I often encountered burn [email protected].

WEB LINKS
[1] A well-known SMD marking code catalog: https://smd.yooneed.one
[2] Another useful SMD marking code catalog: http://marsport.org.uk/smd/mainframe.htm
[3] Source of the bulging capacitor picture: https://commons.wikimedia.org/wiki/File:D865PERL_bulge_2.jpg
[4] The Signal Path YouTube channel: https://youtube.com/@Thesignalpath
[5] Feedback Loop YouTube channel: https://youtube.com/@feedback-loop
[6] DiodeGoneWild YouTube channel: https://youtube.com/@DiodeGoneWild
[7] Tony359 YouTube channel: https://youtube.com/@tony359

32 May & June 2024 www.elektormagazine.com


BASIC COURSE

Starting Out in
Electronics…
...Continues the Opamp Theory

By Eric Bogers (Elektor)


100 000

Last time, we were introduced to the


operational amplifier, or so-called
10 000

opamp. We looked at some amplifier 1000


circuits and saw how to calculate
the gain. With some justified 100

simplifications, two very simple and 10


insightful formulas remain. In this
installment, we continue with some 1

of the properties and (unfortunately)


imperfections of this wonderful 1 10 100 1k 10k 100k 1M
component.
Figure 1: The open-loop gain as a function of frequency.

Open-Loop Gain and Transition Frequency the open-loop gain is significantly larger than the gain set using
The open-loop gain of an opamp is specified for DC voltages. For those two resistors.
alternating voltages, the gain decreases with frequency (Figure 1).
If we want to dimension a circuit “safely,” we must ensure that the
This figure shows the course of the open-loop gain as a function open-loop gain is at least a factor 10 larger than the externally set
of the frequency for an internally frequency-compensated opera- gain. If, for an opamp with a transition frequency of 1 MHz, we set
tional amplifier. (For the sake of simplicity, we restrict ourselves to the gain to 10×, we could operate the circuit up to about 10 kHz.
frequency-compensated opamps). The open-loop gain decreases Operational amplifiers for audio applications therefore excel not
by 20 dB per decade — that is equal to 6 dB per octave. Internally, only by low noise, but also by a high transition frequency — in the
therefore, a first-order low-pass filter is present. case of the NE5534, for example, it is at 10 MHz.

For the opamp in our example, the open-loop gain for DC voltage The Slew Rate
is 100,000, and the transition frequency — the frequency at which An operational amplifier such as the LM324 has a transition
the open-loop gain has decreased to 1 — is at 1 MHz. We see that frequency of 100 kHz; for a simple 1× amplified buffer stage, this
the open-loop gain remains at the DC level of 100,000 until about is just about sufficient for audio applications: As long as the output
10 kHz, before decreasing by 20 dB per decade. (For the record, voltage does not exceed much more than about 100 mV, such a
the transition frequency is also called the unity gain frequency). circuit will function without any problems.

Earlier, we saw that, for determining the gain of an opamp circuit, But, when the amplitude of the output voltage is increased to,
the open-loop gain is irrelevant, but is solely determined by the let’s say, 10 V (at a frequency of 20 kHz), we are rewarded with
ratio of two external resistors. However, this is true only as long as some nasty distortion. That is an issue of the so-called slew rate.

May & June 2024 33


This is because the output voltage of an opamp cannot change AC Amplifiers
infinitely fast; the slew rate indicates the rate at which it is chang- The opamp circuits we have discussed so far were DC voltage
ing (in volts per unit time). In the case of the LM324, the slew rate is amplifiers. Of course, these can also amplify alternating voltages
0.05 V/µs. The maximum undistorted amplitude (top-to-top) is then — within the limits imposed on them by the transition frequency
and slew rate, of course.

In audio applications, however, we aim not to amplify DC voltages


at all — the transmission range is from 20 Hz to 20 kHz.
And that means for the effective value:
To limit the transfer range, we just need to add a couple of capacitors
to the circuit (Figure 3). We will calculate their value later on, but
first let us consider the cutoff frequencies. The cutoff frequency is
that frequency at which the gain (relative to the gain in the transfer
range) has decreased by 3 dB. We tend to run this transfer range
initially from 20 Hz to 20 kHz. However, if we put several amplifier
For audio applications, an output top voltage of 15 V should be possi- stages in series, all dimensioned for this particular range, then we
ble (to have some headroom or output reserve), and that means have to add up the attenuation of the individual stages and, with
for the minimum required slew rate: higher-order filters, we have to deal with correspondingly steep
flanks, and, because of the inevitable tolerances of the compo-
nents used, the cutoff frequencies will also no longer be at the
point where we wanted them.

Offset Current To make a long story short: With cutoff frequencies of 20 Hz and
In operational amplifiers with bipolar transistors, the problem 20 kHz, we would “ruin” the frequency characteristics of the
arises that small currents (in the order of a few nanoamperes) flow circuit; therefore, it is better to put the cutoff frequencies of the
to the inputs. These currents cause a voltage drop across the exter- individual amplifier stages well outside the actual transmission
nal resistors, and these in turn are responsible for a corresponding range. The actual limiting of that range to 20 Hz at the lower
DC voltage offset. end and 20 kHz at the upper end then takes place at the input
stage (if possible, preferably with an LC filter even before the first
This offset voltage that appears on the output of the opamp can semiconductor, to avoid demodulating HF disturbances from
be reduced by making the external resistors as small as possible local transmitters).
(while taking care not to create issues due to a too low an input
resistance). Another possibility is to make the resistors on both Of course, everyone has to decide for themselves where they actually
inputs as equal as possible, as sketched in Figure 2. define these cut-off frequencies: it also depends, for example, on
the number of amplifier stages connected in series. In our example,
Resistor R3 would have to be chosen to be the same value in this we keep a factor 3 as a “safety margin” and therefore choose 6 Hz
circuit as the combined parallel circuit of R1 and R2; if these were and 60 kHz, respectively. Our amplifier stage needs to amplify
10 kΩ and 100 kΩ, respectively, we would select a resistor of 9.1 kΩ by a factor of 10, so we take values of 10 kΩ and 100 kΩ for the
from our box of components. external resistors.

An alternative solution — mainly used in audio engineering — is to Since there is a virtual zero point at the inverting input of the
leave the offset voltage as it is and fit coupling capacitors between opamp, the input resistance of the circuit is equal to the value
the individual stages. of R1, which thus forms a high-pass filter together with C1.

Figure 2: Reduction of the DC voltage offset. Figure 3: Transfer range limitation.

34 May & June 2024 www.elektormagazine.com


At the -3dB point, the impedance of C1 is exactly equal to the resis-
tance value of R1. Thus:

Figure 4: Input resistance for the non-inverting amplifier.

The nearest available value is 2.2 µF, which puts the cut-off
frequency at 7.2 Hz. Since this still keeps us far enough away from input resistance, R3 should have a value of 100 kΩ…1 MΩ in the
20 Hz, we don’t need to worry about it any further. case of bipolar opamps and a value of 1 MΩ…10 MΩ in the case of
opamps with FET inputs.
The value of capacitor C2 is chosen in a way that its impedance at
the upper cutoff frequency is the same as the resistance value of R2: That’s it for now; next time we’ll discuss (among other things)
symmetrical connections and the summing amplifier.
Translated by Hans Adams — 240031-01

Again, we can use the standard value of 22 pF without further ado. Editor’s Note: This series of articles, Starting Out in Electronics, is
based on the book, Basiskurs Elektronik, by Michael Ebner, which
Offset Issues With a Non-Inverting Amplifier was published in German and Dutch by Elektor.
Unlike the inverting amplifier, the non-inverting amplifier in
its basic configuration has an open input; that means its input
impedance is equal to the (high) input impedance of the opera- Questions or Comments?
tional amplifier. If you have any technical questions or comments about this article,
feel free to contact the Elektor editorial team at [email protected].
In metrology, such high-impedance inputs are often desirable,
but in other areas, they only cause us inconvenience: The offset
currents cause a correspondingly large DC voltage offset, and irradi-
ation into the inputs causes enormous interference. It is therefore
Related Products
absolutely necessary to apply a resistor from the open input to
ground, as outlined in Figure 4. > B. Kainka, Basic Electronics for Beginners
(Elektor, 2020)
To minimize the DC voltage offset, R3 should be equal to the parallel Book: www.elektor.com/19212
Ebook: www.elektor.com/19213
circuit of R1 and R2; however, if we are more interested in a high

POWERING INNOVATION
DISCOVER THE R24C2T25 –
THE NEXT GENERATION IN
12.83

DC/DC CONVERSION
mm

Seamlessly Integrate Cutting-Edge Efficiency


with Our 2W Isolated SMD Converter for
Advanced IGBT/SIC GATE DRIVERS mm
3.1 7.5
8m
m

recom-power.com/gate-drivers
11th- 13th JUNE | BOOTH 6-452

May & June 2024 35


PROJECT

A Simple
DDS Signal Generator
Direct Digital Synthesis in Its Purest Form

By Willem den Hollander (Switzerland)

Want to build your own signal generator?


Follow along for instructions and tips
about constructing a high-performance
yet simple signal generator using
an AD9851. Module modification,
theory of operation, and software are
all covered.

Figure 1:
Analog Devices offer a range of integrated The AD9851 module.
circuits containing complete DDS signal
generators. These ICs cannot operate by
themselves, but need a low-pass filter and a an adjustable DC voltage, thus produc- a digital-to-analog converter (DAC). The
controlling device for initialization and setting ing a square wave with an adjustable duty AD9851’s datasheet [2] provides more detailed
of the desired output frequency. At AliExpress cycle. The addition of a small microproces- information. Figure 1 shows the module with
[1], complete modules are offered carrying the sor, a rotary encoder and a display makes a the AD9851. To make it fit into the selected
AD chip together with the filter and some complete signal generator. enclosure, the LED was removed and a corner
other components for a very competitive of the module was cut off. The potentiome-
price. In the little signal generator described What’s Under the Hood ter for adjusting the comparator’s DC input
below, a module with the AD9851 is used. This Signal generation is accomplished by direct voltage was removed as well, as it was not
module can produce a sine wave signal with digital synthesis (DDS). It uses a numerically needed: That DC voltage will be generated
a frequency of between 1 Hz and 70 MHz. controlled oscillator (NCO) and a lookup by a DAC within the microcontroller used to
A comparator is present on the chip, which table (LUT) to produce a digital sine wave. control the module.
compares the sine wave output signal with The latter is converted into analog form with
The AD9851 can be controlled in either a
parallel or a serial mode. Since the serial mode
needs only four connections and the parallel
DATA W0 W1 W2 W3 W39
mode more than twice as many, we use the
serial mode for initialization and frequency
FQ_UD selection. The “serial load” signals, as they
are called in the datasheet, are shown in
Figure 2. The fourth signal resets the device
W_CLK
to initialize it. A microcontroller provides
these signals using the built-in SPI peripheral.
40 W_CLK Cycles
Since the frequency will be variable, a rotary
230695-010

Figure 2: Serial load signals. (Source: AD9851 datasheet [2]) encoder is used to allow the user to change it.

36 May & June 2024 www.elektormagazine.com


+5V
J1

1
VCC
2
D–
C1 C2 C3 3
D+
4

10
9
8
7
6
5
4
3
2
1
GND
10n 100n 10µ
POWER 1 14
VDD Vss USB
LED 2 13

VCC

GND
D0
D1
D2
D3
D4
D5
D6
D7
RA5 U2 RA0
3 12
ADJ RA4 RA1
4 11 U3
U1 RA3 RA2
AD9851 5 10 4
RC5 RC0 SDA
6 9 3
RC4 RC1 SCL
7 8 2

W_CLK
RC3 RC2 VCC

FU_UD

RESET

Qout1
Qout2
Zout1
Zout2
DATA
1

GND
VCC

GND
PIC18F04Q41
OLED 128x32
11
12
13
14
15
16
17
18
19
20
SW1

J3 J2
Encoder
Square Sine

230695-009

Figure 3: Schematic diagram of the DDS signal generator.

A small display is added to show informa- with a PICkit 4, PICkit 5, ICD 4, ICD 5, or is easier to set up than with the older type
tion on the currently selected frequency. One MPLAB Snap. Earlier versions of these tools PICs. The current frequency of the generated
should be aware of the fact that a DDS signal are not compatible with this PIC. The proces- signal is shown on a small 0.91″ OLED display,
generator does not produce pure sine wave sor was programmed before mounting on the which is controlled via an I2C bus with a clock
signals — the output signal contains multiple PCB. It is possible, however, to program the frequency of 400 kHz.
harmonics of the sampling frequency. processor on board by soldering temporary
wires to the processor pins and then desol- How to Change Settings
A Look at the Circuit Diagram der them after programming. The 5 V supply Pressing the rotary encoder’s knob moves
Figure 3 depicts the schematic diagram. voltage is provided via a USB connector. an underline cursor from left to right, circling
Because only a limited number of IOs is back to the left when the far right is reached.
required, a Microchip PIC18F04Q41 14-pin The PIC18F04Q41 belongs to a new series of Turning the encoder will increase or decrease
microcontroller is used. It controls the DDS PICs. In particular, the serial IO modules for the number underneath and to the left of
module with four outputs, reads the rotary SPI and I2C have been improved compared to the decoder. This provides an easy way to
encoder with three inputs, and drives the older devices. This is very useful in this appli- quickly cover the total range from 1 Hz to
display via the I2C bus, which needs another cation. The SPI module now has a buffered 70 MHz. Any change of the displayed number
two outputs. The DC output voltage is gener- output register, giving us the opportunity to will cause an output signal to the DDS module
ated on pin 11. produce the required forty-bit serial output to adjust the output frequency accordingly.
signal in a single continuous stream. For this
The last pins remaining are 1 and 14 for serial signal, a clock of 16 MHz is used, so that As mentioned, the DC voltage that goes to
power supply and 12 and 13 for program- a change of the generator’s output frequency the input of the comparator on the module is
ming. The PIC18F04Q41 can be programmed takes less than 3 µs. Also, the I2C module produced by a DAC inside the microcontroller.

Figure 4a: The front of the PCB, with the display. Figure 4b: The back of the PCB, without the Figure 4c: The back of the PCB with the DDS
DDS module. module installed.

May & June 2024 37


Component List

Modules
U1 = AD9851 module
U3 = 0.91” 128×32 OLED display

Microcontroller made pluggable. Here, we run into a space About the Author
U2 = PIC18F04Q41-I/SL problem: The enclosure is only 20 mm high. Willem den Hollander has been passion-
Using an ultra-low-profile socket connec- ate about electronics since the age of 12.
Capacitors tor and accompanying low-profile pins, the He has a Master’s degree in electronics
All capacitors are SMD, 0805 height could just be kept within this restric- engineering and worked for 37 years in
C1 = 10 nF tion. The microprocessor is only available in R&D in the field of consumer electronics.
C2 = 100 nF an SMD package. The three capacitors and His favorite subjects are power supplies,
C3 = 10 µF the USB connector are also SMDs, which digital circuits, programmable logic, and
made the layout very simple. microprocessors. Several of his projects
Miscellaneous have been published in Elektor.
SW1 = Rotary Encoder Firmware
J1 = Mini USB connector The firmware [3] has been written in assem-
J2, J3 = SMA connector, 90˚ bler and occupies only 13% of the proces-
Enclosure = Strapubox 1551RGY sor’s program memory. At first, the ports Questions or Comments?
Rotary Encoder Knob are set up and then two configurable logic Do you have technical questions
PCB cells (CLC’s) are set as flip-flops that detect or comments about this article?
any positive transient caused by turning the Feel free to contact the author at
rotary encoder. Hereafter, timer2 is configured [email protected] or the Elektor
to provide a 10 ms delay for debouncing the editorial team at [email protected].
This voltage can be changed by pressing the switch, and timer4 to set a delay of about
encoder’s switch for about two seconds until 100 ms. The latter is required after initializ-
the display shows a three-digit number. In this ing the OLED display. After setting up the
situation, the voltage may be adjusted in 256 DAC that produces the DC voltage for the
steps by turning the encoder until the square comparator, the I2C bus module is configured
wave’s duty cycle is as desired. Pressing the to communicate with the OLED display with
knob again for longer than two seconds makes a clock frequency of 400 kHz, and finally the
the display return to frequency display. The SPI module that controls the DDS module.
value of the selected DC voltage is stored in After this, the display, the DDS module, and
the PIC’s internal EEPROM. the interrupts are initialized.

Construction Everything is completely interrupt-driven.


The circuit uses only a few components. A The program section consists solely of
little printed circuit board was made so that NOPs. Here, the processor waits for inter-
everything could be put into a little enclo- rupts. The switch’s interrupt service routine
sure made by Strapubox, with dimensions moves the cursor to the right. If the switch is
50×50×20 mm3. Two SMA connectors serve pressed longer, the output value of the DAC
Related Products
as outputs. There would not have been suffi- is shown as described above. If the flip-flop
cient space for BNC connectors. As shown in of the second CLC changes state, the second
Figures 4a, 4b and 4c, the encoder’s connec- interrupt service routine will run. The CLC’s > OWON AG051 Arbitrary Waveform
tor pins have been bent 180˚ so that they can output status indicates whether the displayed Generator (5 MHz)
www.elektor.com/18874
be soldered to the PCB. This must be done frequency value has to be incremented or
carefully, since they break easily. decremented. After displaying the new value, > FNIRSI DPOX180H (2-in-1) 2-ch
the control bytes for the DDS module are Digital Phosphor Oscilloscope
One of the mounting screws used to attach calculated and transmitted, and the proces- (180 MHz) & Signal Generator
the PCB to the enclosure is covered by the sor starts waiting for the next interrupt. www.elektor.com/20640
DDS module. Therefore, the latter has been 230695-01

WEB LINKS
[1] AliExpress online store: https://aliexpress.com
[2] AD9851 Datasheet: https://analog.com/media/en/technical-documentation/data-sheets/ad9851.pdf
[3] Firmware download on this article’s webpage: https://elektormagazine.com/230695-01

38 May & June 2024 www.elektormagazine.com


They trust us,
do you?

UPDATED
STORE

We love electronics and projects, and we do


our utmost to fulfil the needs of our customers.
The Elektor Store: ‘Never Expensive, Always Surprising’
Rated 4.5 / 5 | 360 reviews

Check out more reviewsw.on tor.com/TP/en


our Trustpilot page: ww elek
Or make up your own mind by
w.elektor.com
visiting our Elektor Store, ww
May & June 2024 39
COMMUNICATIONS

Sparkplug
at a Glance

Source: Adobe Stock


A Specification for MQTT Data

By Tam Hanna (Hungary) In addition, MQTT only offered rudimentary authentication for a long
time, and managing the connected devices (beyond issuing a Last
The popular MQTT protocol is one Will message [2]) required developer involvement or the use of a
of the most straightforward ways second service. The lack of standardization also meant that this work
had to be done by each developer and, in the worst case, anew for
to connect distributed electronics, each project.
such as sensors, controllers, and
data storage devices. As long as the The new protocol, called Sparkplug, now forces the user data transmit-
ted via MQTT into a schema, which ultimately ensures an organized
transmitted messages follow the and manageable structure.
(lax) rules of the standard and the
broker can be addressed correctly, In this article, we will take a look at the basic concepts and also carry
out initial practical experiments with the technology, which is still at
the data exchange works. A new an early stage.
protocol called Sparkplug attempts
to formalize the user data with an
Please Also Read the Standard Document!
additional layer, which makes it For reasons of space alone, this technical article cannot provide
easier to offer auxiliary services and a complete description of Sparkplug. However, the specification
create a diverse ecosystem, among of the protocol in version 3.0 is well written. It is therefore advis-
able to have the 140-page PDF document at hand [3]. This article
other benefits. Here is a first look – repeatedly contains cross-references to sections of the document
including some practical examples, where background information can be found.
as always.
First Overview
Originally created by Cirrus Link, the Sparkplug specification [3] has
The MQTT protocol [1], which is based on TCP/IP, has become a kind been managed by the Eclipse Foundation for some time now, which
of standard on the Internet of Things; it is lightweight, flexible, and has been trying to position itself as a “jack of all trades” in the IoT
easy to understand. In addition, MQTT can also deal very well with sector for quite a while.
network participants that are only temporarily active or accessible.
However, MQTT only ensures reliable communication — the organi- The second version of the standard introduced the use of Google
zation of the user data is up to the developer. Protocol Buffers [4] as a container data format. Sparkplug version 3.0,

40 May & June 2024 www.elektormagazine.com


which is exclusively used in this article, focused on making the param- implementations that support Sparkplug networks through “Value-
eters defined in the specification clearer. Added Intelligence” — what they require exactly is listed in the speci-
fication document in section 12.66.
To understand a Sparkplug system, let’s take a look at the overview
diagram shown in Figure 1, which illustrates an IoT network. It should be noted that the majority of the infrastructure components
shown in Figure 1 are not absolutely necessary for an MQTT network
Just like in a classic MQTT network, we see an MQTT server in the center. — the “basic” variant only consists of an MQTT server and a Sparkplug
It should be noted that this is — in general — an ordinary MQTT server. Edge Node, which can be implemented in the form of an MQTT client.
According to the specification, MQTT implementations designated as
Sparkplug-Compliant MQTT Server in the basic version only have to The diagram contains familiar elements — Edge Nodes are the sensors
fulfill the following four criteria, which are not particularly complicated: or remote stations that feed the information to be processed into the
network in the form of MQTT messages structured according to the
A Sparkplug conformant MQTT Server MUST support Sparkplug rules.
. . . publish and subscribe on QoS 0
. . . publish and subscribe on QoS 1 MQTT clients that consume these incoming messages and use them
. . . all aspects of Will Messages including use of the retain flag and to fulfill a business purpose are referred to as Host Applications. The
QoS 1 Primary Host Application is relevant insofar as it enters into a particu-
. . . all aspects of the retain flag larly close relationship with individual Edge Nodes. The standard refers
to this as an application whose online or offline status influences the
Sparkplug-Aware MQTT Servers, on the other hand, are advanced behavior of the Edge Node.

Figure 1: These components work together to create a Sparkplug system. (Source: [3])

May & June 2024 41


NDEATH messages are responsible for the disappearance of a node
and are sent by the MQTT server when the node disappears. Registra-
tion takes place as part of the NBIRTH message. The DDEATH message
responsible for a device death is sent by the node instead — it is
important to note that sending this message is solely the responsi-
bility of the node.

The NDATA and DDATA messages allow measured values to be trans-


mitted and commands to be sent in order to change the status of an
Figure 2: There are only nine types of Sparkplug messages. (Source: [3]) attribute held in the end device to a new value.

The DDATA message is relevant because it introduces the concept of


The next important element is the message structure, described in detail Report by Exception — in the specification, the abbreviation RBE is
in section 4.1. When sending messages, MQTT clients must adhere often used for this procedure. In the world of Sparkplug, this means
to the following structure when assembling the topic infrastructure: that state changes should only be sent to the host if an “exception” —
a change that deserves attention — has occurred.
namespace/group_id/message_type/edge_node_id/[device_id]
The procedure normally used — referred to in the specification as
namespace is used to “encode” Sparkplug-compatible channels, and Time-Based Reporting — is also permitted, but is explicitly described
must always be spBv1.0. group_id describes the structure — analo- as undesirable:
gous to the Tag used by various cloud providers, it is a way of further
specifying the location of the individual nodes. “Again, time-based reporting can be used instead of RBE, but is discour-
aged and typically unnecessary.”
The message_type is more important. At the time this article went
to press, the Eclipse Foundation only specified nine of these, which Payload: Google Protocol Buffers
are listed in Figure 2. Anyone who has dealt with low-level programming will be familiar with
the problems associated with serializing data structures. With Proto-
The edge_node_id/[device_id] attributes describe which end device col Buffers, Google offers a standardization — conceptually based on
and which sub-end device was responsible for actually sending the JSON and co. — that facilitates the creation of “platform-independent
message. serializable containers.”

It should be noted that the MQTT standard allows the creation of “filters” The Sparkplug specification relies on Protocol Buffers as a payload,
with various special characters — it is therefore possible, for example, probably also due to their immensely broad support, for which there
to register all messages belonging to a certain type as relevant. Further are now suitable libraries in almost every programming language. The
information on this can be found in [5], for example. Protocol Buffers website is well worth reading for developers seriously
interested in Sparkplug [4].
Analysis of the Message Structure
The second factor when working with the Sparkplug specification is It should be noted that Protocol Buffers represent a binary protocol. In
the role of the individual messages, as outlined in Figure 2. Since the practice, however, as well as in the specification document, you often
specification describes the data flow by means of (confusing) timing see JSON annotations structured according to the following scheme:
diagrams, we will try to group important message types by role and
payload. However, if you want to look at the diagrams yourself, section 5 {
of the specification is recommended. "timestamp": <timestamp>,
"metrics": [{
Let’s start with the DBIRTH and NBIRTH messages. As suggested by "name": <metric_name>,
“birth” in the names, these are messages that indicate new parts of "alias": <alias>,
the Sparkplug network becoming available. NBIRTH deals with the "timestamp": <timestamp>,
appearance of a new node, while DBIRTH indicates the appearance "dataType": <datatype>,
of a new device. "value": <value>
}],
It is important that the payload of the messages must deliver a struc- "seq": <sequence_number>
ture that enables the receiver to generate a complete digital image }
(often referred to as a Digital Twin) of everything that creeps and flies
in the newly added endpoint. It follows from the same logic that both This is a format rehydrated from the binary data, which has nothing
NDEATH and DDEATH are responsible for the disappearance of endpoints. in common with the information physically sent over the airwaves. In

42 May & June 2024 www.elektormagazine.com


principle, however, the snippet shown here shows us everything that mosquitto.conf eclipse-mosquitto
can be expected in a Sparkplug message.
After setting up the MQTT broker, the next step is to visit the website
[8], where we download Ignition. The software is delivered with an
The timestamp must be given in UTC and is a 64-bit integer that installation wizard, which is activated as follows:
describes the elapsed milliseconds since the Unix epoch. The metrics
field, which is “single-valued” here, then contains the actual user data tamhan@TAMHAN18:~/Downloads$ chmod +x
to be transmitted in the message. ignition-8.1.25-linux-64-installer.run
tamhan@TAMHAN18:~/Downloads$
Finally, there is a sequence number, which — analogous to various ./ignition-8.1.25-linux-64-installer.run
other protocols — helps to ensure the integrity of the data transmission.
It should be noted that this command does not always start the
A complete discussion of the data fields transmitted in the various Mosquitto container, while the system later integrates itself into
messages would go beyond the scope of this article and would be of the systemd start process. If strange behavior occurs because the
little benefit — if you want to carry out a “low-level implementation” Mosquitto server was only started after the actual platform container,
by hand, section 6 of the specification is recommended. In practice, this can be rectified with the following command sequence:
libraries are usually used to take care of the implementation.
tamhan@TAMHAN18:/usr/local/bin/ignition$
Let’s Get Practical! ./ignition.sh stop
In the interest of keeping the specification “real”, the official specifi- tamhan@TAMHAN18:/usr/local/bin/ignition$
cation document mentions the fact that a Raspberry Pi using an I/O ./ignition.sh start
board is more or less “officially” part of the specification and serves as
an example implementation of a Sparkplug Edge Node. An interesting During the installation, the superuser password is requested in order to
question in this context is what we want to use as the data entry point carry out the “integration”. In the following steps, the author decided to
or implementation of the host application (on a PC). use the installation directory /usr/local/bin/ignition — this is important
to know because the script required later for uninstallation is hidden
It should be noted that the Eclipse Foundation offers a list of compati- there.
ble implementations [6]. In order to have a product listed there, it must
pass a compatibility test — but this is beyond the scope of this article. In the module selection area for Ignition, you should first select the
Eclipse Tahu [7] also provides an almost turnkey wrapper library that Custom option in order to mark all options in the module list window
makes it easier to deploy the packages. that appears afterwards. It is explicitly important to select the Web
Browser and Web Dev packages, among others.
In the following steps, we want to use Ignition from Inductive Automa-
tion — it is one of the few implementations of a Sparkplug host. The installation wizard will offer to start the platform once the work
is complete. This normally works, and is confirmed by the output of a
A message broker is required in the background — the author works success message that is structured according to the following scheme:
with Ubuntu 20.04 LTS, which is why we will start Mosquitto in a
Docker container. INFO [IgnitionInstaller ]
[2023/03/12 22:15:50]:
A configuration file is required here — Mosquitto safeguarded the Gateway Address: http://localhost:8088
configuration in version 2.0.0, which is why connecting anonymous
clients is not permitted without the intervention shown here: In some cases, the system crashes. In this case, go to the installation
directory according to the following scheme to force a manual restart:
tamhan@TAMHAN18:~$ cat mosquitto.conf
allow_anonymous true tamhan@TAMHAN18:/usr/local/bin/ignition$ ./ignition.sh
listener 1883 start
persistence true
persistence_location /mosquitto/data/ The next step is to visit the Ignition Gateway URL and decide to install
log_dest file /mosquitto/log/mosquitto.log the Maker Edition. This is a slightly limited version of the product, which
is free of charge for non-commercial users.
The actual start then takes place as follows:
After the successful start (the Ignition Gateway is starting
tamhan@TAMHAN18:~$ docker run -it message may appear on the screen for some time) we select the
-p 1883:1883 -p 9001:9001 Enable QuickStart option to put the platform into a “quick-start ready”
-v $(pwd)/mosquitto.conf:/mosquitto/config/ state.

May & June 2024 43


Figure 3: The Mosquitto instance was automatically detected.

The system is fully modular internally. For this reason, in the first step, tamhan@TAMHAN18:~/designerlauncher/app$
we opt for the Config → Systems → Modules option to activate module ./designerlauncher.sh
management. We then see a group of ready-to-use archives [9] with
modules from third-party providers — to use the Sparkplug platform, The next step is for the newly launched Designer application to estab-
we need the MQTT Transmission and MQTT Engine elements, which lish contact. To do this, we first choose the Add Designer option, then
we install one by one using the web interface. click the Localhost option to add a new “platform entry.” The Open
Designer button then allows us to edit the information.
In the next step, we switch to the configuration option Config →
Mqttengine → MQTT Engine Settings, where we are informed — as In the next step, we decide on the SampleQuickStart option and click
shown in Figure 3 — that the Mosquitto instance living in the Docker on Open to load the start example. Clicking on the View → Panels →
container has been successfully found. OPC Browser option then opens another panel in which various OPC
data sources are available. Expand the Expand Devices section there
There is also a further setting under Config → Mqtttransmission → to show the [Sample_Device] device. A drag and drop operation is
MQTT Transmission Settings, the correctness of which must also be then required, as shown in Figure 4.
checked. In the interests of keeping the server platform compact, the
system has a modular design here, too. The Get Designer button allows Next, we must ensure that we close the Designer and use the Save
you to download a separate component called Designer, which allows and Close option to save and “upload” all changes made in the local
you to parameterize the settings existing in the platform. Download the application. We can then return to the web interface, where we can
archive in the first step and unpack it — the actual start of the appli- set a new configuration using the MQTT TRANSMISSION Settings
cation then occurs as with any other command line utility: → Transmitters → Create new Settings option. It is then important
that the text default is entered in the Tag Provider field — saving the
changes updates the system status.

In the next step, we open the workstation’s console, where we activate


the test subscriber contained in the Mosquitto package and connect
it to the spBv1.0/# channel. The only important thing to know here
is that the # symbol serves as the wildcard symbol, commonly repre-
sented by *:

tamhan@TAMHAN18:~$ mosquitto_sub
-h localhost -t spBv1.0/#

The reward for our efforts is the appearance of binary files, as shown
in Figure 5.

Setting Up the Raspberry Pi


The next step requires a process computer — since the specification
refers to the Raspberry Pi in several places, we want to use it in the
following steps. The author uses a Raspberry Pi 4 with a fairly up-to-
date version of the operating system.

The following command sequence is required for the actual “arming”


Figure 4: Drag-and-drop into the “default” section is helpful. of the components:

44 May & June 2024 www.elektormagazine.com


pi@raspberrypi:~/sparkspace $ git clone pi@raspberrypi:~/sparkspace/tahu/java/
https://github.com/eclipse/tahu.git examples/raspberry_pi $ ls
Cloning into ˈtahuˈ... dependency-reduced-pom.xml pom.xml
. . . src target THIRD-PARTY.txt
pi@raspberrypi:~/sparkspace pi@raspberrypi:~/sparkspace/tahu/java/
$ cd tahu/java/examples/raspberry_pi examples/raspberry_pi $ mvn clean install
pi@raspberrypi:~/sparkspace/tahu/java/
examples/raspberry_pi $ mvn clean install If you have already installed a Java version on your Raspberry Pi, the
resulting program can be started according to the following scheme:
The sample code provided by the Eclipse Foundation is not functional
on its own, but must be extended with the necessary dependencies pi@raspberrypi:~/sparkspace/tahu/java/
and libraries using the Maven package management in the first step. examples/raspberry_pi/target $ java
-jar example_raspberry_pi-1.0.1.jar
In the next step, the SparkplugRaspberryPiExample.java file is of interest,
which can be opened in an editor according to the following scheme: In most cases, an error occurs at this point, which refers to the libdio
library — this is not critical for us though, as we will turn to the struc-
pi@raspberrypi:~/sparkspace/tahu/java/ ture of the program in the next step and want to take a closer look at
examples/raspberry_pi/src/main/java/ some particularly interesting aspects.
org/eclipse/tahu $ pico SparkplugRaspberryPiExample.java
First, we will look at the calculation of the sequence number, which is
The sample code assumes that an external MQTT broker will be respon- done according to the following scheme:
sible for the actual processing of the information. In the configuration
of the author’s workstations, its IP address is 192.168.1.68, which is why // Used to get the sequence number
an adaptation is required according to the following scheme: private long getNextSeqNum() {
long retSeq = seq;
public class SparkplugRaspberryPiExample if (seq == 256) {
implements MqttCallbackExtended { seq = 0;
private static final String } else {
DFLT_MQTT_SERVER_HOST_NAME = "192.168.1.68"; seq++;
}
After that, Maven needs to be called again to download the missing return retSeq;
elements: }

Figure 5: The strange characters


indicate: This is binary data.

May & June 2024 45


Also interesting is the way in which the information supplied by the SparkplugBPayload inboundPayload =
I/O board (not used here) is packaged in a format that the host can new SparkplugBPayloadDecoder().
understand. The code required for this looks like this: buildFromByteArray(message.getPayload());

SparkplugBPayload payload = for (Metric metric : inboundPayload.getMetrics()) {


new SparkplugBPayloadBuilder(getNextSeqNum()) System.out.println("Metric: " +
.setTimestamp(new Date()) metric.getName() + " :: " +
// Create an "Inputs" folder of process variables metric.getValue());
.addMetric(new MetricBuilder
(PibrellaInputPins.A.getPin().getDescription(), if (metric.getName().equals
MetricDataType.Boolean, ("Node Control/Next Server")) {
pibrella.getInput(PibrellaInputPins.A) System.out.println("Received a Next Server command.");
.isHigh()).createMetric()) } else if (metric.getName().
.addMetric(new MetricBuilder equals("Node Control/Rebirth")) {
(PibrellaInputPins.B.getPin().getDescription(), publishBirth();
MetricDataType.Boolean, } else if (metric.getName().
pibrella.getInput(PibrellaInputPins.B). equals("Node Control/Reboot")) {
isHigh()).createMetric()) System.out.println("Received a Reboot command.");
. . . } else if (metric.getName().
.createPayload(); equals("Node Control/Scan Rate ms")) {
scanRateMs = (Integer) metric.getValue();
// Publish the Device BIRTH Certificate now if (scanRateMs < 100) {
executor.execute( // Limit Scan Rate to a minimum of 100ms
new Publisher(NAMESPACE + "/" + scanRateMs = 100;
groupId + "/DBIRTH/" + }
edgeNode + "/" + deviceId, payload));
For the following steps, however, we want to use a somewhat simpler
Messages are then generally received in the same way using the example, which is available under /home/pi/sparkspace/tahu/java/
Target API: examples/simple/src/main/java/org/eclipse/tahu.

public void messageArrived In the first step, open the Java file and adjust two of the dozens of
(String topic, MqttMessage message) throws Exception { member variables according to the following scheme:
System.out.println("Message Arrived on topic " + topic);
public class SparkplugExample
// Initialize the outbound payload if required. implements MqttCallbackExtended {
SparkplugBPayloadBuilder outboundPayloadBuilder =
new SparkplugBPayloadBuilder // HW/SW versions
(getNextSeqNum()).setTimestamp(new Date()); . . .
private String serverUrl =
String[] splitTopic = topic.split("/"); "tcp://192.168.1.68:1883";
if (splitTopic[0].equals(NAMESPACE) && private long PUBLISH_PERIOD = 1000;
splitTopic[1].equals(groupId) && // Publish period in milliseconds
splitTopic[2].equals("NCMD") &&
splitTopic[3].equals(edgeNode)) { As above, the value stored in the serverUrl variable must, of course, be
adapted to the situation existing in your network. Reducing PUBLISH_
SparkplugBPayload inboundPayload = PERIOD then ensures that the main application is supplied with data
new SparkplugBPayloadDecoder(). more quickly.
buildFromByteArray(message.getPayload());
... After saving the modified file, it is necessary to return to the project
root directory and run a compilation again using the package manage-
In this context, it is also interesting to note that the standard is capable ment tool, Maven:
of processing extensive payloads. A good example of this is the follow-
ing for loop, which enumerates the various command types supplied pi@raspberrypi:~/sparkspace/tahu/java/
on the Raspberry Pi: examples/simple $ mvn clean install

46 May & June 2024 www.elektormagazine.com


Changing to the root folder is primarily necessary because the pom.
xml file is located there — it has the job of controlling the compilation
of the project as a whole.

The reward for our efforts is the creation of a .jar file, which can be
found in the ~/sparkspace/tahu/java/examples/simple/target direc-
tory. Activation then takes place according to the following scheme:

pi@raspberrypi:~/sparkspace/tahu/java/
examples/simple/target $ java
-jar example_simple-1.0.1.jar

To harvest the results, you must switch back to the Designer applica-
tion, where the result is displayed as shown in Figure 6.

For the Forgetful: Resetting the Gateway


Let’s be honest: It’s easy to forget the gateway password. Fortunately,
solving the problem is not difficult. Go to the installation directory and
execute the following three commands: Figure 6: Make sure you set the combo box correctly.

tamhan@TAMHAN18:/usr/local/bin/ignition$
./gwcmd.sh --passwd the case of many other systems, however, the true value of such a
Password has been reset. Gateway needs to be restarted. standard only becomes apparent when it is widely adopted. There is
tamhan@TAMHAN18:/usr/local/bin/ no way around the “network effect law.”
ignition$ ./ignition.sh stop Translated by Jörg Starkmuth — 230038-01
Stopping Ignition-Gateway...
tamhan@TAMHAN18:/usr/local/bin/
ignition$ ./ignition.sh start
Starting Ignition-Gateway with systemd... Questions or Comments?
Waiting for Ignition-Gateway... Do you have questions or comments about this article? Email
running: PID:382296 the author at [email protected], or contact Elektor at
[email protected].
After restarting the gateway, you can log in via the URL — the gateway
then presents the first user with a window in which a new username
and the corresponding password for the administrator account can About the Author
be specified. As an engineer, Tam Hanna has been working with electronics,
computers and software for more than 20 years. He is a self-employed
A Solid System designer, book author and journalist (@tam.hanna on Instagram). In
With Sparkplug, the Eclipse Foundation is entering the race with a his spare time, Tam designs and produces 3D-printed solutions and,
solid ecosystem that seems well suited to “taming” the uncontrolled amongst other things, has a passion to trade and enjoy high-end
proliferation that can undoubtedly be found in the MQTT area. As in cigars.

WEB LINKS
[1] MQTT basics: https://hivemq.com/mqtt
[2] MQTT: Last Will: https://hivemq.com/blog/mqtt-essentials-part-9-last-will-and-testament
[3] Standard document: https://sparkplug.eclipse.org/specification/version/3.0/documents/sparkplug-specification-3.0.0.pdf
[4] Google Protocol Buffers: https://developers.google.com/protocol-buffers
[5] MQTT: Topics: https://hivemq.com/blog/mqtt-essentials-part-5-mqtt-topics-best-practices
[6] Sparkplug software: https://sparkplug.eclipse.org/compatibility/compatible-software
[7] Eclipse Tahu: https://github.com/eclipse/tahu
[8] Inductive Automation Ignition download: https://inductiveautomation.com/downloads
[9] Third-party modules: https://inductiveautomation.com/downloads/third-party-modules/8.0.17

May & June 2024 47


COMPONENTS

The CRTC
Peculiar Parts, the Series

By David Ashton (Australia)

Back in the ’80s, getting text on


screens was a Herculean task, far from
today’s plug-and-play ease. Spare
a thought for those wrestling with
cathode ray tube controllers (CRTCs),
the unsung heroes of early computing.

Figure 1: Intel 8275 CRTC. (Source: Jameco Electronics)

These days, displaying text or even graphics or movies on your


microcontroller is… well, maybe not child’s play, but not too difficult.
You can use one of the ubiquitous LCD text or graphic displays, or
if your microcontroller is a bit more upmarket like a Raspberry Pi,
just plug in an HDMI monitor. There are software libraries to make
displaying your desired content pretty easy.

Spare a thought, then, for the microprocessor designers of the 80s.


LCD screens were still primitive and only really suited for calcu-
lators. You were limited to LEDs or maybe a few seven-segment
displays, multiplexed so as not to use too many precious I/O lines.
CRT monitors were available, but how to generate all those video
signals with their precise timings and levels?

Enter the CRTC, or cathode ray tube controller. (We used to


pronounce it “Krrrt-kuh.”) These were peripheral chips, usually with
40 pins (Figure 1), offered by the main microprocessor manufac-
turers, to make outputting text to CRT monitors a bit easier. CRT
monitors need pixel data to be written to the screen one line at a
time, usually using up to 600 lines. For a TV signal, the line would
have varying levels of brightness, but, for text display, the levels
would be either high (display a dot) or off (no dot). In this fashion,
patterns of dots could be displayed to make up characters and
symbols readable by us humans — see Figure 2.

These chips were used with a character generator (CG) ROM. These
had usually seven character address lines, which were driven by
Figure 2: Building up text from lines of pixels — here using a 5×7 character the ASCII code for the character to be generated, and, for each
matrix. (Source: Intel) ASCII code, they output the pixel pattern for that character, stored

48 May & June 2024 www.elektormagazine.com


Figure 3: Typical CRTC system diagram. (Source: Intel)

as rows and columns. Common character formats were 5×7 dots I worked on terminal systems that used CRTCs, but never did any
high, and 7×9 for better resolution. The CRTC would select which programming for them. Although they made a system designer’s
line of a character it needed by means of more address lines (called life easier, there was still a lot of work to be done setting them up
Line Count). for the desired character and screen format, and programming
the DMA access.
Building Characters, Line by Line
The CRTC would address the CG ROM with the code for the first So, the next time you’re struggling to get a text or graphics LCD
character, line address 1, to get the top row of pixels for that charac- working, spare a thought for the designers of yore who had to work
ter. It would then change the address to that of the second charac- with CRTCs!
ter, and get the top row of pixels for that character. This would 240058-01
continue until the end of that line. Then the CRTC would change
the line count address to 2, and repeat the process for the second
line of row pixels. All the time, the CG pixels were being sent to
the monitor in serial form. In this way, a complete line of charac-
ters would be output to the monitor. Then a new row of characters
would be loaded into the CRTC memory, and it would repeat the
whole process for another line of characters. Up to 80 characters
× 64 rows could be programmed, and the CRTC also generated the
horizontal and vertical sync signals. About the Author
David Ashton was born in London, grew up in Rhodesia (now Zimba-
Most CRTCs only had enough memory to hold two lines of character bwe), lived and worked in Zimbabwe, and now lives in Australia.
codes. One would be processed while the other was loaded. Usually, He has been interested in electronics since he was “knee-high to
DMA (direct memory access) was used — in this way, the load on a grasshopper.” Rhodesia was not the center of the electronics
the microprocessor was much-reduced (Figure 3). universe, so adapting, substituting, and scrounging components
were skills he acquired early (and still prides himself on). He has run
They had ancillary functions such as light pen detection — a pen an electronics lab, but has worked mainly in telecommunications.
or (for games) or a gun with a light-sensitive resistor or transistor
could be used to load a register with the screen coordinates where
the pen was pointed. A cursor position could be programmed, and Questions or Comments?
a whole character block would be lit to show the cursor. The CRTCs If you have technical questions or comments about this
could also have attributes programmed so that a character could article, feel free to contact the Elektor editorial team by
be underlined or shown in reverse, bright, or blinking. email at [email protected].

May & June 2024 49


PROJECT

Radar-Controlled
Lighting
Automatic Stairway Light With
Human Presence Detection

Source: Adobe stock


lab • Ele
tor k
ek

to
El

r lab
TES
By Gino de Cock (Belgium)
TED

Ele k
rl
PIR-controlled lights and presence detectors are

to

ab
ab rl
• E l e kt o
found everywhere. They work quite well, but only for
warm moving targets. Radar-based human presence
detectors offer better precision and can detect speed of the target. This is known as the
stationary human bodies. This makes them suitable Doppler effect. We all know it from the sound
of cars and trains passing by. The pitch of
for automatic lighting control in offices and small, the sound is higher when the vehicle comes
dark rooms. In this article, we use such a radar to towards you and lower when it moves away.
turn a dark staircase’s lights on and off.
Measuring the distance of a target with a
CW radar can be done by adding frequency
modulation (FM). When the signal frequency
is swept up (or down) linearly, the received
You surely know those automatic lights a.k.a. 24 GHz amateur, amateur satellite, reflected signal will not have the same instan-
controlled by PIR sensors. They switch on radio location, and Earth-exploration satellite taneous frequency as the transmitted signal
when you pass in front of them and switch service band far from the busy 2.4 GHz Wi-Fi because it is delayed. The two frequencies
off automatically when movement is no band. Developed by Hi-Link Electronics, the are slightly different, and this difference is
longer detected. Practical as they may be, module provides human body detection proportional to the distance between the
they do have a mind of their own, making for home automation systems. Its working transmitter and the target. However, since
them behave a bit quirkily sometimes. With principle is based on frequency-modulated there is also the Doppler effect, this method
the introduction of low-cost radar-based continuous wave (FMCW) radar to detect only works accurately for static or slow-mov-
human-presence detectors, it has become both moving and stationary human bodies. ing objects.
possible to solve some of the issues that a
PIR sensor has. Radar detectors provide FMCW Radar Theory in a All the complexity from the above explanation
real presence detection even when you’re Nutshell is reduced inside the HLK-LD2410 module to
not moving, keeping the light on when you’re The radar is based on two working princi- a single digital output indicating the detected
reading on the toilet. It’s radar, so it’s immune ples. First, it uses the Doppler effect to detect target state. The output is high when a person
to false positive detections due to changing objects. A continuous wave (CW) signal is is detected, moving or not. The application
light conditions, a bee, moving hot air, etc. transmitted, then reflected by conducting using the radar module can therefore remain
materials such as metal or water, and thus simple, as it only has to react to a binary state.
The HLK-LD2410 Radar Module also by human bodies. When the reflecting
The HLK-LD2410 sensor [1] is such a object (the target) is moving, the wavelength The Circuit
high-sensitivity human-presence sensing of the reflected signal (and therefore its The application described in this article is
module. It works in the 1.2 cm wavelength frequency) changes proportionally to the an automatic light for a staircase (Figure 1).

50 May & June 2024 www.elektormagazine.com


A radar-based human-presence detec- of MOD2 goes high and switches on T2,
tor switches the light on when a person is which, in turn switches on the load. Pretty
detected, and off otherwise. Furthermore, the straightforward, isn’t it?
system must only work when the ambient
light intensity is low (i.e. darkness detec- Disco Lights
tion). The schematic of the circuit is shown There is one thing, though, which is that when
in Figure 2. the light is switched on, the LDR no longer
sees darkness. The voltage on the gate of IC1
A light-dependent resistor (LDR, R2) is drops and IC1 switches off. This powers down
used to detect darkness. When it is dark, the rest of the circuit and the light switches off.
the resistance of R2 is high, much higher Now the LDR sees darkness and it switches
than the value of R1 + P1, so the voltage on on IC1, etc. The system starts to oscillate.
IC1’s gate is high. This turns on IC1, resulting Figure 1: The author used the circuit described in
in P-channel MOSFET T1’s gate being pulled To avoid this disco lighting effect, R4 and IC2 this article to provide safe lighting for a staircase.
low. T1 starts to conduct and switches on have been added. IC2 has the same function Under no circumstances may the light switch off
MOD1, a low-cost DC-DC converter module. as IC1, except that it is controlled by the output when someone is on the stairs. The LED strip is
mounted under the stair railing and illuminates
Now, MOD2, the radar module, switches on of the radar module instead of by the LDR. IC1 the steps. The sensor is located at the top of the
too, and the detection of human presence and IC2 have open-collector outputs and can staircase, so all of the steps are within the radar’s
is activated. The circuit is thus armed. This therefore be connected in parallel to drive T1 range.
situation is indicated by LED1. in a wired-OR configuration.

In the absence of humans, the output of As soon as a person is detected, IC2 is


MOD2 is low, N-channel MOSFET T2 blocks, switched on. This will keep the circuit powered the human presence has disappeared. This
and the load (an LED string) is not powered. in the same way as IC1 did, even when IC1 assures that the circuit has two stable states.
When a human body is detected, the output switches off. The light will switch off only when
Power Supply
The circuit is intended to drive a basic LED
string with a DC voltage up to 24 V. The supply
voltage is to be connected to pins 3 (+) and
4 (−) of connector K1. The load connects to
pins 2 (+) and 1 (−).
K2
1 1 2 3 4 5
2 JP1 TX RX OUT GND VCC

The radar module requires 5 VDC. Therefore,


3
Serial 4
5 MOD1, a cheap MP1584 DC-DC converter
6
module, is used to lower the LED string
MOD2 LD2410
supply to a suitable value for the radar module.
VCC MP1584-based DC-DC converter modules can
be found online in many variations, adjustable
R3 R4 or with a fixed output voltage. Either can be
P1
used, even when the output voltage is not 5 V,
2k2

4k7

47k
S
T1 1
K1
as it is enough to change a resistor value to
R1 G
IRF9540
T2 D
2 obtain a 5 V output. Use the following equation
to calculate the resistor value:
3
1k

IC1 IC2
4
D 1 8 G
IN+ OUT+
2x 2 7 R5
TLP431LP IN+ MOD1 OUT+ IRF540 S
R2
MP1584
1k

3 6
IN– OUT– LED1
4 5
IN– OUT–
1k...75k
RED

Here, RA is the resistor between pin 4 of the


230320-011

MP1584 IC and Vout; RB is the resistor between


Figure 2: The schematic. The use of two low-cost modules makes the design pin 4 and GND. On the module used for our
simple and economical. prototype, RB had a value of 8.2 kΩ. Since
the module was configured for a 12 V output,

May & June 2024 51


Figure 4: Two versions of HLK-LD2410-based human presence
detectors. Both can be used with our PCB design.

Figure 3: The prototype built and tested at Elektor


Labs fits in a low-cost plastic enclosure.

RA had a value of 115 kΩ. To lower the output at least two different shapes (Figure 4): a Configuring the Radar
to 5 V, R A must have a value of 43 kΩ. On 16×22 mm board with a large 5-way 0.1″-pitch The HLK-LD2410 module works out of the box,
our prototype, this could be arranged for by pin header and as a 7×39 mm long and but it can be configured over a serial port with
soldering a 68 kΩ resistor in parallel to RA. narrow board with a small, 0.05″-pitch connec- a Windows program named LD2410 Tool [2].
Another way is to replace RA with a 39 kΩ tor. Even though either type can be used, their This explains the presence of connector K2,
resistor in series with a 3.9 kΩ resistor (when connectors are not wired the same way. The a serial port wired up for a 3.3 V FTDI-com-
RB = 8.2 kΩ). first type’s signals are ordered TX, RX, OUT, patible USB-to-serial cable.
GND, and VCC, while the second has OUT,
PCB TX, RX, GND, and VCC. The PCB is wired for The radar module must, of course, be powered
At the Elektor lab, we designed a small printed the first type, but has room for the second before you can configure it, and there are two
circuit board (PCB) for the project with test type. The long and narrow module we ordered ways to do this: from the USB-to-serial cable
points for checking some vital signals. The came with an adapter cable that can easily be (JP1 closed) or from the circuit’s power supply
board fits in a cheap, plastic (ABS) 1591XXA connected to the PCB. Therefore, both types (JP1 open). In the second case, ensure that the
enclosure from Hammond (Figure 3). The can be used without too much fiddling. LDR sees darkness; otherwise the circuit will
radar features good shell penetration and does not turn on. Use P1 to adjust the light intensity
not require holes in front of it. This allows for a Power connector K1 is intended to be mounted (the level of darkness) that turns on the circuit.
more aesthetic enclosure. Although the sensi- “looking down,” meaning that the power supply
tivity is focused in front of the antenna, if you and light wires run down over the PCB to the With the radar module powered, you can
want to avoid detection from the back, shield opposite, short side. The two holes on that side configure it. First, connect to the module. The
the rear with a piece of metal (film). can be used for strain relief with e.g. a cable tool has two main modes. To align the radar,
tie or so (see Figure 3), but if you want to do it’s best to enable Engineering Mode and click
The HLK-LD2410 radar module comes in things another way, feel free to. Start (Figure 5). This then shows live sensing
in two graphs. On the left, the moving target
and on the right, the motionless target. The
detection aperture is divided into eight gates
of 75 cm each. The sensitivity of each gate
can be set from 0 to 100, where 100 is the
least sensitive (meaning “disable this gate for
detection”). If the blue or red line reaches or
crosses the green line, the output pin switches
to a high level. When you’re satisfied with the
chosen sensitivity levels, click Config to save
the settings to the sensor persistently.

That’s it, your human presence detector is


ready for use (Figure 6). Another idea for an
application would be a red light / green light
motion detector ( just like in the popular TV
series Squid Game), where a person must
be in a certain location but is not allowed to
move. Enjoy!
Figure 5: Use LD2410 Tool to configure the radar. 230320-01

52 May & June 2024 www.elektormagazine.com


Figure 6: The prototype
built by the author.

About the Author


During his electronics studies and in the
years that followed, Gino de Cock honed
his skills by repairing televisions. Today,
he finds himself immersed in the dynamic
world of the broadcast industry. But,
whenever an intriguing challenge arises,
he dons his metaphorical “electronics hat”
once more.

Gino de Cock says: “I wouldn’t be where


I am today without the guidance of the
incredible Benjamin Van Osselaer. He
wasn’t just a television master; he was
my mentor, and I take this opportunity to Component List
express my deepest gratitude for his invalu-
able teachings and inspiration.” Resistors (THT, 0.25 W)
R1, R5 = 1 kΩ
R2 = LDR
R3 = 2.2 kΩ
Questions or Comments? R4 = 4.7 kΩ
Do you have technical questions or P1 = 47 kΩ trim pot
comments about his article? Email the
author at [email protected] or contact Semiconductors
Elektor at [email protected]. IC1, IC2 = TL431, TO92
LED1 = LED 3 mm, red
T1 = IRF9540
T2 = IRF540

Miscellaneous
JP1 = 2-way pinheader, 2.54 mm pitch + jumper
K1 = 4-way screw terminal, 5 mm pitch
K2 = 6-way pinheader, 2.54 mm pitch
MOD1 = MP1584 DC-DC converter
Related Products MOD2 = HLK-LD2410 radar module + 5-way pin socket, 2.54 mm pitch
Enclosure Hammond 1591 XXA
> SunFounder Kepler Kit
(Ultimate Starter Kit for Raspberry
Pi Pico W)
www.elektor.com/20730 WEB LINKS
> Seeed Studio Grove Ultrasonic [1] HLK-LD2410 human-presence detector: https://hlktech.net/index.php?id=988
Distance Sensor [2] LD2410 configuration tool:
www.elektor.com/20027 https://h.hlktech.com/Mobile/download/fdetail/204.html

May & June 2024 53


PROJECT

Digital Bubble
Level and Active
Stroboscopic Disc
for Turntables
Fine-Tune Your Record Player With
This All-In-One Tool

By Antonello Della Pia (Italy)


Inspired, I envisioned creating a modern digital alterna-
To operate at its best, a turntable must be tive to the classic bubble level and strobe disc typically
placed in a perfectly horizontal position used for turntable tuning. This became feasible with the
availability of a particular round-shaped LCD display
and spin at the correct speed. The from Waveshare [1] and the impressive capabilities of
Raspberry Pi Pico-based tool presented the Raspberry Pi Pico [2]. This project also incorpo-
here performs both of these checks and, rates the GY-521 module, which includes the MPU-6050
position sensor by TDK InvenSense, and two buttons for
through an innovative solution, features power, calibration, mode selection, and battery voltage
a stroboscopic disc that does not require monitoring.
the usual 50 or 60 Hz pulsing strobe
The device aims to be self-powered, compact, and
light. lightweight, so it can sit on the turntable platter without
affecting rotation. It offers a level measurement range
of +/-10° on the x and y axes (with 0.1° resolution) and a
It may seem surprising, but despite the dominance of “linear” mode for +/-90° measurements on the x-axis. It
high-resolution multimedia streaming, the resurgence not only displays numerical inclination but also graphi-
of interest in analog music playback, especially vinyl cally represents the “bubble” movement within the display
records, is undeniable. This trend is supported by sales area. In strobe mode, it can verify the standard rotation
statistics from the record market. Concurrently, the market speeds of 33.33 and 45.00 RPM (revolutions per minute)
for dedicated hardware (turntables, cartridges, phono without external light.
preamplifiers, accessories) is more extensive, varied, and
accessible than ever, attracting both new enthusiasts and The Raspberry Pi Pico
veteran aficionados of high-fidelity music reproduction. The heart of this project is the Raspberry Pi Pico, a small
and inexpensive board, shown in Figure 1. It was launched
From Idea to Realization in January 2021 and more recently made available with
Avoiding the debate on analog vs. digital sound quality, the wireless connectivity option as well. Unlike previ-
it’s clear that optimal vinyl record reproduction hinges ous Raspberry Pi boards, which are considered SBCs
on a delicate balance of several electrical and mechan- (single-board computers) capable of hosting and running

ical factors. Assuming the hardware is in good working operating systems based on the Linux kernel (typically
Figure 1: The order and correctly set up, critical factors include the Raspberry Pi OS), the Raspberry Pi Pico actually houses
Raspberry Pi Pico used alignment of the pickup, the leveling of the turntable, and a microcontroller and only the components strictly neces-
in the project. the accurate rotational speed of the platter. sary for its operation. It is thus more similar in concept

54 May & June 2024 www.elektormagazine.com


to the classic Arduino UNO, although, as we shall see, and exploited, for example, in mechanical engineering
with much greater capabilities, thanks to the RP2040 (phasing of internal combustion engines and verification
microcontroller, a dual-core Arm Cortex-M0+ with 264 KB of high-speed rotating elements such as turbines). The
of internal RAM and 2 MB of flash memory, a clock moving object under observation, rotating at a constant
frequency of 133 MHz, and this can easily be overclocked. speed, is illuminated by a pulsating light source, at a
known frequency, so that it only becomes visible to the
Given the presence of USB, UART, SPI, I2C, ADC, PWM human eye only when it is struck by light. If the frequency
interfaces, 26 multifunction GPIO (general-purpose of the light pulses is equal to or a multiple of the rotational
input/output) pins, and the version with 2.4 GHz 802.11n speed, the object appears stationary.
wireless LAN, for quite a low price it is possible to have
a board suitable even for rather demanding projects in On the typical disk visible in Figure 3, one notices a
terms of computing power and management of external pattern of equidistant lines drawn along the circumfer-
components. The complete features and all documen- ence and the “50 Hz” indication. In fact, it should have
tation related to the Raspberry Pi Pico can be found on been illuminated with a common incandescent lamp (now
the manufacturer’s website [3]. obsolete) powered by mains alternating current, which,
by lighting at both the positive and negative half-wave,
The GY-521 Module With MPU-6050 actually generated one hundred light pulses per second
The GY-521 module is based on the MPU-6050 chip, an (50 × 2 = 100 Hz). The number of “notches” required to see
IMU (inertial measurement unit) sensor in six-axis MEMS them stationary at that frequency is given by the formula:
(micro electromechanical system) technology that imple-
ments a gyroscope and an accelerometer. Although it is n = (f × 2 × 60) / ω
not of recent production, it is still often used in projects
with Arduino or other microcontrollers when determining where f is the mains frequency in Hz and ω is the angular
the position of an object in the surrounding space (e.g., speed to be controlled, in revolutions per minute (33.33
for robots, drones, gesture reconnaissance, virtual reality and 45.00 RPM). It is evident at this point that the same
interfaces, wearable devices) is required. It is off-the-shelf,
inexpensive, and well-supported by dedicated libraries.
Figure 2: Sensing axes.

After some testing, it proved to be easily interfaced and 


sufficiently accurate and stable for the needs of the
project. The operating principle of this type of sensor +Z +Y
certainly deserves further investigation. In the chip’s few Figure 3: A traditional
square millimeters, in addition to the electronic compo- +Y stroboscopic disk (left)
nents, a MEMS is also integrated, which, for simplicity’s and a digital, active one
sake, can be thought of as a tiny moving mass producing (right). (Source of the
disk image: Wikimedia
a variation in distance and thus of capacitance between a
Commons https://
series of electrodes, in response to the dynamic stresses en.wikipedia.org/wiki/
to which the chip is subjected. +X File:Stroboscopic_disc.
+X
svg)
These variations are converted into a 16-bit digital signal,

available via an I2C interface for further processing. In
the case of the digital bubble level, the x- and y-axis
data will then be converted into readily understandable
numerical and graphical indications shown on the display.
An article that very effectively describes the technology
and use of this and other MEMS sensors is available on
the Last Minute Engineers website [4]. Figure 2 shows
a schematic of the sensing axes and rotation polarity
redrawn from a diagram in the datasheet [5].

The Stroboscopic Disk


Underlying the operation of the stroboscopic disk,
commonly used to verify the rotational speed of a turnta-
ble, is an optical phenomenon that has long been known

May & June 2024 55


U2 MPU-6050
R1
C2 C3
1 USB 40

3k3
GP0 VBUS
2 39
100n 100µ GP1 VSYS
3 38

INT
VCC
GND
SCL
SDA
XDA
XCL
AD0
GND LED GND
4 37
GP2 3V3_EN
5 36

BOOTSEL
GP3 3V3_OUT
6 35
Q2 D GP4 ADC_VREF
7 34
GP5 GP28
8 33
G GND GND LCD
9 32 1
GP6 U3 GP27 VCC
FDS9435A 10 31 2
S GP7 GP26 GND
D 11 30 3
Q1 GP8 RUN DIN
12 29 4
GP9 GP22 CLK
G 13 28 5
GND GND CS
FDS9435A 14 27 6
GP10 GP21 DC
S C1 100n 15 26 7
D1...4 = BAT46W GP11 GP20 RST
16 25 8
R2
D1 D3
GP12 PICO GP19 BL
17 24
100k GP13 GP18 JP1
18 23
GND GND
U1 D D2 D4 19 22
Q3 GP14 GP17

SWCLK
TP4056 v2

SWDIO
20 21

GND
R4 GP15 GP16
IN+ BAT+ R5
G
330Ω

100Ω
Charge
Full

BAT1
USB S 2N7002
LiPo
3V7 BZ1
200mAh R3
IN– SW1 SW2
BAT–
470k

230358-008


result can be obtained by leaving the number of refer- as we shall see in the description of the firmware. Note
Figure 4: Project ence lines fixed and varying the frequency of the illumi- that the other graphic elements on the display still remain
schematic diagram. nating source. Specifically, with sixty reference points, clearly visible, thanks to the persistence-of-vision effect.
it turns out that to see them stationary, the frequency of
the light pulses will have to be equal to the number of Schematic Diagram
revolutions per minute: As can be seen in Figure 4, the wiring diagram is not
particularly complex. The display and sensor module are
ω = (f × 60) / n = (f × 60) / 60 ω=f connected to the default pins of the SPI and I2C inter-
faces, respectively, on the Raspberry Pi Pico, as can be
In practice, in the digital version of the stroboscopic disk, verified from the pinout given in the datasheet. Connect
sixty equally spaced segments are drawn via software JP1 is connected to the LCD, and its leads are soldered
along the outer circumference of the LCD. Then, by directly to the board. Power for the display is taken from
feeding the LEDs responsible for the backlight (BL termi- the regulator on the microcontroller board, whose GPIO
nal of the display) with a square wave signal of appro- pins, it should be noted, do not support voltages greater
priate frequency (33.33 and 45.00 Hz), we will see the than 3.3 V.
“notches” still when the speed of rotation of the turntable
(and thus of the display) is equal to the frequency itself, This avoids any interfacing problems at the outset. The
considering that the LEDs light up only at a semi-period sensor module incorporates a dedicated LDO (low-drop-
(high level) of the square wave. out regulator), so signal level compatibility is assured.
Buttons SW1 and SW2 are monitored by pins GP13 and
In this way, instead of relying on an external light source, GP14 (configured as input with pull-up resistor) and allow
it is the segments themselves that light up and become the selection of available functions and to turn the device
visible at the desired cadence, hence the name “active” on and off by interacting with the power circuit. Module
disk. To achieve exactly the required frequencies, I used an U1, equipped with the TP4056 chip and Micro-USB input
unconventional approach, but it proved to work perfectly, provides charging for the compact rectangular lithium

56 May & June 2024 www.elektormagazine.com


Figure 5:
Raspberry Pi Pico
power chain. (Source:
Raspberry Pi Pico
Datasheet [15])

polymer (LiPo) battery of 3.7 V nominal and 200 mAh a VBUS presence sensor. Finally, in the wiring diagram
capacity, necessarily of the type with built-in protection of this project, C1 prevents immediate startup when the
circuitry, which ensures at least one hour of runtime for battery is connected, C2 and C3 are the usual power
the project. bypasses, and the buzzer confirms with a short beep
when the device is turned on and off.
It is advisable to charge the battery (a common phone
charger will suffice) with the device switched off, to obtain Realization of the Prototype
the correct end-of-charge indication. MOSFET Q1 [6] is The design was made, as I usually do it, on a prototype
the real switch of the device, normally held in the OFF board. This time I used two 60 mm diameter circular
state by R2 (gate terminal at the same potential as the baseplates, which can be found easily on the market,
source). When either switch is pressed, the gate, via stacked with the insertion of four spacers, to make a
D1 or D2, takes a negative value relative to the source, sort of “layered” assembly. Looking at Figure 6, it can
causing Q1 to conduct and reach (through Q2) the VSYS be seen that on the upper face of the first board are the
terminal on the Raspberry Pi Pico board, activating the buttons with the diodes, the buzzer and the motion sensor
microcontroller. module. Above the latter, the circular display is attached,
with its own connector from which wires connect to
As soon as firmware execution begins, GP15 goes high, the lower face, which houses the Raspberry Pi Pico, as
turning Q3 on (and consequently Q1), the display turns shown in Figure 7. From this side, the connections begin
on, and the button can be released. MOSFET Q2 can — via a five-pin connector made with strip contacts —
normally be considered “transparent” to the current flow, to the second baseplate, which houses the components Figure 6: The prototype
until the USB cable is connected for programming; in responsible for the power supply (the TP4056 module, — both the power supply
fact, in this case, the presence of the VBUS voltage deter- battery, MOSFETs, etc.). and the display side.
mines the disabling of Q2, preventing the return of the

same voltage to the battery through internal diode Q1.

On the other hand, shutting down the circuit is achieved


by long-pressing either button until the display turns
off. GP15 returns to level Low and Q3 to the OFF state,
then releasing the button Q1 stops the current flow. As
mentioned earlier, this on/off configuration (which is
easy to find on the web, in more or less similar designs)
can be applied to any microcontroller, requires only two
free pins (only one button is needed) and a few lines of
code. The function of D3 and D4 is only to prevent the
battery voltage — normally greater than 3.3 V — reach-
ing GP13 and GP14 via R2, D1, and D2, possibly causing
some damage.

The board’s power chain schematic, taken from the


Raspberry Pi’s datasheet and shown in Figure 5, helps
to clarify the operation of the power circuit further. Note
diode D1, which prevents voltage applied to VSYS (as
in this case) from flowing to the Micro-USB socket and
the resistive divider that allows GPIO24 to be used as

May & June 2024 57


with a few tricks, Assembly code can also be included in
the sketches — and being able to take advantage of most
of the libraries that already exist for Arduino. The cores
are generally in the public domain, written by passionate
and competent programmers.

The one installed for the Raspberry Pi Pico was created


by Earle F. Philhower, III and outperforms even the
official Arduino core in versatility and performance. All
related information and documentation is available on
the author’s GitHub page [8]. When using a Raspberry
Pi Pico with Arduino IDE for the first time, it is neces-
sary to perform some simple steps. After installing the
core and selecting the correct board, as per Figure 8,

In turn, This baseplate is attached in turn to a small disk of connect a micro USB cable to the board and, before
Figure 7: The prototype, the same diameter and one centimeter thickness (which connecting it to the computer, press and hold the board’s
shown from the I made from wood, but any stiff, lightweight material will BOOTSEL button.
Raspberry Pi Pico side do), drilled in the center to allow the center pivot of the
(left). turntable to pass through, for stable support in both level Select the classic Blink sketch from the examples and
mode (platter still) and strobe mode (platter rotating). I load it. The Raspberry Pi Pico’s onboard LED should start
used both SMD and through-hole components, depend- blinking, and the name of the board and its port number
ing on availability, for an assembly that was not without will be visible in the Tools→Port menu. From this point
its difficulties, given the need to fit everything into the on, you will be able to edit, compile and load sketches
dimensions of the boards, taking care of the centering of directly, as with any Arduino board.
the display and sensor and trying to achieve a rigid and
stable assembly. Certainly, a specially designed printed Firmware and Operation
circuit board would have greatly simplified the fabrica- I wrote the program that runs the project with
tion but involving, however, too much effort for a single Arduino IDE 1.8.19 after installing the Raspberry Pi Pico
prototype, in my opinion. Arduino core, as described in the previous section. The
display mounts the GC9A01 controller, which is not widely
Raspberry Pi Pico and Arduino IDE used and not supported by freely available libraries, so I
It may seem an unlikely comparison, but the Pico actually chose to use the demo library provided by the manufac-
has an RP2040 microcontroller on board and is there- turer, adapting it to the needs of the project.
fore more like an Arduino UNO (although the perfor-
mance comparison is merciless) than the single-board All necessary files (configuration, drivers, fonts, librar-
computers in the regular Raspberry Pi range. In general, ies) are contained in the sketch folder along with the
the Arduino IDE (integrated development environment) main one named Raspberry_Pico_Livella_Digital_Strobo.
allows code to be written to program a wide range of ino and are all visible in Arduino IDE and available at
microcontrollers and boards, far more than the “official” [9]. Furthermore, the installation of two other libraries is
Arduino models. With the Boards Manager tool, integrated required, MPU6050_light .2.1 [10], which is very well-doc-
into the IDE, it is possible to install so-called “cores,” which umented, for managing the sensor module, and Runnin-
can be defined, simplifying at best, as additional software gAverage 0.4.2 [11], which is useful for calculating the
modules capable of ensuring compatibility between new moving average of the data coming from it, via a circular
boards and microcontrollers, even third-party ones, with buffer. The listing is rather long and articulate — several
the Arduino environment (IDE, existing libraries, sketch hundred lines of code.
structure).
I therefore advise interested readers to open it in the
The — rather impressive — list of available cores and editor and examine it with the help of the many comments
thus compatible boards and MCUs can be accessed at and information I have included there. However, I will try
[7]. Among the most popular cores are certainly those to describe here the logic of the program and the most
for AVR ATtiny and ATmega microcontrollers, ESP8266, interesting sections of the code. Scrolling quickly through
ESP32, STM32, and now RP2040. All of the devices on the listing, you should immediately notice the presence
the list can therefore be programmed without leaving the of the functions setup1() and loop1() in addition to
Arduino IDE environment and the C/C++ language — those present by default in every sketch for Arduino.

58 May & June 2024 www.elektormagazine.com


This is due to the dual-core property of the RP2040 micro- effect is realistic enough. Otherwise, if strobe mode has
controller. Each core can independently execute the been selected, loop() executes only the routine that
instructions contained in the respective setup() and drives the display backlight LEDs. Just in case of simul-
loop(). At startup, after the usual inclusion of external taneous pressing of the two buttons, the function that
libraries and files, definition of the necessary variables displays the battery voltage is called. Setup1() contains
and instances, the main setup routine, core0, provides only the delay(1000) instruction that delays the start
pin definition, initialization of the EEPROM, SPI and I2C of loop1() by 1 s. The second core then executes the
communication protocols, the MPU-6050 sensor, and drawBackgroundElements() and buttonsOperation()
the display. functions, which are responsible for continuously redraw-
ing the fixed background elements of the display and for
After checking the battery voltage, (GP15 at logic level detecting and handling any button presses, respectively.
high), power is enabled. Then a series of conditional
instructions, based on the state of the buttons, handles The division of tasks between the two cores greatly
the calibration routines, the first information displayed improves the interface response speed and the smooth-
by the display, and sets the operating mode. Notice ness of the graphics. Following in the listing are all
already at this point the recurring instructions rp2040. the functions employed, which are, however properly
idleOtherCore() and rp2040.resumeOtherCore(), described and commented in the code. I add here brief
which are necessary because the two cores cannot simul- explanatory comments for those that I find most inter-
taneously write to flash memory and other peripheral esting. The drawStrobeMarks() function, taken from
devices, so, to ensure proper code execution, without an example available on the web [13], simplified and
blocking, each core must, if necessary, be able to pause tailored to the project, draws 60 equidistant segments,
and later reactivate the other. of the desired length, along the circumference of the
display. Starting from the concept of dividing the circum-
Below, if the bubble-level mode has been selected, the ference into 60 parts, each represented by the value
main loop() (always core0) is responsible for handling of 2π / 60 radians, through appropriate trigonomet-
the data from the MPU-6050 sensor (x and y coordinates), ric functions, the x and y coordinates of the 60 points,
processing the moving average, formatting the strings and consequently the coordinates needed to draw the
through the sprintf() function [12], displaying the data segments are calculated within a for loop and then
and drawing the moving “bubble” on the display through passed to the Paint_DrawLine() function.
the Paint_DrawString_EN() and Paint_DrawCircle()
functions found in the GUI_paint.cpp library provided The flashBacklight() function handles the backlight-
by its manufacturer. The effect of bubble movement is ing in stroboscopic mode, generating a square wave at
achieved simply by drawing a black circle with the current a frequency of 33.33 or 45.00 Hz with a 50% duty cycle,
coordinates and, immediately afterward, a green or white which allows the display to be illuminated during the
circle with the new coordinates, in a continuous process high-level half-period, making the segments on the
of erasing and rewriting. circumference visible at the appropriate time intervals.
The exact duration, in µs, of each half-period is obtained
Thanks to the clock frequency of the microcontroller by measuring the elapsed time using the rp2040.
— increased to 250 MHz from the appropriate menu in getCycleCount() function, which returns the number
the IDE — and the moving average buffer, the motion of clock cycles executed since the microcontroller was

Figure 8: Selection of the


Raspberry Pi Pico board
in the Arduino IDE.

May & June 2024 59


operation to be performed is calibration, which consists of
placing the device on top of a reference surface, perfectly
stable, flat and horizontal. Without moving it, press the
two buttons simultaneously: the message, Calibra-
tion, wait..., will appear on the display and, within a few
seconds, Calibration done!, followed by the operating
screen of the circular bubble-level, showing the green
CAL indication — visible only in this case — indicating
successful calibration. That means that the reference
values for correcting any offset errors have been stored
and will be automatically recalled at each subsequent
power-up.

powered up. At a clock frequency of 250 MHz, a cycle
Figure 9: A few lasts 1/250,000,000 = 0.000000004 s. This gives a granu- You can then turn off the device by holding down either
snapshots of the larity of measurement of 4 ns, with one elapsed micro- button for a long time. In normal use, pressing the red
prototype. second corresponding to 250 cycles. button turns the instrument on in circular bubble-level
mode (subsequent short presses of the same button will
The square wave is present on the GP22 pin named DEV_ switch between circular and linear modes). You then
BL_PIN, which controls the backlighting of the display. place the bubble-level on the platter, using the pin as a
On the prototype, the frequencies obtained, measured reference, and if the turntable is not perfectly horizontal,
with a frequency counter/tachometer, were 33.333 Hz you will need — depending on the type of your installa-
and 45.000 Hz, which is very accurate, with a fluctuation tion — to level the plate or adjust the feet or the suspen-
of just a few thousandths of a Hertz. Furthermore, function sion system, until the electronic bubble on the display
rp2040.fifo.push(pushCount) provides for sending the stabilizes in the center position by turning green, and the
second core the count (by 60) of the elapsed half-peri- numerical indications come as close to zero as possible.
ods, to display a longer reference segment on the display
with each completed revolution. I have already mentioned Use the yellow button to turn on and activate the strobe
the use of an EEPROM to store calibration parameters. function (pressing it again briefly changes the test mode
Actually, the RP2040 microcontroller is not equipped with between 33.33 and 45.00 RPM). Then, with the turntable
this type of memory. However, the EEPROM.h library allows rotating, preferably in dim ambient light, the speed will
it to be simulated using a portion of the flash memory. be checked. If it is correct, the segments on the circum-
With the instruction EEPROM.begin(4096) the sectors of ference of the display will appear still. If they appear
the emulated EEPROM are copied into RAM so that the to be rotating clockwise, the speed is too high; if they
program can access them for read and write operations. appear to be rotating counterclockwise, it is too low.
An additional reference is the longest center segment,
The storeOffsetsValues() function takes care of which lights up briefly with each revolution. If the speed is
calculating the measurement offset values, populating correct, it will always appear in the same position. Some
a user-defined structure (struct) with this data, and turntables allow adjustment of revolutions with a special
writing it, in bulk, to the EEPROM thanks to the EEPROM. control, others with more or less accessible trimmers.
put(eeAddress, offsetValues) function. At each On belt-driven equipment, an incorrect value may also
power-up, the setOffsetsValues() function reads the be due to the age of the belt. Other general causes may
data via EEPROM.get(eeAddress, offsetValues) and be inadequate lubrication of the pivot or problems with
sets the correct offset values for the gyroscope and accel- the power supply or motor. When in doubt, it is always
erometer. The struct (user-defined composite type) data advisable to consult a specialist technician in the field
type allows multiple values even belonging to different data for a thorough overhaul. Finally, Figure 9 shows some
types (byte, int, float, string, boolean, char) to be snapshots of the unit’s display in operation.
treated as a single block at the same time. Finally, it is useful
to point out that the EEPROM.h library and the program’s Wrapping Up With a Video
EEPROM.begin() and rp2040.xxxxx() functions are Various topics were covered in this project, such as the
specific to the Raspberry Pi Pico Arduino core. use of the Raspberry Pi Pico and its potential, program-
ming it in the Arduino IDE while also taking advantage
Practical Use of the dual-core functionality, MEMS inertial measure-
At the end of the article, it seems fair to add a few ment sensors, with a practical example of interfacing and
brief notes on the practical use of this device. The first use, the use of the circular LCD display, the operation

60 May & June 2024 www.elektormagazine.com


Component List
Resistors
R1 = 3.3 kΩ (all 1/4 W 1%)
R2 = 100 kΩ
R3 = 470 kΩ
R4 = 330 Ω
R5 = 100 Ω
of the stroboscopic disk, a special method of generat-
ing a square wave with a very precise frequency, power Capacitors
management using a button, applicable to any microcon- C1, C2 = 100 nF, 50 V, polyesther or ceramic multilayer
troller with just a few lines of code, and battery voltage C3 = 100 µF, 10 V, electrolytic
measurement. Although the premise might suggest a
project aimed at a very specific target audience, I believe Semiconductors
that even all makers who do not own a turntable and a Q1, Q2 = FDS9435A P-Channel MOSFET
collection of LPs can find useful information and interest- Q3 = 2N7002 N-Channel MOSFET w
ing insights to develop and use for new, different projects. D1, D2, D3, D4 = BAT46W Schottky Diode, Small Signal
Finally, a short demonstration video can be viewed on U1 = TP4056 Charging module, no protection
YouTube [14]. U2 = GY-521 MPU-6050 Module
230358-01 U3 = Raspberry Pi Pico board

Miscellaneous
Display = Waveshare 1.28” 240x240 Round LCD 19192
About the Author BUZZER = SMD Buzzer
Since childhood, Antonello Della SW1, SW2 = N.O. pushbutton, PCB type
Pia has been attracted to electric- BAT1 = 3.7 V LiPo battery, 200 mAh, with protection
ity and electronic devices. He holds M/F strip connectors
an Electrical Engineering Techni- Spacers
cian high school diploma. Anton- Solderable, round breadboard, PC-15, 60 mm
ello has always cultivated and developed his passion
for analog and digital electronics. Currently, he plays
around with microcontrollers and programming, trying
to improve his skills. Antonello likes to develop and
propose projects that are as original as possible and
— as he hopes — interesting, as well. Related Products
> Raspberry Pi Pico RP2040
www.elektor.com/19562
Question or Comments?
Do you have technical questions or comments about > Dogan Ibrahim, Hardware Projects for
this article? Please contact the Elektor editorial team Raspberry Pi, Elektor 2014 (E-book)
www.elektor.com/16969
at [email protected].

WEB LINKS
[1] Waveshare LCD display module webpage: http://tinyurl.com/5n87a8pt
[2] Raspberry Pi Family: https://en.wikipedia.org/wiki/Raspberry_Pi
[3] Raspberry Pi Pico webpage: https://raspberrypi.com/products/raspberry-pi-pico/
[4] MPU6050 tutorial on LastMinuteEngineers website: http://tinyurl.com/rxr8av6k
[5] MPU6050 datasheet: http://tinyurl.com/mwr5fwb6
[6] FDS9435A datasheet: https://onsemi.com/pdf/datasheet/fds9435a-d.pdf
[7] Unofficial list of 3rd party boards support URLs — Arduino IDE: http://tinyurl.com/5edvv332
[8] Raspberry Pi Pico Arduino core — Earle F. Philhower, III: http://tinyurl.com/489kwb3k
[9] SW package for this project: https://elektormagazine.com/230358-01
[10] MPU6050_light — Arduino library: https://github.com/rfetick/MPU6050_light
[11] RunningAverage — Arduino library: https://github.com/RobTillaart/RunningAverage
[12] C library function — sprintf() — tutorialspoint: http://tinyurl.com/58ymn9wz
[13] ArduinoWatch — moononournation: https://github.com/moononournation/ArduinoWatch
[14] Video demo — YouTube: https://youtu.be/tun6wH5gKDA
[15] Raspberry Pi Pico Datasheet: https://datasheets.raspberrypi.com/pico/pico-datasheet.pdf

May & June 2024 61


BACKGROUND

Open
Source
and Its Significance for
the Electronics Industry (2) Arduino UNO and Raspberry Pi are two
long-standing open-source solutions.
(Source: Mouser Electronics)

By Mark Patrick (Mouser Electronics)

In part one [1] of this two-part open- The Impact of Open-Source Software on the EU’s
source series, we explored the GDP
In 2021, the European Commission published the results of its
definition and certifications available study [2] on the financial benefits of open-source software and
for open-source electronic software hardware. It found that, in 2018, companies within Europe invested
and hardware, as well as some of the €1 billion in open-source software. This resulted in a significant
impact on the EU’s GDP, adding between €65 and €95 billion to the
successful development and education economy. The Commission went on to state that a 10% increase
hardware products. In this second in open-source contributions could result in a GDP increase of
article, we will analyze the value of around 0.4% to 0.6% (€100 billion).

open-source solutions to the electronics When open-source software is coupled with powerful repository
market, look at trends such as closed- sites such as GitHub, thousands of developers from across the world
source hardware in combination with can push the system forward and fix bugs together. With produc-
tivity and engagement far beyond what is seen in even the best
open-source solutions, and examine the community-backed proprietary solutions, users feel a sense of
viability of using open-source hardware ownership over the software.
(OSHW) in commercial products.
In some cases, the complexity and breadth of modern applica-
tions can make it hard for proprietary solutions to develop quickly
enough to meet market expectations. Equally, interoperability in
What Does Open-Source Mean to the Electronics the digital world is key, especially for the internet of things (IoT)
Industry? and web-based applications, and this can be enhanced through
The major strength of an open system is its accessibility, which open-source solutions.
comes with several related advantages. For software, open-source
design removes all entry barriers, allowing more developers to get The Challenges of OSHW
their hands on source code, thus increasing collaboration, innova- With household names such as Mozilla Firefox and Android,
tion, and the rate of development for the host solution. the value and success of open-source software is obvious.
But OSHW solutions have had a harder time. Even the aforemen-
In terms of hardware, although there is always an expense linked tioned 2021 EU report acknowledged the difficulty in assessing
to the physical device, many of these advantages remain. Addition- the market impact of OSHW.
ally, with open design files, OSHW can mitigate supply shortages
by allowing for localized manufacturing and facilitating the rapid So, how viable is an OSHW solution for going to market, and how
development of design variants. does it impact the electronics market?

62 May & June 2024 www.elektormagazine.com Partner Content


As a prototyping tool, it can help speed projects up, allowing for been to use open-source development and evaluation solutions
easier R&D experiments and the use of pre-made reference designs before transitioning to a bespoke stripped-back final design.
and libraries. But, when you consider the transition from devel-
opment to a final market solution, these strengths can become For example, after creating a working prototype with an
weaknesses. Arduino UNO R4, an engineer can move to a bespoke final design
built around the same Renesas R4M1 32-bit MCU [7] that powers
The adaptability of OSHW comes at a cost, and very few final the UNO R4 but features just the required components.
hardware applications will use every I/O option that solutions such
as the Raspberry Pi 5 [3] and Arduino UNO R4 [4] provide. There- Another hybrid approach is to use open-source software with
fore, in any production run above even a small batch of products, closed-source hardware platforms. For manufacturers producing
an off-the-shelf open-source solution may present a much higher the hardware, their intellectual property (IP) and business viability
cost than a stripped-back design with just the microcontroller unit are protected, and, for the end-user, their development pathway is
(MCU) and necessary supporting components. streamlined by supporting a wide range of open-source reference
code and resources.
Equally, open hardware is open by nature, making it susceptible
to easy cloning, which can undermine any business prospect — Open-Source Smart Homes
especially if the produced solution also uses relatively simple-to- As smart home technology has grown in popularity, unfortunately,
copy or open-source code. so has the number of interfaces and protocols. This has led to the
end-user experience being diminished through the incompatibil-
3D Printers ity of products and the complexity of networks.
The 3D printer market is an area of the electronics industry that has
often touted the strengths of open and community-led solutions. Within the world of smart homes, the Matter protocol [8] is looking
However, the issue of clones has caused problems in this space. One to resolve issues created by proprietary solutions by leveraging
example of the issues around OSHW comes from MakerBot, now open-source Wi-Fi and Thread communication. To help guide
part of Stratasys, one of the world’s largest 3D-printing companies. its development, the protocol is managed by the Connectivity
Standards Alliance (CSA), which includes high-profile hardware
As a long-time advocate for OSHW, the company built its initial component suppliers, software developers, and product manufac-
success off the open-source RepRap 3D printer project. However, turers such as Google, Amazon, Intel, and Infineon.
it moved from machine hardware and GUI to a closed design for
its Replicator 2. Many see Matter as the perfect resolution for smart home commu-
nications. It is an open-source, free software solution for wireless
In a 2012 blog post, MakerBot cited the need to combat the impact of communication governed by a wide range of suppliers and
carbon-copy clones undercutting and damaging their business [5]. manufacturers. It removes barriers to increase interoperability,
The reaction across the community and wider electronics industry raises security, and allows for local operation without an internet
at the time was mixed. While many sympathized with the issues of connection.
clones and understood the change, seeing it as necessary, others
were less pleased with the move away from an open and commu- The nRF52840 Development Kit (DK) [9] from Nordic Semiconduc-
nity-backed business model. tor [10] allows for the development of the nRF52840 Multi-Protocol
2.4GHz System-on-Chip (SoC) [11] with the open-source Matter
In an open letter to the 3D-printing community earlier this year protocol (Figure 1). This extensive development tool supports
[6], Josef Prusa, CEO of Prusa Research and a vocal advocate for
open-source solutions, called for an update of the OHSW defini-
tion so that it could restrict 1:1 clones for commercial purposes
without undermining other key aspects of open-source design. He
also highlighted the growing issue of companies across the globe
using aspects — or the entirety — of open-source solutions, then
filing for patents based on these designs before commercializing
them and closing a previously open market.

Combining Open-Source and Closed-Source


Solutions
Combining open- and closed-source solutions can help to Figure 1: Nordic Semiconductor’s nRF52840 Development Kit supports
deliver the benefits of both models, without being exposed to the both Matter and Arduino UNO R3-compatible shields. (Source: Mouser
weaknesses. Traditionally, the most common hybrid approach has Electronics)

Partner Content May & June 2024 63


Through the combination of NXP’s i.MX RT MCUs, MCUXpresso,
and open-source embedded software and middleware such as
Zephyr, developers can quickly produce high-quality, real-time
industrial and consumer solutions ranging from human-machine
interfaces (HMI) to high-end audio systems.

Conclusion
While the importance of open-source solutions for software
cannot be argued, it can be harder to draw the same conclusion
Figure 2: NXP’s i.MX RT1050 MCU. (Source: Mouser Electronics) for hardware. Many engineers designing commercial products feel
that OSHW is too vulnerable to be copied or undermined, which
can lead to damage to reputation and loss of market position.

Bluetooth 5.2 (including Bluetooth Low Energy), 802.15.4/Thread, Equally, in most cases, selecting hardware for a project is primarily
ANT/ANT+, and proprietary 2.4 GHz applications as well as NFC. based on performance and costs, and if an open-source solution
misses these requirements, it is unlikely to be selected over a propri-
Alongside open-source Matter compatibility, the hybrid approach etary product. That said, market-ready hardware is benefiting from
of the nRF52840 DK also supports Arduino’s UNO shields designed open-source solutions. This might be through assisting develop-
to the open R3 standard, making it possible to mount open-source, ment and prototyping, or through the combination of proprietary
third-party hardware. Nordic’s solution allows engineers to lever- hardware solutions and open-source software, firmware, and third-
age open-source hardware and software with its closed hardware, party hardware add-ons.
streamlining the development of IoT devices as well as promot-
ing interoperability within the smart home to the benefit of the By using a hybrid approach, it is possible for engineers to leverage
end user. the strengths of open solutions without being susceptible to their
potential weaknesses — combining the best of both worlds and
Open-Source MCU Development reducing development time and adding value to designs. For the
This hybrid theme of bringing together proprietary hardware with end-user, this approach can help to create a product that is more
open-source software is seeing similar success with real-time attractive than a completely closed design, with greater interoper-
operating systems (RTOS) for MCUs. The rising complexity of code ability, lower costs, and enhanced operation familiarity, all possible
in current RTOS implementations has resulted in the prominence thanks to using open-source solutions.
of the open-source community-supported solution Zephyr [12]. Led 240184-01
by a consortium of industry-leading vendors, including Intel [13],
Google, Meta, and NXP Semiconductors, Zephyr has been devel-
oped to cater to the evolving requirements of MCU deployments,
such as edge solutions and IoT.

Zephyr’s modular design and simple code reuse shorten the initial
steps for developers and encourage collaboration within its expand-
ing community. It already boasts the highest number of unique
contributors and upstream commits per month out of all other
RTOSes [14], as well as a wide range of supported hardware, demon- About the Author
strating the platform’s popularity and continued ability to adapt. As Mouser Electronics’ Director of Technical Content for EMEA,
Mark Patrick is responsible for creating and circulating techni-
The i.MX RT Crossover MCU [15] family from NXP (Figure 2) is one cal content within the region – content that is key to Mouser’s
example of a closed-source hardware solution that is designed to strategy to support, inform, and inspire its engineering audience.
operate with open-source software such as Zephyr. Before leading Technical Content, Mark was part of Mouser’s EMEA
Supplier Marketing team and played a vital role in establishing
Further pushing a hybrid approach, NXP supplies the closed-source and developing relationships with key manufacturing partners.
but free MCUXpresso development suite with its hardware. This Mark’s previous experience encompasses hands-on engineering
comprehensive offering is deeply integrated with its developer roles, technical support, semiconductor technical sales, and various
community and encompasses IDE interfaces, evaluation kits, and marketing positions. A “hands-on” engineer at heart, Mark holds a
configuration tools that enable the seamless and efficient imple- first-class Honors Degree in Electronics Engineering from Coventry
mentation of open-source software, such as Zephyr and Matter, University. He is passionate about vintage synthesizers and British
with NXP’s MCUs powered by Arm Cortex-M cores. motorcycles and thinks nothing of servicing or repairing either.

64 May & June 2024 www.elektormagazine.com Partner Content


WEB LINKS
[1] Mark Patrick, “Open Source and Its Significance for the Electronics Industry,” Elektor embedded world 2024 Special:
https://elektormagazine.com/240087-01
[2] Study about the impact of open source software and hardware on technological independence, competitiveness and innovation
in the EU economy: https://tinyurl.com/uk5janxs
[3] Raspberry Pi 5 Single Board Computer: https://tinyurl.com/raspberry-pi-5-mouser
[4] Arduino UNO R4 Microcontroller Board: https://tinyurl.com/arduino-uno-rev-4-mouser
[5] Bre Pettis, “Let’s try that again,” September 24, 2012:
https://web.archive.org/web/20121029023851/http://www.makerbot.com/blog/2012/09/24/lets-try-that-again/
[6] Josef Průša, “The state of open-source in 3D printing in 2023,” March 29, 2023:
https://blog.prusa3d.com/the-state-of-open-source-in-3d-printing-in-2023_76659/
[7] Renesas Electronics RA4M1 32-Bit Microcontroller Group: https://tinyurl.com/Renesas-Electronics-RA4M1
[8] Mouser Presents — “Matter for a smarter home”: https://tinyurl.com/matter-mouser
[9] nRF52840 Development Kit (DK): https://tinyurl.com/nRF52840-Development-Kit
[10] Nordic Semiconductor: https://tinyurl.com/Nordic-Semiconductor
[11] nRF52840 Multi-Protocol 2.4GHz System-on-Chip (SoC) : https://tinyurl.com/nRF52840-Multi-Protocol
[12] Zephyr: https://zephyrproject.org/
[13] Intel: https://tinyurl.com/intel-mouser
[14] Zephyr Project Overview [PDF]: https://zephyrproject.org/wp-content/uploads/sites/38/2023/09/Zephyr-Overview.pdf
[15] NXP Semiconductors i.MX RT Crossover MCUs: https://tinyurl.com/iMX-RT-Crossover-MCUs

Ignite Your Electronics


Innovations with

ElektorLabs
• Free Project Sharing
• Expert Support
• Collaboration Opportunities
• Access to Exclusive Resources
• Get published in
Elektor Magazine

Share Your Projects Now!


www.elektormagazine.com/e-labs

Partner Content May & June 2024 65


BACKGROUND

M12 Circular
Connector Dust and liquids cannot harm the M12-A circular connector from Würth
Elektronik eiSos: The connectors, which comply with protection classes

With A-coding
IP67 and IP68 are suitable for use in harsh environments. (Source: Würth
Elektronik eiSos)

housing for specific applications) that comply with the standards


First Choice for (DIN EN 61076-2-xxx) for the respective areas of application.

Industrial Applications The A-coding mechanical shape is the origin of all M12 codings;
all other different codings (B, D, L, X, S) have branched out from it,
which is why there are different codings (A, D, L, X, S, etc.), each with
different numbers of contacts available. Although M12 interfaces
can have from 2 up to 17 contacts, in practice, the most commonly
By Baptiste Bouix and Caroline Poulard used are three, four, five, eight, or twelve pins. The number of pins
(Würth Elektronik France) depends on the various requirements. For example, sensors and
power supply applications require three and four pins, whereas
Automation requires networking, and in the Profinet and Ethernet applications require four and eight pins,
industrial environment there is a proven and fieldbus, CAN bus, and DeviceNet typically require four or
five pins. 12 pins are required for sophisticated signal transmis-
versatile solution for connecting modules sion. Table 1 shows an overview of the protocols and number of
such as sensors or actuators: M12 circular connector pins required at the physical level.
connectors with A-coding can be used to Data Line With Power Supply
transmit signals, data, or as electrical cables. Würth Elektronik eiSos offers the M12 circular connectors as male
What needs to be considered is explained and female connectors with A-coding (DIN EN 61076-2-101). M12-A
below. offers the option to mix signals and DC power delivery, which are
particularly suitable for fieldbus applications in industrial automa-
tion. The WR-CIRC M12 family is available in panel-mounted
connectors, field attachables and cable assemblies with four, five
When connectors from different manufacturers can be combined, or eight pins. The current Würth Elektronik eiSos portfolio includes
a standard has been established. This is the case with M12 circu- plugs and sockets panel- and PCB-mounted in THT version, and
lar connectors. The industrial connectors represent a compact, pre-wired and solder buckets for cables (see “Comprehensive
standardized interface that is suitable for many applications: from Portfolio” text box). Areas of application can be found in industrial
the transmission of signals and data to power transmission. Pretty environments, particularly in automation and robotics, as well as
much anything is now possible using this robust, mechanically and in the field of renewable energies, communication technology, and
environmentally resistant long-serving connector. The term “M12” mechanical engineering. In addition, the panel and Field-Attach-
refers to the 12 mm nominal diameter of the locking thread. The able models of the M12 connectors are cULus-certified (UL2238).
wide range of applications for M12 connectors is also reflected in the All M12 connectors provide minimum protection to IP67 or IP68
number of mechanical codings (unique mechanical profiles of the against the ingress of dust, dirt, and water.

66 May & June 2024 www.elektormagazine.com Partner Content


Comprehensive Portfolio
Würth Elektronik eiSos has the right M12-A connection
technology for Ethernet, industrial bus systems, USB 2.0,
and I/O-Link. For circular connectors, users can choose
between THT-soldered versions for PCBs in horizontal and
Table 1: Overview of the physical level of the M12-A coding. vertical designs. There are also panel-mount cable solutions
Würth Elektronik offers circular connectors with M12-A coding with solder cups or pre-wired versions. All parts are available
with 4, 5, or 8 pins. in metal and plastic versions with panel cut-outs PG9, M12
and M16 and in four, five, and eight-pin configurations, as
Physical Layer Suitable M12 A-coded [1] well as with IP68 protection. Würth Elektronik also provides
M12-A-coded cable assemblies with IP67 protection as a
10BASE-T 8-pin
single-sided solution, which are available as straight and
100BASE-T 8-pin angled, as well as male and female with four, five, and eight
Higher BASE-T 8-pin pins. The coupling nuts can be made of metal or plastic;
IO LINK Class A (Master) 5-pin metal couplings with shielding are also available. Reliable
IO LINK Class A (Cable) 4-pin data transmission over a cable length of up to 2 m is ensured.
Customized cable solutions are available on request. Finally,
IO LINK Class A (Device) 4-pin or 5-pin
field attachable solder cup solutions ensure high flexibility
IO LINK Class B 5-pin in the respective application, as they are available as four-,
USB A 2.0 4-pin five- and eight-pole male and female, can be assembled
Micro-USB 2.0 5-pin in the field and comply with protection class IP68. Here,
CANbus 5-pin too, the coupling nuts are available in metal and plastic.

RS-485 4-pin or 5-pin


RS-422 4-pin or 5-pin
RS-423 4-pin or 5-pin circular connectors with two-pair cables, or higher Base-T for data
RS-232 8-pin rates of up to 10 Gbps. For the latter, however, X-coded circular
connectors with four-pair cables are required.

The question is: Can higher clocked EOTP standards be imple-


Fast and Error-Free mented alternatively with M12-A coding without compromising
Fast and error-free transmission of digital signals via cable are vital on speed and signal integrity? For 100 Mbit/s EOTP standards, it
for sensor and actuator applications. The basis for this is Ether- is possible to create an interface with an A-coded circular connec-
net Over Twisted Pair (EOTP), which is considered one of the most tor by following the same pin assignment as for 10-BASE-T. Signal
important physical layers for Ethernet. It serves as the basis for the integrity must be considered when designing such an interface.
EtherCAT, EtherNet/IP, Profinet, CC-Link IE, Powerlink, Sercos III, The entire cable assembly, including the connectors, must conform
and Modbus TCP protocols.

Although M12A is not the original connector on which the EOTP


interface was developed, it is still possible to use the connector
in various adaptations. For example, the eight-pin M12 circular
connector can be used as a replacement for the RJ45 in an ANSI/
TIA-568 Category 3 cabling system used for the 10BASE-T Ether-
net interface at 10 Mbit/s. The Cat 3 cable consists of four twisted
pairs with a typical differential impedance of 100 Ω. Figure 1
shows the recommended assignment when wiring an RJ45 (8P8C
modular plug) with an M12 A-coded circular connector. On the Figure 1: 10BASE-T transmission: Recommendation for wiring an RJ45 (8P8C
other hand, when wiring an M12 A-coded circular connector with modular plug) with an M12 A-coded circular connector. (Source: Würth
Elektronik eiSos)
an M12 A-coded circular connector, a pin assignment as shown in
Figure 2 is recommended.

This pin assignment minimizes the delay offset between contacts of


the same pair. This wiring is a widely used configuration for A-coded
M12 EOTP cabling. Although 10BASE-T uses only two pairs for signal
transmission, it is not advisable to have only two pairs in the cable
or to use a four-pole A-coded circular connector, as this can lead to
confusion with other widely used applications. On the other hand,
a D-coded connector is recommended for two-pair EOTP cabling
with M12. Other Fast Ethernet variants are also possible, specifically Figure 2: This is the recommended pin assignment from M12-A to M12-A for
100Base-T for applications up to 100 Mbps, which require D-coded 10BASE-T transmission. (Source: Würth Elektronik eiSos)

Partner Content May & June 2024 67


M12-A circular connector family WR-CIRCM12
The technical article is taken from Application Note
ANE019 from Würth Elektronik eiSos and is available for
free download at www.we-online.de/ane019.

to ANSI/TIA-568. Each of the plug/socket pairs and the cable itself Figure 3: Pin assignment of a five-pin M12-A coded socket for the RS-485
have a budget for loss and crosstalk that must not be exceeded. It is interface. (Source: Würth Elektronik eiSos)
recommended to test the S-parameters of such an interface, which
mainly depends on the cable category and the cable length. Even
at significantly higher data rates of up to 10 Gbit/s, it is possible to
create an interface with an M12 circular connector with A-coding
by implementing the same pin assignment as for 10-BASE-T and
100-BASE-T and applying the same signal integrity considerations.
Such an interface will generally have a much shorter cable length.

Other Applications Figure 4: Pin assignment of a five-pin M12-A coded socket for used to power
There are more applications for the robust M12-A circular connec- Profibus peripheral devices. (Source: Würth Elektronik eiSos)
tors. For example, the IO-Link communication system can be used
to cleverly connect intelligent sensors and actuators to an automa-
tion system in accordance with IEC 61131-9 — using four- or five-pin supply, the B-coded circular connectors are specifically designed
A-coded M12 circular connectors that are connected to a three- for Profibus signal transmission (Figure 4).
or five-wire 20-meter cables. The connection on the three-wire
cable is referred to as “Class A” and the connection connected to a Other industrial bus systems in which the M12 circular connec-
five-wire cable as “Class B”. The device connection can be a captive tors with A-coding are used are RS-411, RS-423, and finally RS-232.
cable or a four- or five-pin M12 A-coding, depending on the desired Eight-, five- and four-pole connectors are suitable for this. The
cross-compatibility. wiring depends mainly on the required signals, the power supply,
and the required earthing.
The M12 connection technology is ideally suited as an intermedi- 240202-01
ate link for industrial bus systems, especially for CANbus, RS-485,
Profibus and the physical levels RS-422, RS-423, and RS-232. While
the CANbus was originally designed for use with a small D-SUB
connector, the five-pin M12-A coded round connector is a popular About the Authors
interface for the CANbus. Only the CAN_H and CAN_L signal pair,
which is wired to pins 4 and 5, is mandatory. The device can be Baptiste Bouix is Product Manager Interna-
supplied with power in this configuration. Twisted signal cable tional at Würth Elektronik France. His areas
pairs with a nominal impedance of 120 Ω is used for electrical of responsibility include board-to-board,
transmission. card connectors and Ethernet connectors.
Previously, he worked in the microelectronics
The RS-485 physical layer is often used for the industrial protocols industry in research and development of
Modbus, OSDP, SSCP, SCSI-2, SCSI-3, Profibus, Nanoréseau, DMX 512 manufacturing processes. With degrees in materials science and
and AES 3. Figure 3 shows a typical RS-485 pin assignment for nanotechnology, he has extensive expertise in silicon technologies,
five-pole A-coded cables. Alternatively, four-conductor shielded signal processing and measurement technology and has become a
cables can also be used. The wiring largely depends on the required specialist in signal chain-oriented product management and design
power supply, but always includes at least the symmetrical TxD/ over the years.
RxD pair in positions two and four to minimize the delay time.
Caroline Poulard is Product Manager for
Profibus enables decentralized concepts. The fact that Profibus circular connectors and DSUB connectors at
can be adapted to different applications using a modular principle Würth Elektronik France. She is a mechanical
also makes this technology attractive in production automation engineer who started working in the automotive
and the process industry. Here, the M12 connection technology industry and then reached for new challenges
is indispensable. While the A-coded variants are used for power in the electronic field.

WEB LINK
[1] M12 A-coded types of connectors:
https://we-online.com/en/components/products/em/connectors/circular_connectors/circular_connectors_m12_a

68 May & June 2024 www.elektormagazine.com Partner Content


ELEKTOR BOOKS

The Arduino-Inside
Measurement Lab
An 8-in-1 Test & Measurement Instrument for the Electronics Workbench

By Burkhard Kainka (Germany)

The Elektor book publication


with the above title describes a
set of Arduino-driven test and
measurement instruments — from
their principles of operation right
up to hands-on use, including
programming and fair scrutiny of
strengths and limitations. In this
article, we plunge into the book
at a relatively advanced point
where some of the basic functions
such as frequency generation and
frequency measurement get software
refinements aiming for precision
and practical use in the home lab.
If the Arduino deserves one place
in your maker lab, for sure that’s
inside a multifunction, all-DIY test
instrument for real use on the bench! The Arduino Nano has a lot more to offer than covered so far (in the
book, Ed.). Several ports, analog inputs and timers are still avail-
able for use, so let’s try to exhaust all possibilities that can be used
at the same time. The goal remains to use all functions as if they
Editor’s Note. This article is an excerpt from the Elektor book: The belonged to independent devices. The MSR laboratory thus grows
Arduino-Inside Measurement Lab. This excerpt was formatted and without the need for additional hardware. The ultimate goal of the
lightly edited to match Elektor Magazine’s conventions and page layout. development is a combination of various functions:
The author and editor are happy to help with queries. Contact details
are in the Questions or Comments? box. In German, “MSR” stands > Oscilloscope with up to two channels, switchable time axes,
for “messen, steuern, regeln,” which translates to “measure, control, and trigger functions
regulate,” or “measurement and control” for short. The MSR acronym > Two DDS sine wave generators
is retained in the English translation of the book to match the control > Added DDS square wave outputs
software developed by the author for the project. > Two adjustable voltage sources

May & June 2024 69


Figure 1: Additional functionality and connectivity for ‘MSR,’ the software Figure 2: A phase difference of 90 degrees.
core of the Arduino-Inside Measurement Lab.

As far as software goes, the MSR lab program and further infor- To set the frequency, two bytes must be transmitted for the prescaler
mation about the project is posted at [1] where you can also find and the timer. Command 90 has been defined for this purpose.
further information from the author on his (originally German)
publication. if (c == 90){ // OC0A frequency
TCCR0B = USART_Receive();
For a good overview, even with many more inputs and outputs, OCR0A = USART_Receive();
all functions are named according to the pin designations on the }
Arduino. Figure 1 shows a sample screen of the MSR U/I up and
running and indicating the pin name agreement. In the user program, every change at the frequency control HScroll8
leads to a new output. For the finest possible setting, five ranges
DDS Phase Adjustment with different prescalers (1, 8, 64, 256, 1,024) are used. The output
The DDS generator’s sine table (discussed earlier in the book, Ed.) frequency is calculated and displayed on the user screen. Listing 2
has a length of 256 bytes. For a complete period, the high byte in shows the code extract, Figure 3 the pin connections, and Figure 4
the phase accumulator must pass through the range from 0 to 255. the MSR user screen.
Thus, with the same frequency on both channels, a phase relation-
ship of 360 degrees in total is mapped in this range. Accordingly,
a1 = 0x0000 is set, and a received byte parameter is shifted into
the high byte of a2. Command 82 thus triggers a phase jump at
both channels, after which the desired phase relationship exists. D6 (OC0A) A0
Listing 1 shows the relevant program code.

In the user program, the desired phase difference is set with the
HScroll9 slider (Figure 2). At each operation, the command 82
is sent together with the new phase byte.
Figure 3: Pin connections for the frequency generator.
Signal Generator up to 8 MHz
Timer 0 (with a resolution of 8 bits) can be used to generate a
symmetrical square wave signal. For initialization, TCCR0A = 0x42
is set. The following register sets the prescaler. With TCCR0B = 0x00,
the generator is switched off, and with TCCR0B = 0x01 it gets the
full 16 MHz clock frequency. Further prescaler levels reach up to a
divisor of 1,024. The exact frequency is set with OCR0A = 255 (/256,
lowest frequency) to OCR0A = 0 (/1, largest frequency). The counter
increments and jumps to 0 each time OCR0A is reached. At the
same time, output OC0A is toggled at port D6. This results in the
highest frequency of 8 MHz. The lowest frequency is 16 MHz / 2 /
1,023 / 256 = 30.528 Hz.

TCCR0A = 0x42; // Timer0 Toggle OC0A


TCCR0B = 0x00; // off
OCR0A = 255;
Figure 4: Output and display of a 1,000 Hz signal.

70 May & June 2024 www.elektormagazine.com


Listing 1: Triggering a phase jump.
if (c == 82) { // DDS Phase
a2 = (USART_Receive()) << 8;
a1 = 0x0000;
}

Private Sub HScroll9_Change()


phase = HScroll9.Value
Label15 = "D3 " + Str(Round(phase / 256 * 360)) + " °"
SENDBYTE 82
SENDBYTE phase
End Sub

Listing 2: The output frequency is calculated and displayed.


Private Sub HScroll8_Change()
d = HScroll8.Value
If d = 0 Then pre = 0: n = 0
If d > 0 Then
pre = 5
n = 256 - d
If n > -1 Then f = 8000000 / 1024 / (n + 1)
End If
If d > 192 Then
pre = 4
n = 448 - d
If n > -1 Then f = 8000000 / 256 / (n + 1)
End If
If d > 384 Then
pre = 3
n = 640 - d
If n > -1 Then f = 8000000 / 64 / (n + 1)
End If
If d > 608 Then
pre = 2
n = 864 - d
If n > -1 Then f = 8000000 / 8 / (n + 1)
End If
If d > 832 Then
pre = 1
n = 1088 - d
If n > -1 Then f = 8000000 / (n + 1)
End If

If f < 100000 Then Label11.Caption = "D6 " + Str(Round(f))


+ " Hz"
If f >= 100000 Then Label11.Caption = "D6 " + Str(Round(f
/ 1000)) + " kHz"
SENDBYTE 90
SENDBYTE pre
SENDBYTE n
End Sub

May & June 2024 71


Figure 5: Measurement of 2 kHz alias at 127 kHz real. Figure 6: Triangular waveform display at 308 kHz.

Many important frequencies can be set precisely, but most frequen- TIMSK1 = 0x01; // Timer1 Overflow Interrupt
cies are odd fractions of 16 MHz. The resolution is high at low TCCR1C = 0;
frequencies and becomes coarser towards the end. The four highest
frequencies are 2 MHz, 2.667 MHz, 4 MHz, and 8 MHz. For compar- For initialization, the counter is connected to input T1 at port D5.
ison: The DDS generator made in this way has a resolution of about Additionally, the interrupt is enabled. The Timer2 interrupt is also
1 Hz across the range, but only reaches up to 5 kHz. used to control the gate time. A time counter t is set up here. At t = 0,
Timer1 is reset together with its external high byte fh1. At t = 1, the
With the square wave generator, frequencies can be set exceed- timer is started. And exactly one second later it is stopped and read:
ing the sampling rate of the oscilloscope. However, reliable
measurements with the oscilloscope are only possible up to half ISR (TIMER2_OVF_vect)
the sampling rate, i.e., up to about 31 kHz. Near the sampling rate {
or its multiples, completely false images are delivered. The double PORTB |= 1;
sampling rate is 125 kHz. If you set the square wave generator to …
127 kHz, an apparent signal of 2 kHz appears, i.e., the difference t++;
frequency. In principle, this problem can be observed with any if (t == 0) { TCCR1B = 0x00; TCNT1 = 0; fh1 = 0; }
DSO, while it never occurs with an analog oscilloscope. Figure 5 if (t == 1) { TCCR1B = 0x07; }
shows an example. Also noticeable are the sloping edges in the if (t == 62501) { TCCR1B = 0x00;f=TCNT1; fh2=fh1; }
oscillogram, despite the actual rectangular shape. They are caused …
by the finite sampling time of the AD converter. The sample-and- PORTB &= ~1;
hold capacitor needs some time to charge up to the actual voltage. }
However, at very high frequencies, the state will already have
changed within the sampling time. As a result, voltages between The lower 16 bits are then in f. In addition, there are the upper 8
the extreme values are measured in the transitions. At very high bits in fh2. Command 91 was defined for transmission to the PC.
frequencies, triangular voltages are even displayed as illustrated In the MSR user program, the frequency readout is refreshed once
in Figure 6. per second. For this purpose, the measured value must be read
out within the timer function. A total of three bytes is combined
Frequency Measurement to form a 24-bit number. Here are the code snippets relevant for
The digital counter uses timer 1, having a resolution of 16 bits. these operations:
Because it is only possible to count up to 65,535 with this arrange-
ment, an interrupt is triggered at each overflow to increment an if (c == 91) { // Timer 1 frequency
additional counter. This contradicts the principle that there should USART_Transmit(fh2);
be only one active interrupt to not disturb the running DDS output. USART_Transmit(f >> 8);
However, the Timer1 interrupt rarely occurs and only occurs when USART_Transmit(f & 0xFF);
frequencies above 65 kHz are measured. }

This listing shows the relevant code:


CLEARBUFFER
ISR (TIMER1_OVF_vect) SENDBYTE 91
{ f = READBYTE
fh1++; f = 256 * f
} f = f + READBYTE
… f = 256 * f
TCCR1A = 0x00; f = f + READBYTE
TCCR1B = 0x07; // Timer1 Input Label9 = "D5 " + Str(f) + " Hz"

72 May & June 2024 www.elektormagazine.com


D8 (62.5 kHz) D5 (T1)

Figure 7: Pin connections for the frequency meter.


The frequency meter works permanently in the background without
disturbing the DDS output and the oscilloscope. If you connect input
D5 to output D8, the sampling rate and the regular call of the Timer2
interrupt function can be monitored (Figure 7). Here, 62,500 Hz is
reliably displayed (Figure 8). Should this frequency ever fluctuate
or drop as a result of a firmware extension, this indicates an error
caused by too much time spent in the interrupt.

The square wave output, D7 or D4, is best suited for measuring


the DDS frequency. Here you can find deviations of one hertz
partly caused by rounding errors. Usually, the lowest digit of a
frequency counter fluctuates because the signal frequency is mostly
completely asynchronous with the counter’s time base.

In this case, the 1 kHz frequency is also confirmed by the oscillo-


scope, which simultaneously measures the corresponding sinusoi-
Figure 8: Measurement of the sampling frequency at D8.
dal signal (Figure 9). However, the MSR oscilloscope can only
measure frequencies below 31 kHz. The MSR frequency counter,
on the other hand, works up to 8 MHz.

A deviation of 4 Hz is observed at the highest measuring frequency


of 8 MHz (Figure 10). This is due to calculation time in the Timer2
function, which causes a slight extension of the gate time. More
precisely, this time error can be narrowed down to 0.5 µs.

Overall, the frequency counter seems to have excellent accuracy.


However, you have to keep in mind that all measured signals are
derived from the same clock, namely the Arduino’s system clock.
Unfortunately, the controller does not use a quartz crystal but a
16 MHz ceramic resonator. Accurate measurements show that
this can have a deviation of up to about 0.3%, which equals about
50 kHz at 16 MHz. Consequently, with the displayed frequency of
8 MHz, an error up to 25 kHz is possible. Figure 9: Measurement of the DDS-generated 1,000 Hz output frequency.

These tolerances must be considered in any frequency measure-


ment. However, there are often tasks where only relative accuracy
or the observation of frequency changes (delta-f) is important. In
other cases, consider removing the ceramic resonator and replacing
it with a quartz crystal and matching capacitors if necessary.
240119-01

Questions or Comments?
Do you have any questions or comments related to this article? Email
the author at [email protected] or Elektor at [email protected].

Related Products Figure 10: Measurement of 8 MHz at D6.

> Burkhard Kainka, The Arduino-Inside Measurement Lab,


Elektor 2024
Book: www.elektor.com/20818 WEB LINKS
E-book: www.elektor.com/20819
[1] MSR software: https://b-kainka.de/MeasurementLab.html

May & June 2024 73


PROJECT

Sound Card Performs Gain/


Phase and Impedance Analysis
For Frequencies From 100 Hz to 90 kHz

By Dr. Martin Ossmann (Germany)


Soundcard 16 Bit

Tucked away inside your PC is a piece of


192 kSamples/sec

hardware that generally just sits there


In Out
Speaker Device

swapping audio information between the


Under
Line In Left Test

analog and digital domains. Armed with Line In Right

the right software, you can turn it into a


pretty cool measuring tool that can analyze
GND

230644-014

the gain and phase behavior of four-pole


networks, as well as the complex impedance Figure 1: Connection of a four-pole network to the sound card.

of two-pole networks for frequencies of up


to 90 kHz. And the best part? It doesn’t need 90 kHz. It is therefore entirely possible to measure the characteristics
any extra equipment or outlay! of a component such as a DCF77 antenna. The card’s high resolution
also enables the measurement of relatively weak signals.

To perform the measurements, the sound card needs to be configured


This article explains how you can use your PC’s sound card to measure so that the output signal from a signal generator on the card is routed
the frequency characteristics of components in terms of gain and to the Speaker output and the left and right Line In signals are the only
phase response, as well as the complex impedance of simple two-pole ones routed through to the sound card’s A/D converter.
components such as resistors, capacitors, and inductors.
Gain and Phase
The software accompanying this project was developed using the To analyze a component’s frequency response characteristics, at the
(open-source) Processing integrated development environment [1], input to the sound card, we analyze an analog signal of a known
which is great for accessing sound card signals and creating display frequency but unknown gain and phase compared to the excitation
graphics. You can find these programs on the Elektor project page [2]. signal. The signal (the yellow trace in Figure 2) also contains some
interference and noise signals. To find the gain and phase, we solve a
To measure the frequency response of a component (the device under linear optimization problem using values of A and B so that the signal
test, or DUT), you can drive the component with a variable frequency
sinusoidal signal and measure the phase shift and amplitude ratio s(t) = A cos(k α) + B sin(k α)
between the signal at the input and output.

The Sound Card


The sound card in your computer has a speaker output that can supply
an external circuit with a sinusoidal signal (Figure 1). In addition, there
are stereo line inputs. By also feeding a DUT’s input signal to the
sound card’s left channel, and the output from the DUT into the right
channel, you can measure both signals simultaneously and deter-
mine their phase shift. The sound card in the PC measures signals
using a sampling rate of 192 kHz with a 16-bit resolution. This allows
measurements of frequencies up to half the sampling rate, or about Figure 2: Input signal y(t) (yellow) and cosine/sine approximation s(t) (red).

74 May & June 2024 www.elektormagazine.com


C1 C3

4n7 R3 2n2 R6

10k

10k
R1 C2
2
In 10k R4 C4
1 6
4n7 OP1a 10k
R2 3 R5 7
achieves the best fit with the measured signal y(t). For this, 2n2
5
OP1b Out

we use the method of least squares. It is reasonable to set

1k

1k
the sample number N = 4,096. This value can be relatively +5...12V

easily changed in the program. To determine A, the signal R7

is multiplied and summed with the sampled cosine wave. OP1 = LM4562

10k
For B, use the corresponding sampled sine wave. A is the C5 8
OP1
value of the cosine function of the signal, while B is the value C6
R8
100n 4

of the sine function. This process functions in the same way

10k
10µ
that an I/Q mixer in an SDR receiver design works. The 16V

receiver signal is multiplied by the cosine and sine functions 230644-015

of the sampled signal. Low-pass filtering is then applied,


which is performed here by summing the samples. This is Figure 3: Two-stage band-pass filter.
also referred to as summing through the mean.

Amplitude U and phase φ can then be determined using the follow-


ing equation:

U=√A2+B2 and φ = arctan(B/A)

If complex AC calculations are used, A is the real and B the imaginary


part of the signal’s phasor representation. The approximated signal, s, is
shown in red in Figure 2. Comparing the remaining approximation error
between signal y(t) and approximation s(t) we can derive the quality
of the measurement. When this error is too great, the measurement
can be discarded. The program outputs the relative approximation
errors between the input and output signal, both of which should be Figure 4: The two-stage band-pass filter built on a small square of perfboard.
less than 50%. If the measured waveform has a high level of noise, it’s
often because the signal level is set too low. To avoid this, it is possi-
ble for the program to display the input and output signal levels. This
information also helps to identify if the signal generator is possibly
being overloaded.

From the magnitude and the phase of the input and output signals, it’s
easy to determine the magnitude and phase of the transfer function,
g. The ratio of the signal magnitudes and the phase difference can be
calculated as shown in the example below.

An Active Band-Pass Filter


The DUT used here is a two-stage active band-pass filter. The circuit
diagram is given in Figure 3, and Figure 4 shows the circuit built on a
small square of perf board. Each of the two stages has a slightly differ-
ent resonant frequency. Figure 5 shows the combined gain (in dB)
and phase response (in degrees) of the filter over a frequency range
from 1 kHz to 90 kHz. This shows the filter’s relatively flat response Figure 5: Frequency response of the band-pass filter in Figure 3.
at its resonant frequency f0 = 17 kHz. The phase shift occurs around
the resonant frequency. The curve corresponds nicely to an LTspice
Rq
simulation of the same filter configuration.

Impedance measurement Uin


Z
Uout = g x Uin
To measure the impedance of a component, you can build a voltage
divider network made from the unknown impedance, Z, and a source
resistor, Rq (Figure 6). The (complex) transfer function of this voltage g = Z / (Rq + Z)
divider is given by: 230644-016

g = Z / (Rq + Z) Figure 6: Voltage divider network for measuring impedance.

May & June 2024 75


We can arrange this so that the impedance, Z, can be determined
from the g factor

Z = Rq · g / (1 - g)

This allows us to calculate the impedance as a function of frequency,


unlike simple impedance meters that only work at a fixed frequency.
The impedance is split into real and imaginary parts or by magnitude
and phase, from which we can determine the components of an equiv-
alent circuit. This provides us with the equivalent values of capaci-
tance or inductance. The source resistance, Rq, should be chosen
to be in the order of magnitude of the impedance to be measured.
Figure 7: Plug board wiring for measuring the inductor. It should also not be too small, as it may overload the sound card’s
signal generator output.

For initial tests, we can experiment with a fixed coil with an inductance
Rs Ls
L = 10 mH. The circuit can be built on a small prototyping plug board,
which can be seen in Figure 7. The source resistance is Rq = 10 kΩ.
230644-017 The series equivalent circuit of the coil is shown in Figure 8. The
series resistor represents the DC resistance of the coil wire as well
Figure 8: Series equivalent circuit of the inductor. as the (frequency-dependent) losses in the core material and other
properties. The frequency-dependent equivalent circuit values are
shown in Figure 9.

Input Impedance
The frequency-dependent characteristics of this setup flags up a
problem. At frequencies below 30 kHz the value of the series induc-
tance Ls is about 10 mH as expected. The same is true for series resis-
tor Rs. At higher frequencies, Ls increases sharply and even becomes
negative. This means that, at high frequencies, the two-pole network
behaves capacitively. This is because we have not considered the input
impedance of the sound card, which is effectively in parallel with Z.
This impedance can be measured by the system itself by omitting the
impedance, Z, in the voltage divider network according to Figure 6
so that it is only made up of the input impedance. A parallel network
of capacitor Cp and resistor Rp is used as the equivalent circuit to
represent the input impedance. The resulting measured values are
shown in Table 1.
Figure 9: The coil properties, Ls and Rs, from 10 kHz to 90 kHz.

sound card input impedance.


Table 1: Measured values of the

Rp = 12.462 kΩ Cp = 713.40 pF
k=0 frq = 1.00 kHz
Rp = 12.044 kΩ Cp = 647.35 pF
k=1 frq = 12.13 kHz
Rp = 11.591 kΩ Cp = 633.22 pF
k=2 frq = 23.25 kHz
Rp = 11.094 kΩ Cp = 624.68 pF
k=3 frq = 34.38 kHz
Rp = 10.582 kΩ Cp = 618.75 pF
k=4 frq = 45.50 kHz
Rp = 10.049 kΩ Cp = 614.45 pF
k=5 frq = 56.63 kHz
Rp = 9.514 kΩ Cp = 610.30 pF
k=6 frq = 67.75 kHz
Rp = 8.984 kΩ Cp = 606.95 pF
k=7 frq = 78.88 kHz
Rp = 8.387 kΩ Cp = 605.17 pF
k=8 frq = 90.00 kHz

76 May & June 2024 www.elektormagazine.com


Vgnd

R1
2
C2

1M
1
C1 OP1a Out1
3
In1 100µ
10µ

Vgnd

R2
6
C4
1M

7
C3 OP1b Out2
5
In2 100µ
10µ

OP1 = LM4562 Figure 11: Two-channel buffer build using perfboard.


Vgnd R5 +5...12V
22Ω

R4
Soundcard 16 Bit
10k

8 192 kSamples/sec
C5 C6
OP1 Speaker
R3
C7 100µ 100n 4
Out1 In1 In Out
10k

Line In Left Device


100µ R1 Under R2
Line In Right Buffer1 Test

1M

1M
230644-018
GND
Out2 In2

Figure 10: Two-channel buffer circuit design.


Buffer2

230644-019

As you can see, the sound card has a relatively low input imped-
ance of about 11 kΩ. The impedance has a capacitive component of Figure 12: Buffer, sound card, and DUT wiring.
approximately 650 pF, which is considerable when compared to the
input characteristics of a typical oscilloscope. It was this capacitive
component which influenced the resonant behavior when the induc- low-noise and highly linear and it’s also low cost, for example, from
tor was being measured. Mouser [3] where it retails for £2.28 for the through-hole version.

Impedance Conversion The connection of the buffer, sound card, and DUT is shown in
To reduce the influence of the sound card’s input stage impedance, we Figure 12. Now, there is a buffer stage in front of each input of the
can use impedance converters. These have high-impedance inputs sound card. Since the same circuit is used for both channels, their
with low capacitance and can be easily built using IC amplifier buffers. influence cancels out when calculating transfer factor g. These buffer
In Figure 10, a suggested circuit uses an LM4562 op-amp, which can stages have a 1 MΩ input similar to the input characteristics of an
be easily built on a piece of prototyping board (Figure 11). oscilloscope, allowing the use of regular scope probes.

The LM4562 op-amp suggested here uses a low bias current, so the Now, using the buffers, a parallel circuit made up of a resistor of
voltage drop across the 1 MΩ input resistor is small. Its gain/bandwidth Rp = 10 kΩ and capacitor of Cp = 100 pF is tested. The results are
product of 55 MHz is sufficiently high for this application. This IC is given in Table 2.

Table 2: Measurement of a para


llel circuit where Rp = 10 kΩ and
Cp = 100 pF.
k=0 frq = 1.00 kHz Rp = 9.831 kΩ Cp = 104.31 pF
k=1 frq = 10.89 kHz Rp = 9.828 kΩ Cp = 102.55 pF
k=2 frq = 20.78 kHz Rp = 9.827 kΩ Cp = 102.42 pF
k=3 frq = 30.67 kHz Rp = 9.821 kΩ Cp = 102.49 pF
k=4 frq = 40.56 kHz Rp = 9.816 kΩ Cp = 102.47 pF
k=5 frq = 50.44 kHz Rp = 9.809 kΩ Cp = 102.51 pF
k=6 frq = 60.33 kHz Rp = 9.800 kΩ Cp = 102.60 pF
k=7 frq = 70.22 kHz Rp = 9.792 kΩ Cp = 102.56 pF
k=8 frq = 80.11 kHz Rp = 9.780 kΩ Cp = 102.53 pF
k=9 frq = 90.00 kHz Rp = 9.761 kΩ Cp = 102.20 pF

May & June 2024 77


Figure 13: Real and imaginary plots of a parallel resonant circuit with Figure 14: Nyquist plot of the parallel resonant circuit.
Lp = 10 mH and Cp = 4.7 nF.

Here you can see that the measurement is now quite accurate through- The yellow curve represents the magnitude of the transfer function.
out the frequency range due to the high input impedance and low You can clearly see that, at resonance, it peaks at about +30 dB.
capacitance properties of the buffer stages. You can also determine The curve extends over a range from -50 dB to +30 dB, resulting in a
the real and imaginary parts of the transfer function of a component. total dynamic range of 80 dB. The red curve at the bottom shows the
The real and imaginary characteristics of a parallel resonant circuit phase response. As expected, the phase shift occurs mainly around
with Lp = 10 mH and Cp = 4.7 nF are given in Figure 13. the region of resonance. The gray/blue crosses track the behavior
of the model function associated with Figure 15. You can see that it
The real and imaginary characteristics can also be represented in the fits quite well. Only the resonance peak is lower in practice than in
x-y plane, as shown in Figure 14. This is called a Nyquist plot. For a theory, which is due to additional losses in the coil. If you reduce the
parallel resonant circuit, it results in a circular trace. value of Rp to 30 kΩ, it produces a curve that, even during resonance,
matches more closely. From this, we can estimate losses in the coil.
Reference Curves This approach is common practice for parameter estimation, where
Often you will already have an idea of how the measured curves should the parameters are adjusted so that the model function matches the
look. The software allows you to overlay such reference curves so you real measurement as closely as possible.
can check how well the model matches up with reality. For conve-
nience, a library of complex AC calculations will be useful for the Options
creation of reference transfer functions and is available for download Table 3 lists the circuit parameters and component values that can
with the project. As an example, we will measure a series resonant be set in the program. This gives a wide range of possibilities for
circuit (Figure 15). circuit analysis.

At resonance, this series-resonant circuit will generate a high output This article has demonstrated how you can measure the frequency
signal. If the signal generator is set to the normal output level, the response of four-pole networks and component impedances in the
output signal from this circuit will overload the voltage measurement frequency range of 100 Hz to 90 kHz using an ordinary sound card,
input at resonance. The simplest remedy is to reduce the generator
signal by a factor of 10. Now it becomes apparent that the sound card
can process even small signals very accurately. The measurement of
the transfer function (magnitude and phase) yields the curves shown
in Figure 16.

Cp

4n7 Rp
Lp
100k

In Out
10mH

230644-004

Figure 15: Series resonant circuit. Figure 16: Gain and phase of the transfer function of a series resonant circuit.

78 May & June 2024 www.elektormagazine.com


possibly augmented with two op-amp buffers working as impedance
converters. The program, developed using the Processing graphics About the Author
library and IDE, allows the display of frequency-dependent parame- Martin Ossmann had already got into reading Elektor and tinkering
ters for the various equivalent circuits in different formats. Altogether, with electronics by the time he was twelve. He went on to study
with very little effort, you can, for example, measure the characteris- electrical engineering and spent several years as a development
tics of four-pole networks, capacitors and inductors over a range of engineer. From there, he became a professor at the Department of
frequencies. Electrical Engineering and Information Technology at FH Aachen.
Translated by M. Cooke — 230644-01 He is not only the author of numerous scientific papers and publica-
tions but has also written many fascinating hardware and software
projects featured in Elektor over the past three decades.

Table 3: The main program parameters.


Evaluated function selection
Questions or Comments?
selectGreGim Real and imaginary part of the transfer If you have any questions or comments regarding this article please
function contact the author at [email protected] or get in touch with
selectZreZim Real and imaginary part of the the Elektor team at [email protected].
impedance
selectRpCp Equivalent capacitive impedance in
parallel to resistor Rp
selectRsLs Equivalent inductive impedance in
series with resistor Rs Related Products
selectGainPhase Gain (dB) and phase (degrees) of the > Peak Atlas LCR45 – LCR Meter with LCR Impedance
transfer function Measurement
www.elektor.com/17563
selectGasXY Real and imaginary part of the
transfer function as a locus
selectErr Error level for the sine approximation
of both sample sequences
selectRms Amplitude (RMS) of the two signals

fSample=192000 ; The sound card sample rate


nSamples=512 ; Number of samples in one
measurement

frqStart=5*kHz ; Frequency sweep start


frqStop= 80*kHz ; Frequency sweep stop
FrqNsteps=16 ; Number of measurements during
sweep
logSweep=!true ; Logarithmic sweep option

SigGenAmplRms=0.25 ; Sine wave signal generator (RMS)


amplitude
Rsource=150*Ohm ; Source resistance for impedance
measurements

WEB LINKS
[1] Processing: https://processing.org
[2] Elektor project page: https://elektormagazine.com/230644-01

May & June 2024 79


Source: Freepik / @lifeforstock
PROJECT

Measuring pH Value
With the Arduino UNO R4
Check the Quality of Your Water

By Boris Landoni (Italy)

If you want to know the acidity (or alkalinity) level of your


pool or aquarium water, you need a pH meter. In this article,
you’ll find a simple but effective solution based on off-the-
shelf components.

In this article, we present a pH meter that can In addition, this pH measurement system Conversely, if the hydrogen ion concentration
accurately measure the pH value of a solution. also finds application in aquaria, where water is low, the pH will be high, indicating alkalinity.
We use a dedicated sensor, the Arduino quality is vital to the health of fish and all other
UNO R4 Minima board, and a small 0.96″ living organisms. Incorrect pH can upset the As mentioned above, pH is an important
OLED display. The versatility of this system aquatic ecosystem’s balance, causing stress parameter in many scientific and industrial
allows it to be applied in different areas, and disease to its inhabitants. With this pH fields. But it is also fundamental to human
providing reliable and user-friendly results. meter, you will be able to monitor the water’s health, as various biological systems require
pH in real time and make any corrections to an environment with a specific pH to function
Water is a crucial factor in many working ensure an ideal value for each application. properly. pH measurement can be done using
contexts. For example, in hydroponic agricul- chemical indicators or electronic instruments
ture, where plants are grown without the use What Is pH called pH meters, which provide an accurate
of soil, water pH plays a key role in ensuring Before proceeding with the project’s descrip- reading of the solution’s pH and are commonly
optimal nutrient uptake by plants. Constantly tion, let’s see what pH is. pH (potential of used in chemistry laboratories and environ-
monitoring water pH allows farmers and Hydrogen) is a measurement scale used to mental analysis.
operators to adjust acidity or alkalinity levels, indicate a solution’s level of acidity or alkalinity.
thus creating an ideal environment for plant This scale ranges from 0 to 14, where a value Probe for Measuring pH
growth and development. But it is not only of 7 represents neutrality, while values below In our project, we will use an electronic probe
hydroponic agriculture that benefits from this 7 indicate acidity and those above 7 indicate to measure pH (Figure 2). An electronic pH
project. Maintaining the correct pH value of alkalinity (Figure 1). meter probe’s operation is based on electronic
water is also essential, for example, in the and chemical principles. It consists of a
routine maintenance of swimming pools — The pH is determined by the concentration of pH-sensitive glass electrode and a reference
a prerequisite for ensuring a healthy, safe and hydrogen ions (H+) present in the solution. electrode. The former contains a special glass
always-swimmable environment for bathers. When a substance dissolves in water, it can that reacts with hydrogen ions in the solution.
An unbalanced pH can cause irritation to release hydrogen ions that determine the
swimmers’ eyes and skin, as well as encour- solution’s acidity. If these ions’ concentration When the glass electrode is immersed in the
age the growth of bacteria and algae. is high, the pH will be low, indicating acidity. solution, an electrical potential difference is

80 May & June 2024 www.elektormagazine.com


Figure 2: Electronic probe for pH measurements.
(Source: Elettronica In)
Figure 1: The scale used to indicate the level of a solution’s acidity or alkalinity.
(Source: Freepik / @freepik)

created according to the solution’s pH. The case, Arduino UNO. For proper operation, the transition for existing shields and projects,
reference electrode provides a stable refer- module must be supplied with a voltage of taking advantage of the extensive and unique
ence point for pH measurement. Usually, a 5 VDC, and, given its low-power consump- ecosystem already created for the original
gel or salt solution reference electrode is tion (between 5 and 10 mA), we can supply it Arduino UNO (Figure 5).
used. The pH probe can detect the differ- directly from the 5 V pin of our UNO R4 board.
ence in electrical potential between the glass For proper operation, it is necessary to wait The new version also offers a faster clock,
electrode and the reference electrode. This at least 60 seconds to get accurate readings. allowing it to perform more accurate calcula-
potential is converted into a pH value using tions and handle complex and sophisticated
an electronic circuit. Arduino UNO R4 Minima designs. It also features a USB-C connector,
The fourth version of the Arduino UNO, the which is a smaller, more powerful, and more
Before use, it is necessary to calibrate the Arduino UNO R4 Minima, is a major step durable standard than previous connectors.
instrument using known pH values (usually forward in the field of DIY and electron- To use the Arduino UNO R4 Minima, you’ll
pH 4 and pH 7) to ensure measurement ics (Figure 4). This new version houses a need to install the UNO R4 Minima board
accuracy. Special care should be taken with 32-bit Arm Cortex-M4 processor, providing package, which is part of the Arduino core for
the glass electrode, which should be stored more computing power and 16 times more Renesas devices. To install it, you will need to
in a specific solution and cleaned periodically memory than previous versions. Despite these have a version of the Arduino IDE, which you
to remove deposits that could affect measure- improvements, the size and 5 V compatibility can download from the Arduino downloads
ments. The probe cannot be connected remain the same. This ensures a seamless page [1].
directly to our Arduino UNO R4 board, but
rather the signal must be amplified and made
readable by the microcontroller via a signal
conditioning board (Figure 3).

The pH probe is connected to the condi-


tioning module through a BNC connector,
which ensures a stable and reliable connec-
tion. The module has a voltage output pin that
outputs a level proportional to the measured Figure 3: The signal conditioner board that
pH level. This pin can be connected to the allows us to interface the pH probe to the
an analog input of a board, such as, in our Arduino UNO R4. (Source: Elettronica In) Figure 4: Arduino UNO R4 Minima.

May & June 2024 81


Figure 5: The pinout of this new Arduino board is identical to that of the previous one. (Source: arduino.cc)

In this article, we will use the latest version of


IDE 2 (Figure 6). To install the board package,
open Board Manager from the menu on the
left, search for UNO R4 Minima and install
the latest version (or your desired version)
(Figure 7). Now, connecting the board to the
computer will create a virtual serial port, which
you can use for programming the Arduino.

Figure 7: The package “Arduino UNO R4 Boards”


Figure 6: The latest available Arduino IDE version is 2.2.1. to be installed.

82 May & June 2024 www.elektormagazine.com


Listing 1. Definitions
// the analog output pin of the pH sensor is
// connected to the analog input 0 of the Arduino
# define SensorPin 0

// store the average value of the sensor feedbacks


unsigned long int avgValue;

float b;
int buf[10],temp;

# define SCREEN_WIDTH 128 // OLED screen width in pixels


# define SCREEN_HEIGHT 64 // OLED screen height in pixels
# define OLED_RESET -1 // reset pin (o -1 if the reset handling is shared)

Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

Connections
In this project, we used several components
to create a pH-detection system, as you can
see in the wiring diagram (Figure 8). The main
component, which is the probe that can detect
pH, was connected to its conditioning circuit
via a BNC connector. As mentioned earlier, this
circuit takes its power directly from the Arduino
UNO R4 board’s 5 V and GND pins. The pH-de-
tection module’s pin P0 was connected to the
Arduino board’s analog pin A0. This connec-
tion will allow the main board to read the pH
values detected by the sensor.

The OLED display used provides an I 2C


connection that allows, with only two wires
besides power, to control the display. The
display’s SDA and SCL pins are therefore
connected to the Arduino R4 board’s SDA
and SCL pins, while the power supply was Figure 8: Overall wiring diagram of the project.
taken from the 3.3 V and GND pins. This setup
will allow us to measure pH using the probe
and display the results on the OLED display.
It is important to follow the given instructions
carefully, as well as the connections shown
in the wiring diagram, to ensure the system’s
proper operation.

The Firmware
The code written for the Arduino UNO R4
allows us to read the pH sensor values and
display them on the OLED. Let’s look at the
code in detail. The first lines of code include
the libraries needed for the program to work, in
particular the Wire library for I2C and Adafruit’s Figure 9: The completed prototype, ready for testing.

May & June 2024 83


Adafruit_GFX and Adafruit_SSD1306 libraries The system offers a versatile solution for Questions or Comments?
for managing the OLED display are included. accurately measuring a solution’s pH of a Do you have technical questions or
Next, some constants and variables used in solution in various contexts, such as hydro- comments to submit about this article?
the program are defined (Listing 1). ponic farming, swimming pools, and aquaria. Feel free to write to the Elektor Editorial
It’s an excellent starting point for adapting to Team at [email protected].
The setup() function is executed at startup your specific application.
and plays a crucial role in initializing the 230711-01
program (Listing 2). First, digital pin 13 is set
as the output to control an LED. Next, serial
communication via Serial Monitor is initialized About the Author Related Products
at a baud rate of 9,600. After that, the program B oris L andoni is an
checks whether memory can be properly electronics expert and a > Arduino UNO R4 Minima
www.elektor.com/20527
allocated for the SSD1306 OLED display. If true enthusiast in the field.
the memory cannot be allocated, an error His dedication led him > Arduino UNO R4 Experimenting
message is displayed and the program aborts. to become the manag- Bundle
ing director of Elettronica In, the most www.elektor.com/20648
If, on the other hand, the display can be popular electronics magazine in Italy. He
initialized correctly, a series of commands is also the curator of open-electronics.org,
is executed to configure it. A short pause is a platform dedicated to open-source
initiated, then the display is cleared. The text projects that brings together enthusiasts
size is set to 2, and the cursor is placed at and professionals.
display coordinates (10, 5). Next, the text “PH
Sensor“ is displayed by calling the display.
display() function. A pause of three seconds
is inserted to allow the user to read the
message on the display before the program
transfers to the loop() function. The loop() Listing 2. setup()
function is the heart of the Arduino sketch
void setup() {
and is executed continuously after the setup
pinMode(13, OUTPUT);
phase (Listing 3).
Serial.begin(9600);
Serial.println("Ready");
Within loop(), ten sample values are acquired
from the pH sensor via analog pin 0. These
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
values are then sorted in ascending order to
Serial.println(F("SSD1306 allocation failed"));
calculate the middle six samples’ average
for (;;);
value, for the purposes of noise reduction. This
}
value is then converted to millivolts and then
into the corresponding pH value. After that, the
display.display();
pH value is printed on the serial monitor with
delay(2);
two decimal places of precision and displayed
display.clearDisplay();
on the OLED.
display.clearDisplay();
display.setTextColor(WHITE);
Then a light connected to digital pin 13 is
display.setTextSize(2);
turned on and off to provide visual feedback,
display.setCursor(10, 5);
and finally the program pauses for 800 ms
display.print("pH Sensor");
before starting the loop over again, perform-
display.display();
ing the same operations to acquire and calcu-
delay(3000);
late pH values. This loop repeats indefinitely as
}
long as the Arduino remains powered. Figure 9
shows the completed, functional prototype.

Let’s Check the Waters WEB LINKS


This article presented a pH measurement [1] Arduino IDE 2 Download Page: https://arduino.cc/en/software
system using a dedicated sensor, the Arduino [2] Elektor Labs webpage for this project:
UNO R4 Minima board, and an OLED display. https://elektormagazine.com/labs/measuring-ph-value-with-arduino

84 May & June 2024 www.elektormagazine.com


Listing 3. loop()
void loop() {
// Get 10 sample values from the sensor to
// get a more accurate measurement
for (int i = 0; i < 10; i++) {
buf[i] = analogRead(SensorPin);
delay(10);
}

// Sort the analog values from smallest to largest


for (int i = 0; i < 9; i++) {
for (int j = i + 1; j < 10; j++) {

if (buf[i] > buf[j]) {


temp = buf[i];
buf[i] = buf[j];
buf[j] = temp;
}
}
}

avgValue = 0;

// take the average value of 6 center sample


for (int i = 2; i < 8; i++)
avgValue += buf[i];

// convert the analog into millivolts


float phValue = (float)avgValue * 5.0 / 1024 / 6;

// convert millivolts into pH value


phValue = 3.5 * phValue;

Serial.print(" pH:");
Serial.print(phValue, 2);
Serial.println(" ");

display.clearDisplay();
display.setTextSize(2);
display.setCursor(20, 5);
display.println("Ph Value");
display.setTextSize(3);
display.setCursor(30, 35);
display.print(phValue);
display.display();

digitalWrite(13, HIGH);
delay(800);
digitalWrite(13, LOW);
}

May & June 2024 85


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

Source: Adobe Stock


From Life’s
Experience
Pangpong Butt Launcher

By Ilse Joostens (Belgium)

Those who know me are aware that I can get caught up in the finer word games,
sometimes resulting in hilarious situations, like the time I accidentally wanted to
order a “pizza salmonella” from the local pizza place instead of a “pizza salmone.” I
won’t elaborate on the butcher’s wife’s facial expression when my partner accidentally
turned “filet de sax” into something less suitable for publication. Eric Bogers from the
Elektor editorial team is also quite fond of word games, and the strange subtitle of this
piece comes from Eric’s childhood, when his father invariably called ping pong balls
“pangpong butts.” Coincidentally, this pun has grown into the unofficial codename for
this project — and work in progress — of a target with floating balls for air rifles, which
was previously featured in the series, Homelab Tours [1].

Building the Project a euphemism for shooting at all kinds of from insurance premiums, about as dangerous
Judging by the reactions of readers, there objects — including ping-pong balls — is a as bridge. Well, just about, because I know
seems to be quite some interest in this project, welcome change (Figure 1). one shooter who is fond of using extremely
especially from shooting clubs that want to offer heavy calibres, causing his teeth fillings to
something different to their young members. After quite a while of inactivity due to circum- come loose as a result. Since safety is import-
To be honest, repeatedly aiming at cardboard stances, I have picked up the thread, so, ant, even when it comes to airguns, and
cards at your own pace does become a time for an update. If you feel the urge to get because electrical wiring in a shooting range
bit monotonous eventually. Plinking [2], started, I have good news for you, as you can is usually not a good idea, I opted, as far as
now download the CAD drawings, along with the electronics are concerned, for a wireless
photos (see Figure 2 for an example), of the remote control and components from reputa-
entire mechanical construction from [3]. I ble companies. If you thought this could be
have also started designing the electron- a low-cost solution, I have to disappoint you:
ics. In case you fear the thought of tiny SMD This project is a bit more expensive in terms
parts, I can reassure you: To keep things as of material costs. It’s better than having to run
engineer-friendly as possible, except for one up and down through a shooting range every
radio module, everything is built with classic time to get a failing system working again after
through-hole parts (Figure 3). Even that yet another malfunction.
module, with a pitch of 2 mm, is not too diffi-
cult when it comes to soldering. There were also questions about the possi-
bility of customizing the system’s mechanical
You might not suspect it, but shooting sport is components according to one’s own tastes
Figure 1: The prototype (2023). one of the safest sport disciplines and, judging and preferences. The system is based on the

86 May & June 2024 www.elektormagazine.com


Figure 2: Construction of the sliding mechanism (example). Figure 3: Rendering of the classic through-hole print.

anaconda… koala… err… coandă effect [4], Unfortunately, No Kit world’s largest “Silicon Valley” with 430 billion
although some will claim that Mr Bernouilli If you want to replicate these projects, it’s euros? Those bureaucrats in Brussels [7]
is actually behind it. Despite this, I did not useful to have access to a laser cutter. Perhaps couldn’t care less.
use any complex mathematical formulas in your local makerspace or fablab can assist Translated by Hans Adams — 240030-01
the design and followed the principle of trial you with this. I would have liked to offer you a
and error. So, above all, dare to experiment construction kit, but due to European regula-
yourself. tions, that’s unfortunately no longer possible.
Are you also annoyed by the endless series
Caffeine of irritating cookie pop-ups, caps attached to
Designing is quite exhausting and requires drink bottles, patronizing attitudes, a jungle
serious mental effort. I must confess that I am of labels on consumer products, and a sea
a caffeine junkie of the nocturnal type as well of rules? Tough luck — despite our collec-
as a lover of coffee in capsules because of the tive disdain for bureaucracy, we keep getting
ease of use. Now, ping-pong balls and coffee more of it thrust upon us. This includes the
capsules have one thing in common: they are current regulations around the recycling
both rather round in shape, which is why I had of packaging material [6], which are being
been thinking for some time about applying more strictly enforced and would require us
the operating principle of the ping-pong ball as a small company to register in multiple
dispenser to coffee capsules. The end result European countries, including the submis-
became a coffee capsule dispenser with six sion of annual declarations, not to mention
magazines of ten capsules each (Figure 4). the costs. More and more small companies
If you would like to work on this, CAD files are therefore throwing in the towel because
and photos of the mechanical design are the bureaucracy is becoming unbearable and
also available [5]. The practical purpose of unaffordable. But what’s really important, such
this device may be doubtful, but it is a nice as a stronger industry, strategic independence
gimmick for a maker or hacker space or, if in light of the upcoming American presidential
desired, for the cafeteria of your favorite shoot- elections, or investing in our own chip indus- Figure 4: Caffeine-on-demand: Coffee capsule
ing range — why not? try like South Korea, which wants to build the dispenser.

WEB LINKS
[1] Ilse Joostens, “HomeLab Tours - Work in Progress,” Elektor 5-6/2023: https://elektormagazine.com/magazine/elektor-300/61645
[2] Wikipedia: Plinking: https://en.wikipedia.org/wiki/Plinking
[3] Downloads ping-pong-ball launcher: https://bit.ly/3SRssG1
[4] Wikipedia: Coandă-effect: https://en.wikipedia.org/wiki/Coand%C4%83_effect
[5] Downloads Nespresso-machine: https://bit.ly/3SRCvuz
[6] Packaging license in the EU: The obligations in all member countries: https://verpackungslizenz24.de/en/eu-packaging-licence
[7] Bazarow: Review of the book “Bureaucracy is a squid” by René ten Bos by Bas Leijssenaar:
https://bazarow.com/recensie/bureaucratie-is-een-inktvis-2

May & June 2024 87


REVIEW

FNIRSI 1014D
Digital
Storage
Oscilloscope
loscope is powered by a USB power supply that provides 2 A at 5 V.
With dimensions of 310×145×70 mm, it is compact and portable,
yet large enough to be operated comfortably. With fold-out stands,
it sits at a good angle on the lab bench.

Specifications
Good Performance for The most important technical specifications are:
Tight Budgets > 2 Channels, each with a bandwidth of 100 MHz
> 7-inch LCD with an 800×480 resolution
> 1 GSample/s Sampling Rate
> 240 Kbit memory depth
By Günter Spanner (Germany) > 1 MΩ (1×) or 10 MΩ (10×) input impedance
> 50 mV to 400 V sensitivity
An oscilloscope is an essential tool > 50 s to 10 ns time base
in an electronics lab. For developing > Trigger Mode: Single/Normal/Auto on rising or falling edge
> AC/DC coupling
digital and simple analog electronics, > One-button Auto setting
a bandwidth of 100 MHz and two > Frequency generator with 14 waveforms up to 10 MHz (sine)
channels are entirely sufficient. A > USB export

frequency or function generator is also As is customary with digital oscilloscopes, in addition to signal
practical in many applications. With the representation, values such as voltage (peak, RMS, minimum,
FNIRSI 1014D, you get both functions in maximum, etc.), frequency, and duty cycle are displayed numer-
ically (Figure 1). Users can select which values to display from a
one device. We take a look. menu. Two cursors allow precise measurement of time intervals

Besides a soldering station, a multimeter, and a power supply,


the next essential tool to consider in an electronics workshop
is an oscilloscope [1]. However, for a hobbyist workshop, there
is no need for a device with a 500 MHz bandwidth, numerous
channels, or sophisticated analysis functions. For activities such
as tinkering with amplifiers, sensors, and microcontroller boards
such as Arduinos, ESPs, and Raspberry Pis, or repairing consumer
electronics, an oscilloscope with a 100 MHz bandwidth and two
channels is perfectly adequate. For many applications, a frequency
or function generator for generating test signals or checking
filters also comes in handy. With the FNIRSI 1014D [2], you get
both functions in one device.

The scope comes with two switchable probes (1× and 10×), a USB
power supply, a manual, and a probe adjustment tool. The oscil- Figure 1: Waveforms and measurement results.

88 May & June 2024 www.elektormagazine.com


Figure 2: A 100 MHz, 5 V signal on the FNISRSI 1014D. Figure 3: X/Y operation and Lissajous figure.

and voltages. An auto-set function automatically configures the criterion, even though it displays a 100 MHz signal in an accept-
oscilloscope to sensible parameters based on the input signal. Even able way (Figure 2).
a simple FFT representation of the signal can be displayed.
For further details, see the section “For professionals: Bandwidth
The FNIRSI 1014D can handle a maximum input voltage of 400 V. and Sampling Rate” below.
Triggering can be set on the rising or the falling edge. The scope
also features an automatic triggering function that works reliably. The minimum sensitivity of 50 mV / div is not spectacular. Typically,
a sensitivity of at least 10 mV / div is available on most DSOs. Never-
Power Supply: USB PSU or Power Bank theless, the measured values are within the specified tolerances,
In addition to the standard USB power supply, the scope can and the analysis options are satisfactory.
also be operated by a power bank. In this case, the oscilloscope
is completely electrically isolated, allowing measurements in Saving and Analyzing Signals
switching power supplies, etc., without the need for an isolation All measurements can be saved as a screenshot and/or waveform
transformer. This alone makes the FNIRSI 1014D worthwhile for and accessed through a gallery view. When saving a waveform, it
this application, saving the expense of costly differential probes, can be analyzed even after the measurement, as if the measurement
which, even in a budget version, cost as much as the oscilloscope. signals were still present (Figure 3). For waveforms and screen-
Additionally, by using a power bank, the scope becomes very porta- shots, 1 GB of internal memory is available, and this can be read
ble and can be used in any location, such as power racks or cars. out via a computer. During USB operation, the FNIRSI 1014D is
simply recognized as a removable disk, and no drivers or additional
Using a standard 12 Ah (I max > 2 A) power bank, the FNIRSI 1014D software are required.
runs for about 5 hours in continuous operation. This will be suffi-
cient for most applications. No advanced functions, such as mathematical functions, bus decod-
ing, etc., are available, which is acceptable given the price point.
Nevertheless, a simple Fourier transform display is provided. As
Warning: The FNIRSI 1014D manual states that “the original power it does not allow detailed measurement applications, its value is
supply must be used.” So, using a power bank is at your own risk, limited to simple harmonic analysis (Figure 4).
even though no problems came up during the tests.

Performance Check
Regarding the specified bandwidth of 100 MHz, some things
should not be overlooked. To measure a signal with a maximum
frequency component of 50 MHz, an oscilloscope with a bandwidth
of 100 MHz is required. If a measurement is to be truly meaningful
and well-resolved, the commonly used guideline is the 1:5 rule.
An oscilloscope with a 100 MHz bandwidth can effectively and
accurately display a signal with a maximum frequency compo-
nent of 20 MHz.

For measurements on Arduinos, audio amplifiers, Raspberry Pis,


etc., a 100 MHz bandwidth is fine. Nevertheless, the specified
bandwidth of the FNIRSI 1014D of 100 MHz is somewhat on the
high side. The device barely meets the classical −3 dB bandwidth Figure 4: The FFT display is quite simple.

May & June 2024 89


For Professionals: Bandwidth and Sampling Rate adjusted. The FNIRSI 1014D obviously uses fixed averaging. This
As mentioned earlier, the specifications regarding bandwidth usually indicates that there is something to hide. In this case, the
(100 MHz) and sampling rate (1 GSamples/s) are a bit “stretched.” FNIRSI 1014D implements some mathematical tricks to compensate
In the context of oscilloscopes, the terms sampling rate, bandwidth, for the limited bandwidth and sampling rate or the low sensitivity.
and oversampling are crucial, as they influence the performance
and accuracy of these devices. Finally, bandwidth refers to the frequency at which the ampli-
tude of the oscilloscope’s input signal is attenuated by 3 decibels
Here are some basics: Sampling rate refers to the number of data (dB) compared to its low-frequency value. In other words, it is
points an oscilloscope records per second and is measured in the frequency at which the voltage of a sinusoidal input signal
samples/s (1 GSamples/s = 1,000,000,000 samples per second). is reduced to approximately 71% of its original value. For oscil-
A higher sampling rate allows for a more accurate reconstruction loscopes, the −3 dB bandwidth is a critical parameter because
of fast signals. The sampling rate must be sufficiently high to repre- it indicates the range of frequencies that the oscilloscope can
sent a waveform appropriately. According to the Nyquist-Shannon accurately capture and display. In practical terms, a signal with
sampling theorem, the sampling rate should be at least twice the a frequency equal to the −3 dB bandwidth is still displayed on the
highest frequency component of the signal to be analyzed to ensure oscilloscope, but its amplitude is reduced by approximately 30%
correct reproduction. Therefore, for a signal with a maximum compared to lower frequencies. Beyond the −3 dB point, the oscillo-
frequency of 100 MHz, a sampling rate of at least 200 MSamples/s scope’s ability to faithfully represent higher-frequency components
(megasamples per second) is required. of a signal diminishes (Figure 5). This usually implies that the pass
band is flat. This is the FNIRSI 1014D’s main issue: The frequency
Oversampling involves the oscilloscope operating with a sampling response is not smooth and barely meets the 100 MHz mark.
rate significantly higher than the minimum sampling rate required
for displaying the signal. It allows oscilloscopes to capture signals The dashed green line in Figure 5 indicates the usual roll-off of an
with higher accuracy, especially when it comes to displaying rapid oscilloscope. The blue data line was measured on the FNIRSI 1014D.
signal changes. So, even if the −3 dB criterion for a 100 MHz signal is met, the
wobbly pass band may lead to incorrect measurement results at
An oscilloscope can capture the signal with a high sampling rate higher frequencies.
and then use digital signal processing techniques to generate a
more accurate representation of the signal. This enables better The Function Generator
capture of details and rapid signal events. In summary, the sampling One of the most intriguing features of the FNIRSI 1014D is its
rate indicates how many data points per second an oscilloscope integrated function generator. Although it may not be as crucial
records, while oversampling is a technique where the oscilloscope as an oscilloscope itself, a generator is a standard tool in most
operates with a higher sampling rate to capture and display more electronics labs. Whether for testing amplifiers, resonators, or
accurate signal information. serving as a reference clock for digital circuits, a function gener-
ator is indispensable.
So, a sampling rate of 1 Gigasample/s (= 1000 Megasample/s) is
well-suited for a 100 MHz bandwidth (5× oversampling). Unfor- The FNIRSI 1014D generator offers the following features:
tunately, the FNIRSI 1014D has a real-time sampling rate of only > Fixed peak-to-peak amplitude of 2.5 V
200 MSamples/s, not 1 GSample/s. It employs two two-channel > Frequency range: 1 Hz to 10 MHz (sine); 1 Hz to 2 MHz (all
analog-to-digital converters with 100 MHz in interleaved mode. The others)
scope employs a medium-performance ADC and uses successive
shifted sampling, requiring a stable signal to combine the actual
waveform.

A real-time oscilloscope, as the name suggests, digitizes the input


in real time by sampling fast enough to accurately capture and
display an incoming signal. Each data point on the display has
been sampled directly after the previous one. These instruments
are sometimes called single-shot scopes based on their ability to
capture a signal with a single acquisition. A sampling oscilloscope,
on the other hand, uses a “sweep” across a time window. This is
done by adding a small, fixed delay with each iteration. This works
only with repetitive signals. Using this technique, an “effective”
sampling rate of 1 GSamples/s is achieved by the FNIRSI 1014D.

Another issue is averaging. Usually, the averaging depth can be Figure 5: FNIRSI 1014D’s measured bandwidth.

90 May & June 2024 www.elektormagazine.com


Cons

> No math functions (add, subtract, etc.)


> Fixed averaging
> “Unusual” pass band shape
> 1 GSample/s only in sampling mode

Affordable and Portable


The FNIRSI 1014D will probably not find its way into many high-end
research and development laboratories. However, for those looking
for an affordable, entry-level device, it serves its purpose well. Its
strengths do not lie in high-frequency measurements or extreme
Figure 6: Integrated function generator. precision of signal magnitudes. Nevertheless, for most tasks involv-
ing and Arduino [3], ESP32 [4], or Raspberry Pi [5], the device can
undoubtedly provide useful services.

> 14 function types: sine, square, triangular, saw-tooth, step, All in all, the FNIRSI 1014D is an affordable, portable digital oscillo-
half-wave, full wave, exponential, logarithmic, exp-log, square scope with two channels and sufficient features and performance.
root, multi-audio, sync pulse, custom It is well-suited for hobby workshops, schools, electronics enthu-
> Duty cycle: 1% to 99% (square wave) siasts, or common repair tasks.
240074-01
Unfortunately, the generator’s amplitude is fixed at 2.5 Vpp, limit-
ing its versatility to a certain extent. Nevertheless, most standard
applications, such as checking resonance curves on audio ampli- Questions or Comments?
fiers, remain possible. Thanks to the variable duty cycle, pulses If you have any technical questions, you can contact the Elektor
and asymmetric square waves are also available. editorial team at [email protected].

So, the integrated frequency generator (Figure 6) can replace an


additional device on the workbench, as long as no special features
are required.
Related Products
Pros and Cons > FNIRSI 1014D (2-in-1) 2-ch Oscilloscope (100 MHz) &
All in all, the test results lead to the following impression: Signal Generator
www.elektor.com/20639
Pros

> Easy to use


> Small size, but big screen for the size
> Sharp and bright display with all information (Vpp, Vavg,
frequency, etc.) clearly visible
> Function generator with BNC connector on the front is
included
> Basic FFT function is available
> Powered by USB (5 V, 2 A), battery powering easily possible

WEB LINKS
[1] Jean-François Simon, “Select and Use an Oscilloscope: A Beginner’s Guide,” elektormagazine.com, November 2023:
https://elektormagazine.com/articles/oscilloscope-beginner-s-guide
[2] FNIRSI 1014D in the Elektor Store: https://elektor.com/fnirsi-1014d-2-in-1-2-ch-oscilloscope-100-mhz-signal-generator
[3] Arduino articles on our website: https://elektormagazine.com/tags/arduino
[4] ESP32 articles on our website: https://elektormagazine.com/tags/espressif/esp32
[5] Raspberry Pi Select Page on our website: https://elektormagazine.com/raspberry-pi

May & June 2024 91


AI

2024 An AI Odyssey
Getting Object Detection Up and Running

By Brian Tristam Williams (Elektor) even using a keyboard, as I’m using the PuTTY app [2] in Windows to
SSH into the Pi (Figure 1). Just enter the device’s host name — in my
Exploring object detection on our headless case raspberrypi — in the PuTTY window and click Open. You could
Raspberry Pi, we detail setting up the camera also use an IP address.

and tweaking TensorFlow Lite for real-time Once you’ve established a connection, you’ll need to enter your login
applications. name and password for the Raspberry Pi. It is possible to save these
credentials, and, because you’ll be doing this a lot, recommended.

In our previous installment [1], I installed Tensorflow Lite on the In the past, we needed to run sudo raspi-config and enable Camera
Raspberry Pi, which is running a version of Raspberry Pi OS with under Interface Options, but with the latest Raspberry Pi OS distros,
no graphical user interface (GUI), otherwise known as a “headless” the camera is detected automatically.
installation. This time, I’ll detail how I got the camera up and running
and trying to detect things. To give the camera a quick test on the headless system, I installed a
couple of packages:
Getting the Camera Working
The first thing I wanted to do was to get some camera packages sudo apt-get install -y libraspberrypi-bin
installed to test the camera. I’m running a headless version of Raspberry sudo apt-get install libcamera-apps
Pi OS, so I can’t just click to a camera application. This time, I’m not
After logging in again, it was time to test the camera by sending its
live output directly to my monitor, using

libcamera-hello

That worked, and it’s great that I can see the on-board camera’s live
output on the monitor (Figure 2), but that’s where that hardware
success ended, and we’ll get into that later.

Because I rebooted, I had to enter the tflite1 subdirectory again and start
the virtual environment. Due to much debugging and trial and error,
I ended up creating a new virtual environment called new-tflite-
env, so I entered it using

source new-tflite-env/bin/activate

Because this is a headless installation, I had to install opencv-py-


thon-headless in that environment, by entering

pip3 install opencv-python-headless

Then, I had to throw out the recommended scripts from the guide I
was looking at on GitHub, as the Python methods used there were
Figure 1: PuTTY user interface. intended for an OS with a GUI, and we don’t have one. We need

92 May & June 2024 www.elektormagazine.com


Figure 2: libcamera-hello tells us our camera is working.

the TensorFlow Lite package, which we already installed, as well as Figure 3: The packages installed in my virtual environment.
numpy. By this time, I had quite a list of Python packages installed,
ready to take on the job. To see what packages you have installed in
your environment, enter pip3 list at the command prompt. My list on your Raspberry Pi’s horsepower, so I would expect more from a
looks like that in Figure 3. If you don’t have numpy, install it using the Raspberry Pi 5 when compared to the 4 that I’m using.
same method as for opencv-python-headless above.
To run the script, at the prompt, just enter
Test Script
Now, onto the test script (Listing 1). Our little Python script uses the python3 objdet.py
TensorFlow Lite Interpreter to load the model and perform object
detection on input images. It continuously captures video frames from Hurdles
a camera, processes each frame to fit the input requirements of the That’s all great, in theory, but when I ran this script, it refused to detect
pre-trained TensorFlow Lite model (detect.tflite), and then uses the anything. Eventually, I tried reducing the confidence threshold to 0.2
model to detect objects within those frames. Detected objects with a instead of 0.5, and then all it would detect is “???” with varying levels
confidence score above 0.5 are printed to the console with their labels, of confidence. To debug, I then added a line to save the captured
confidence scores, and bounding box coordinates. The script uses frame to a file:
OpenCV for video capture and frame preprocessing, and TensorFlow
Lite’s Python API for model inference. cv2.imwrite(ˈtest_frame.jpgˈ), frame

Key components of the script include: I put this right after the cap.read() instruction. Running that and
checking the output, I found out that it was saving a 5,427-byte file
> TensorFlow Lite Interpreter Initialization: Loads the detect.tflite that looked like this, according to the file command:
model and prepares it for inference.
> Video Capture Setup: Initializes video capture from the webcam test_frame.jpg: JPEG image data, JFIF standard 1.01,
using OpenCV (cv2.VideoCapture(0)). aspect ratio, density 1x1, segment length 16, baseline,
> Frame Preprocessing: Converts captured frames to RGB, resizes precision 8, 640x480, components 3
them to match the model’s input dimensions, and wraps them in
a batch format expected by TensorFlow Lite. That all looks as one would expect, albeit that it’s a rather small file,
> Object Detection: Feeds the preprocessed frames into the so I suspected nothing amiss there until I took a look at the file on my
TensorFlow Lite model and retrieves detection results. PC. I used SCP in Windows Command Prompt to bring the file over:
> Result Processing: Iterates over detection results, filtering by
a confidence threshold of 0.5, and prints the label, confidence C:\Users\Brian>scp briantw@raspberrypi:/home/briantw/
score, and bounding box for each detected object. tflite1/test_frame.jpg .

The script uses real-time processing suitable for applications requiring What this does is, after you enter your password, collect the file from
immediate object detection feedback from video streams, showing the Raspberry Pi and write it to the current directory (.) in Windows
objects identified and their locations in the image, with the help of — in my case my default user directory. When I opened the file, much
bounding boxes. How many detections you can do per second depends to my surprise, it had captured nothing but a black image.

May & June 2024 93


Figure 4: A cat with a snowboard. Figure 5: Not a bicycle in sight.

I tried to remedy this using everything from Google searches to I would like to digitize them and have AI run the gamut of classification
ChatGPT, and I could not get the camera to give my Python script tasks from object detection to speech-to-text transcription, all added
anything but a black image. I even tried activating seconds-long delays to an online metadata database that’s searchable.
in the code to give the camera time to “warm up” and initialize, to no
avail. I also did an update and an upgrade again, and even updated While the detection accuracy currently leaves me much to desire, the
the firmware using sudo rpi-update and then did a sudo reboot. awesome thing is that you can change the detection source from live
Oddly, the camera does work, as libcamera-hello continues to prove, camera to video file by changing just one line in the script — the one
so this is a software mystery to me. with the VideoCapture() call. I tried a sample video file, one taken on
the grounds of Churchill College in Cambridge last year, and uploaded
Eventually, on a lark, I pulled out a Logitech webcam of mine, and it to the Raspberry Pi using SCP again:
plugged it into the Raspberry Pi. After rebooting the system and re-en-
tering the virtual environment, I ran the script again, and it worked. C:\Users\Brian>scp 20230919_174323.mp4 briantw@
In the script, you can select the camera in use, and, as you see in raspberrypi:/home/briantw/tflite1/20230919_174323.mp4
Listing 1, it says:
and then changed the line in Listing 1 to:
# Initialize video capture from the camera
cap = cv2.VideoCapture(0) cap = cv2.VideoCapture(ˈ20230919_174323.mp4ˈ)

This tells cv2.VideoCapture() to use camera 0. Once I plugged the and off it went, detecting objects in the video. The good news is that
USB webcam in, it became camera 0, and the onboard Raspberry Pi it was so easy to change sources. The bad news is that there was not
Camera Module 3 became camera 2. So, as it stands, the webcam a bicycle to be seen anywhere in the video (Figure 5).
(0) works, and the onboard Raspberry Pi Camera Module 3 (2) just
outputs a black image. Next Time
Now that I have the system running and able to detect objects, I will turn
Detection Results my attention to improving accuracy, and explore different models and
Well, now that the object detection is working, the system outputs the training thereof. If I’m lucky, I’ll get the system to produce pleasing
what it sees. I have pointed my webcam at everything from Elektor results that serve a productive purpose. Will I be lucky? We’ll see.
Magazine editions to movies on my monitor to things in my office, and 230181-F-01
I can report that it sure likes bicycles. It picked up “TV,” “remote,” and
“potted plant” alright, with some false positives, such as “cake” for my
camera light, and it found a “tie” where there wasn’t one. In Figure 4, Questions or Comments?
you see it confidently looking at a dog with a ball and detecting a cat Do you have technical questions or comments about this article?
with a snowboard. When scenes get busy, it reaches for “bicycle” a lot. Email the author at [email protected].

Still Work to Be Done


Obviously, there is a lot of tweaking that needs to be done, and different
models to try, and it’s even possible to train our own. As to the appli-
cations? A friend of mine has had great success at detecting people
on his home security system using OpenCV, while Elektor engineers About the Author
have had many purposes for object detection in live video as well, for Brian Tristam Williams has been fascinated with computers and
example investigating the YOLO object-detection model rather than electronics since he got his first “microcomputer” at age 10. His
OpenCV [3]. I, on the other hand, am interested in classifying objects journey with Elektor Magazine began when he bought his first issue
in archived video and photographs. at 16, and since then, he’s been following the world of electronics and
computers, constantly exploring and learning. He started working
As I mentioned last time, I have hundreds of hours of video recorded at Elektor in 2010, and nowadays, he’s keen on keeping up with the
from vintage television news, etc., that I would like to categorize, but I newest trends in tech, particularly focusing on artificial intelligence
certainly don’t have time to watch them all while carefully taking notes. and single-board computers such as Raspberry Pi.

94 May & June 2024 www.elektormagazine.com


Listing 1: Test Camera and Object Detection
import cv2
import numpy as np
from tflite_runtime.interpreter import Interpreter

# Initialize the TensorFlow Lite interpreter


model_path = ˈSample_TFLite_model/detect.tfliteˈ
interpreter = Interpreter(model_path=model_path)
interpreter.allocate_tensors()
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
input_shape = input_details[0][ˈshapeˈ]

# Load labels
with open(ˈSample_TFLite_model/labelmap.txtˈ, ˈrˈ) as file:
labels = [line.strip() for line in file.readlines()]

# Initialize video capture from the camera


cap = cv2.VideoCapture(0)
while True:
ret, frame = cap.read()
if not ret:
break

# Preprocess the frame


frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frame_resized = cv2.resize(frame_rgb, (input_shape[1], input_shape[2]))
input_data = np.expand_dims(frame_resized, axis=0)

# Perform detection
interpreter.set_tensor(input_details[0][ˈindexˈ], input_data)
interpreter.invoke()

# Retrieve detection results


# Bounding box coordinates of detected objects
boxes = interpreter.get_tensor(output_details[0][ˈindexˈ])[0]
classes = interpreter.get_tensor(output_details[1][ˈindexˈ])[0] # Class index of detected objects
scores = interpreter.get_tensor(output_details[2][ˈindexˈ])[0] # Confidence of detected objects
count = int(interpreter.get_tensor(output_details[3][ˈindexˈ])[0]) # Total number of detected objects

# Loop over all detections and print detection info


for i in range(count):
class_id = int(classes[i])
score = scores[i]
bbox = boxes[i]
# Filter out weak detections by ensuring the confidence is greater than a minimum threshold
if score > 0.5:
label = labels[class_id]
print(f"Detected: {label} with confidence {score}, Bounding Box: {bbox}")

cap.release()

WEB LINKS
[1] Brian Tristam Williams, “First Forays Into TensorFlow,“ Elektor 3/2024: https://elektormagazine.com/magazine/elektor-333/62725
[2] PuTTY — Terminal program for remote access to your headless Pi: https://putty.org
[3] Saad Imtiaz, “CaptureCount,” Elektor 3/2024: https://elektormagazine.com/magazine/elektor-333/62717

May & June 2024 95


PROJECT

10 MHz Reference Generator


Highly Accurate, With Distributor and Galvanic Isolation

By Alfred Rosenkränzer (Germany)


level Oscillator Outputs

In complex measurement
Quartz Oven
FTM301 / AOCJY Divider
Ref. Voltage OSC

setups where frequencies


/2 Filter
VDD RF OUT

AGC

and times must be accurately


VREF

VC GND

recorded and precisely


correlated, the measuring Quartz Oscillator

devices should operate in


near synchronization. They OE

are synchronized using a


FO

XO91SMD
highly accurate reference
frequency. This article AGC

explains the construction of


such a reference generator. Ref. Input

Balun + Filter
AD8368

180385-008 Enable

If there are no conflicting reasons, the device


with the most accurate time base is declared
the master in such measurement setups and
its output signal serves as a reference for the
other devices. The signal distribution can be
implemented in the form of a “daisy chain,”
for example, in which each device passes the Figure 1: Block diagram of the reference
reference frequency at its input through to its generator. Amp level Balun + Filter

output, creating a serial chain. The alterna-


tive is a star connection using a distribution
amplifier, so that several reference signals are
available in parallel. A frequency of 10 MHz signals are thus impaired by unwanted inter- seem to be available on the market at present.
has been established as standard reference. ference signals. This shortcoming inspired me to develop a
reference generator that is not only equipped
Ground Issues For reference signals, ground loops can be with a high-precision, heated oscillator, but
A frequently encountered problem in such prevented by galvanic isolation using HF also offers several ungrounded outputs.
measurement setups are ground loops, which transformers. Such transformers are available
can severely interfere with sensitive measure- in small housings with BNC connectors, for Basic Circuit
ments. Background: The grounds of the input example from Mini-Circuits. For a daisy chain A block diagram of the generator circuit is
and output sockets are connected to the arrangement, they must be inserted between shown in Figure 1. The generation of the
protective earth (PE) of the mains socket, the each pair of devices. When using a distribu- 20 MHz base clock can be seen at the top
plug connectors of the data interfaces (GPIB, tor, such a transformer is inserted between left, with a simple quartz oscillator or a more
USB) and the grounds of the sockets of the the distributor and each reference input of a complex, calibratable oven-controlled crystal
reference signals. Magnetic interference fields measuring device. Distributors with integrated oscillator (OCXO). After halving to 10 MHz and
can couple into the resulting ground loops RF output transformers for simplified, ground- filtering, the reference frequency is ready for
or equalizing currents can flow; the useful free connection of measuring devices do not buffering and distribution (right-hand side).

96 May & June 2024 www.elektormagazine.com


Component List
Resistors C28, C31 = 100p
SMD 0603, unless otherwise specified C29 = 12p
R1, R3, R9, R53, R309, R314, R315 = 10k C30 = 39p
R2, R310 = 4k7 C66, C68, C70, C72, C74, C76, C78, C87 = 47p
R4 = 820 Ω C67, C69, C71, C73, C75, C77, C79, C88 = 3p3
R5 = 0 Ω, SMD 2012 * C81, C89, C94 = 10n
R6, R7 = 1k2 C84…C86, C91..C93 = 1n
R8, R14, R52, R64, R75, R86, R97, R108, R123 = 390 Ω
R10, R17 = 100 Ω Inductors
R11, R18, R54, R57, R58, R61, R63, R66, R69, R72, R74, R77, R80, R83, R85, All SMD 1210
R88, R91, R94, R96, R99, R102, R105, R107, R110, R115, R118, R121, R124, L1…L7, L301 = 4µ7
R126, R129, R130 = 50 Ω L8 = 1µ8
R13, R67, R68, R78, R79, R89, R90, R100, R101, R111, R112, R113, R114, R119, L9 = 1µ5
R120, R307, R308, R318 = 0 Ω *
R15 = 130 Ω Semiconductors
R16 = 2k5, multi-turn trim pot, vertical, RM 1/10″ D1…D4 = SK56, Schottky, 60 V / 5 A, DO214AA *
R25 = 1k D5…D8 = SK56, Schottky, 60 V / 5 A, DO214AA
R50 = 120 Ω D9, D10 = SK540, Schottky, 40 V / 5 A, DO214AC
R51 = 200 Ω, multi-turn trim pot, vertical, RM 1/10″ D31 = 1N4148, SOD-123
R55, R56, R60, R65, R71, R76, R82, R87, R93, R98, R104, R109, R116, R117, LED1…LED3 = LED, SMD 0805
R122, R127 = 470 Ω T1…T2 = 2N3904, SOT23-BEC
R59, R70, R81, R92, R103, R128 = 330 Ω IC1 = 7805
R62, R73, R84, R95, R106, R125 = 500 Ω, multi-turn trim pot, vertical, IC2 = 7905
RM 1/10″ IC3 = LT1963AET-3.3 *
R301, R306 = 150 Ω IC4…IC11 = MAX4392ESA, SOIC8
R302, R305 = see text IC6 = MCP1525TT, SOT-23-3 *
R303, R304 = 75 Ω U1 = AD8368ACPZ-WP, LFCSP-24 *
R311…R313 = 10 Ω, SMD 2012 U2 = SN74LVC1G80DBVR, SOT-23-5 *
R316 = 68 Ω Y1 = AOCJY-20.000MHZ-F, SMD *
R317 = 180 Ω XO1 = XO91, 20 MHz, SMD *

Capacitors Miscellaneous
SMD 0603, unless otherwise specified X1 = 2-pin screw terminal, RM 5 mm
C1 = 4,700 µ / 16 V, electrolytic, RM 5 mm, ø 13 mm * X5 = 3-pin screw terminal, RM 5 mm
C2, C4, C8…C11, C19…C22, C34, C35, C51…C54, C56…C65, C82, C83 = JP1, JP2 = 2-pin header
100n Tr1 = transformer 2× 6 V, 2 x 300 mA, RM 20 mm, PCB mounting *
C3, C5, C12…C18, C33, C36…C40 = 22µ / 20V, SMD SMCB Tr3 = transformer 2× 6 V, 2 x 233 mA, RM 27.5 mm, PCB mounting
C6, C7 = 2,200 µ / 16 V, electrolytic, RM 5 mm, ø 13 mm Tr51…TR81 = ADT1-1, RF transformer, SMD *
C23, C32 = 33p F1 = fuse 250 mA, 20× 5 mm
C24 = 120p Fuse holder for F1, PCB mounting
C25, C90 = 5p6 K1 = relay FTR-B4S, SMD
C26 = 10p
C27 = 150p * See text

Alternatively, the circuit can also be used 3.3 V power supply around Tr1 and IC3. The an external reference signal via AGC takes
simply as a distribution amplifier. If you have heating of an optional OCXO is also fed from place via the +5 V branch, with small RC filters
a high-quality external reference frequency this branch. Its configuration ensures that an (R311/C85 and R312/C84) included. Two LEDs
available, you can feed it into the reference accurate and low-drift reference frequency on the circuit board indicate that the system is
input at the bottom left. After amplitude stabi- is obtained. ready for operation. An additional LED can be
lization by a special RF amplifier (AGC), this mounted on the front panel. When all output
signal is fed to the distribution amplifier bank The analog amplifiers are supplied symmet- stages are fitted, a current of around 180 mA
on the right as a reference. rically with ±5 V from Tr3 and the two classic flows in the ±5 V branch.
voltage regulators IC1 and IC2. To ensure clean
Circuit voltages, a large number of small decoupling Oscillators
As you can see in the circuit in Figure 2, the electrolytic capacitors, each with 22 µF and A high-precision, heated quartz generator
digital and analog parts are supplied separately. 100 nF multilayer capacitors, are distributed of type FTM301 from FOX or, for example,
The clock generation is supplied by the across the circuit. The level stabilization of type OH300-50503CF-020.0M [1] from

May & June 2024 97


+3V3 C25 C29
+3V3
C21
5p6 12p
100n C26 C30
C18 C19
R13 5
22µ 100n 10p 39p
1 VCC
20V D C22


R14 L8 1µH8 L9 1µH5
4
+3V3 MCP1525TT R18 U2 /Q 390Ω
3 4 2
50Ω CLK 100n
VDD RF OUT GND R51 OSC
IC6 R17 R15 R50
2 3 C23 C24 C27 C28 C31 C32 200Ω
VREF Y1

130Ω

120Ω
100Ω
R52
VC GND 33p 120p 150p 100p 100p 33p AGC

390Ω
1 5
C34 C35 U2 = SN74LVC1G80DBVR
R16

100n 100n 2k5 AOCJY


20.000MHz-F

+3V3

R9

XO91SMD
10k

4
+5V C94 +5V
VCC R11
XO1 1
50Ω
OE 10n
C20
3
R312 R311 R317 R313
FO R10
100n

10Ω

180Ω
23

10Ω

10Ω
100Ω

VPSI
11 10
GND VPSI_2 VPSO
12 9
2 VPSI_3 VPSO_2
13
R303 R307 VPSI_4
22 1
75Ω 0Ω VPSI_5 GAIN
LSP1 C81 C87 U1
R304 L301 4µH7
19 8
75Ω INPUT OUTPUT
R318
10n 47p R314
R301 R302 R305 R306 24
TR1 C88 10k ENABLE


150Ω

150Ω
nb

nb

5 2
ADT1-1 3p3 DETI DETO
R316
LSP2
68Ω

AD8368ACPZ-WP
R308
4 3
0Ω DECL HPFL
14
DECL_2
15 7
DECL_3 OCOM
6
OCOM_2
20
ICOM
16 21
ICOM_2 MODE
17
ICOM_3 +5V
18 25
ICOM_4 EP

R25
T2 R310

1k
4k7
R309 R315
C82 C84 C85 C92 C90 C91 C89 C93 C86 C83 AGC
2N3904
10k

10k

100n 1n 1n 1n 5p6 1n 10n 1n 1n 100n

TR1 OSC

D3 D1 LT1963AET-3.3 +3V3
X1
IC3
2 4
IN OUT
R1 R4 +5V
820Ω

1 5
10k

/SHDN SENSE
D4 D2
JP2
GND
C1 C2 C3 C4 C5
T1 3
2 x 6V R2
2 x 300mA 4700µ 100n 22µ 4k7 100n 22µ
16V 20V R3 20V
D31 K1
LED1
D1...D8 = SK34 2N3904
10k

1N4148 FTR-B4S

TR3
R5
F1 +5V
250mA

D8 D5

X5
7805
IC1
R6
1k2

D7 D6 C6 C8 C10 C12 C14 C16 C33 C36 C37 D9

LED2
2200µ 100n 100n 22µ 22µ 22µ 22µ 22µ 22µ MBR0540
2 x 6V 16V 20V 20V 20V 20V 20V 20V
2 x 233mA
LED3 JP1

C7 C9 C11 C13 C15 C17 C38 C39 C40 D3 LED Front


R7
2200µ 22µ 22µ 22µ 22µ 22µ 22µ R8
100n 100n
390Ω

MBR0540
1k2

16V 20V 20V 20V 20V 20V 20V

IC2
7905

–5V

Figure 2: The detailed circuit of the reference generator is somewhat more extensive, but the seven output amplifiers are constructed in the same way.

98 May & June 2024 www.elektormagazine.com


+5V
C51 C52 C53 C54 C56 C57 C58

8 8 8 8 8 8 8
100n 100n 100n 100n 100n 100n 100n
IC4 IC5 IC7 IC8 IC9 IC10 IC11
4 4 4 4 4 4 4
C59 C60 C61 C62 C63 C64 C65

100n 100n 100n 100n 100n 100n 100n

–5V
Connor-Winfield (Y1 in Figure 2) is used as
50Ω
R54
3
R118
R113

the oscillator. For lower quality requirements,
a simple 20 MHz quartz oscillator (XO1 in
1 5
IC5A 50Ω R115 C66
L7
2 7
LSP15
Figure 2, [2]) is also sufficient. Of course, only
IC5B 50Ω
4µH7
6
R56 47p

one of the two alternatives has to be fitted. If


470Ω R116 C67 TR51
470Ω

R53 R55 R57 R117 3p3 ADT1-1 Y1 is fitted, the circuit will draw up to 800 mA
50Ω
470Ω

470Ω

from the 3.3 V branch for a few seconds after


10k

LSP16
R114

switching on during heating. The current is
R58
3
R67 then reduced to approx. 350 mA.
50Ω R61 R63 0Ω
1 5
IC4A 50Ω 50Ω R66 C70
L1
2 7

R60
6
IC4B 50Ω

47p
4µH7
LSP3
The frequency of Y1 can be influenced to a
470Ω
R62
R65 C71 TR53 small extent via input VC (pin 1) with a control
voltage of 0…2.5 V generated by IC6 and
470Ω
500Ω ADT1-1
R59 R64 3p3
330Ω

390Ω

LSP4
adjustable with R16. If XO1 is fitted instead of
R68 Y1, IC6 and the trimming potentiometer R16
can be omitted. Some oscillators contain their

R69 R78
3
50Ω
IC7A
1
R72
50Ω
R74
50Ω
5
R77 C72

own reference voltage, which can be tapped at
L2
pin 2. In this case, IC6 can be omitted and R17
2 7
IC7B 50Ω LSP5
6 4µH7

can be fitted instead. For oscillators without


R71 47p
470Ω R76 C73 TR54

their own reference voltage, IC6 must be


R73 470Ω
500Ω ADT1-1
R70 R75 3p3
fitted and R17 can be omitted. The reference
330Ω

390Ω

LSP6
R79 frequency can be calibrated with R16, which
R80

R89
of course requires a suitable and, above all,
50Ω
3
1
R83 R85
5
0Ω highly precise external reference frequency.
IC8A 50Ω 50Ω R88 C74
L3
2 7
IC8B 50Ω LSP7
6 4µH7

470Ω
R82
R87
47p
C75 TR55
If absolute accuracy is not very important, the
R84
500Ω
470Ω simple and inexpensive XO1 crystal oscillator
ADT1-1
in an XO91 housing will also do. Once again:
R81 R86 3p3
330Ω

390Ω

R90
LSP8
Only one oscillator is to be fitted — either Y1
0Ω or XO1. Due to the lower current consumption,
no extra transformer TR1 is required for XO1
R91 R100
3
50Ω R94 R96 0Ω
1 5
and the rectifier from D1...D4 is also omitted.
IC9A 50Ω 50Ω R99 C76
L4
2 7
IC9B 50Ω LSP9
Instead, R5 is fitted to derive the required 3.3 V
6 4µH7
R93 47p
C77
from the 5.5 V branch. R11 is fitted when XO1
470Ω R98 TR56
R95 470Ω

is used and R18 when Y1 is used.


500Ω ADT1-1
R92 R97 3p3
330Ω

390Ω

LSP10

In order to achieve an optimum duty cycle


R101

R102
50Ω
3
R105 R107
R111

of 50% of the 10 MHz signal, the 20 MHz of
the primary clock generator is divided by a D
1 5
IC10A 50Ω 50Ω R110 C78
L5
2 7
LSP11
flip-flop. An alternative is to fit 10 MHz gener-
IC10B 50Ω
4µH7
6
R104 47p

ators, which means that U2 is omitted and


470Ω R109 C79 TR57
R106 470Ω

R103
500Ω
R108 3p3 ADT1-1 its input is connected to the output pin by
330Ω

390Ω

LSP12 fitting R13. The 10 MHz signal is then freed


R112

from harmonics by a passive fifth-order Cauer
R129
3
R119 low-pass filter around L8 and L9, turning the
rectangular signal into a sine wave. The cut-off
50Ω R126 R124 0Ω
1 5
IC11A 50Ω 50Ω R121 C68
L6
2 7

R127
6
IC11B 50Ω

47p
4µH7
LSP13
frequency of the filter is 11 MHz, its ripple is
470Ω
R125
R122 C69 TR52 only 0.1 dB, and the input and output imped-
ance is 100 Ω. The voltage divider R14/R15
470Ω
500Ω ADT1-1
R130 R128 R123 3p3
330Ω

390Ω

reduces the input signal, and C22 removes the


50Ω

LSP14
R120 DC voltage components (= half the operat-
ing voltage).

180385-009

R50, R51, and R52 terminate the output of the


filter. The amplitude can be adjusted with trim

May & June 2024 99


Figure 4: A partially assembled circuit board installed in
Figure 3: The partially assembled circuit board of the prototype. a Teko housing.

pot R51 and adapted to the input level range Reference Input and AGC One more note on the design: Good thermal
of the AGC. The relay K1 and a switch on the An AGC IC of type AD8368 [5] from Analog insulation of the OCXO will reduce its power
front panel can be used to select between Devices (U1) is used for this subcircuit. The consumption. It has reached its maximum
the signal from the internal generator and the wiring in Figure 2 corresponds to the recom- accuracy after 30 minutes at the latest.
reference input. mendation in the data sheet. In order not to
overdrive the input, an attenuator of 6 dB is Fitting Options
Distribution Amplifier connected before the HF input transformer As has already become clear, the circuit
IC5A amplifies the signal by a factor of 2 and Tr81. If galvanic isolation is not required, the board provides for several fitting options.
distributes it to six of the seven output stages transformer can also be omitted here and The optional components are marked with
via a line terminated with 50 Ω (R130) to avoid replaced by the two resistors R307 and R308. an asterisk in the parts list. For the sake of
reflections on the PCB traces and to achieve Level stabilization via AGC works with input clarity, the fitting options are specified here
as equal a level as possible at all inputs of signals between 70 and 2,000 mVSS at 50 Ω. once again:
the seven output stages. The 50 Ω resistor Lower input levels will reduce the output level
of these stages is used to decouple the input — higher input levels will increase it. OCXO or Simple Quartz Generator
capacitance of the op-amps installed there. For the OCXO Y1, Tr1, the diodes D1…D4, and
Six of these stages are fitted with two video Power Supply C1 must be fitted. R5 is omitted. For XO1, Tr1,
op-amps each. The amplitudes of these six After switching on the circuit with a cold D1…D4 and C1 are omitted. R5 is fitted instead.
channels can be individually adjusted with OCXO, significantly more current flows than
their 500 Ω trimpots. later in the tempered state. For this reason, Oscillator with 20 or 10 MHz
a relatively powerful transformer with For 20 MHz oscillators, the divider U2 must be
The second op-amp of IC5 drives a serial Schottky diodes and a large filter capacitor fitted. R13 is omitted. For 10 MHz oscillators,
bandpass filter consisting of the two paral- is provided. The stabilized 3.3 V is gener- U2 is omitted. R13 must be fitted.
lel-connected capacitors C66 and C67 plus ated by the LT1963AET-3.3 low-drop regula-
the coil L7 and finally the HF transformer tor (Analog Devices). The regulator must be Reference Voltage of the OCXO
Tr51 of type ADT1-1 [3] via a 50 Ω resistor. cooled. For this purpose, it can be screwed If the OCXO has an internal reference voltage
This output stage has no trimmer potentiom- onto the rear wall of an aluminum housing source, IC6 is not required and R17 must be
eter and its output voltage is therefore not with insulation. Its output voltage can be fitted. Without an internal reference voltage
adjustable. switched off via the shutdown input if you source, IC6 is required. R17 should not be fitted
want to use the external reference frequency in this case.
Generally speaking, if you don’t need galvanic and operate the circuit as a distribution ampli-
isolation, you can leave out the HF trans- fier only. This measure prevents interfer- Internal or External Frequency Generation,
formers Tr51 to Tr57 and fit two 0-Ω resistors ence between the internal generator signal or Both
instead. In my prototype, I used MAX4392ESA and the external reference signal. Relay K1 It is possible to equip only the internal oscil-
[4] op-amps in a SOIC8 package. However, is controlled by a switch on the front panel, lators or only the input for an external refer-
you can also use other video amplifiers that which is connected to JP2. A changeover ence with AGC, or both parts. When using an
are suitable for a power supply of ±5 V. With contact of the relay selects the input signal internal generator, the AGC is switched off.
galvanic isolation and a metal front/rear panel, for the distribution amplifier. The other contact When using the external input with AGC, the
it is obviously necessary to ensure that the controls the SHDN input of IC3 via T1 and the 3.3 V power supply and thus the oscillators
BNC sockets are insulated! ENBL input of the AGC via T2. and the divider are switched off.

100 May & June 2024 www.elektormagazine.com


Galvanic Isolation The reference generator described in this
If galvanic isolation is not required, the RF article is versatile, very accurate, and avoids Related Products
transformers can be omitted. In this case, the ground loops in complex test setups. By the
two 0 Ω resistors per transformer must be way, some empty boards are still available from > JOY-iT JDS6600 Signal Generator
fitted to bridge them. In this case, the correct the author. & Frequency Counter
www.elektor.com/18714
polarity must be observed when connecting Translated by Jörg Starkmuth — 180385-01
the BNC sockets. > OWON SDS1202 2-Channel
Oscilloscope (200 MHz)
R302 and R305 Questions or Comments? www.elektor.com/20251
These resistors are used to achieve an exact Do you have questions or comments
resistance value by connecting them in paral- about this article? Email the author at
lel with R301 and R306. The specified values [email protected], or contact
of R301 and R306 are accurate enough for the Elektor at [email protected].
attenuation of 6 dB envisaged here. R302 and
R305 can therefore be omitted.
About the Author
Construction Alfred Rosenkränzer worked for many years
Figure 3 shows the partially assembled board, as a development engineer, initially in the
the layout files of which can be downloaded field of professional television technology.
free of charge in Eagle format from the Elektor Since the late 1990s, he has been devel-
website [6]. Figure 4 shows a board installed oping digital high-speed and analog
in a plastic case with metal front and back circuits for IC testers. Audio is his private
panels. As already mentioned, the BNC sockets hobbyhorse.
should be installed with galvanic isolation.

WEB LINKS
[1] OH300-50503CF-020.0M datasheet [Digikey]: https://tinyurl.com/4j6bzren
[2] AOCJY-20.000MHZ datasheet [Digikey]: https://tinyurl.com/4v4n23en
[3] HF Transformer datasheet [minicircuits.com]: https://tinyurl.com/4fzxkfky
[4] MAX4392 datasheet: https://analog.com/en/products/max4392.html
[5] AD8368 datasheet: https://analog.com/en/products/ad8368.html
[6] Elektor web page for this article: https://elektormagazine.com/180385-01

CONNECTED. WE meet @ PCIM Europe

NO MATTER
Hall 6 - 342

THE CONDITIONS. The IP67 & IP68 Protected Industrial Connection


Discover high-quality circular connectors designed for demanding environments.
With its ingress protection, our connectors ensure reliable connections for appli-
cations such as fieldbus, actuators/sensors, and robotics.

Ready to Design-In? Take advantage of personal technical support


and free samples ex-stock. www.we-online.com/circular

Highlights
• New M12 A-coding portfolio
• Adapted to work in demanding environments
with IP67 & IP68 protection
• Male & female versions of all connectors
© eiSos

• Available in 4, 5 and 8 polarities #CIRCULARCONNECTORS

May & June 2024 101


PROJECT

lab • Elektor
or

kt

lab
Ele
O R IG IN A L

ab
Ele

rl
to
r la b k to

k
• Ele

Project Update #2:


ESP32-Based
Energy Meter
Some Enhancements
Figure 1: New enclosure design rendering of the ESP32 Energy Meter.

By Saad Imtiaz (Elektor)


the size of the prototype PCB was 100×100 mm. After testing, some
In the previous installment of this components were removed and the layout of the PCB was optimized,
series, we discussed the schematics, hence the size for this version is reduced to 79.5×79.5 mm — that’s
about 20% less from last time. In Figure 1, the new enclosure for the
and circuit isolation strategies of the new version of PCB is shown. Along with that, to make the ESP32
ESP32 Energy Meter. Now let’s discuss Energy Meter safer to use, instead of powering the PCB directly with
further enhancements, a PCB design, the mains voltage, now a 220 V-to-12 V Step Down Transformer is
required for voltage sampling and also powering the circuit. Adding
and more. a transformer does have some drawbacks in terms of phase delays,
but safety first! Since we are not looking to measure voltage spikes, or
fast sags or surges, but energy, this shouldn’t hurt our measurement.
In 2023, we started with the goal of creating a reliable, user-friendly
energy meter using an Espressif ESP32 microcontroller. In our last The Updated Schematic Design
article, “Project Update: ESP32-Based Energy Meter” [1], we went over We made some upgrades, and now, rather than the ESP32, the ESP32-S3
the block diagram, the schematics, circuit isolation strategy, features, is on board. This also unlocks more potential for the Energy Meter. The
and project strategy. Let’s start with a small recap before we get into ESP32-S3 offers significant enhancements over the ESP32, including
the next update. improved processing power, AI and signal processing capabilities,
more memory, and better security features. The updated schematic
The main idea revolved around developing a precise and efficient further improves the capability of the Energy Meter along with more
energy meter leveraging the capabilities of the Espressif ESP32 functionality. The design references guides from Espressif [2] and other
microcontroller and the ATM90E32AS IC for energy measurement. useful internet resources [3…6] were used to integrate the ESP32-S3
The project aimed to enhance user experience and reliability through into the project. In Figure 2, the schematic of the project is shown.
meticulous schematic design and circuit isolation using the ADuM3151
to provide safe communication between ESP32 and the ATM90E32AS The circuit board layout has been optimized to improve the safety,
by Atmel (now Microchip). It emphasized safety and efficiency by usability, and efficacy of the ESP32-S3. We’ve made substantial adjust-
incorporating noise reduction techniques, signal integrity enhance- ments by lowering the PCB size for a more compact footprint, moving
ments, and protective mechanisms such as fuses and MOVs. With a to transformer-based power for increased safety, and adding versatility
focus on future-ready features, the plan included integrating remote with single and three-phase compatibility. The utilization of a more
monitoring and data analysis tools for improved energy management efficient AP63203WU-7 buck converter in place of Hi-Link modules,
and efficiency insights. along with the addition of user-friendly features such as a USB-C
connector and a Qwiic connector for expandability, all contributed
In this article, our main goals remain the same, and plenty of changes to the advancement of the project. These improvements build on the
have been made to make the project safer to use, reduce its produc- ESP32-S3’s capabilities, focusing on providing a practical, adaptable,
tion cost, and reduce its size. As mentioned in the previous article, and safer energy monitoring solution.

102 May & June 2024 www.elektormagazine.com


+3V3
GND
+5V
+5VA GND_B

WARNOUT

PM0
PM1
CF4
CF3
CF2
CF1
CS

ZX0
ZX1
ZX2
SDI
SDO
IRQ1
IRQ0

CLK
JP7 D2
VBUS_B
JP5 JP6 1 2 3
+3V3 +5VA 4k7 CC2
+5VA IC2 +3V3-U 1 2 3 4 5 6 7 8 1 2 3 4 5 6 7 8 1N5819HW-7-F
R31 SBU1
NJM2882F33-TE1
PM1 DP2
1 5 K2
IN OUT +3V3 DN1

Figure 2: Project schematic.


DP1 GSB1C41110SSHR
+3V3 DN2

GND
CONTROL
NOISE
D4 D5 D3 CC1
R38 PM2 4k7
2 3 4
R32 SBU2

80Ω
R37

R20
R21
R19
R18
100k VBUS_A

C26 C27 C25 LED7 GND_A

10k
10k
10k
10k
3 x SZSMF4l5.0AT3G
22µ 10n 22µ

+3V3
R22

10k
42
R2 R3 R6 R7 R10 R11 VDD18
C2 C3 C4 C6 C9 C11 C24 43 +3V3
VDD18

2Ω4
2Ω4
2Ω4
2Ω4
2Ω4
2Ω4
1 C1
41 AVDD
18n 18n 18n 18n 18n 18n 100n /RESET 48
K1 DVDD
11 100n 1 40
6 R1 3 VREF +3V3-U GND GND
I1P 1k I1P 2 39
5 R4 4 C12 C13 C8 C10 C5 C7 3V3 IO2
I1N 1k I1N 22 3 38
4 R5 5 ZX0 EN IO2
I2P 1k I2P 23 4 37
R8 6 ZX1 100n 10µ 100n 100n 100n 10µ IO4 TXD0
3
I2N 1k I2N 24 5 36
2 R9 7 ZX2 IO5 RXD0
I3P 1k I3P 6 MOD1 35
1 R12 8 IO6 IO42
I3N 1k I3N 25 7 34
IC1 CF1 IO7 ESP32-S3-WROOM-1 IO41
26 8 33
+12V 13 CF2 IO15 IO40
V1P 27 9 32
14 CF3 IO16 IO39
V1N 28 10 31
D6 D7 15 CF4 IO17 IO38
V2P 11 30
16 ABM8G R33 R34 R35 R36 IO18 IO37
2 x B140HW-7 V2N 29 16.384MHz B4Y-T 12 29
K4 17 WARNOUT IO8 IO36
V3P X1
80Ω
80Ω
80Ω
80Ω

2 4 13 28
6 R30 18 GND GND IO19 IO35
UC 100k V3N 30 14 27
R28 IRQ0 IO20 IO0 +3V3-U
5 LED3 LED4 LED5 LED6
IO9
IO10
IO12
IO13
IO14

IO11

IO46
IO21
IO47
IO48

UB 100k 31 IO3 IO45


4 R29 33 IRQ1
UA 100k PM0 1 3
3 34 XIN XOUT R16
15
16
17
18
19
20
21
22
23
24
25
26

GND R24 C22 R23 C21 R25 C23 R15 C16 R14 C15 R13 C14 PM1 20
2 OSCI
GND 21

1k
1k
1k
1k
1k
1k
10k

1 37 OSCO
DC IN /CS
38
18n 18n 18n 18n 18n 18n SCLK 9
39 IC

ATM90E32AS-AU-R
SDO 10 K3 C19 C18
40 IC 1 +3V3-U R27 R26
EN1

JP8 SDI 36 +3V3 GND


IC 2
3V3 100n 100n
80Ω
80Ω

32 S1 S2
35 TEST Qwiic 3
NC 19 SDA
45 DGND C20 4 LED2 LED1
NC 44 SCL
AP63203WU-7 46 DGND +3V3 +3V3-U
C28 NC 47
1 6 DGND 100n JP3 JP4
FB BST 12 JP1 1 1 GREEN RED
AGND GND 3V3
+12V IC3 100n L1 R39
+3V3 2 2 2
2 5 AGND 3V3 GND C17
EN SW 0Ω 3 3
SRN6028C-3R9M
SCL SCL
D1
BOOT1

4 4
3 4 R40 SCA SCA 100n
VIN GND +3V3-U

80Ω
BAT760-7
1 2 3 4 5 6
C32 C30 C29 C31 LED8
JP2
100n 220µ 220µ 100n
TX
D0

RX
EN
GND

3V3-U

240093-001

May & June 2024 103


Figure 3: Overall wiring of a three-phase voltage system and coil
transformers with the ESP32 Energy meter.

Refined Voltage and Current Sampling


IC1 remains the same ATM90E32AS, but the change is that it now
requires a 220 VAC-to-12 VAC step-down transformer, between it and
the mains. This change has been made to make the project more safe
to test and use, as the transformers provide galvanic isolation. In my
testing there was no notable difference in doing so.

Figure 4:
Thus, for each of IC1’s voltage sampling inputs, there is now only one The front and
100 kΩ resistor (R27 to R29). Last time we combined all the phase back of the
voltages into one input, and a lot of feedback was given by the readers PCB layout.
to have the option to use it with either three-phase or single-phase
power if needed. We thought about it, and now we can use it with
both. By default, three-phase mode is configured, but if one wants provided on terminal JP5 and JP6. This enables the energy meter
to make it single-phase, jumper JP8 needs to be shorted. Figure 3 to be used as a module as well with another MCU if the onboard
shows the general wiring illustration for a three-phase system. Note ESP32-S3 is not required.
that the phase wires are connected after the step-down to 12 VAC
from a transformer — using a 12 VAC doorbell transformer can be The ESP32-S3 has the USB feature built in, so it’s really convenient to
useful in this case. program the MCU this way, which is why we added USB-C connector
K2. For troubleshooting, terminal JP2 has been added. Status LEDs
For current sampling and measurement, instead of using the headphone LED1 and LED2, which can be controlled by the ESP32-S3, and push
jack as the connector, a 5.08 mm pitch screw terminal block is used, buttons S1 and S2 are added for interacting with the OLED screen,
i.e., K1. This adds to the overall ruggedness of the energy meter. For which can be connected to JP3 and JP4. Why two connection points?
current coil sensors, the YHDC SCT013 100 A : 50 mA is selected Some I2C OLED screens have ground as the first pin and some have
and the resistors R1 to R12 for all three current sensing inputs are 3V3 supply instead. This way, both types of OLED pinout variants can
calibrated accordingly. be worked with.

Power Supply Optimization Finally, the Qwiic connector at K3 has also been added to enhance
The energy meter is now powered with buck switching regulator IC3, the functionality of the Energy Meter, in case one wishes to add some
i.e., the AP63203WU-7 by Diodes Incorporated. Previously, Hi-Link additional sensors or modules to this project.
HLK5M05 modules were used, but they are much bulkier and more
expensive than this buck converter. This is done as buck converters The PCB Layout
are more efficient than these Hi-Link modules, they cost less, and The PCB layout has been meticulously optimized for compactness,
their size is much smaller. Using IC3 also lets us power the circuit with and easy soldering, shown in Figure 4. At the top, voltage and current
12 VDC at K4 for development purposes and also from the UA, i.e., sampling connections are strategically positioned in one place for DIN
voltage phase 1 of from the same connector, K4, for normal operation. rail format integration. On the right side, connections for any external
microcontroller (MCU) are facilitated through 2.54 mm pitch headers,
Interactive and Modular Features ensuring ease of access and modularity. Centrally located is the connec-
For active, reactive, apparent, active fundamental, and harmonic tion for the OLED screen, flanked by push buttons for intuitive inter-
energy pulse outputs CF1 to CF4, LEDs have been added [7][8]. For action. Adjacent to the OLED display, power and status LEDs provide
the power mode selection of IC1, jumpers PM1 and PM2 are added. immediate visual feedback, while energy pulse output LEDs are conve-
In this version, all the output pins of IC1 ATM90E32AS for MCU are niently situated near the MCU output terminals for direct monitoring.

104 May & June 2024 www.elektormagazine.com


Figure 5: 3D model of the assembled PCB.

At the foundation of the design, the USB-C port and the ESP32-S3
module are positioned away from the AC voltage areas to improve
safety. A ceramic capacitor, placed adjacent to the 3 V input of the
ESP32-S3, serves to decouple and significantly reduce any potential
noise. Additionally, electrolytic capacitors are incorporated into the
design, further stabilizing the power supply and ensuring the circuit’s
reliability and performance. This layout streamlines the assembly
process and enhances functionality and user experience by provid-
ing a clear and logical component arrangement. In Figure 5, you can
see the rendering of the assembled PCB. Questions or Comments?
If you have questions about this article, feel free to email the
This design requires the use of mains-powered author at [email protected] or the Elektor editorial team
transformers. People inexperienced with mains at [email protected].
voltages should not attempt this project or should ask
someone with experience who can help them with this
project!

Next Steps and Prospects


Following the prototype phase with the original schematic, we’ve made
several enhancements to increase the reliability of the ESP32 Energy About the Author
Meter. Currently, we are also focusing on the further development of Saad Imtiaz (Senior Engineer, Elektor) is a mechatronics engineer
its firmware. with experience in embedded systems, mechatronic systems, and
product development. He has collaborated with numerous compa-
The latest PCB design has been dispatched for production, and we nies, ranging from startups to enterprises globally, on prototyping
anticipate conducting extensive tests upon its receipt to ensure system and development. Saad has also spent time in the aviation industry
reliability. Concurrently, software development is progressing, aimed and has led a technology startup company. At Elektor, he drives
at maximizing the capabilities of the ESP32-S3 module within our project development in both software and hardware.
energy meter.

Looking forward, we plan to integrate the ESP32 Energy Meter with


Home Assistant, aiming for simplified user engagement. Neverthe- Related Products
less, we are equally committed to developing bespoke firmware to
fully utilize the device’s potential. > Qoitech Otii Arc - Power Supply, Power Meter and Data
Acquisition
www.elektor.com/19270
In summary, the project is moving forward with both hardware improve-
ments and software advancements. Our goal remains to provide a > ESP Terminal
dependable and efficient energy metering solution. This project is www.elektor.com/20526
also on the Elektor Labs platform [9], so feel free to comment and
contribute there!
> Arduino Nano ESP32
www.elektor.com/20562
240093-01

WEB LINKS
[1] Saad Imtiaz, “Project Update: ESP32-Based Energy Meter,” Elektor 1/2024: https://elektormagazine.com/magazine/elektor-324/62641
[2] ESP32 S3 DevKit-C Schematic: https://dl.espressif.com/dl/schematics/SCH_ESP32-S3-DevKitC-1_V1.1_20221130.pdf
[3] ESP32 S3 Pinout Help Guide: https://luisllamas.es/en/which-pins-can-i-use-on-esp32-s3
[4] SCH_ESP32-S3-USB-Bridge-MB_V2.1 Schematic: https://tinyurl.com/usbbridgeschematic
[5] ESP32-S3 Pin Reference: http://wiki.fluidnc.com/en/hardware/ESP32-S3_Pin_Reference
[6] ESP32-S3: Which Pins Should I Use?: https://atomic14.com/2023/11/21/esp32-s3-pins.html
[7] Application Note Poly-Phase Energy Metering IC M90E32AS: https://tinyurl.com/polyphasemetering
[8] Atmel M90E32AS | Datasheet: https://eu.mouser.com/datasheet/2/268/Atmel_46003_SE_M90E32AS_Datasheet-1368788.pdf
[9] ESP32 Energy Meter | Elektor Labs:
https://elektormagazine.com/labs/esp32-energy-meter-an-open-source-solution-for-real-time-energy-monitoring

May & June 2024 105


UPDATES & MAIL

Err-lectronics
Corrections, Updates, and Readers’ Letters
Compiled by Jean-François Simon (Elektor)

Transistor Curve Tracer


Elektor 02/2009, p. 24 (080068-1)
After my letter to the editor was printed in the last
issue, I hope that my current request can be answered
too! I need to read characteristic curves from old
Hitachi MOSFETs in order to select them, it’s about
the Crescendo and 2SK135/2SJ50. Can you tell me if
the “Transistor Curve Tracer” from 2/2009 can do this
in principle or whether it is only suitable for small
MOSFETS. Or do you have a better idea? Thank you
very much, and greetings from Munich East!

Martin Vogl (Germany)


Valve Preamplifier
Elektor 9/2003, p. 18 (020383)
Hello, I would like to know if it is still possible for you to In principle, the MOSFETs you mentioned can also be
supply the silkscreen of the front panel of this preamp. selected using the Transistor Curve Tracer up to a drain
Also, I can’t find the input switching relays. There are current of 400 mA and a drain-source voltage of 10 V.
eight of them, the article indicates the Conrad refer- However, if you want to build the Curve Tracer now,
ence RFA 504602. Could you please help me? Thank please bear in mind that neither the printed circuit
you very much! board nor the corresponding R8C/13 controller board
are likely to be available.
Jean-Paul Termonia (France)
Rainer Schuster (Author of the article)

The relays needed for this part of the circuit are reed
relays, with one row of contacts (SIP), 5.08-mm pitch,
12-V coil, type MES1A12, or SIP-1A12, or equivalent, see
for example: Conrad 2273680, Farnell 9561935, Digikey
3008-SIP-1A12-ND. You can also search the part numbers
above on eBay. Concerning the front panel drawing, I
took a look in our archive but, unfortunately, it is not
available anymore. Our apologies for the inconvenience!

Jean-François Simon (Elektor)

_
Got a bright idea or
valuable feedback for Elektor?
Reach out to us at editor@elekto
r.com
– we’re eager to hear from you!
_

106 May & June 2024 www.elektormagazine.com


ESP32 and ChatGPT
Elektor Guest-Edition 2023, p. 16 (230485) Then you shouldn’t get compilation errors anymore.
The “ESP32 and ChatGPT” project from the December issue You will need to edit the .INO file later and re-compile
appealed to me, so I would like to try it out. The hardware because you need to write the Wi-Fi network credentials at
has been ordered, so I can get started. Unfortunately, I’m lines 29 and 30, and the API key for OpenAI (line 32) that
already failing to get the C-software for the ESP32-1 up maybe you’ve not created yet. You also need to enter the IP
and running. None of the libraries used can be installed address of the other Nano ESP32 board (the one running
in the Arduino IDE. I found WiFi.h after some searching MicroPython), that you may not know yet. For that, follow
and installed it manually. Unfortunately, I failed with the the steps related to MicroPython installation in the article,
HTTPClient.h. and edit the ESP32xESP32_2.py file that you also find in
the GitHub repository, to also add the Wi-Fi credentials
Can you please help me with this? Maybe extend the in the code. Then you may power on the NanoESP32-2
description on GitHub or provide the required libraries. board, look at what IP it gets from the router, and finally
I would like to spend my time working on this and not edit the code in the NanoESP32-1 .INO file accordingly.
on getting the basics up and running… Many thanks in
advance. You will also need to change something in line 140 of
the .INO file. While the code worked as-is at the time of
Andreas Petereit (Germany) writing and at the time of publication, OpenAI changed
their API and informed users that starting from the
4th of January 2024, the model text-davinci-003 is no
I recommend you start with a fresh, brand new install of longer usable. So, please change text-davinci-003\
Arduino IDE 2.2.1. If you manually installed some librar- to gpt-3.5-turbo-instruct\ at line 140. Also, please
ies and they didn’t work, you may want to uninstall them note that for this demo to work, and to be able to call
to start from a “known good” point of reference. See the the OpenAI API from the Arduino NanoESP32-1 as it is
instructions here [1]. suggested in the article, you will need to have “free credits”
on your OpenAI account. When you create a new account,
In case of a fresh install, when you plug one of the two you get $5 worth of “free credits”, but they expire after a
Nano ESP32 boards to the computer, you will get a popup few months, so keep that in mind if you receive “Error
asking if you want to install the Arduino ESP32 Boards core, 429 Rate limit reached for requests” as a response to the
so click Yes. Otherwise, you can check that this package is ChatGPT queries from the NanoESP32-1.
installed by opening the Boards Manager and searching
for “ESP32”. If it’s not installed, you have to install it. As As a final note, I think that this article was designed more
part of this install, you will automatically get the Wifi.h to show examples of communication between two micro-
and HTTPClient.h libraries. controller boards, and to show an example of a micro-
controller accessing an on-line AI through an API, rather
On the other hand, the ArduinoJson.h library must be than to provide a turnkey solution. I highly recommend
installed, by searching for “ArduinoJson” in the Library you try out other approaches for yourself!
Manager, which you can open by clicking Sketch → Include
Library → Manage Libraries… Jean-François Simon (Elektor)

May & June 2024 107


Energy Storage Today and Tomorrow
Elektor 01-02/2024, p. 32 (230636-01)
What is the energy advantage of prismatic Li-ion batter-
ies (block batteries) compared to the individual 18650
cells welded into a battery pack? Thank you very much.

Hans-Rüdiger Funk (Germany)

PICProg 2003, A Versatile PIC Production


Programmer Prismatic cells have an advantage in terms of the
Elektor 09/2003, p. 12 (010102-1) volume/capacity factor. However, they are more diffi-
Where can I get the programmed PIC, order code cult to cool or heat because there are no gaps between
010202-41? It is mentioned in the September 2003 them. For the latter reason, round cells are used in cars.
issue which presents the universal PIC programmer.
I would like to build one. Also, could you tell me what Thomas Scherer (Elektor)
cable I need to connect it to my PC, as its outputs are
USB? Thank you in advance.

X. R. (France)

We no longer sell programmed microcontrollers;


however, we try to provide our subscribers with
downloadable programs whenever possible. In this case,
the PC program and the microcontroller firmware in
HEX format are available in the ZIP file on the page [7].
However, although I’d like to thank you for your inter-
est in our projects, I’d like to take the liberty of advising
you against building this programmer. It’s obsolete, and
can only program a limited number of older PICs. The
associated software is also old, and there’s no guarantee
that it will run smoothly on a recent version of Windows.
You’ll need a PC with a serial port, or a USB-to-RS232
converter. Finally, this PIC programmer is based on a PIC
that you’d have to program, using another programmer! Optimizing Balcony Power Plants
Elektor 01-02/2024, p. 10 (230660-01)
Instead, I would recommend you to use a ready-to-use I have noticed that no mention is made of OpenDTU
programmer, such as a PicKit 3 (itself a few years old, derivatives, e.g. Open DTU onBattery. This is a very
but still relevant), PicKit 4, PicKit 5 or MPLAB Snap. The interesting solution that allows zero feed-in, but also
PicKit 3 is no longer sold by Microchip, but cheap clones the operation of a battery. The project is already avail-
from China work well. The advantage is that there’s able from April 2023. There is a lot of potential here to
“PicKit3 standalone software” that lets you run it, with solve the problems described in the article. Zero feed-in
the HEX file containing the PIC program you want to as well as constant feed-in at night should be possible
program, without having to install MPLAB X, which is with admittedly a little more effort. Energy prices are
quite bulky. To use versions 4 and higher, however, you’ll already on the rise again. The project can be found at
need to install MPLAB X. You can insert the PIC into [4], and the wiki at [5].
a breadboard and make the connections with jumper
wires, or use an adapter (look for “ICD2 ZIF” on Google). Joachim Nolte (Germany)

Jean-François Simon (Elektor)


Thank you very much for the suggestion!

Thomas Scherer (Author of the article)

108 May & June 2024 www.elektormagazine.com


Eisenloser Kopfhörerverstärker mit 4 x EL504
Elektor Schaltungs-Sonderheft, Elektor January 2020 [6]
I would like to know the value of the input capacitors for the headphone amplifier circuit
with 4 x EL504 tubes, page 92 of the book. Thank you!

Helmut Liebetrau (Germany)

Thank you for your e-mail. The value is not critical; you often see between 1 µF and 10 µF for
the input capacitors in this type of setup. If you want to calculate more precisely, you have to
look at the high-pass filter, which consists of the capacitor in question and the input resis-
tance, in this case 10 kΩ. We use the classic formula for a first-order filter, f = 1/(2*π*R*C).
You can use a 1 µF capacitor, which will pass all frequencies above about 16 Hz, or a 2.2 µF,
which will pass signals from about 7 Hz. I recommend capacitors of type MKP4 or MKS4,
250 V or 400 V.

Jean-François Simon (Elektor)

TimeClick Programmable camera controller


Elektor 02/2011, p. 53 (100371)
Hello, I would like to build the TimeClick circuit, for two digital
Canon cameras. I think the programmed microcontroller,
100371-41, is old and was discontinued by Elektor. Additionally,
the ATtiny861-20SU seems to be no longer available under this
number. Is there another type of chip available for this circuit
with the same functions? Looking forward to your message.

Dick van den Berg (The Netherlands)

It is true that we do not sell programmed microcontrollers


anymore, but the ATtiny861 is still available from Digikey,
Mouser, etc. You can program it yourself if you want. The code is
available at [2]. According to the Device Support list at Microchip
[3], the programmers which are compatible with ATtiny861 are:
ICD5, PICKIT5, ICE4, PICKIT4, SNAP, Atmel Embedded Debugger
EDBG, mini EDBG, nano EDBG, Atmel-ICE, Atmel-ICE Power
Debugger. Good luck!

Jean-François Simon (Elektor)

240144-01

WEB LINKS
[1] Uninstalling Arduino Libraries: https://support.arduino.cc/hc/en-us/articles/360016077340-Uninstall-libraries-from-Arduino-IDE
[2] TimeClick project software: https://www.elektormagazine.com/magazine/elektor-201102/19542
[3] Microchip Device Support list: https://packs.download.microchip.com/DeviceDoc/Device_Support.pdf
[4] OpenDTU OnBattery: https://github.com/helgeerbe/OpenDTU-OnBattery
[5] OpenDTU OnBattery wiki: https://github.com/helgeerbe/OpenDTU-OnBattery/wiki
[6] Elektor Schaltungs-Sonderheft (Elektor, 2020): https://www.elektor.de/products/elektor-schaltungs-sonderheft-2020
[7] PICProg 2003 software: https://www.elektormagazine.com/magazine/elektor-200309/17563

May & June 2024 109


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

Tektronix Epic Oscilloscopes


An illustrated chronicle of Teknology for collectors and restorers
Oscilloscopes have made a major contribution to the
advancement of human knowledge, not only in electronics, but
in all sciences, whenever a physical quantity can be converted
into a timerelated electrical signal.
This book traces the history of a crucial instrument through
many Tektronix products. This is the company that invented and
patented most of the functions found in all oscilloscopes today.
Tek is and will always be synonymous with the oscilloscope.

Price: €69.95
Member Price: €62.96

www.elektor.com/20749

Miniware TS1C Cordless Soldering Station


The Miniware Cordless Soldering Station TS1C (with
integrated OLED screen and Bluetooth) is an intelligent
soldering tool that heats up to 400°C in less than 20 seconds.
Thanks to the built-in battery, the wireless soldering pen sits
comfortably in the hand and is easy to use.

Price: €169.95
Member Price: €152.96

www.elektor.com/20777

110 May & June 2024 www.elektormagazine.com


Dragino LoRa/LoRaWAN Pimoroni NVMe Base for
IoT Kit v3 Raspberry Pi 5 (500 GB SSD)

Price: €249.00 Price: €84.95


Member Price: €224.10 Member Price: €76.46

www.elektor.com/20775 www.elektor.com/20796

Quick 861DW Hot Air FNIRSI SG-003A


Rework Station (1000 W) Signal Generator

Price: €349.00 Price: €89.95


Member Price: €314.10 Special Price: €74.95

www.elektor.com/20787 www.elektor.com/20774

May & June 2024 111


With Eben Upton
(CEO of Raspberry Pi) (Source: Raspberry Pi)

Raspberry Pi 5
and Beyond
Questions by Jean-François Simon (Elektor)

It’s been a few months now since the


Raspberry Pi 5 was released, and we
were lucky enough to be able to put a
few questions to Eben Upton, the iconic
CEO of Raspberry Pi and cofounder of
the Foundation. We had the chance to
discuss key aspects of the Raspberry Pi 5’s
development and impact. Topics covered also
include the full, no-compromise computing
experience in their latest model, programming Eben: I think, for me, the most exciting thing about
language evolution, the integration and future Raspberry Pi 5 is that we’ve finally produced the “no
compromises” desktop PC experience that we’ve been
of AI in Raspberry Pi products, the outlook for chasing since the launch of the very first Raspberry Pi
the RP2040 microcontroller, and more. in 2012. You see people (my daughter included) using
Raspberry Pi 5 as their “daily driver” computer without
ever feeling held back by it.

J.F. Simon, Elektor: The Raspberry Pi 5 has been The addition of a single-lane PCIe “user port” is also
out for a few months now. How are the sales going? opening up new opportunities for experimentation.
We’ve been watching with interest as Jeff Geerling
Eben Upton: Very well. We’re closing in on shipping tries to get his giant collection of PC graphics cards
our first million units. This is a little slower than the up and running with Raspberry Pi 5.
Raspberry Pi 4, and has been limited by production
until very recently. Kudos to the team at Sony for JF: Do you have interesting or funny anecdotes about
getting us to a production rate of 90,000 units per things that happened during the development of the
week. [Editor’s Note: The Sony UK Technology Centre Raspberry Pi 5, and that you may be able to share now
in Pencoed, Wales, manufactures Raspberry Pi boards.] that it’s out?
We won’t need to stay there forever, but it gives us a
chance to catch up with demand and to start to build Eben: What people don’t appreciate about
a little inventory. Raspberry Pi 5 is how long it’s been in development.
The first ASIC team members started work on the
JF: Have you seen exciting projects made with the RP1, then called Project X, in the summer of 2015.
Raspberry Pi 5, that would have been harder to make [Editor’s Note: The RP1 is a custom southbridge, designed
with any prior versions, and that made you particu- in-house by Raspberry Pi, which provides the majority of
larly proud you released it? the I/O capabilities for the Raspberry Pi 5.] So that’s an

112 May & June 2024 www.elektormagazine.com


eight-year program, started at a company that was less interesting things happen, which is not practical on
than three years old at the time! One of the fun things a Raspberry Pi. Could you share your thoughts about
about working at Raspberry Pi is that we can make AI, and how AI and Raspberry Pi products can work
these really long-term bets and watch them pay off. nicely together?

JF: In the early 2010s, when you were working on Eben: If you accept my suggestion that we want to do
the first Raspberry Pi, one of the main goals was to a good job for AI workloads, but can’t tax non-AI-cen-
promote the study of computer science, get people tric users with dedicated acceleration hardware, I
to roll up their sleeves and program, and understand think there are two natural consequences for system
how it works. Now there are tools such as ChatGPT design: We end up adding a lot of CPU performance,
that can generate code for you, which mostly works if so low-to-mid-end inference workloads can be run on
it’s given some guidance. Do you think that this kind the CPU (we deliver this with our quad-2.4 GHz A76s on
of tool can make people more and more intellectually Raspberry Pi 5, and our dual 133 MHz M0+s on RP2040
lazy? How do you feel about these tools? for TinyML), and fast interfacing to talk to accelerators
for high-end workloads (USB 3 on Raspberry Pi 4 and
Eben: I’m not sure I agree that ChatGPT can currently 5, PCIe on Raspberry Pi 5).
generate production-quality code even with “some
guidance.” But, in any case, I don’t think they make JF: Just after the Raspberry Pi 5 launch, many press
people lazy or put people out of work: We’ve been articles were published about the differences between
designing tools (assemblers, compilers, higher-level the 4 and the 5. Personally, what is your favorite new
languages) that have increased productivity since feature?
the dawn of the computer age in the 1940s, and they
mostly have the effect of increasing demand for Eben: Honestly, the performance. As I say, it’s the first
computer programmers (see Jevon’s Paradox)! The Raspberry Pi that I sit down in front of and find myself
term for carefully asking ChatGPT to write you some forgetting that I’m not using a legacy Intel PC.
Python is “computer programming:” it’s just program-
ming in a different — and, unfortunately, less precise JF: Now that Bloomberg has broken the news about
— language. the possible initial public offering, and Raspberry Pi
shares being sold to investors, some hobbyists and
JF: In the 1980s, many young enthusiasts cut their makers have been sharing concerns on Reddit, X
teeth on programming with BASIC on systems such as (formerly Twitter), etc. Will you be able to maintain
the BBC Micro. Today, Raspberry Pi champions Python your community-focused ethos in the face of pressures
as the go-to language for beginners. How do you think that come with being a publicly traded company?
this shift in starting languages influences the learn-
ing experience and approach for young programmers Eben: It’s early days in our exploration of the possi-
today? bility of an IPO, but I’m certain we could. You have to
remember we’re already highly incentivized to make
Eben: I think it’s very motivational for young program- great, cost-effective products (because we’re geeks,
mers to be given a language that combines the low and want to make the products we want to buy), and
barrier to entry of BASIC with the high ceiling of a to make money (because the profits from Trading fund
“proper” programming language. Any time you ask the Foundation, which we care deeply about). So, our
someone to change, between computers, or between incentives wouldn’t change post-IPO, and I struggle
languages, there’s always a chance they just say “no,” to see why our behavior would.
and stop. So getting students to use Python, which is a
very beginner-friendly language, and telling them that
they are writing “hello world” in the same language
that professional engineers use to build enterprise
en in
software is very valuable.
Elektor caught up with Ebpte mber
JF: You mentioned in the past that it was difficult
Cambridge, UK, back in Se Eb had
en
of 2023. Check out what erview.
to say during that int
to integrate hardware-based AI in any Raspberry
_gf2M
https://youtu.be/YkXCUW
products, because it’s expensive, and doing so
would have taxed users who don’t need it in favor of
a certain percentage of people who will maybe use it.
Anyway, AI often needs beefy GPUs in order to make

May & June 2024 113


Ultimately, though, the proof of the pudding is in the Questions or Comments?
eating. Come back in five years, and see how we’re Do you have technical questions or comments
getting on. about this article? Feel free to contact the author
at [email protected] or the Elektor
JF: Switching topics, the RP2040 is three years old editorial team at [email protected].
now. Any plans to expand your microcontroller range
with other products anytime soon?
About Eben Upton
Eben: I think we understand what people love about Eben Upton is the CEO of Raspberry Pi (Trading) Ltd.
RP2040: the comparatively high integer performance, and cofounder of the Raspberry Pi Foundation. He has
large memory, and flexible I/O. And we understand been passionate about computers since childhood.
where the deficiencies are: comparatively high standby After earning degrees in Physics and Engineering,
current, lack of floating-point and DSP support, and Computer Science, and an MBA from the University
lack of a security model or on-chip non-volatile of Cambridge, he had a varied career that included
storage. So there’s an obvious specification there for being a technical director at Broadcom, publishing
a successor device, and we’ll be looking very carefully academic works on computing technologies, found-
at how we might deliver that. ing two software companies and, of course, managing
the Raspberry Pi company, where among other things
JF: After the success of the Raspberry Pi 400, will there he oversees the hardware and software architecture
be a Raspberry Pi 500 based on the Raspberry Pi 5 of the Raspberry Pi computer. He received several
hardware? awards for his contributions to business and educa-
tion. Under his leadership, Raspberry Pi production
Eben: Nothing to announce yet, but Raspberry Pi 400 was moved from China to Pencoed, Wales, at the Sony
has been a great success for us, and we’d love to bring UK Technology Centre, not far from his hometown.
Raspberry Pi 5 performance to that form factor.

JF: I heard there are official Raspberry Pi stores in


Cambridge and Leeds. This is great! Could you tell
us more about how they’ve been doing, and who are
the main customers? I’m sure these stores are great
for engaging with new customers, but do you also
see people walking in and buying larger volumes of About Jean-François Simon
products for their professional needs? Do you have Jean-François Simon has a longstanding passion
plans to open more of these brick-and-mortar shops? for electronics and enjoys topics as varied as circuit
design, test and measurement, prototyping, playing
Eben: The Cambridge store was solidly profitable with SDRs, and more. He likes to create, modify
in 2023, and our short-duration pop-up stores also and improve his tools and other systems. He has an
do very good business. Leeds is loss-making at the engineering background and also enjoys mechanics,
moment, but we know that it takes time to grow a machining, and all things technical. Jean-François
customer base, and we can afford to be patient. I don’t recently joined Elektor’s Lab and Content team.
think we’re going to open stores on Apple’s scale, but
you might see a very gradual expansion, with a new
store opened as the previous store reaches profitabil-
ity. Probably on in the UK for now, but in the longer
Related Products
term who knows?
> Raspberry Pi 5 (8 GB RAM)
JF: Thank you very much for your time and for this www.elektor.com/20599
interview. I’m sure it will be of great interest to our
readers. We wish you great success at Raspberry Pi
> Raspberry Pi 5 (4 GB RAM)
www.elektor.com/20598
for 2024 and beyond.
> Raspberry Pi Pico RP2040
Eben: Thank you! www.elektor.com/19562
240145-01

114 May & June 2024 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]
May & June 2024 115
Full speed ahead
Trust the new product introduction leader™
to move from concept to prototype at lightspeed

mouser.com/new

116 May & June 2024 www.elektormagazine.com

You might also like