0% found this document useful (0 votes)
171 views116 pages

EN202305

Uploaded by

Dragan Ivanov
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
171 views116 pages

EN202305

Uploaded by

Dragan Ivanov
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 | €13.50 | $12.

95

521 MAY & JUNE 2023


ELEKTORMAGAZINE.COM
S

*
1

*
IN
CE 196

Test Servos: Up to Four


Stand-Alone or In-System

SUPER
Servo
Tester
M

I
1256
1557
1971
1162
µs
Vcc 4.96
Inputs
FOCUS ON

Test &
Measurement
Automating Test Analog Signals and
and Measurement Microcontrollers
Tips for Programming ADCs, DACs, Current Measurement, and More
Test Equipment
(MSB) RF
R4
1k
VD 1k

R3
Digital Logic "1" VC 2k
Inputs or A
(4-bit) Logic "0" R2
VB 4k Analog
VOUT
output
R1
VA 8k
(LSB) 220047-075

Energy Logger Android Smartphone Here, IR Remote Control with


Measure and Record p. 74 ESP32 There? p. 26 Smartphone p. 48
Power Consuption Using the Android Wi-Fi API Adaptive and Universal
COLOPHON EDITORIAL

Jens Nickel
Volume 49, No. 521 International Editor-in-Chief, Elektor Magazine
May & June 2023
ISSN 1757-0875

Knowledge for All!


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
Programming is a discipline that also rewards beginners with a sense of achievement. With
www.elektor.com | www.elektormagazine.com basic knowledge of a programming language and a few good ideas, you can create small tools
to handle a few tasks that would otherwise require laborious manual work. And let’s be honest:
For all your questions
Who hasn’t proudly demonstrated something like this to their acquaintances?
[email protected]

Become a Member
Programming a small database, setting up a server, or implementing similar nerdy things are
www.elektormagazine.com/membership unfortunately not often appreciated by all relatives and friends. However, the coolness factor
increases when something is measured, regulated, and controlled — especially when you can
Advertising & Sponsoring demonstrate how your solution makes everyday life easier.
Büsra Kas
Tel. +49 (0)241 95509178 Some young “makers” in particular quickly reach their limits. Anyone who has already written a
[email protected] few apps for the PC can quickly come to grips with the basic programming of microcontrollers,
www.elektormagazine.com/advertising thanks to languages like Python. But how do I connect a microcontroller to sensors, actua-
tors, and display elements? What must I consider? Incidentally, many electrical engineering
Copyright Notice
students are not quite sure about this either, as university teachers keep telling us.
© Elektor International Media b.v. 2023

The circuits described in this magazine are


At Elektor, our goal is to impart such basic knowledge to both beginners and pros who have been
for domestic and educational use only. All soldering for decades. On page 12, you will find an article by Mathias Claussen that describes
drawings, photographs, printed circuit board how analog variables such as temperatures can be recorded with microcontrollers using sensors
layouts, programmed integrated circuits, that convert these variables into voltages and currents. As usual, the practical side of things is
digital data carriers, and article texts published not neglected. By the way, there are also a few gems in our archive on this topic — for example,
in our books and magazines (other than the “Sensors Make Sense” series by Burkhard Kainka (Elektor 11/2016). As always, Elektor
third-party advertisements) are copyright members can download the PDFs for free; and, of course, the articles are also loaded in our
Elektor International Media b.v. and may not USB stick archive (www.elektor.com/20372).
be reproduced or transmitted in any form
or by any means, including photocopying,
Even in times of pluggable ready-to-use modules and automatic code generation, solid basic
scanning and recording, in whole or in part
knowledge must not be lost. I’m sure you agree with me here. If you have any requests or
without prior written permission from the
Publisher. Such written permission must also
suggestions, write to me at [email protected]!
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!
or information published in or in relation with Your electronics expertise is welcome! Want to submit an article proposal, an electronics tutorial
Elektor magazine.
on video, or an idea for a book? Check out Elektor’s Author’s Guide and Submissions page:
www.elektormagazine.com/submissions.
Print
Senefelder Misset, Mercuriusstraat 35,
7006 RK Doetinchem, The Netherlands The Team

Distribution
International Editor-in-Chief: Jens Nickel | Content Director: C. J. Abate | International Editorial
IPS Group, Carl-Zeiss-Straße 5 Staff: Asma Adhimi, Eric Bogers, Jan Buiting, Stuart Cording, Rolf Gerstendorf, Ton Giesberts,
53340 Meckenheim, Germany Hedwig Hennekens, Qiëlle Lont, Alina Neacsu, Dr Thomas Scherer, Clemens Valens,
Phone: +49 2225 88010 Brian Tristam Williams | Regular Contributors: Roberto Armani, David Ashton, Tam Hanna,
Priscilla Haring-Kuipers, Ilse Joostens, Prof Dr Martin Ossmann, Alfred Rosenkränzer | Graphic
Design & Prepress: Harmen Heida, Sylvia Sopamena, Patrick Wielders | Publisher: Erik Jansen |
Technical questions: [email protected]

lektor May & June 2023 3


THIS EDITION
Volume 49, No. 521
May & June 2023

Super Servo Tester


Test Up to Four
Servos Stand-Alone
or In-System I
2611
1 791
7 5 51
6521

69.4 ccV

6
stupnI

I
1256
1557
1971
1162
µs
Vcc 4.96
Inputs
M
Inputs Vcc 4.96 µs
1256

Regulars
1557
1971
1162
I

44 The New I3C Protocol


A Worthy Successor to I2C or Just More Hot Air?
3 Colophon 52 Microcontroller Documentation Explained (Part 2)
Registers and Block Diagrams
FOCUS
24 Developer’s Zone 79 Assembling the 4tronix M.A.R.S. Rover Kit
Sub-Nyquist Sampling in Practice
92 Behind the Scenes of DIY High-End Audio
39 Starting Out in Electronics… Elektor’s Ton Giesberts Interviewed on the Fine Art of
…Multivibrating Cheerfully Further! Analog Design
42 Err-lectronics 106 Robot Arm Kit
Corrections, Updates, and Readers’ Letters Using Raspberry Pi Pico and MicroPython
72 From Life’s Experience
High-Level Electronics
94 HomeLab Tours
Work in Progress
Industry
FOCUS
110 Ethics in Action
56 Automating Test and Measurement
Generative AI
Programming Test Equipment to Do What You Want
114 Hexadoku
FOCUS
The Original Elektorized Sudoku
60 Elektor Infographic
Test and Measurement

Features
62 Overvoltage Protection for Safe Operation
Transient Protection for Non-Isolated DC/DC Power Modules

FOCUS
FOCUS
66 Wiha Measuring Equipment
12 Analog Signals and Microcontrollers
Reliable Electrical Testers and Meters
ADCs, DACs, Current Measurement, and More
FOCUS
20 Embedded World 2023
68 Automating Testing and Collaborating on Test Results
Interesting Tech from the Fair
26 Android Smartphone Here, ESP32 There?
Practical Project Using the Android Wi-Fi API

4 May & June 2023 www.elektormagazine.com


Automating eCO2 Telegram Bot
Test and Measurement Air-Quality Measurement with
Programming Test Equipment Telegram Notification

56 89

Projects Next Edition


FOCUS
Elektor Magazine Edition 7-8/2023 (July & August 2023)
6 Super Servo Tester
Our next regular edition deals with the Internet of Things and
Test up to Four Servos Stand-Alone or In-System
Sensors, and you can expect the usual mix of projects, circuits,
FOCUS fundamentals, and all the resources a hobbyist maker or electronics
34 Active 1-kHz Filter for Distortion Measurement engineer needs.
Better Measurements Through Optimization of the
From the Contents:
Measurement Signal
> A low-power LoRa weather station
48 BlueRC > ESP32-based impedance analyzer
IR Remote Control with Smartphone and ESP32 > GPS-based speed monitor
> Doppler Sensor in practice
FOCUS
74 Energy Logger
> Rotary-dial phone as remote control
Measuring and Recording Power Consumption
> All about the Matter protocol
> Raspberry Pi Pico W NTP clock with CircuitPython
82 Parking Disk with E-Paper Display > Step-by-step guide to TinyML
An Innovative Digital Replacement
And Much More!
FOCUS Elektor Magazine edition 7-8/2023 (July & August 2023) will be
89 eCO2 Telegram Bot published around July 12th, 2023. The arrival of printed copies for
Air-Quality Measurement with Telegram Notification Elektor Gold Members is subject to transport. Contents and article
titles are subject to change.
98 RFID Tag Reading and RFID Door Lock
Sample Projects from the Elektor Arduino Experimenting
Bundle

FOCUS
103 Oscilloscope Current Probe for RF
RF Current Measurements Made Easy

Robot Arm Kit FOCUS ON


with Raspberry Pi Pico
and MicroPython Test &
106 Measurement
lektor May & June 2023 5
PROJECT

• Elek
r lab to
to

r la
Ele

b
Super
TESTED

ab
Ele
to

rl
to

k
r la
b • Ele k

Servo
Tester Test Up to Four Servos
Stand-Alone or In-System
Figure 1: The quadcopter for which the
Super Servo Tester was designed.

By Olivier Croiset (France)


supposed to be in the range from one to two millisec-
I developed the Super Servo Tester presented here onds, the rest of the time the signal is low. The servo is in
because the drone I am working on sometimes its center position when the pulse width is 1.5 ms. When
the pulse is shorter, the servo will turn in one direction
produces an unpleasant smell of burned electronics (e.g., left); when it is longer, it will turn in the other direc-
and scorched copper varnish during test flights. I tion (e.g., right).
needed a tool to diagnose the problem and to help me
In a typical flight system, five parameters are to be
understand the cause of the issues. checked: the duration of the four servo command
impulses (thrust, roll, pitch, and yaw), and the supply
voltage. In the case of a complex design, for example the
On the Internet, you can find many servo tester designs development of a flight controller (of a drone or other
for testing a single servo. They allow you to check that type of RC model) or any pulse mixer, this tester allows
the servo you just bought is working properly. The tester seeing the result of the mixer.
presented here takes this concept several steps further.
Not only can you use it to test up to four servos at the Note that in the remainder of this article, the term
same time, it also allows for testing the Electronic Speed ‘servo’ may be replaced by ESC or any other device that
Control (ESC) unit or flight controller together with servos produces and/or recognizes servo signals.
in multiple configurations.
Features and Capabilities
The drone for which I needed the Super Servo Tester is The Super Servo Tester (SST) measures the duration of
shown in Figure 1. It is based on [1]. the control pulses of up to four servo signals and provides
information about the quality of the power supply. It can
Servo Signals 101 be inserted between the remote-control receiver and
As a reminder, a servo is controlled by a PWM signal the servos, between the receiver and the flight control-
with a frequency (or pulse repetition rate, PRR) of 50 Hz. ler of the drone, or between the flight controller and the
The width of the pulse (the time the signal is high) is servos. Figures 2 to 6 show the possible configurations.

6 May & June 2023 www.elektormagazine.com


Servo 1 
Servo Tester
Operating Modes Servo 2 Figure 2: Configuration 1,
The SST features two operating modes, selectable by simple test of four servos
M Servo 3
(Manual Mode), allows
a (slide) switch:
Inputs Vcc 4.96 µs
1256
1557

testing four servos at the


1971
1162
I

> Manual: In this mode, the SST generates the pulses Servo 4
same time. The servos
Power
for four servos or for the flight controller. The widths Supply are powered by the
of the pulses are controlled by four potentiometers. tester and controlled by
In this mode, it is the SST that provides power to the the potentiometers.
servos (or ESC) and the model’s power supply must
not be connected to any of them. The supply voltage
Servo 1 
of the SST must be between 7.5 V and 12 VDC.
> Inputs: In this mode, the lengths of the pulses Servo Tester
Servo 2 Figure 3: Configuration 2,
coming from the receiver or controller are flight controller test
M Flight Servo 3
measured. The signals are also forwarded to the Inputs Vcc 4.96 µs
1256
1557 controler (Manual Mode), allows
for testing a (drone’s)
1971

I
SST’s outputs to control the servos (or the flight
1162

Servo 4
flight controller without
controller). In this mode, the SST, and servos (or Power
Supply transmitter or receiver.
ESCs) are powered by the model’s power supply. The servos and the
The power supply may not exceed 7.49 V and the flight controller are
SST should not be connected to its own power powered by the tester
supply. Also, all four input channels must be and controlled by the
potentiometers.
connected, otherwise the SST’s LED and buzzer will
signal a fault.
Servo 1
Display Modes
Servo Tester
The display shows the duration of the pulses graphi- Servo 2

cally on four bar graphs together with their numer- M Servo 3


ical value in microseconds (from 1000 µs to
Inputs Vcc 4.96 µs
1256

Emitter Receiver
1557
1971
1162
I

2000 µs). The bar graphs are limited to the range Servo 4
1000 µs to 2000 µs, but the numerical value is not. Battery

When a value is out of bounds, a box is drawn around its


Figure 4: Configuration 3, test of the transmitter and receiver (Inputs Mode) to verify
numerical value. In this case, the LED will light up too,
the transmitter and receiver. The tester, servos and flight controller are powered by the
and the buzzer, if switched on, will beep. receiver’s battery.

The display also shows the value of the servos’ supply Servo 1
voltage in either operating mode (Manual or Inputs).
Servo Tester
Indeed, the quality of the model’s power supply is Servo 2

important for the flight controller and for the safety of Flight M Servo 3
the pilot and the people admiring his/her flying skills. controler
Inputs Vcc 4.96 µs
1256

Emitter Receiver
1557
1971
1162
I
The measured supply voltage is boxed when its value is Servo 4
below 4.5 V. The LED will light up too, and the buzzer will Battery
beep, so you don’t have to watch the tester all the time.
Figure 5: Configuration 4, transmitter, receiver, and flight controller test (Inputs Mode), is
for checking the correct operation of the transmitter and receiver with the flight controller
The SST features two display modes, Stack and Square (in case of a drone). The tester, servos and flight controller are powered by the receiver’s
(see Figure 7). The second type is better suited for a battery.
quadcopter. The position of potentiometer P4 at power-up
determines the display mode. When P4 is turned all the Servo 1
way to the left before powering up, the SST will use the
Servo Tester
stacked display. Turning potentiometer P4 to the right Servo 2

before power-up selects the square display when the M Flight Servo 3
device is switched on. controler
Inputs Vcc 4.96 µs
1256

Emitter Receiver
1557
1971
1162
I

Servo 4

The Circuit Battery

Now that we know how to use the tester, let’s have a Figure 6: Configuration 5, transmitter and receiver test (Inputs Mode), allows testing the
look at the circuit. This is shown in Figure 8. It is not too flight controller with the transmitter and receiver. The tester, servos and flight controller
complicated as it mainly consists of connectors. are powered by the receiver’s battery.

lektor May & June 2023 7


Inputs Vcc 4.96 µs
1256 Inputs Vcc 4.96
1557 4 1 Servo number
 1156 1457 Pulse
1971 duration [µs]
Figure 7: The display 1162 3 2
shows the operating 1853 1687
mode (Inputs or Manual)
1000 µs 1500 µs 2000 µs 1000 µs 2000 µs
selected by switch S1,
1250 µs 1750 µs
the voltage VBATT (as
Vcc) and a bar graph
with numerical value for
each of the four servos.
Three markers allow The heart of the circuit is an ATmega328P microcontroller, the servo signal inputs on K1. The servo signal outputs
to quickly estimate the the same as found on an Arduino UNO board. Its clock (PD5, PD6, PD7 and PB4) are connected to K2. These
value of the received
pulses.
frequency is determined by X1, a 16 MHz quartz crystal, two connectors are wired in such a way that standard
helped by C5 and C6. servo cables can be connected directly. In other words,
the pin triplets 1-3-5, 2-4-6, 7-9-11 and 8-10-12 all corre-
Four of its GPIO ports (PB0 to PB3) are connected to spond to a servo connection. These connections often use

Vbat
+2V5
+5V +5V +2V5
Inputs
2 1
R2 4 3
10k

Vbat 6 5
P4A P3A P2A P1A
10k 10k 10k 10k 8 7
20 7 21
10 9
AVCC VCC AREF
R4 1 12 11
RES
10k

23 14 K1
C0 B0
24 15
R5 C1 IC2 B1
25 16
C2 B2
10k

26 17
C3 B3
27 18
C4 B4
28 19
R6 C5 B5
+5V +5V
ATmega328p
10k

SDA 2 13
D0 D7 ISP
R9 R10 SCL 3 12
D1 D6 VCC 2 1 MISO
4 11
10k

10k

D2 D5 MOSI 4 3 SCK
5 6
D3 D4 GND 6 5 RST

GND X1 X2 GND K3

8 9 10 22
1b 1a X1

2b 2a
Vbat
3b 3a
4b 4a C5 16MHz C6
Outputs
K4 * 22p 22p 2 1
+5V
4 3
6 5
8 7
R3
Vbat 10 9
S2 12 11
Vbat +5V
1k

K2
BUZ1 S1
LED1
R8 R1 Measure Control
(inputs) (manual)
22Ω

1k

RED
+5V +2V5
D
T1 K5
LM7805 D1
G
Figure 8: The Super IC1
D3 D2
Servo Tester has its LM385Z-2.5 C4
S 2N7000 C3 C2 C1 1N5817
10k

R7
ATmega328P brain 10µ 100µ
100n 100n
surrounded by many 5V1
16V 35V
connectors.
220069-001

8 May & June 2023 www.elektormagazine.com


an orange-red-brown color code. Orange (pulse signal) same order. K4A and K4B let you use either type. Using
connects to pin 1 (or 2 or 7 or 8), red (VCC) to pin 3 (or a double footprint instead of (solder) jumpers consumes
4 or 9 or 10) and brown (GND) to pin 5 (or 6 or 11 or 12). less board space and saves two (solder) jumpers. The
Of course, there will be exceptions to this rule, so check inconvenience is, of course, that the position of the display
first before connecting anything. opening in the enclosure depends on the display because
K4A and K4B are not in the same place. Also, depending
Analog Inputs on the manufacturer, the dimensions of this display may
The four potentiometers are connected to the MCU’s vary. Therefore, you must choose your display before
analog inputs on PC0 to PC3. The supply voltage is machining the enclosure.
connected through a voltage divider (R4, R5 and R6)
to analog input PC4. The ratio between (R4+R5) and Operating Mode Selection
R6 must be 2:1, but their absolute values are not critical. Slide switch S1, a double-pole, double-throw (DPDT) type,
Using three resistors of the same value simplifies sorting selects the operating mode of the Super Servo Tester.
them for precision. In Manual Mode, it connects the 5 V supply voltage to
the servo connectors. In Inputs Mode, the SST’s supply
To measure the microcontroller’s supply voltage, a refer- voltage is VBATT, so its own 5 V supply must be discon-
ence voltage other than the supply voltage itself is required nected to avoid conflicts. Actually, you are supposed to
for the analog-to-digital converter (ADC). The ATmega328P disconnect the SST’s supply in this mode, but as it is
features a built-in reference of 1.1 V, but that value is a bit better to be safe than sorry, S1 disconnects it for you.
low. I therefore used D2, an LM385-2.5, as external refer- Zener diode D3 together with R8 ensure that the power
ence of 2.5 V. This component is more accurate than a supply to the rest of the circuit derived from VBATT does
simple 2-terminal Zener diode, which improves the quality not exceed the maximum values supported by the other
of the servo supply voltage measurement: 1% to 2% instead components. The position of S1 is read by PD4, so the
of about 5% for an ordinary Zener diode. MCU can pick the corresponding operating mode.

Note that D2 comes in a tall package. To keep the assem- Strictly speaking, S1 does not have to be a DPDT type,
bly low, it may be folded to the PCB. On the other hand, it is but it must be capable of passing the power consumed
also possible to use it as a supporting stud for the display. by up to four servos and even more if there is also an
ESC or flight controller connected to the outputs. Suitable
The power supply voltage measurement must not be DPDT slide switches are often cheaper than single-pole
higher than 7.49 V as the MCU input’s maximum input types, which explains why it is used here.
voltage is 5 V. Therefore, the power supply to the receiver
and servos must never exceed this value. Miscellaneous
GPIO port PD2 of the MCU controls the alarm LED and
Display Issues buzzer. As they are connected in parallel, MOSFET T1
The SSD1306-based I2C OLED display is plugged on provides some extra oomph to drive them both without
connector K4. The display’s I2C port is not connected overloading the MCU. S2 is a second slide switch used to
to the MCU’s I2C port, but to PD0 and PD1. The I2C bus mute the buzzer, as it can be a bit annoying sometimes.
is emulated by the software. This is because on the This switch is a small, low-power type.
ATmega328 the I2C bus is shared with analog input
PC4 which is already used for measuring the supply The 5 VDC power supply for the SST in Manual mode
voltage. Therefore, the built-in I2C peripheral cannot be is obtained from a classic linear 7805 voltage regulator
employed here. (IC1). Make sure to use a TO220-type for this component,
as it must power up to four servos. To keep the assembly
R9 and R10 are pull-ups for the I2C bus. Officially they low, C1 and C2 may be mounted lying down.
should have a value of something like 4.7 kΩ, but 10 kΩ
works too and saves a line on the bill of materials, as Finally, connector K3, a boxed type, is available for
most of the other resistors too have a value of 10 kΩ. programming the microcontroller without removing it
from the circuit. It is wired in the same way as the Arduino
Note that K4 is drawn as an 8-pin connector with two ICSP (in-circuit serial programming) connector.
rows, but on the PCB, you should mount a single-row
4-pin socket in position ‘A’ or ‘B’, not both. The position Some Words on the Software
depends on your display. These displays have the GND For this project, I used the Arduino IDE, which proves
and VCC pins on pins 3 and 4, but not always in the that it can be used for complex projects. I first built a

lektor May & June 2023 9


proof-of-concept with an Arduino UNO and a breadboard.
When everything was working as intended, I loaded the
Battery monitor
(from the receiver)
program into the final device via the ICSP connector. Note
that, when programming the microcontroller via the ICSP
connector K3, nothing must be attached to connectors K1
4 Potentiometers
I2C OLED display and K2 as these connectors each share a signal with K3.
128 x 64
All the libraries needed for the project are included in
the download [3] except for the Servo library, as it is part
of the Arduino IDE. The project is organized in three
files: Display.ino, Inputs.ino and the main sketch file. The
names of the files explain pretty well what they contain.
The main sketch file contains the functions setup() and
loop() but also the interrupt routines used to time the
M
input pulses. Level changes in the input signals produce
I pin-change interrupts. This way, the function micros()
can be used to measure the length of the pulses. The
4x Servo in 4x Servo out measured pulse widths are copied to the output and
passed on to the display functions for printing. Figure 9
Mode shows a high-level overview of the signal flows inside
(’Manual’ or ‘Inputs’)
the microcontroller.

Use of the OLED_I2C Library


Figure 9: High-level overview showing what is going on inside the microcontroller. As mentioned before, the OLED display is controlled over
an I2C bus. On the ATmega328P, this bus is shared with the
ADC. PC4 can be either the SDA pin or analog input A4. To
work around this, the I2C bus is emulated in software. The
OLED_I2C library from Rinky-Dink Electronics [2] does
this and allows us to assign any GPIO port to the I2C bus.

I had to modify slightly the file OLED_I2C.cpp of this


Figure 10: The author’s library as an incorrect include directive prevented its
prototype controlling compilation. Replace line 25:
four servos in Manual
Mode.
#include "hardware/avr/HW_AVR.h"

by

#include "HW_AVR.h"

Also, in the file HW_AVR.h, in the function OLED::up-


date(), I commented out line 24, as below:

//noInterrupts();

This is necessary as interrupts are used by the Servo


library for generating the 50 Hz PWM signals on the SST’s
Figure 11: The Elektor
outputs. They must also remain enabled for measuring
Labs prototype mounted
in its enclosure. incoming pulses.

 Before Power-Up
If potentiometer P1 is at its minimum position (turned left)
when powering up, the screen displays a white frame.
This helps to position the cut-out for the screen and

10 May & June 2023 www.elektormagazine.com


COMPONENT LIST

Resistors (THT, 0.25 W, 5%) Miscellaneous (THT)


R1, R3 = 1 kΩ BUZ1 = Piezo buzzer with oscillator, 12 mm diam., 6.5 mm
R2, R4, R5, R6, R7, R9, R10 = 10 kΩ or 7.6 mm pitch
R8 = 22 Ω K1, K2 = 2-row, 12-way pinheader, 2.54 mm pitch, 90°
P1, P2, P3, P4 = 10 kΩ, linear, vertical K5 = Barrel jack
K4* = 4-way pin socket, 2.54 mm pitch (mount A or B
Capacitors (THT) depending on display)
C1 = 100 µF, 35 V, 8 mm diam., 3.5 mm pitch K3 = 2-row 6-way boxed pinheader, 2.54 mm pitch
C2 = 10 µF, 16 V, 5 mm diam., 2 mm pitch S1 = Slide switch DPDT, 90° (e.g. MFS201N-16-Z)
C3, C4, C7 = 100 nF, 2.5 mm or 5 mm pitch S2 = Slide switch SPDT, 90° (e.g. OS102011MA1)
C5, C6 = 22 pF, 2.5 mm pitch X1 = Crystal, 16 MHz, HC-49S (low-profile)

Semiconductors (THT) OLED display, 0.96“, 128 x 32 pixels, 4-pin I2C


D1 = 1N5817 (e.g. www.elektor.com/18747)
D2 = LM385Z-2.5, TO-92 Elektor PCB 220069-1
D3 = BZX79-C5V1 Suggested enclosure: Hammond 1593N
IC1 = 7805, TO220
IC2 = ATmega328-P * = see text
LED1 = LED, 3 mm, red
T1 = 2N7000, TO-92

allows adjusting the opening if needed. Not everyone


has a CNC machine at home. Turn P1 to the center to Questions or Comments?
return to normal operation. If you have technical questions, feel free to e-mail the
Elektor editorial team at [email protected].
Similarly, if P4 is in its minimum position at power-up,
the display will use stacked mode. If P4 is in its maximum
position at power-up, the square display mode is
activated. In this second case, this means the motor
connected to output 4 will be at full speed at the start up.

Time to Take Off Related Products


The Super Servo Tester was a fun thing to design and
develop and is a useful tool to have around if you are > Arduino Uno R3 (SKU 15877)
into drones and quadcopters or RC modeling in general. www.elektor.com/15877
Not only did this project help me to increase my program-
ming skills, but I can now finally take out my drone too,
> 0.96” 128×64 I2C OLED Display (SKU 18747)
www.elektor.com/18747
which is impatiently waiting to take off!
220069-01

WEB LINKS
[1] Joop Brokking’s drone website: http://www.brokking.net/ymfc-al_main.html
[2] OLED_I2C library: http://www.rinkydinkelectronics.com/index.php
[3] Project downloads at Elektor Labs: https://www.elektormagazine.com/labs/super-servo-tester

lektor May & June 2023 11


BACKGROUND

Analog Signals
and Microcontrollers
ADCs, DACs, Current Measurement, and More

By Mathias Claussen (Germany)


then assigns the applied voltage to one of these values. The range
While an MCU internally deals of values is now finite and the analog signal must be assigned to
with ones and zeros, the world the best fitting digital value, even if it does not exactly match the
computationally determined level. This deviation is called quanti-
around it is analog. Therefore, it zation error.
is sometimes necessary to read or
output analog values. With just a The second quantity, the sampling rate in samples per second,
indicates how many times per second the ADC is able to convert an
few components, an MCU can be analog value into a digital value. Unless the signal is a DC voltage,
connected to the analog world. the sampling frequency also determines the maximum bandwidth
of a signal that can be processed. The reciprocal of the sampling
frequency indicates how long it takes for the ADC to complete an
analog-to-digital conversion – in other words, how long the software
No matter whether your microcontroller (MCU) of choice is an has to wait after a conversion is started before the resulting value
Arduino UNO, STM32, or whatever, it is often necessary to process can be processed.
more than just digital signals. The world around us is analog; there
is not just light or dark, but every shade in between. Therefore, Voltage Range, Resolution, and Reference
this article provides some insight into how analog values can be Voltage
read by a microcontroller and how they can be output as well. If we assume an input voltage range of 0 V to 5 V with 10-bit resolu-
For experienced developers, this text surely falls into the category tion, we get
“light reading,” but each of us had to start somewhere. And, while
setting and reading digital pins is very straightforward, things get
a bit trickier when it comes to input and output of analog values.
A voltage of, for example, 452 mV, would thus internally be assigned
The basic questions are: How do analog values get into a digitally the value 92
operating MCU, and how do they need to be prepared for that
purpose? And, how can an MCU output analog values? To answer
these questions, let’s first look at two important basic elements,
the analog-to-digital converter (ADC) and the digital-to-analog and would thus be further processed as 449.88 mV. The quanti-
converter (DAC). zation error is, therefore, 2.12 mV. The deviation cannot be more
than 0.5 LSB (least-significant bit), which is just under 2.5 mV in
Analog-to-Digital Converter (ADC) this example.
An analog-to-digital converter (ADC) is capable of converting an
analog signal into a digital representation. This digital represen- If the voltage range to be measured is significantly smaller than the
tation can then be used later by the microcontroller to process allowed input voltage range of the ADC, this range can be modified
the data. Two frequently encountered parameters of an ADC are on most ADCs. The ADC always compares the analog values to
the resolution in bits and the sample rate in samples per second. a reference voltage. Many MCUs nowadays provide an internal
In microcontrollers, the resolution is usually in the range of 10 reference voltage, or even several. The AVR128DB from Microchip
to 12 bits. This means that the ADC subdivides its analog input shall serve as an example. Figure 1 shows the block diagram of
voltage range into 1024 values (10 bits) or 4096 values (12 bits) and the voltage reference of this controller.

12 May & June 2023 www.elektormagazine.com


Reference request
ALWAYSON
REFSEL[2:0]
1.024V
2.048V
Bandgap 4.096V
Reference Internal
2.500V BUF
Generator Reference
VDD
Bandgap VREFA
enable

Figure 1: AVR128DB voltage reference (Source: Microchip, AVR® DB Family datasheet [PDF] - https://elektor.link/AVR128DBDatasheet).

Six reference voltages of 1.024 V, 2.048 V, 4.096 V, 2.5 V, VDD and back and forth between zero and one if the signal value cannot
VREFA are available. The first three voltages can be represented as be matched exactly with the available resolution of the ADC. Taking
2N and allow the digital values from the ADC to be converted back the average of this least-significant bit will result in a fraction of
to volts very easily later. Something that can be found on almost a one, which means a higher resolution. However, this method
all MCUs is GND (ground) vs. AGND (ground for the analog part of reduces the effective sample rate. For each bit added by oversam-
the MCU). Since there can be high-frequency noise in the digital pling, there is a quartering of the sample rate. If, for example, an
domain that also travels through the ground path, anything that ADC with 12 bits can handle a maximum of 130 ksps (kilosamples
is an ADC or DAC has its own ground. Thus, in the circuit design, per second), four oversampling bits, i.e. 16 bits overall, would result
GND and AGND can be decoupled from each other to avoid inter- in only 507 samples per second:
ference. If it is expected that the measured quantity will not exceed
1 V, then 1.024 V can be selected as the reference. This would result
in a resolution of 1.00098 mV/bit. 452 mV would correspond to
the digital value 452; during further processing, the quantization In addition, depending on the ADC, the processor must perform
error would thus be significantly smaller than in the above example. the averaging necessary for oversampling, which means additional
However, the appropriate choice of reference voltage is not the computational overhead. Some newer ADCs, such as some STM32
only thing that can ensure that the results of the conversions are controller families, perform this task completely autonomously
closer to the physical (analog) value. The quality of the reference without additional load on the CPU.
voltage also has an influence.
ADCs come in a variety of designs. The most common ADCs in
In the AVR128DB, VDD and VREFA can be considered reference controllers are SAR (successive approximation) types. For high
voltages as well. VDD is the supply voltage of the chip, and VREFA resolutions of 24 bits and more at relatively low sample rates (in the
is an external pin on the AVR128DB which allows you to connect range of ksps down to a few samples per second), delta-sigma ADCs
your own external reference voltage source. Using VDD as the refer- are most commonly used. The details of delta-sigma conversion
ence can be an unfortunate choice, because this voltage is loaded and its implementation in a CPLD/FPGA (Complex Programmable
with noise from the digital part of the MCU, and it is difficult to Logic Device / Field-Programmable Gate Array) can be found in an
“filter away” this noise. The situation is different with VREFA: Here, Elektor article [1]. There are other ADC types, of which the Flash
an external high-precision voltage source can be used as the refer- ADC type promises the fastest conversion time, which is why it is
ence. Of course, it is still connected to the “dirty” supply voltage, often used in modern flash memory.
but as an external component, it can be filtered a lot better. A stable
and interference-free reference is the basis of a good analog-to-dig- Digital-to-Analog Converter (DAC)
ital conversion. With a DAC, you generate an analog value again from a digital value.
Not as commonly as ADCs, some MCUs have DACs built in. On the
There is another way to increase the resolution of an ADC without AVR128DB, it is a 10-bit DAC, which can thus output 1024 different
changing the reference voltage, which is called oversampling. voltages. If there is no DAC in the MCU, an external DAC chip like
Oversampling uses the least-significant bit, which is switched the Microchip MCP4922 can be used. Both are resistor string DACs,

lektor May & June 2023 13


VCC

SW1
R1
R

RF
(MSB) R4 1k
SW2 VD 1k
R2
R

R3
VC 2k
VCC Digital Logic "1" A
Inputs or
SW3 R2
VOUT Analog
R3 (4-bit) Logic "0" VB 4k output
R

R1
3 5 VA
DAC_OUT 8k

SW4 1 (LSB)
R4 IC1 220047-075
4

Figure 3: Circuit of a binary-weighted DAC.


R

SW5
R5
R

R3 R5 R7
470Ω 470Ω 470Ω
SW6
R6 R1 R2 R4 R6 R8
IC1 = Rail-to-Rail Op-Amp VOUT
R

1k

1k

1k

1k

1k
SW7
R7
0V
R

(LSB) (MSB)
VA VB VC VD
SW8 230027-001
4-bit Binary Output 220047-074

Figure 2: Structure of a string DAC. Figure 4: Principle of an R-2R DAC.

the MCP4922 is a 12-bit DAC with two channels. While a resistor values, while in a binary weighted DAC N, there are mostly incon-
string DAC can be well integrated into a chip, it is hardly feasible venient fractional values. The schematic for such a DAC is shown
with discrete resistors. A look at the three-bit resistor string DAC in Figure 4.
in Figure 2 gives an idea why this is so: The DAC requires
However, if I/O pins are a scarce commodity on the MCU used, the
(N = Number of bits) PWM unit can also serve as a DAC with some external circuitry. The
analog.Write() function for the Arduino UNO produces analog
resistors and N switches. For a 16-bit DAC, this would thus be values this way using the digital pins.
65,535 resistors and 65,536 switches!
Figure 5 shows an example from the Elektor article at [3] for an
Just like an ADC, a DAC also requires a reference voltage that speci- Arduino UNO.
fies the range in which the output voltage can move. However,
the DAC itself can only drive a few milliamps, even if the output
is buffered by an operational amplifier.

However, if there is no internal DAC and enough pins on an MCU LM78L05 +7...24V
are still available, there are other ways to build an external DAC. One IC2

option is a binary-weighted DAC, as shown in Figure 3. Here, only D9


R2 C1 C2 8

N+1 resistors and an operational amplifier are needed for N bits.


5k1

IC1
100n 10µ 4
25V
The values of the resistors are given by R1
330
ARDUINO UNO

IC1 = LM358
2 8 6 C2
3 6
R3 0...5V
1 200n 7
IC1A 100k R4 IC1B
2 5
and are thus doubled each time. Such a DAC can be used to generate IC3
100k

C4
analog VGA signals, for example, as shown in the data sheet at [2]. GND 3 7 5
100n
6N136
220136-001

Another frequently used variant is an R-2R DAC. In contrast to


a binary-weighted DAC, here N × 2 resistors and an operational
amplifier are needed for N bits, but there are only two resistor Figure 5: Isolated analog output for the Arduino UNO.

14 May & June 2023 www.elektormagazine.com


U
R1

U1 I IH
SCL Uout ADCn C S/H Vcc/2
Arduino Uno SDA
I
AREF
R2 1...100k 14p
GND
RESERVED 13
U2 I IL
IOREF 12
RESET 11
3.3V 10
230027-009
5V 9
POWER

230027-008
GND 8
GND
Figure 7: Unloaded voltage Figure 8: ATmega328P ADC input internal
DIGITAL (PWM)
VIN 7 R1 Out
6 divider. structure (Source: Microchip, Atmel
A0 5
C1
Atmega328P datasheet [PDF] - https://
elektor.link/ATmega328PDatasheet).
ANALOG IN

A1 4
ICSP
A2 3
RESET

MISO
SCK

A3 2
A4 TX 1
A5 RX 0

problem. If a sample-and-hold stage is installed in the ADC, as in


GND
MOSI
5V

230027-007 the ATmega328 shown in Figure 8, this can lead to incorrectly


measured values. The ADC has a small capacitor at its input, which
Figure 6: Arduino UNO with RC low-pass filter. is charged. During a conversion, the capacitor is connected to the
analog input for a short time (for the duration of the configured
sampling time) and charged. If the current is too small, the capac-
A simpler setup is the circuit in Figure 6, which consists only of an itor may not be fully charged during the sampling time. If the ADC
RC low-pass filter to smooth the signal. However, such a DAC comes later converts the value of the incompletely charged capacitor, the
with disadvantages. Since the PWM signal needs to be smoothed, result will be incorrect.
the values for R and C have to be calculated for the respective desired
application. There will also always be a small residue of the PWM A look at the datasheet of the MCU of choice should help to deter-
in the analog signal, which will be noticeable as undesired noise. mine the appropriate values. For the AVR in this case, a value of
4.7 kΩ each for R1 and R2 and thus a current of 1.06 mA would be
Signal Conditioning appropriate.
The signals to be measured or output are not always directly
compatible with the MCU of choice. In the digital world, many Negative Voltages
developers are familiar with the problem of connecting 5 V compo- Positive voltages are quite easy to measure, e.g. by using a voltage
nents to 3.3 V systems. Similar problems can also be found in the divider. But what happens if the voltage to be measured is negative?
analog world and its interfaces. Audio, video, as well as 4-20 mA By using an op-amp as an inverting amplifier and a pair of resistors
current loops are just a few examples that require signal condition- as shown in Figure 9, the voltage can be inverted.
ing. Probably the simplest form of signal conditioning is a voltage
divider, which can be used not only for analog values, but also for
adapting digital signals.

Voltage Dividers and ADCs


Figure 7 shows an unloaded voltage divider, which is an idealized
form of voltage divider. With a voltage (U) applied, a current (I)
results at R1 + R2. A voltage of R1 × I = U1 now drops across resistor SCL

Arduino Uno SDA


R1 and a voltage R2 × I = U2 across R2, where U = U1 + U2. If you AREF

now want to measure, for example, a range from 0 to 10 V with an RESERVED


GND
13
ADC that can only process 0 to 5 V, the voltage must be halved. It +5V IOREF 12

is obvious that this requires R1 = R2. RESET 11


3.3V 10
+5V
5V 9
POWER

However, the current (I) must also be considered when choosing GND 8
MCP6001U GND
resistor values. Although 10 Ω for R1 and R2 would mathematically
DIGITAL (PWM)

VIN 7
5
result in the desired voltages for U1 and U2, a current of 500 mA
1
6
4
Vin IC1
would flow through the resistors. This could not only overload the
R1 A0 5
3
ANALOG IN

10k A1 4

voltage source, but also the resistors themselves. This is because


2 ICSP
A2 3
RESET

MISO
SCK

a power dissipation of P = R * I2 = 2.5 W, which each resistor must R2 A3 2


10k A4 TX 1

dissipate in the form of heat, is far too high for most smaller sizes. A5 RX 0
GND
MOSI
5V

Another option to reduce the power dissipation would be 1 MΩ 230027-010

resistors. Then a current of only 5 µA would flow, and the power


dissipation would be 25 µW, but this other extreme causes a new Figure 9: Inverting amplifier.

lektor May & June 2023 15


+5V

R3
10k

MCP6001U
1 5
R6
4
U1 10k

Audio Signals and ADCs


3 +5V
R4
2
An interesting application for an MCU is the processing of audio
10k

MCP6001U signals. Common audio signals have a peak-to-peak voltage of


1 5
Vout 0.894 VPP (-10 dBV) to 3.472 VPP (+4 dBV), depending on the source
Vin R1 R5 U2
4
providing the signal. Most home devices operate at -10 dBV, which
is 0.894 VPP. The signal thus has a minimum voltage of -0.477 V
3
10k 10k
R2 2
R7 and a maximum of +0.477 V. The ADC of an MCU such as the
10k

10k Raspberry Pi RP2040 cannot handle this. But, why would you want
to process audio with a 10-bit ADC at all? For example, the AVR
230027-011
and faster MCUs are quite capable of calculating and displaying
the frequency spectrum of an audio signal. For this application, we
Figure 10: DC offset with operational amplifiers. can take advantage of the fact that the DC portion is not of interest;
only the AC portion of the audio signal is needed (C1) and provided
with a DC offset of half the supply voltage for the ADC (R1 / R2) to
lift the audio signal into the positive range. A schematic for this
Raspberry Pi PICO is shown in Figure 11.
1 USB 40
2
GP0 VBUS
39 With such a signal, the (quite narrow) voltage range must be consid-
GP2 VSYS
3
GND LED GND
38 +3V3 ered. With a maximum voltage of less than 1 V, the signal must be
4
GP2 3V3_EN
37
amplified or the internal reference voltage of the ADC must be
R1
chosen appropriately to avoid unnecessarily large quantization
5 36
BOOTSEL

GP3 3V3_OUT
6 35
100k

7
GP4 ADC_VREF
34 errors.
GP5 GP28
8 33
GND GND
9
GP6 MOD1 GP27 32
C1 Audio Current Measurement
An ADC can usually only measure voltages. But, in many cases,
10 31
GP7 GP26
11 30
12
GP8 RUN
29
220n currents also need to be determined. The simplest method for this
GP9 GP22
13
GND GND
28 R2 is to use a shunt resistor. If the current consumption of a circuit
14 27
is to be measured, there are two options: low-side and high-side
100k

GP10 GP21

measurement. Figure 12 shows a very simple circuit for a high-side


15 26
GP11 GP20
16 25
17
GP12 GP19
24 measurement using the Arduino Nano.
GP13 GP18
18 23
GND GND
19 22
GP14 GP17
SWCLK

SWDIO

20 21
GND

GP15 GP16

230027-012 Arduino Nano


1 30
TX VIN
Figure 11: Audio input for the ADC of a Microchip AVR. 2
RX GND
29 +5V
3 28
RST RST
4 27
GND 5V
5 26
As long as the voltage at the input of this circuit remains below 6
D2 A7
25
0 V, the op-amp will work correctly. However, if a voltage range
D3 A6
7 24 R1
D4 A5
of -5 V to +5 V is to be covered, a little more effort is required.
RESET
8 23
10Ω

D5 A4

Assuming that the allowed input range of the controller is 0 to 5 V, 9


D6 A3
22
10 21
the signal with a swing of 10 V must first be halved by a voltage 11
D7 A2
20
D8 A1
divider R1 / R2. Thus, we would have to deal with values from 12
D9 A0
19

-2.5 V to +2.5 V. This range is now raised by 2.5 V by the voltage 13


D10 AREF
18
LA1

divider R3 / R4. The second, non-inverting operational amplifier, 14


D11 3V3
17
15 16
U1, buffers this voltage. The complete circuit diagram is shown D12 D13

in Figure 10.
USB
When evaluating the measured values later, it must be remembered 230027-014

that the zero point of the input voltage is now raised by half of the
supply voltage, i.e. 2.5 V in this example. Figure 12: High-side measurement.

16 May & June 2023 www.elektormagazine.com


Raspberry Pi PICO +6...12V
Arduino Nano
1 30 1 USB 40
TX VIN GP0 VBUS
2 29 2 39 R3
RX GND GP2 VSYS
3 28 3 38
RST RST

0Ω1
GND LED GND
4 27 4 37
GND 5V GP2 3V3_EN
5 26 +3...5V 1W
5 36

BOOTSEL
D2 A7 GP3 3V3_OUT
6 25 6 35 R1 R4
D3 A6 GP4 ADC_VREF
7 24 7 34
D4 A5

10k

10k
RESET GP5 GP28
8 23 8 33
D5 A4 R1 GND GND
9 22 9 32
D6 A3 GP6 MOD1 GP27

10Ω
10 21 10 31
D7 A2 GP7 GP26
11 20 11 30 R2 R5
D8 A1 GP8 RUN LA1
12 19 12 29
D9 A0

2k7

2k7
GP9 GP22
13 18 13 28
D10 AREF LA1 GND GND
14 17 G4 20W
D11 3V3 14 27
GP10 GP21
15 16 15 26
D12 D13 GP11 GP20
16 25
GP12 GP19
17 24
GP13 GP18
18 23
USB GND GND
230027-014 19 22
GP14 GP17

SWCLK

SWDIO
20 21

GND
GP15 GP16

Figure 13: High-side measurement before and after the shunt resistor.
230027-015

The shunt resistor is placed between the positive supply voltage and Figure 14: Modified circuit with voltage dividers.
the load. To determine the current flowing through the resistor and
thus through the load, the voltage drop across the resistor must be
measured. If the (constant and known) voltage supplied to the load In this case, using a high-side current sense amplifier such as the
is less than or equal to the reference voltage of the ADC, the voltage INA138 from Texas Instruments or the MCP6C02 from Microchip is
drop across the shunt can be determined with manageable effort. a much better solution. In addition, the value of the shunt resistor
However, if the supply voltage of the load is variable (but still less can be considerably smaller in this case. The 10 mΩ shunt causes
than the reference voltage of the ADC), the voltages on both sides significantly lower heat dissipation than its ten times larger counter-
of the shunt resistor must be measured, as shown in Figure 13. part. Figure 15 shows the circuit with current sense amplifier.

Admittedly, this example is very idealized because the supply The output voltage is proportional to the voltage drop across the
voltage of the load is less than or equal to the reference voltage of resistor and can thus be easily processed with an ADC channel.
the ADC. If the supply voltage is greater than the reference voltage
of the ADC or even the MCU, things become more difficult.

Monitoring a Halogen Lamp Using Current


Measurement Raspberry Pi PICO
In the following example, we want to measure and monitor the
current consumption of a dimmable G4 halogen lamp, which is 1
GP0
USB
VBUS
40

supplied with a maximum DC voltage of 12 V. The lamp is allowed 2


GP2 VSYS
39
+3V3 +6...12V
to “consume” a maximum of 20 W (1.67 A at 12 V). Currents higher
3 38
GND LED GND
4 37
than 2 A and lower than 25 mA are supposed to be interpreted as 5
GP2 3V3_EN
36
BOOTSEL

GP3 3V3_OUT
a faulty lamp by the MCU. 6
GP4 ADC_VREF
35
R1
7 34
GP5 GP28
0Ω1

We could now use voltage dividers to bring the voltage before and
8 33 3
GND GND 6
9 32 1
MOD1 GP27
after the shunt resistor into a range that can be processed by the 10
GP6
31
IC1
4
ADC. Figure 14 shows a circuit that has been modified accordingly.
GP7 GP26 2
11 30
GP8 RUN 5
12 29
GP9 GP22
LA1
The MCU is supplied with 3.3 V and the resistors are selected so
13 28 C1 C2
GND GND
14 27
that, at 12 V, a maximum of 2.6 V is applied to the pins of the ADC. 15
GP10 GP21
26 2µ2 100n G4 20W
GP11 GP20
The value of the shunt resistor is 0.1 Ω. At 2 A, it causes a voltage
6V3
16 25
GP12 GP19
drop of 0.2 V, but still dissipates 0.4 W as heat. The method works 17
GP13 GP18
24

in principle, but it is not very clever, as we will see in a moment.


18 23
GND GND
19 22
GP14 GP17
SWCLK

SWDIO

20 21 IC1 = MCP6C02-100
GND

GP15 GP16
The voltage divider reduces the measurement range even further,
so that the MCU’s ADC must be able to handle a maximum voltage
230027-016
drop of less than 0.05 V at 2 A. This is not a good idea. Also, the
fact that the voltage drop is measured via two ADC channels does
not make further processing easier. Figure 15: Circuit with current measurement amplifier.

lektor May & June 2023 17


Raspberry Pi PICO

1 USB 40
GP0 VBUS +6...12V
2 39
GP2 VSYS
3 38
GND LED GND
4 37
GP2 3V3_EN
5 36 LA1

BOOTSEL
GP3 3V3_OUT
6
GP4 ADC_VREF
35 Low-Side Measurement
Instead of placing a shunt resistor directly before the load, it can
7 34 G4 20W
GP5 GP28
8 33
9
GND GND
32 also be connected between the load and ground. Let’s stay with the
MOD1
example of the halogen lamp. Figure 16 shows such a low-side
GP6 GP27
10 31
GP7 GP26
11
GP8 RUN
30
measurement.
12 29
GP9 GP22
13 28
14
GND GND
27 Here, a 0.1 Ω resistor is used, which causes a voltage drop of 0.2 V
GP10 GP21
15
GP11 GP20
26
R1
at 2 A. The advantage now is that the potentials of the voltages
16
GP12 GP19
25
to be measured are below those of the reference voltage of the
0Ω1

ADC and the supply voltage of the MCU. However, at 25 mA, only
17 24
GP13 GP18
18 23
19
GND GND
22 2.5 mV can be measured (0.1 mV per mA). Under ideal conditions,
the 12-bit ADC with a 3.3 V reference voltage would still resolve
GP14 GP17
SWCLK

SWDIO

20 21
GND

GP15 GP16
0.8 mV per bit. However, a look should be taken at the effective
230027-017
number of bits (ENOB) of the ADC, which takes into account the
measurement errors that occur in practice due to quantization
error, distortion, noise, and similar adversities. For the RP2040, an
Figure 16: Low-side measurement. ENOB of about 9 is specified, which means around 6.44 mA per bit.
For this application, the resolution of the current measurement
would be just about sufficient. However, if a finer resolution is
needed, useful may be an op-amp, which would also allow for a
smaller resistance value.

Operational Amplifiers and Temperature Sensors


A1 Arduino Nano Every
Entire libraries of books have been written about operational ampli-
1
TX VIN
30
fiers. When wired appropriately, these fundamental and versatile
2 29
3
RX GND
28
components have a myriad of applications, a few of which have
+5V
already been mentioned in this article. When it comes to measur-
RST RST
4 27 +5V
GND 5V IC2
5
D2 A7
26 ing voltages, it’s not only shunt resistors where the voltages are in
6
D3 A6
25 1
SDA +Vs
8
a less than ideal range for an MCU’s ADC. Temperature sensors are
7 24 2 7
8
D4 SCL/A5
23 3
SCL A0
6
candidates for this problem, too, at least if they are purely analog,
LM75B
resistive types like a PT100 or thermocouples made of two different
D5 SDA/A4 O.S. A1
9 22 4 5
D6 A3 GND A2
10
D7 A2
21 metals, unlike those with a digital interface such as the DS18B20
11
D8 A1
20
or the DHT11.
12 19
D9 A0

Thermocouples
13 RESET AREF 18
D10
14 17
MOSI/D11 3V3
15
MISO/D12 SCK/D13
16 These elements consisting of two metals act as temperature-de-
+5V
pendent voltage sources. The widely used K-type thermocouple
shall serve as an example. At 21 °C or 69.8 °F, such a component
USB
outputs a voltage of 0.838 mV due to the Seebeck effect; at 22 °C
C1
or 71.6 °F, it is 0.879 mV. The difference of only about 40 µV per
MCP6001U 100n degree puts the ADC of an MCU to a hard test. In addition, using
thermocouples also requires cold junction compensation [4].
R3 5
1
1k
4
IC1
3
TC1
2
However, an operational amplifier can be used to amplify the
voltage of a thermocouple. Figure 17 shows an example of such
a circuit implemented for an Arduino Nano Every, where a tempera-
R2
200k
R1 ture range of 0 °C to 400 °C is expected (0 to 16.396 mV voltage
C2
Thermocouple
from the thermocouple).
Type K
1k

100n

Here, the non-inverting operational amplifier is operated with


230027-018 a gain of A = 200. To minimize interference at the input of the
operational amplifier, an RC filter was added; a simple LM75 digital
temperature sensor takes care of temperature detection for cold
Figure 17: Reading a thermocouple with the Arduino Nano Every. junction compensation.

18 May & June 2023 www.elektormagazine.com


+3V3

R1 R2 C1

10k

10k
MCP6001U 100n 1 18
RST TX0
1 5 2 17
IO5 RX0
4 3 IC2 16
IC1 IO2 IO4
3 4 15
IO11 BL602 EVB IO3
2 5 14
IO12 IO1
6 13
R3 R4 IO14 IO0
TH1 7 12 +3V3
IO17 GND

850Ω
PT1000 10k
8 11
GND GND
9 10
5V 3V3

RST

L IO8 H

USB
230027-019

Figure 18: Wheatstone bridge for a PT1000.

PT100 and PT1000 ADC is something everyone should try. The examples shown here
PT100 and PT1000 are temperature-dependent resistors, which are meant to be suggestions for your own attempts to let the micro-
have a resistance of 100 Ω (PT100) or 1000 Ω (PT1000) at 0 °C. In controller interact with the analog world outside its housing.
order to calculate the temperature, the resistance value of the sensor
must first be measured. A good option for precisely determining the Translated to English by J. Starkmuth — 230027-01
resistance value is a Wheatstone bridge. As with thermocouples,
the voltages are quite low with PT100 and PT1000, and the small
difference between two measuring points must be determined. Questions or Comments?
Again, an op-amp wired as a non-inverting differential amplifier Do you have questions or comments about this article? Email Elektor
provides the necessary assistance. The circuit for a board with a at [email protected].
3.3 V supply voltage, such as the Pinecone BL602 Evaluation Board,
is shown in Figure 18.

The voltage difference between the positive and the negative input
of the operational amplifier is amplified. But what if the tempera-
ture goes lower than 0 °C? In this case, the op-amp would have to
output a negative voltage, which is not possible. One option here
would be to replace 10 kΩ resistor R3 with an 850 Ω resistor. The
voltage between R1 and R2 would then be 0.3917 V, which would
Related Products
also apply to the point between R3 and the PT1000 at a tempera-
ture of -38 °C. Thus, the measuring window would start at -38 °C > Arduino Nano (SKU 17002)
with a voltage difference of 0 V. At 20 °C, the voltage difference in www.elektor.com/17002
the circuit would be 0.09444 V.
> Raspberry Pi Pico RP2040 (SKU 19562)
www.elektor.com/19562
Summary
The processing and output of analog values can be done with a > Pinecone BL602 Evaluation Board (SKU 19914)
microcontroller and a manageable effort. Even if the whole thing www.elektor.com/19914
doesn’t seem as simple as controlling a digital I/O pin, handling the

WEB LINKS
[1] Guido Nopper, “A Simple A/D Converter Using a PLD,” Elektor 9-10/2019:
https://elektormagazine.com/magazine/elektor-110/51146
[2] Hardware design with RP2040: https://datasheets.raspberrypi.com/rp2040/hardware-design-with-rp2040.pdf
[3] Giovanni Carrera, “Isolated Analog Output for Arduino Uno,” Elektor 11-12/2022:
https://elektormagazine.com/magazine/elektor-280/61046
[4] Cold junction compensation (Wikipedia): https://en.wikipedia.org/wiki/Thermocouple#Reference_junction

lektor May & June 2023 19


EVENT

embedded world 2023


Embedded world 2023 in Nuremberg — a must for everyone dealing with
microcontrollers and tools — took place at its customary time in spring again. This
year, there were 27,000 visitors, which is a 50% increase compared to the 2022 show,
with more than 950 exhibitors in 6 halls. Elektor editor Stuart Cording, Content Director
C. J. Abate, and Chief Editor Jens Nickel had the chance to go around and find a lot of
interesting things, but, of course, their personal selection can only be a very small section
of all the things playing on the market. You can find even more on our
Elektor TV: Industry YouTube channel at https://youtube.com/@ElektorIndustry.

oxid[OS]
been the mainstay of
The C programming language has
des. But, for how much
the automotive industry for deca
spok e to Flavi a Opre a to learn why the up-and-
longer? We
as a way of avoiding the
coming language , Rust , is seen
kes inhe rent to emb edde d C programming.
traditional mista
has been deve loping a
Based in Romania, the startup
real- time oper ating syste m (RTO S) which was
Rust-based
troller at the trade
demonstrated on an STM32 microcon
ve deve lope rs are alrea dy showing interest
fair. Automoti
oved secu rity and
thanks to the promise of impr
of isola ted legac y C/C+ + code .
its support

https://oxidos.io/
Check out the interview:
1398
Siglent https://youtu.be/BNdvgJdN5_Q?t=
Elektor’s DC Dual LISN was put to
use at the Siglent
booth. The 5-µH, 50-Ω Dual DC LISN
supports voltages
up to 60 V and currents up to 10 A.
It measures RF
interference on both channels by way Axelera
of 5-µH blocking
inductances. The internal 10-dB atten The Dutch company Axelera provides modules which can
uation network
(one in each channel) contains a third process AI inference applications as image recognition
-order, high-pass
filter with a cutoff frequency of 9 kHz right on the edge. Boards come in different form factors
to protect the input
of instruments like a spectrum anal as M.2 (picture) or PCIe. Powered by a single Metis AIPU,
yzer from potentially
harmful DC voltages or low frequencie the M.2 module delivers up to 214 tera-operations per
s coming from the
equipment under test. second (TOPs) while minimizing power consumption and
simplifying integration through the downloadable software
Watch the demo at: stack. Price is USD/EUR 149.
https://www.elektormagazine.com/e
w-lisn https://axelera.ai/ai-product-solutions/

20 May & June 2023 www.elektormagazine.com


Espressif
The ESP32 is well known for its ease of use when
implementing wireless applications, which is why ESP32
and other espressif solutions were featured in dozens of
interesting demos at embedded world 2023. Examples
included: an ESP-ZeroCode module for smart blinds, ESP
RainMaker demos, and Matter Wi-Fi devices. Elektor also
caught up with Espressif’s Amey Inamdar at embedded
Mikroelektronika world to find out what’s new. Among the highlights: RISC-V
quipped frame for
On the fair, Mikroe showed a camera-e SoCs along with a dual-core version in the pipeline;
et Debu g syste m: Deve lope rs and students can
their Plan support for Matter to make IoT devices using differing
ocon trolle r proje ct remotely
develop and debug a micr protocols easier to deploy; and the RainMaker platform for
witho ut the need to have the same boards really
together, implementing the cloud backend of IoT.
igure their hardware
on their desks. Users can now conf
own spec ial need s, selec ting motherboards ,
to their Watch Stuart Cording’s interview!
large num ber of peripherals and
processor boards, and a https://youtu.be/EFnUtAJX2aA
displays.

https://mikroe .com/planet-debug

Live Show Mash-up


For the second time, Stuart Cording from Elektor Engineer-
ing Insights and Jens Nickel from Elektor Lab Talk came
together to report live from an electronics fair. In the
one-hour show, Stuart and Jens talked shop with Elektor’s
content director C. J. Abate about the most interesting things
seen on the embedded world 2023 (for example, a beer-
tapping, cloud-controlled robot). Special guest: Elektor
author Viacheslav Gromov, who won the “embedded award”
in the category “AI” with his company AITAD.

re:
t c h t h e f ull video he
Wa be.com/
www.youtu 5lVKZx7Q
Od
watch?v=o

lektor May & June 2023 21


Slint
Slint is a toolkit to efficiently develop graphical user
interfaces for embedded and desktop displays. Multiple
programming languages are supported, such as Rust,
C++, and JavaScript. According to the developers, the
Seco
solution just needs a few hundred kilobytes of RAM and
Italy-based IPC and solution provider Seco presented the
little processing power. There are commercial licenses, but
modular IoT platform CLEA. At the edge, it can monitor
also an open-source one under GPLv3.
event data of the hardware itself and of the customer ’s
applications. For this purpose, CLEA offers open APIs
https://slint-ui.com/#tryout
and protocol converters as well as AI-based edge logic
for analyzing raw data and images. CLEA is hardware
and cloud-agnostic with an open-source base, ensuring
long-term availability. Applications that have already
been realized include smart coffee vending machines,
charging stations and medical devices.

https://north.seco .com/en/products-and-services/
clea-iot-platform

Arm
As we’ve covered in our Elektor Engineering Insights
show, the world of automotive is changing dramatically. Digi
Today, once the software for an ECU is complete , it never The Digi XBee® XR 868 module is a compact and reliable
gets updated — unless a safety-related issue is found. solution that supports the use of long-range connectivity
But this is changing, as Robert Day explained with Arm’s applications in the European region. The pre-certified
new SOAFEE initiative. Drawing upon how orchestrators module operates between 863 and 870 MHz and supports
and containers are used in cloud software and CI/CD both point-to-point and mesh networking protocols with a
development processes, such methodologies are being line-of-sight range of over 14 kilometers. Of course, a dev
adapted for safety-critical automotive software . Currently, kit is also available (picture).
a range of semiconductor vendors, automotive OEMs, and
their suppliers are engaged. https://digi.com/products/embedded-systems/digi-xbee/
rf-modules/sub-1-ghz-rf-modules/digi-xbee-xr-868

Check out the video interview!


https://youtu.be/nr_6W4UgihM

230202-01

22 May & June 2023 www.elektormagazine.com


ktor TV Show
Ele s
Elektor Engineering Insights
Elektor Industry Insights is a go-to resource for busy
engineers and maker pros who want to stay informed
about the world of electronics. During each episode, Stuart
Cording (Editor, Elektor) will discuss real engineering
challenges and solutions with electronics industry experts.
www.elektormagazine.com/elektor-engineering-insights

Elektor
Are you passionate about DIY electronics, embedded
programming, or engineering theory? Join Elektor Lab
team engineers and editors as they share engineering
tips, plan future electronics projects, discuss Elektor
Mag and answer community questions.
www.elektormagazine.com/elektor-lab-talk

Do you want to enhance your electronics skills?


Turn to Elektor Academy for resources to level
up your engineering capabilities. Our Expert
Stuart Cording will guide you through the Elektor
academy courses
www.elektormagazine.com/elektor-academy

Stay informed and join our


YouTube channel Elektor TV
www.youtube.com/c/ElektorIM

lektor May & June 2023 23


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

Sub-Nyquist
Sampling in Practice
ies Using Subsampling
Reliably Capturing Higher Frequenc

) (Germany)
By Sebastian Westerhold (AI5GW The Problem
s will soon
Anyone dealing with sampling system
The Nyquist-Shannon sampling theorem is an
sed by the extremely important theorem when dealing
become aware of the limitations impo with sampling systems. The very simpli-
According
Nyquist-Shannon sampling theorem. fied version of the theorem states that the
encies higher
to this rule, signals containing frequ
sampling frequency needs to be at least twice
no longer the highest frequency occurring in the signal
than half the sampling frequency can to be sampled. You have certainly heard or
only half
be reliably detected. However, this is read something like this before.
ing higher
the truth. A reliable method for captur
pling, also What happens if you sample a pure sinusoi-
frequency signals is known as subsam dal signal of 120 kHz with a sampling rate of
icle presents
called sub-Nyquist sampling. This art only 100 kS/s (kHz)? This will result in what is
a simple
the method in a practical way, using
called aliasing at 20 kHz. The acquired samples
would therefore look as if a sinusoidal signal
Arduino UNO. with a frequency of 20 kHz (120 kHz - 100 kS/s)
had been sampled. And aliasing errors should
be avoided by all means. Or should they?

Whether aliasing errors are an interfering


factor or can be used as a useful technique
120 kHz
80 kHz

depends on the specific application. In the


20 kHz

example with the sampling rate of 100 kS/s,


falias

Power
it would be impossible to distinguish between
f2

f1

a 20 kHz signal and a 120 kHz signal; both


signals would look like a 20 kHz signal.
Incidentally, an 80 kHz signal would also
produce aliasing of 20 kHz (100 kS/s - 80 kHz)
(Figure 1). However, this circumstance is criti-
cal only if a distinction between the signal
frequencies mentioned is necessary at all. If
all frequency components actually occurring
in the signal fall within a clearly identifiable
0.5 fs fs 1.5 fs range, the sampling can be meaningful if
100 kS/s aliasing effects are intentionally exploited. The
uniqueness is given if all frequency compo-
Figure 1: At a sampling rate of 100 kS/s, both a signal of 120 kHz (f1) and a signal of 80 kHz (f2) produce nents occurring in the signal to be sampled
an aliasing effect (fALIAS) of 20 kHz. fall within the same Nyquist zone.

24 May & June 2023 www.elektormagazine.com


Power

1 2 3 4 5 6
to about 462 kHz) using subsampling and
demodulate FSK signals (NAVTEXT, RTTY,
fs etc.) even with the relatively low-speed
0.5 1 1.5 2 2.5 3 Arduino UNO.

Figure 2: Nyquist zones 1 to 6. zone 1 = “normal range”, zones 2, 4, 6 = inverting ranges, zones Notes
3 and 5 = non-inverting zones. In order for subsampling to work as desired,
the ADC used must have the required analog
bandwidth. This is usually much higher than
The frequency range from 0 Hz (DC) to half Thus, the signal frequency is a few kHz higher the sampling rate. In the datasheet you typically
the sampling frequency (fs) is called Nyquist than the sampling rate itself, but less than 1.5 fs find this figure as “full-power bandwidth.” With
zone 1 (Figure 2). This zone is the “normal” (corresponding to Nyquist zone 3). Accord- the ATmega328P, subsampling seems to work
operating range for a sampling system. ingly, the aliasing to be expected due to subsa- very cleanly up into the MHz range, accord-
Nyquist zone 2 extends from 0.5 fs to fs. These mpling is between 6 kHz (160 kHz - fs) and ing to my experiments. Unfortunately, my own
zones then continue theoretically infinitely at 11 kHz (165 kHz - fs). experiments with the Raspberry Pi Pico did
0.5 fs intervals. The Nyquist zones with even not yield promising results.
numbers have a special characteristic: Within The Arduino code is structured so that the Translated by J. Starkmuth — 220629-01
these zones, an inversion of the frequency Arduino’s A/D converter uses an interrupt
spectrum takes place. service routine (ISR) to sample the signal at
Analog Input 0 until a buffer of 512 discrete Questions or Comments?
Therefore, if the bandwidth of a signal to be samples is filled. The (aliasing) signal Do you have questions or comments
captured is limited to the range of one of these frequency is then calculated from these values about this article? Email the author at
Nyquist zones, subsampling can be used to before the next 512 samples are sampled and [email protected], or contact
capture signals whose frequency components the game starts all over again. Elektor at [email protected].
significantly exceed the sampling rate.
To determine the frequency, the Goert-
A Practical Example zel algorithm was used, a resource-saving
For a project, the frequency of a signal in the special form of the discrete Fourier transform
Related Products
range of about 160 kHz to 165 kHz is to be [1]. The result is then output for demonstra-
reliably acquired with an Arduino UNO [2]. tion purposes via the serial interface, visually > Siglent SDG1032X 2-ch Signal
For technical reasons, the sampling rate formatted for Serial Monitor (Figure 4). Generator (30 MHz) (SKU 20276)
was set to about 154 kS/s using the appro- https://elektor.com/20276
priate registers (prescaler 1:8) (strictly speak- Using the same principle, one could, for
> OWON XSA810 Spectrum Analyzer
ing, it is 153,846 S/s; for the sake of clarity, example, capture a 455 kHz IF from a radio (1 GHz) (SKU 19714)
the rounded number is used in this article). receiver in Nyquist zone 6 (3 fs, equivalent https://elektor.com/19714

> HackRF One Software Defined


Radio (1 MHz to 6 GHz)
(SKU 18306)
https://elektor.com/18306

> MonoDAQ-U-X Multifunctional


USB Data Acquisition System
(50 kS/s) (SKU 18766)
https://elektor.com/18766

WEB LINKS
[1] Sebastian Westerhold (2022):
Goertzel library for Arduino:
https://github.com/AI5GW/Goertzel
[2] Download of the Arduino sketch
https://www.elektormagazine.com/
220629-01
Figure 3: Arduino / signal generator setup. Figure 4: The results are shown in Serial Monitor.

lektor May & June 2023 25


SOFTWARE

Android
Smartphone
Here, ESP32
There?
Practical Project Using
the Android Wi-Fi API

By Tam Hanna (Hungary)


The Android OS is designed to prioritize user interface experience over
Developers of Android apps will know response time to external stimuli. This high latency makes it unsuitable
that the code required to connect to a for servicing time-critical events. Android is equipped with extensive
GUI stacks, and, for demanding tasks such as displaying graphs, there
Wi-Fi network is not trivial, especially are libraries that can be loaded via Gradle.
when you need to make the whole process
as slick and smooth as possible for the In the case where a system needs a fast response to real-time events
and also has UI requirements, it seems logical to distribute process-
end user. Software developers also need ing as shown in Figure 1.
to ensure that their code is compatible
with various versions of Android and be Often, the weak link in the chain is the end user, who ultimately has
to input values to the system. If the end user is required to “manually”
aware of security measures required by establish a link to a certain Wi-Fi network, your product support team
Google so that the app functions trouble- is sure to get countless calls from frustrated customers.
free. This article should help you navigate
Things would go more smoothly if an automatic hookup to a network
a path through the jungle. could be established. Google, however, has functional security and
personal data protection concerns about such a technique.

What’s Going On Here?


If you are not concerned by its relatively high power consumption, then The aim of the following article is to describe the Android code required
Wi-Fi is the radio standard of choice, especially for smaller projects. to establish a communication link with a target Wi-Fi network. An
We can disregard Bluetooth on the grounds of Bluetooth SIG certifi- ESP32 runs SoftAP to establish a remote Wi-Fi access point, to which
cation costs and licensing fees. Communication can take place using the Android device can connect. In practice, this code can also be
a REST interface architecture, and Wi-Fi transmitters are available used with many other Wi-Fi-capable controllers (see download at [1]).
just about everywhere.
The following article is based on a project that the author developed
It’s no surprise that small ESP32 development boards — with their for a client. Pretty much any ESP32 board that runs a variant of the
built-in Wi-Fi access points — are so popular with developers of Android sample program, esp-idf/examples/wifi/getting_started/ (included in
applications. the ESP-IDF [2]) configured as an access point would also be suitable.

26 May & June 2023 www.elektormagazine.com


Combinatorial System
Can call API
Android ESP32

Yes Yes
Do you assert that
Has user granted Has user granted
Yes your app doesn’t No
NEARBY_WIFI_DEVICES ACCESS_FINE_LOCATION
use the permission
to the calling app? to the calling app?
to get location?
No No

Visualization MSR code


Throw exception
Input Data Acquisition

Figure 1: The Android smartphone handles the GUI, while the Figure 2: Additional permissions may be required for wireless
ESP32 is responsible for hardware communication. communication under Android 13 (see image at [4]).

It is assumed the reader has previous experience with the ESP32 in targetSdkVersion. If an app is designed to only run on older OS
development environment. versions, Android Studio will alert you during compilation time with a
message in the format of “Google Play requires that apps target API
On the Android side, you should have two smartphones: one running level 30 or higher,” indicating that the Play Store backend will refuse
Android build ≥ 10, and one running Android 9 or earlier. Android to upload the generated APK. In the not-too-distant future, Google
Studio [3] serves as the development environment. Space is limited intends to phase out “very old” apps from the Play Store.
here, so I will also assume that the reader has some previous experi-
ence of the Android IDE. As a developer, you need to be aware of these limitations and possi-
ble pitfalls.
Configuration
The compilation-configuration of an Android project is quite a compli- Permissions
cated process. Usually, you will find a version of the build.gradle file You can roughly divide the world of Android into the time before and
belonging to the app module so that all of the app’s necessary settings the time after the new permission management system and/or Storage
and dependencies will be set up in Android Studio. This file will typically Access Framework: in the good old days, developers were generally
contain statements such as: free to do whatever they wished, but then Google got serious about
personal data security.
android {
compileSdkVersion 29 In the case of Wi-Fi, the situation is touchy, as location information can
buildToolsVersion "30.0.1" be gleaned from knowledge of the wireless networks in the area (for
defaultConfig { example, Apple’s first iPod touch, with no GPS or cellular capability,
minSdkVersion 26 could determine its location this way).
targetSdkVersion 31
It is now necessary to specify the following declarations in the Android
The minSdkVersion field allows the developer to specify the minimum app’s manifest file to request that certain permissions be granted to
version of the Android operating system for the target or end device the app.
with which the app is compatible. The value 26 refers to Android 8
(Oreo). compileSdkVersion specifies the version of the Software <uses-permission android:name=
Development Kit with which the app will be compiled, and build- "android.permission.ACCESS_FINE_LOCATION" />
ToolsVersion indicates which version of the Android build tools will <uses-permission android:name=
be used to compile the project. The line targetSdkVersion specifies "android.permission.ACCESS_COARSE_LOCATION" />
the version of the Android OS for which an app is being developed. <uses-permission android:name=
"android.permission.ACCESS_WIFI_STATE" />
This distinction, which sounds complicated and confusing at first glance, <uses-permission android:name=
is necessary because the “behavior” of many Android APIs changes "android.permission.CHANGE_WIFI_STATE" />
depending on which OS version it will be running under. <uses-permission android:name=
"android.permission.CHANGE_NETWORK_STATE" />
If targetSdkVersion is set to a certain value, the operating system <uses-permission android:name=
assumes that the developer has considered all the changes introduced "android.permission.ACCESS_NETWORK_STATE" />
in this version in the design of the app — if the value is smaller, the
compatibility mode is activated. If you want to support Android 13 in your application, you must make
an additional change: In the case of WLAN, the Android 13 permission
Unfortunately, Google has strict guidelines for the values specified logic works as shown in Figure 2.

lektor May & June 2023 27


It is now necessary to specify the following declarations in the Android
app’s manifest file to request that certain permissions to be granted
to the app.

<uses-permission android:name=
"android.permission.NEARBY_WIFI_DEVICES"
android:usesPermissionFlags="neverForLocation" />

The android.permission.NEARBY_WIFI_DEVICES permission is


a request by the app developer to allow the app to scan for and
access any nearby Wi-Fi devices, while android:usesPermission-
Flags="neverForLocation" is a special regime that assigns a “never
for location” flag to be granted to the app. This declares that the app
uses Wi-Fi information only for configuration purposes and not for
location information. In this case, the android.permission.ACCESS_
FINE_LOCATION permission is not required under Android 13.

Earlier versions of the operating system require this permission, in


which case a configuration of the following scheme is recommended:
Figure 3: Google requires explicit user consent.

<uses-permission android:name=
"android.permission.ACCESS_FINE_LOCATION"
android:maxSdkVersion="32" />

In this context, the maxSdkVersion attribute ensures that the permis-


sion declaration is only recognized by earlier Android versions. To actually turn on the Wi-Fi, we need to send an Intent of type
Settings.Panel.ACTION_WIFI:
Twin-Track Development
In setting up the Activity responsible for “scanning” the environment else {
for a usable Wi-Fi endpoint, we first need to check if the phone’s wifiManager =
Wi-Fi is enabled: (WifiManager) getApplicationContext().
getSystemService(Context.WIFI_SERVICE);
@Override if (!wifiManager.isWifiEnabled()) {
protected void onCreate(Bundle savedInstanceState) { Toast toast =
... Toast.makeText(getApplicationContext(),
if (android.os.Build.VERSION.SDK_INT < "PLEASE enable WiFi so that we can connect!",
Build.VERSION_CODES.Q) { Toast.LENGTH_LONG);
wifiManager = toast.show();
(WifiManager) getApplicationContext() Intent panelIntent =
.getSystemService(Context.WIFI_SERVICE); new Intent(Settings.Panel.ACTION_WIFI);
if (!wifiManager.isWifiEnabled()) { this.startActivityForResult(panelIntent,
wifiManager.setWifiEnabled(true); ICY_WIFI_REQCODE);
} }
} }

If we are dealing with an older version of Android that is not affected Your reward for all the effort is the message shown in Figure 3 appear-
by API changes, our program can turn on the phone’s Wi-Fi without ing at runtime. The user needs to toggle the button to authorize the
having to seek consent from the user. Unfortunately, this does not activation process.
apply to newer versions of Android — in these versions, user consent
is required. The snippet printed here fires a toast toward the user before sending
the Intent, informing about the need to activate the Wi-Fi.
To distinguish between the two variants at runtime, we rely on the
constant android.os.Build.VERSION.SDK_INT. It refers to the API If the action is not taken, it may be necessary to remind the user of
version supported by the firmware of the current phone. the need to activate the Wi-Fi.

28 May & June 2023 www.elektormagazine.com


Old But Gold
Once you’ve finished your first smartphone app, why not take a
trip back through the mists of time and check out the core princi-
ples that Jeff Hawkins used to create Palm OS, which ran on Palm
and Palm Pilot devices. Even though they are now obsolete, his
philosophy in designing Palm OS is interesting. Zen of Palm is quite
short, and you can find a PDF version at [5].
In the case of a new phone, to avoid a crash, at this point the Wi-Fi
transmitter’s power state is checked again because it is quite possi-
ble for users to turn off the Wi-Fi before the method becomes active.
For Android beginners, it may seem odd that ICY_WIFI_REQCODE is
passed to startActivityForResult(), but this is a correlation code else {
that allows the receiving endpoint to identify the trigger responsible if (wifiManager.isWifiEnabled()) {
for the incoming request. getWifiWorkerOld();
}
Correlation codes are normal integer values to which the operating else {
system does not assign any significant value. The author declares Toast toast =
them in the program using the following scheme; it’s only important Toast.makeText(getApplicationContext(),
that the code generated is unique. "PLEASE enable WiFi so that we can connect!",
Toast.LENGTH_LONG);
public class MainActivity extends toast.show();
AppCompatActivity implements Intent panelIntent =
AdapterView.OnItemClickListener { new Intent(Settings.Panel.ACTION_WIFI);
private final int MY_PERMISSIONS_ this.startActivityForResult(panelIntent,
ACCESS_COARSE_LOCATION = 1; ICY_WIFI_REQCODE);
int ICY_WIFI_REQCODE = 4242; }
}
The next task is to trigger the actual Wi-Fi scan process. Space
constraints mean that we can’t delve into the Android GUI stack, but Once we’ve successfully checked the transmitter’s power state, we
we’re confident that you’ll find a way to activate the getWifi() method. proceed to activate the scan process using the following:

The first step in location information processing is to check if we private void getWifiWorkerOld() {
already have access permission for the Manifest.permission. ...
ACCESS_FINE_LOCATION. Under Android 13, you should also include wifiManager.startScan();
the new permission in the analysis code: }

private void getWifi() { wifiManager is a system class that we obtained as part of Activating
if (ContextCompat. the Activity. The startScan() method then takes care of starting the
checkSelfPermission(MainActivity.this, scan process.
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) { The return of information captured by the scan run is done by Broad-
ActivityCompat. cast. For its reception, we need a Broadcast Receiver. Since we don’t
requestPermissions(MainActivity.this, want to create it in the manifest file, we write it in the Activity’s onPost-
new String[]{Manifest.permission. Resume() method instead:
ACCESS_FINE_LOCATION},
MY_PERMISSIONS_ACCESS_COARSE_LOCATION);
}

Remember that, for Android 6.0 and above, “sensitive” permissions are
only enabled by the operating system when the user explicitly agrees
to them. Dialogs are used for this purpose, as shown in Figure 4.

If we already provided the permission, the next step is another version


switch. If we are dealing with an earlier version of Android, we call the
getWifiWorkerOld() method directly:

else {
if (android.os.Build.VERSION.SDK_INT <
Build.VERSION_CODES.Q) {
getWifiWorkerOld();
} Figure 4: Be aware of the new Permissions system.

lektor May & June 2023 29


if(scanResult.SSID.
@Override contains("NAMEOFTHING"))
protected void onPostResume() { deviceList.add(scanResult.SSID );
super.onPostResume(); }
receiverWifi = myParentAct.myArrayAdapter=
new WifiReceiver(wifiManager, wifiList, this); new ArrayAdapter(context,
IntentFilter intentFilter = android.R.layout.simple_list_item_1,
new IntentFilter(); deviceList.toArray());
intentFilter.addAction wifiDeviceList.
(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); setAdapter(myParentAct.myArrayAdapter);
registerReceiver(receiverWifi, intentFilter); }
} }
}
In the interest of Play Store compliance, it is important that manually
registered BroadcastReceivers are also unregistered by the operating In the first step, the code calls intent.getAction() to check the
system. This can be done most conveniently using one of the activi- name of the Intent. Broadcast Receiver can theoretically contain any
ty’s lifecycle methods. I decided to use the onPause() method here: Intents; by checking against the WifiManager.SCAN_RESULTS_AVAIL-
ABLE_ACTION string, we make sure we are dealing with a “compat-
@Override ible” Intent.
protected void onPause() {
super.onPause(); Since the code example from which the author took the following
unregisterReceiver(receiverWifi); snippets uses a list for display, some tweaking is required in the
} next step. Anyway, the sense of the process is the population of the
deviceList class.
Broadcast Receiver for Data Processing
Since the receipt of network information returned by the Wi-Fi scan At this point in a real application, a list would be filled with informa-
process is done through Android’s broadcast system, we need to tion, but you can proceed differently at this point, of course, if you only
implement the BroadcastReceiver class registered above with the consider a single target Wi-Fi network to be valid.
operating system.
An example of the other approach would be a device that makes
BroadcastReceivers in Android take the form of classes derived from contact with its base application during configuration and indicates
the BroadcastReceiver master class. In our example — ignoring the this by a specific Wi-Fi name. In this case, we could continue immedi-
GUI variables — the “header” looks as follows (we are not printing the ately after detecting that network.
constructor necessary to populate the fields):
A Neat Connection Setup
class WifiReceiver extends BroadcastReceiver { Users dislike long waiting times with smartphone applications. There-
WifiManager wifiManager; fore, it makes sense to show progress bars or similar gadgets that
ListView wifiDeviceList; assure the user that the application has not crashed.
MainActivity myParentAct;
In the client application that serves as the basis for this article, it was
The important question now is how to process the network informa- implemented in the form of a dedicated activity: It displays a company
tion returned from the Wi-Fi transmitters. The answer can be found logo and a progress bar, thus providing some reassurance. It is activated
in the onReceive() method, which the operating system will activate by sending an intent:
when the broadcast information, which is delivered in the form of
Intents, arrives. public void onItemClick(AdapterView<?>
adapterView, View view, int pos, long anID) {
public void onReceive(Context context, Intent intent) { String y = (String) myArrayAdapter.getItem(pos);
String action = intent.getAction(); Intent intent =
if (WifiManager. new Intent(MainActivity.this,ConnActivity.class);
SCAN_RESULTS_AVAILABLE_ACTION.equals(action)) { intent.putExtra("WIFINAME", y);
List<ScanResult> wifiList = startActivity(intent);
wifiManager.getScanResults(); }
ArrayList<String> deviceList =
new ArrayList<>(); In the “Code Behind,” it starts by declaring an AsyncTask that performs
for (ScanResult scanResult : wifiList) { a presence test. This is a verification (not described here) that the

30 May & June 2023 www.elektormagazine.com


Beware the Google Block
For Android 11 onward, Google introduced “one-time permissions,”
which allow the user to grant an app access to a certain feature or
data once only. It also changes the way background apps request
permissions, which may lead to some requests being blocked. The
reasoning behind this is to give users more control over their data
and improve privacy on Android. Developers should be aware of
these possible issues. //Can only come here from permission granted state
@SuppressLint("MissingPermission")
List<WifiConfiguration> list =
wifiManager.getConfiguredNetworks();
for (WifiConfiguration i : list) {
connection peer is part of the client ecosystem: if (i.SSID != null && i.SSID.equals("\"" +
b.getString("WIFINAME") + "\"")) {
public class ConnActivity extends AppCompatActivity { final ConnectivityManager connectivityManager =
PresenceTestAsynctask aT; (ConnectivityManager)getApplicationContext().
ConnActivity mySelf; getSystemService(Context.CONNECTIVITY_SERVICE);
ConnectivityManager.NetworkCallback
In onCreate(), the connection establishment starts without any further networkCallback =
action by the user. The first official action is to configure some member new ConnectivityManager.NetworkCallback() {
variables and call the getIntent().getExtras() methods to make @Override
the information — “packaged” further above by Intent — accessible public void onAvailable(@NonNull Network network) {
with the Wi-Fi name and other support data: super.onAvailable(network);
//ONLY IF ANDROID 9
@Override if (android.os.Build.VERSION.SDK_INT ==
protected void onCreate(Bundle savedInstanceState) { Build.VERSION_CODES.Q) {
super.onCreate(savedInstanceState); connectivityManager.
setContentView(R.layout.activity_conn); bindProcessToNetwork(network);
mySelf=this; }
Bundle b = getIntent().getExtras(); }
String networkPass = "sdsds"; };
connectivityManager.
The next step is another version switch, which checks the “version registerDefaultNetworkCallback(networkCallback);
status” of the target hardware.
wifiManager.disconnect();
If we’re dealing with an earlier version of Android, the next step is the wifiManager.enableNetwork(i.networkId, true);
start of the connection setup according to the following: wifiManager.reconnect();
aT = new PresenceTestAsynctask
if (android.os.Build.VERSION.SDK_INT < (getApplicationContext());
Build.VERSION_CODES.Q) { aT.myAct=mySelf;
WifiConfiguration conf = aT.execute("...");
new WifiConfiguration(); break;
conf.SSID = "\"" + }
b.getString("WIFINAME") + "\""; }
conf.preSharedKey = "\"" + networkPass + "\"";
WifiManager wifiManager = With newer versions of Android, user intervention is again required at
(WifiManager) getApplicationContext(). this point. The work begins by creating a NetworkSpecifier object
getSystemService(Context.WIFI_SERVICE); like this:
wifiManager.addNetwork(conf);
}else{
The addNetwork() method takes over an object of type WifiCon- final NetworkSpecifier specifier =
figuration. Its task is to deliver a complete WLAN information set, new WifiNetworkSpecifier.Builder()
to which the phone can then connect. .setSsidPattern(new PatternMatcher(
b.getString("WIFINAME"),
In our last act, we have to initiate the connection setup according to PatternMatcher.PATTERN_PREFIX))
the following scheme, which is done using three methods: discon- .setWpa2Passphrase(networkPass)
nect(), enableNetwork(), and reconnect(). After that comes the .build();
activation of the AsyncTask — if the remote station is successfully
authenticated, the client application starts with the actual configura- NetworkSpecifier objects are a kind of search filter that helps the
tion of the connected hardware:

lektor May & June 2023 31


super.onAvailable(network);
connectivityManager.
bindProcessToNetwork(network);
aT = new PresenceTestAsynctask
(getApplicationContext());
aT.myAct=mySelf;
aT.execute(". . .");
}
@Override
public void onUnavailable() {
super.onUnavailable();
}
};

If the onAvailable() method is called, the connection was success-


fully established. In this case, the application restarts the AsyncTask
to authenticate the remote end and perform any additional actions
when required.

The final action of our scan method is then to call requestNetwork(),


Figure 5: Android Q prompts the user before
establishing a connection. which activates the user interface shown above.

connectivityManager.
requestNetwork(request, networkCallback);
Android GUI identify wireless network peers relevant to the use case. }
}
The next step is to build a NetworkRequest element, which is done }
as follows:
Is It Worth All the Effort?
final NetworkRequest request = There are often many ways to solve a problem in engineering. It’s true
new NetworkRequest.Builder() that real-time operating systems — I’m thinking here of the Azure RTOS
.addTransportType(NetworkCapabilities. — along with their embedded GUI stacks, running on a microcontrol-
TRANSPORT_WIFI) ler, will indeed realize powerful graphic interfaces in a single-device
.removeCapability(NetworkCapabilities. solution that will cover most advanced use cases.
NET_CAPABILITY_INTERNET)
.setNetworkSpecifier(specifier) To achieve the same functionality provided by the Android configura-
.build(); tion described here would incur higher hardware costs — there will be
no touchscreen for the GUI as the associated logic, such as a frame
The actual connection setup takes place as shown in Figure 5. The buffer memory, would add to the bill of materials. On top of this, we
user needs to enter the name of the Wi-Fi network that will be the need to think about the time and effort required to develop the system:
configuration target. If you wanted to implement, for example, the transfer of images and
sensor readings by email in a real-time operating system, you need
A side effect of this procedure is that the Wi-Fi connection must to set aside a few days for coding and be aware that the additional
be established asynchronously. Feedback on success and failure is loading may impact system latency. The Arduino combination offers
provided via a callback that must be created in the application respon- a slick GUI on a device that most of us already carry around in our
sible for activation: pocket. The idea of pulling out your phone and hooking up to a local
access point, for whatever reason, is pretty cool.
final ConnectivityManager connectivityManager =
(ConnectivityManager)getApplicationContext(). If you decide to develop this project, I hope that some of the exper-
getSystemService(Context.CONNECTIVITY_SERVICE); iments and tweaks described here will offer some pointers through
final ConnectivityManager.NetworkCallback the jungle. If you’re successful or find improvements, we would love
networkCallback = to hear how you got on; send us a reader’s letter.
new ConnectivityManager.NetworkCallback() {
@Override Translated to English by M. Cooke — 210229-01
public void onAvailable(@NonNull Network network) {

32 May & June 2023 www.elektormagazine.com


Questions or Comments?
If you have any technical questions or comments, you can contact
the author at [email protected] or contact the team here
at Elektor at [email protected].

Related Products
> ESP32-PICO-Kit V4 (with female Headers) (SKU 20323) WEB LINKS
https://elektor.com/20323
[1] This article’s web page:
> ESP32-DevKitC-32D (SKU 18701) https://elektormagazine.com/210229-01
https://elektor.com/18701 [2] ESP-IDF: https://idf.espressif.com/
[3] Android Studio: https://developer.android.com/studio
[4] Android Documentation: Request permission to access
nearby Wi-Fi devices:
https://elektor.link/AndroidWiFiPermission
[5] Zen of Palm (2003) [PDF]:
https://cs.uml.edu/~fredm/courses/91.308-fall05/palm/
zenofpalm.pdf

Join the
Elektor C mmunity
The Elektor web archive from 1974! Take out a Ge mOb eLD
m rship
8x Elektor Magazine (print)
8x Elektor Magazine (digital) membership!
10% discount in our web shop and
exclusive offers
Access to more than 5000 Gerber files

www.elektormagazine.com/Member

lektor May & June 2023 33


MEASUREMENT

Active 1-kHz
Filter for Distortion
Measurement
Better Measurements Through Optimization
of the Measurement Signal
By Alfred Rosenkränzer (Germany) With affordable signal generators below the professional class, however,
the quality of the generated signal often leaves much to be desired. A
The detection of low-level signal downstream filter can work a small miracle here and provide a partic-
distortions places great demands not ularly “pure” measurement signal by attenuating the distortions of the
signal generator.
only on the dynamic range and linearity
of the measuring device, but also on Requirements
the measuring signal supplied to the Since most audio measurements are made at the typical measurement
frequency of 1 kHz, a filter with a fixed passband or cutoff frequency at
component that is being tested. With this value is usually sufficient. The filter should allow the test frequency
a downstream filter, however, even to pass unattenuated, but attenuate the harmonics (the multiples of
average signal generators can deliver the test frequency) as much as possible. Another important require-
ment is that the filter itself must not produce any significant distor-
high-quality measurement signals. tion, of course!

For easy handling, it is useful if the filter itself is not too narrow-band,
In the article “A Fliege Notch Filter for Audio Measurements” in Elektor but has some bandwidth. That way, the frequency of the measurement
September/October 2022 [1], it was shown how to extend the measure- signal can be easily matched to the exact frequency of the narrow-
ment range for distortion measurements with a digitizer by using a band notch filter without level fluctuations, so that the filter removes
notch filter. In doing so, the test signal is suppressed, thus preventing the measurement signal before the measurement. Figure 1 shows the
the digitizer itself from generating distortions. A prerequisite for the principle of this measurement with both filters before and after the DUT.
valid detection of low distortion levels of the device under test (DUT)
is, of course, that the signal generator feeding the DUT produces a Filter
high-quality signal. Otherwise, in addition to the distortion of the circuit In principle, the reduction of signal generator distortion in the form
under test, the distortion of the generator is also measured and impure of harmonic attenuation can be achieved not only with a band-pass
measurement results are obtained. filter, but also with a suitable low-pass filter. The question is which

Figure 1: The optimized measurement principle for distortion with one filter before and one after the DUT. The upstream low-pass or band-pass filter (red)
removes distortion from the generator signal.

34 May & June 2023 www.elektormagazine.com


setup and which filter type has the best harmonic attenuation relative
to the component cost. Table 1 shows the measured attenuations of
a 4th-order band-pass in comparison with different low-pass filters
for a test signal of 1 kHz. The attenuation at 2 and 3 kHz is particularly
relevant, since these harmonics have the highest amplitudes with
most generators.

Table 1 Filter damping

Frequency BP 4th-o. LP Bw. LP Ch. LP Bw.


4th-o. 4th-o. 8th-o.
(kHz) (dB) (dB) (dB) (dB)
1.0 0.0 0,1 0,3 0.0
Figure 2: Comparison of the frequency responses of an 8th-order
2.0 -45.0 -11.7 -26.0 -32.0 Butterworth low-pass filter (green) and a 4th-order band-pass filter (blue).
3.0 -56.0 -25.2 -42.0 -60.0
4.0 -62.0 -35.0 -52.0 -80.0
5.0 -66.0 -42.8 -60.0 -90.0
a band-pass of 4th order with a bandwidth of 100 Hz. Figure 2 shows
6.0 -69.0 -49.5 -67.0 -90.0
a comparison of the frequency responses of these two filters. Since
7.0 -72.0 -54.0 -72.0 -90.0 these two filters are to be preferred, developed circuit boards were
8.0 -74.0 -59.0 -77.0 -90.0 developed for them with the same size as the notch filter of [1]. The
9.0 -75.0 -63.0 -81.0 -90.0 voltage regulator board used back then can also be used here.
10.0 -76.0 -67.0 -85.0 -90.0
Circuits
Figure 3 shows the circuit of the 8th-order Butterworth low-pass filter.
To avoid any significant level attenuation in the range of a few tens of
A Butterworth low-pass filter of 4th order reaches an attenuation of just Hz around 1 kHz, its cutoff frequency is fixed at 1.28 kHz with the speci-
under 12 dB at 2 kHz and is thus not suitable for this type of application. fied component values. Figure 4 shows the layout and Figure 5 shows
A Chebyshev low-pass filter of the same order already achieves -26 dB the prototype of the low-pass filter. For the resistors and capacitors
here. An even better option is a Butterworth low-pass of 8th order or determining the frequency, an additional component is connected in

C1 C5 C9 C13

C2 C6 C10 C14
18n 22n 47n 100n
R2 R4 R8 R10 R14 R16 R20 R22
3 5 3 5
11k 6k19 8k25 3k83 8k25 4k64 10k R26
1 7 1 7
R3 R5 IC1a R9 R11 IC1b R15 R17 IC2a R21 R23 IC2b 220Ω
K1 1 2 6 2 6
5k11 129k 28k7
1 K9
IN R7 R13 R19 R25
3k48 3k48 3k48 3k48
OUT
R1 C3 C4 R6 C7 C8 R12 C11 C12 R18 C15 C16 R24
2
47k

2
15n 15n 12n 3n3

+12V
LED1

8 C21 C17 8 C23 C19


+12V +12V +12V +12V
IC2 IC1 R27
100n 22µ 100n 22µ
10k

K2 K3 K4 K5 4 4
1 1 1 1 20V 20V
2 2 2 2
IC1, IC2 = NE5532A
3 3 3 3
R28
10k

C22 C18 C24 C20

–12V –12V –12V –12V 100n 22µ 100n 22µ LED2


20V 20V

220410-012 –12V

Figure 3: Circuit of the 8th-order Butterworth low-pass filter.

lektor May & June 2023 35


Figure 4: Board layout for the 8th-order Butterworth low-pass filter. Figure 5: The author’s finished low-pass prototype.

parallel in each case (no value shown in Figure 3), which allows the component. Now, if you enter a value of 103 nF into the software, you
calculated value to be hit as accurately as possible with the commer- will get the adjusted values for the other components of this stage at
cially available E series. It is particularly advisable to select the capac- a given frequency — and resistors can be obtained easily and cheaply
itors for accuracy before assembly to avoid subsequent replacement even with a tolerance of 1%.
of components. The board also provides space for additional resistors
(R6, R12, R18, and R24), which can be used for filter amplification, but The same procedure was followed for the band-pass filter (circuit:
these are not needed here, and are therefore omitted. Figure 6, layout: Figure 7, prototype: Figure 8). For the frequency-de-
termining components, additional components for a possible parallel
In general, it is recommended to read the article on the Fliege connection were again provided for, and an optional amplification was
band-pass [1] and, if necessary, also the article on filter software [2], realized with R8, R9, R18 and R19. Since the values of the frequency-de-
because they explain in detail the procedure for the exact adjustment termining capacitors are the same here, one should use components
of the filter frequencies and the component calculation software used from the same batch if possible, and compensate for the differences
for this purpose. An optimization example: The measured value of — which will likely be very small — using parallel capacitors. Here,
100 nF capacitor C14 is 103 nF, which is within the 5% tolerance of the entering the resulting value in the software is also recommended.

R26 R25
R10
220Ω

R5 R15
1k78 1k2

R6 R16
46k4 82k
C9
R23 R1 R11 100n
C3 3 C7 5
46k4 3k6 R24 0Ω R20
1 7 C10
R2 IC1a 46k4 R12 IC1b 220Ω
C4 2 C8 6
K8 1
100n 100n 1 K9
R7 R17
IN 1k 1k
R3 R4 R8 R9 R13 R14 R18 R19 OUT
C1 C2 C5 C6
511Ω

511Ω
1k78

23k7

13k9

1k62

19k6

10k

2
2
100n 100n

+12V
LED1

+12V +12V +12V +12V C13 C11


R21
100n 22µ
10k

K2 K3 K4 K5
1 1 1 1 20V
8
2 2 2 2
IC1 = OPA2209AIDR IC1
3 3 3 3
4 R22
10k

C14 C12

–12V –12V –12V –12V 100n 22µ LED2


20V Figure 6: Circuit of the 4th-
220410-015 –12V order band-pass filter with
100 Hz bandwidth.

36 May & June 2023 www.elektormagazine.com


Figure 8: Finished band-pass prototype, mounted in an
aluminum case.

Figure 7: Board layout for the 4th-order band-pass filter.

In order to reach the required resistance values at the input of each and low inherent distortion. The author still has a few empty boards
stage as accurately as possible, a combination of one resistor in series left. If needed, you can contact him by e-mail (see “About the Author”).
to a parallel circuit of two resistors was provided for in each case.
Resistors R10, R25, and R26 are used to measure the characteristics The two filters presented here are not limited to 1 kHz, of course. One
of the individual stages as described in [1] and are therefore omitted. can easily make a whole set of suitable low-pass/band-pass and notch
For fine-tuning, simulating the circuit with the actual, measured values filters for different frequencies, applying the design considerations in
is recommended. [1], and use them to investigate the distortion behavior of audio circuits
at different frequencies.
Which Filter? Translated to English by J. Starkmuth — 220410-01
Now that you have the choice of using either a low-pass or a band-pass,
the question naturally arises: Which filter type is better suited for your
purposes? About the Author
Alfred Rosenkränzer worked for many years as a development
The low-pass needs a higher order for useful attenuation, and there- engineer, initially in the field of professional television technol-
fore requires four op-amps. This increases the inherent noise and, ogy. Since the end of the 1990s, he has been developing digital
of course, the distortion produced by the filter. On the other hand, it high-speed and analog circuits for IC testers. Audio is his private
achieves a better attenuation of higher-order harmonics from about hobbyhorse.
3 kHz than the band-pass does. The fact that it passes all frequencies
below the cutoff frequency can be favorable for other applications.
Questions or Comments?
The 4th-order band-pass, on the other hand, gets by with only two Do you have questions or comments about this article? Email the
op-amps and should therefore produce less inherent noise and distor- author at [email protected], or contact Elektor at
tion of its own. Since it only passes frequencies close to 1 kHz with a [email protected].
bandwidth of 100 Hz, it is hardly suitable for other applications. But,
since it attenuates all frequencies below 1 kHz and thus also undesired
phenomena such as mains hum, low-frequency inherent noise is also
reduced, which can benefit SNR measurements.

Ready to Try? WEB LINKS


Due to the tiny SMD components used, assembling the boards is [1] Alfred Rosenkränzer, “A Fliege Notch Filter for Audio
not a suitable task for people who are soldering by hand for the first Measurements,” Elektor 9-10/2022:
time. Experienced electronics makers should have no problems with https://elektormagazine.com/magazine/elektor-272/60926
it, though. The layout files can be downloaded free of charge in Eagle [2] Alfred Rosenkränzer, “Filter Software,” Elektor 11-12/2022:
format from this article’s web page [3]. Because of their characteristics, https://elektormagazine.com/magazine/elektor-280/61044
high-quality thin film versions should be used for all resistors involved [3] This article’s web page:
with the signal. The signal-carrying SMD ceramic capacitors should https://elektormagazine.com/220410-01
definitely be types with a COG dielectric to guarantee stable properties

lektor May & June 2023 37


COMPONENT LIST: BAND-PASS
Resistors: R13 = 1k62
(Thin film, 1%, SMD 0603) R14 = 19k6 Semiconductor:
R1 = 3k6 R15 = 1k2 LED1, LED2 = LED, green, SMD0603
R2, R12 = parallel connection * R16 = 82 k IC1 = OPA2209AIDR, SO08
R3, R5 = 1k78 R19, R21, R22 = 10 k
R4 = 23k7 Also:
R6, R23, R24 = 46k4 Capacitors: K8, K9 = 2-pin male connector, RM 1/10’’
R7, R17 = 1 k (Unless specified otherwise: 5%, COG, K2..K5 = 3-pin male connector, RM 1/10’’
R8, R18 = 511 Ω SMD0805)
R9 = 13k9 C1, C4, C5, C8, C9 = 100 n, SMD1206 * See text
R10, R25, R26 = not applicable * C2, C3, C6, C7 = parallel connection *
R11 = 0 Ω C10 = not applicable

COMPONENT LIST: LOW-PASS


Resistors: R22, R27, R28 = 10 k C16 = 3n3
(Thin film, 1%, SMD 0603) R26 = 220 Ω C17, C18, C19, C20 = electrolytic capacitor 22 µ
R1 = 47 k / 20 V, SMD-B
R2, R5, R9, R17, R21, R23 = parallel connection * Capacitors: C21, C22, C23, C24 = 100 n, SMD0603
R3 = 5k11 (Unless specified otherwise: 5%, COG,
R4 = 11 k SMD0805) Semiconductor:
R6, R12, R18, R24 = gain, not applicable * C1, C3, C5, C7, C9, C11, C13, C15 = parallel LED1, LED2 = LED, green, SMD0805
R7, R13, R19, R25 = 3k48 connection * IC1, IC2 = NE5532A, SO08
R8 = 6k19 C2 = 18 n
R10, R16 = 8k25 C4, C8 = 15 n Also:
R11 = 129 k C6 = 22 n K1, K9 = 2-pin male connector, RM 1/10″
R14 = 3k83 C10 = 47 n K2..K5 = 3-pin male connector, RM 1/10″
R15 = 28k7 C12 = 12 n
R20 = 4k64 C14 = 100 n * See text

Related Products

> OWON AG051 Arbitrary Waveform Generator (5 MHz) (SKU 18874)


https://elektor.com/18874

> OWON SDS1102 2-Channel Oscilloscope (100 MHz) (SKU 18782)


https://elektor.com/18782

> OWON XSA810 Spectrum Analyzer (1 GHz) (SKU 19714)


https://elektor.com/19714

38 May & June 2023 www.elektormagazine.com


BASIC COURSE

Starting Out in
Electronics...
....Multivibrating Cheerfully Further!

By Eric Bogers (Elektor)


The Monostable Multivibrator
In the previous episode we (finally) got The monostable multivibrator (or monoflop
acquainted with transistors, which presently for short) is derived from its bistable cousin
and has one stable state, as you might guess
can easily be called ‘the beating heart of our from the name. The basic schematic is
society’ – without transistors in some form or shown in Figure 2. Although this circuit
another, our modern-day society would simply can be put into a different state when
triggered by an external pulse, after a
not be possible. Now it’s time to spend a bit certain time it will automatically return to
more time on multivibrators, and then look at its stable initial state. You might be familiar
transistors as amplifiers. with this sort of circuit from those handy
staircase lighting circuits, which switch off
by themselves after a certain length of time.

First a brief preliminary remark, primar- As suggested by its name, this circuit In the circuit shown in Figure 2, the
ily aimed at new Elektor readers who are has two states, each with one of the two left-hand transistor is usually conducting.
experiencing their first episode of the series, transistors conducting (but not both). The Just like the flip-flop (Figure 1), we can cause
“Starting Out in Electronics.” This series pushbuttons can be used to switch between this transistor to switch off by briefly pulling
does not in any way claim to be a thorough the two states. It’s impossible to predict its base to ground by pressing the pushbut-
theoretical course in electronics. Our only which of the two transistors will start ton. This also causes the electrolytic capac-
aim is to give novice electronics enthusiasts conducting immediately after the power itor to discharge.
enough basic knowledge so that they can is switched on — the only thing you can
design and build circuits with a reasonable say for sure is that one of them will be on Then the right-hand transistor starts
chance of success, or modify an existing and the other will be off. conducting, but only temporarily, because
circuit with a workable result. In this, we
do our best to avoid serious calculations,
and sometimes we take shortcuts with the
details and niceties of the theory. We are
well aware that with this approach, we will
occasionally provoke strong criticism from
the perfectionists and theoreticians among
our readers. We apologize for that, but not
too much...

At the end of the last episode, we talked


about the bistable multivibrator, which also
goes by the name of flip-flop. To jog your
memory, the basic schematic of this multi-
vibrator is reproduced here in Figure 1. Figure 1: The bistable multivibrator or flip-flop. Figure 2: The monostable multivibrator.

lektor May & June 2023 39


the electrolytic capacitor is recharged up to UV + 0.7 V. Based on this, we can write
through its series resistor. When the the following equation:
voltage on this capacitor rises to approx-
imately 0.7 V, the left-hand transistor
starts conducting again, causing its collec-
tor-emitter voltage to drop to nearly zero.
As a result, the right-hand transistor is Figure 3: The astable multivibrator.
switched off again, and the circuit returns We can solve this equation for the variable
to its stable initial state. t. Here we won’t bother you with the deriva-
the monoflop to calculate the timing — but tion, but simply give the result:
How long it takes for the monoflop to in that case, you would be off by a factor
switch back to its stable state depends, of around 10. That naturally raises the
as you might expect, on the values of the question of how this circuit actually works.
series resistor and the capacitor, as well as
the value of the supply voltage. Let’s try to Let’s suppose the left-hand transistor is
roughly estimate this time (the monoflop conducting: then U CE of the left-hand If we calculate this with the same compo-
interval) with a bit of guesswork. Here we transistor is nearly zero and the collec- nent values as for the monoflop (R = 100 kΩ
assume the following values: R = 100 kΩ, tor-emitter voltage of the right-hand and C = 100 µF), the result is t = 7.5 s, which
C = 100 µF, and UV = 12 V. The voltage on a transistor is equal to the supply voltage. is 12 times as long as with the monoflop.
capacitor is given by the formula: The left-hand capacitor is gradually charged
through its series resistor, and at a certain Using a Bipolar Transistor as an
point, the voltage on this capacitor will Amplifier
reach 0.7 V and the right-hand transistor Using a bipolar transistor to build an ampli-
will switch on. fier is not especially easy, since all the
parameters depend on each other, none
The current depends on the voltage across When the right-hand transistor switches of these parameters is truly linear, and
the resistor and the value of the resistance. on, the change in UCE is nearly equal to the everything is unfortunately dependent on
This voltage drops steadily as the voltage value of the supply voltage, which means the temperature. If you don’t take suitable
on the capacitor rises. Since the circuit that the capacitor voltage drops by this countermeasures, the operating point will
switches states at a capacitor voltage of just amount. As a result, the voltage on the base be miles away from what you intended.
0.7 V, we can ignore the non-linear behavior of the left-hand transistor goes negative and
here and use the arithmetic average value the transistor switches off. For this reason, discrete transistors are
in our calculation. rarely used for small-signal applications, for
This also means that the capacitor has to which operational amplifiers (opamps) are
be charged from a negative voltage that is the component of choice. Although opamps
nearly the same as the value of the supply are made up of transistors, with them most
voltage, instead of starting from 0 V. That of the problems have already been dealt
takes a lot longer, of course. with by the designers. This makes it very
This means that the average voltage over the easy to build stable amplifiers with opamps.
resistor is approximately 11.65 V, since the Let’s try to calculate this. The capacitor has
circuit switches when the capacitor voltage to be charged from –12 V to +0.7 V. If we However, opamps are only suitable
reaches 0.7 V. assume a linear charging curve for this, we for small-signal operation, since their
introduce an error of approximately 10%, maximum output voltage and/or current
which is about the same as the tolerance of a is too low for power amplifiers. For such
reasonably good-quality electrolytic capac- applications, opamps can be boosted by
itor. But to be nice, let’s try to be a bit more combining them with discrete transistors
accurate here. The voltage on a capacitor (if necessary power transistors), or the entire
The Astable Multivibrator is given by the formula: circuit can be built with discrete transistors.
An astable multivibrator does not have
any stable state. Instead, it constantly We will discuss opamps in a next episode.
switches back and forth between two possi- To make that easier to understand, here we
ble states, which is why it is called astable. briefly touch on transistors as amplifying
The circuit in Figure 3 looks a bit like a components.
double monoflop, so you might be tempted Now, in this case, U0 is equal to twice the
to use the same formulas derived above for supply voltage and the capacitor is charged At this point in most textbooks, you will find

40 May & June 2023 www.elektormagazine.com


I[mA]

12
11
10

a lot of theory and equations, most of which 9


are not especially relevant in practice. The 8
only truly important relationship is the U/I 7
characteristic of the base-emitter junction 6
— and we already saw this in the discus- 5
sion of diodes (see Figure 4). However, one 4
thing we didn’t mention in that discussion
3
is that the U/I characteristic is tempera-
2
ture dependent. When a diode gets warm,
the current increases (assuming that the 1

voltage stays the same). This makes the


diode even warmer. This behavior rarely 0,1 0,2 0,3 0,4 0,5 0,6 0,7 U[V]
leads to problems with ordinary diodes,
but with transistors it is especially annoy- Figure 4: The U/I characteristic of a diode.
ing because the collector current will also
change as a result – and the collector current
can be around a factor of 100 larger than the
base current. This is because the following circuits so that the exact value of hFE is not
formula applies to the collector current: a significant factor. How to do this will be
discussed in the next episode.
Translated to English by K. Cox — 230033-01

Editor’s Note: The series of articles, “Starting


Here, hFE (also called β) is the current gain of Out in Electronics,” is based on the book Basis-
Related Products
the transistor. This current gain is not only kurs Elektronik, by Michael Ebner, which was
subject to a wide range of variation between published in German and Dutch by Elektor. > B. Kainka, Basic Electronics for
individual devices of the same type, but (to Beginners (Elektor, 2020)
make matters even worse) is also dependent (SKU 19212)
www.elektor.com/19212
on the collector current. With small-signal Questions or Comments?
transistors, the value of hFE is somewhere If you have any technical questions or > B. Kainka, Basic Electronics
between 100 and 800, and with power comments about this article, feel free to for Beginners (Elektor, 2020)
transistors, it is between 10 and 100. Since contact the Elektor editorial team by email (E-Book, SKU 19213)
the current gain is such an unreliable param- at [email protected]. www.elektor.com/19213
eter, you have to try to design your transistor

YOUR KEY TO WE meet @


PCIM Europe
CELLULAR Hall 6-217

TECHNOLOGY
Adrastea-I is a Cellular Module with High Performance, Ultra-Low
Power Consumption, Multi-Band LTE-M and NB-IoT Module.

Despite its compact size, the module has integrated GNSS, integrated ARM Cortex
M4 and 1MB Flash reserved for user application development. The module is based
on the high-performance Sony Altair ALT1250 chipset. The Adrastea-I module,
certified by Deutsche Telekom, enables rapid integration into end products without
additional industry-specific certification (GCF) or operator approval. Provided that a
Deutsche Telekom IoT connectivity (SIM card) is used. For all other operators the
module offers the industry-specific certification (GCF) already.

www.we-online.com/gocellular
© eiSmart

• Small form factor • Long range/wordwide coverage


• Security and encryption • Multi-band support #GOCELLULAR

lektor May & June 2023 41


UPDATES & MAIL

Err-lectronics
Corrections, Updates and Readers’ Letters
Compiled by Jens Nickel (Elektor)

Grow It Yourself
Elektor Arduino Edition 2022,
p. 54 (220414)
I did read your article in Elektor with interest. I have planted seeds in
the past, but was not very successful because I failed to administer the
loving care that seeds need. I ended up donating my desktop green
houses to my girlfriend, who is more into plants and caring for them.
Anyway, I liked your article very much and want to build something
similar for my girl.

You mention that plants prefer 450 nm and 650 nm light. RGB LEDs
produce 460, 525, and 625 nm wavelengths (quick Google search). These
Low-Cost Audio Tester values do not quite follow the plants’ preferences. Are they close enough?
Elektor 7-8/2022, p. 6 (200604)
The REW software (roomeqwizard.com) is Elektor Magazine already published an article in 2019 together with
very widely used in the DIY community. Würth Elektronik about an LED-illuminated greenhouse (elektormaga-
REW is basically freeware, although you can zine.com/magazine/elektor-110/51138). Your article inspired me to pursue
(or should) make a donation to the author. this subject. I have had an ultrasonic mist generator lying around here
This software should be able to do every- for many years, so it may finally become useful.
thing mentioned in the article. For those
with significantly higher demands, there Michael Hompus
is also a Pro version, but it costs USD100.

There is a long thread on REW at diyaudio. Thanks for your question! Some time ago, after I published the GIY
com, which also deals with various inter- project online, I started researching this topic of LED lights for plant
faces and how to mod them. growth, and you are welcome to read my summary on that here:
instructables.com/DIY-Grow-LED-Light-Designing-a-Better-Sun
Frank von Zeppelin
To answer your question, and to help you practically apply the latest
know-how in the industry: use white color LEDs plus red or far-red
spectrum LEDs. The idea is to recreate a full spectrum similar to the
sun, and then boost its efficiency by adding some extra red / far-red
/ UV LEDs.

For white, I would recommend Samsung LM301B or LM301H diodes.


For red, Osram hyper-red LEDs. Practically, it will look something like
this: 6 to 10 white LEDs plus two red LEDs on a phyto light bar. Now,
you just play around with the color temperature of the white LEDs — if
you chose cold white, you get more blue in the spectrum, if you chose
warm white, you get more red in the spectrum, and so on. Hope that
the basic idea is clear.

Check out cityfarm.md to see the final version of the GIY project.

Dmitrii Albot (author of the article)

42 May & June 2023 www.elektormagazine.com


The Tube
Elektor 1-2/2023, p. 70 (220089)
I have been a subscriber for many years. My first Elektor project was
an FM tuner with printed coils in 1975, when I was around 20 years
old. I am pleased that over the many decades you have adapted
your magazine concept and all the related offerings to people’s
actual needs. Keep up the good work! In the latest issue, however,
I wondered about some things in the article “The Tube” — perhaps
they are just typos? Or maybe I misunderstood something? Starting Out in Electronics
Elektor 9-10/2022, p. 34 (220256)

Project 2.0
Elektor 1-2/2023, p. 110 (220601)
Unfortunately, an error crept into my
proposal, published as a reader letter in
the January 2023 edition.

There, I suggested connecting a Zener diode


Figure 1a: The explanation in the text suggests (indirectly) that no in series with the freewheeling diode when
negative feedback is applied in the individual stages (for example, driving a relay with a transistor. This not
by cathode resistors). I find it hard to imagine that this approach is only significantly shortens the switch-off
actually possible. Otherwise, the author should have pointed out this time of the relay, but also helps increase
exotic special case, shouldn’t he? the lifetime of the relay contacts because
contact separation is considerably faster.

Unfortunately, in the associated drawing,


the Zener diode was shown the wrong
way around, with the result that only the
forward voltages of the two diodes are
superimposed — and that doesn’t get you
much. In the figure here, the Zener diode is
connected in the correct direction.

Figure 1b: With the stated resistor values, the overall amplification When the transistor
(gain) should actually be 4.3 cubed (79.5), shouldn’t it? (And besides, switches off, reverse
3.3 cubed is about 36, which is a long way from 100.) And, is it even voltage V2 of the Zener
possible to talk about open loop gain in this situation? I think “overall diode adds to forward
gain of the amplifier path” would be a better term. voltage V1 of the recti-
fier diode. This causes
Harald Sonnemann the current through
the relay to drop much
faster. This can not
You are entirely right that no viable audio amplifier can manage only be measured, but
without any negative feedback because the amplifying components is also clearly heard.
are not sufficiently linear. Tube fans often use the term “no negative
feedback” as a loose synonym for “no overall negative feedback.” In this regard, it’s
important to remember that the voltage
What I did was to contrast overall negative feedback specifically with between the collector and emitter of the
the principle of local negative feedback per amplification stage; see transistor is the sum of the supply voltage,
Figure 1 in the article. the reverse voltage of the Zener diode, and
the forward voltage of the rectifier diode.
In the heat of the moment, however, I did indeed get the calculations With a 12 V supply voltage and a 10 V Zener
wrong. As you say, 4.3 cubed is 79, not 100, and 3.3 cubed is certainly diode, at switch-off time the transistor sees
not 100. I did not spot this error when proofreading the text, nor did a voltage of around 22.6 V, which must be
the author when the article was accepted. A revised circuit diagram considered when selecting the transistor
is shown here. and the Zener diode.

And of course, “open loop gain” in Figure 1b actually means a quasi Thomas Klingbeil
open loop gain.

Thomas Scherer (article editor)


230049-01

lektor May & June 2023 43


BACKGROUND

The New
I3C Protocol
A Worthy Successor to I2C, or Just More Hot Air?

By Tam Hanna (Slovakia)

Hardly any bus protocol is as widely used as the I²C bus protocol
launched in the 1980s by Philips Semiconductor. However, the
weaknesses of this bus system have become apparent in the course
of recent years. A successor is waiting in the wings in the form of
the I3C protocol, and in this article we want to present it in detail.

To understand the possibilities and the limita-


tions, you need to remember that the I2C bus
has become a completely free technology
since the patents held by Philips expired.
Although NXP, as the successor to the
semiconductor division of Philips, still owns
the intellectual property rights to the logo and
the name, the technology can now be freely
used by everybody.

The discussion about I2C versus TWI has now


virtually died out, but there are still interesting
comments to be found online (for example at
[1]) with the following tenor: “The concept
behind the license fee was to ensure that
people who claimed they were making I2C Figure 1: Membership in MIPI is unquestionably expensive (Source: [3]).
silicon (and selling it as I2C silicon) were
supporting the standard and thus helping to
grow the standard.”

The results, which are in line with the author’s of the reasons why Philips started collecting are therefore always necessary. First, though,
experience, show that Philips’ aim in collect- licence fees in the first place. With the expira- let’s look at who or what is behind the I3C
ing the licence fee was always to encourage tion of the Philips patents, however, it’s now standard.
licence holders to fully implement the I2C open season.
standard. This explicitly included the glitch I3C and the MIPI Alliance
filter, which in the past was a frequent bone Unfortunately, the interoperability of I2C A standardisation committee called the MIPI
of contention between Philips Semiconduc- devices in an I3C bus system can only be Alliance [2], which offers a variety of standards
tor and third-party manufacturers. This filter regarded as either best practice or wishful for general electronics, is responsible for the
(more about this later) may have been one thinking. Practical tests of such mixed systems I3C standard. The membership fees for this

44 May & June 2023 www.elektormagazine.com


alliance are substantial, as can be seen from
the well-hidden list of fees (Figure 1) [3]. To
stimulate maximum adoption, the standard-
ization committee offers a completely free
basic version of the I3C specification. A list
of advanced functions (only available to MIPI
Alliance members) can be found at [4]. On
that page you can also see that the abbrevia-
tion I3C stands for ‘Improved Inter-Integrated
Circuits’. In the author’s view, if you use I3C
in a commercial circuit, you can only expect
Figure 2: Speed saves power, just like with mobile processors (Source: [8]).
to have ‘issues’ with the MIPI Alliance if you
implement the interface yourself in one way or
another, such as in an FPGA or by bit-banging.
If instead you use only purchased components
(and do not use the I3C logo or the name in
your advertising), you shouldn’t encounter
any problems.

Goodbye to Open Drain


Right from the start, the I2C bus has been
treating developers to annoyances. Firstly,
there is always the question of where the
pull-up resistors (needed to charge the bus
capacitance) should be placed. Secondly, it
is generally not possible to trigger interrupts
from a component that does not generate
the clock signal. If you want to give a ‘clock
sensing’ device the ability to send interrupts,
an additional connection is always neces-
Figure 3: Emergency-stop transistor T3 causes a “hard shutdown” of all sensors connected to the bus
sary with I2C. If you have several sensors in to reset a “blocking” device to its default state.
the field, this comes at the cost of the GPIO
capacity of the clock-emitting component.

The third annoyance is the relatively low SDA pin also changes to open-drain mode in This simplification is also accompanied by a
speed: Philips states a data rate of 3 Mbps some conditions. To avoid various problems simplification of the I/O pins on the microcon-
with an operating frequency of 3.4 MHz. in the placement of pull-up resistors, the troller or clock generating device. I2C requires
A consequence of this is that the leisurely standard specifies that they must always be dedicated GPIO pins due to the previously
behaviour of the transceiver leads to high located in the clock-generating device. mentioned 50 ns glitch filter, but the MIPI
power consumption, since the longer the specification only requires normal GPIO pins
data exchange between two devices takes, Another important thing (leaving aside special with the ability to drive 4 mA of current. The
the later they can enter a low-power standby cases) is that SCL is always and exclusively specification also explicitly states that glitch
mode. The diagram from MIPI (Figure 2) is, in controlled by the clock-generating compo- filters, which in the case of I2C are often
the author’s opinion, quite plausible. nent. If multiple potential clock generating problematic, are not required.
devices are present on a bus, the clock gener-
Last but not least, I2C devices have the fatal ating device currently in the active state is The Rewards of Speed
capability to disable other devices on the bus responsible for switching the SCL pin. Now let’s look at the waveforms of I3C. The
‘forever’. A corresponding circuit detail such previously mentioned glitch filter is only signif-
as that shown in Figure 3 can be found in Clock stretching by the slave device, which icant with I3C if the SCL signal on an I3C
quite a few I2C systems. is possible on a conventional I2C bus, is not bus does not have a duty cycle of 50%, as it
supported by the I3C specification. Operation usually does with I2C. With I3C the high period
Hello to I3C Improvements of such components is therefore not possi- is defined as shorter than 45 ns (Figure 4),
The first change in I3C is that both SCL and ble on a mixed bus. Then again, the author is which logically means that an I2C device imple-
SDA work in push-pull mode in most cases. aware of only very few use cases where clock mented according to the standard will not be
The SCL pin is always push-pull, while the stretching occurs in practice. able to do anything with the SCL waveform.

lektor May & June 2023 45


Automatic Address Assignment
Another annoyance with I2C is that addresses
usually have to be assigned physically to
individual components. With many compo-
nents (the HDC2010 shown in Figure 5 is a
good example) this means that the address
space offered by the standard cannot be fully
utilised.

In place of the 10-bit address mode possible


with I2C, I3C provides for dynamic self-con-
Figure 4: I2C components see this clock edge as ‘low’ (Source: NXP presentation). figuration. In addition, I3C Hot Join capabil-
ity allows ‘hot plugging’ of I3C devices onto
the bus, similar to what is possible with USB.

In the background there is also a procedure


called address arbitration that looks after
assigning addresses to slave devices. For this
purpose each I3C device is allocated three
parameters: two eight-bit fields with status
information, and a 48-bit unique ID (UID). The
specification assumes that each UID (called
Provisional ID) is unique on the bus.

When starting up the I3C bus, the clock gener-


ating device must enumerate all devices on
the bus and assign them dynamic addresses.
This is done using a method similar to the
arbitration process in I2C: the I3C compo-
nent with the lowest UID value is first in line
for dynamic address assignment. The clock
generating device executes multiple assign-
ment cycles until every device on the bus has
Figure 5: The HDC2010 has only one address pin, so only two such devices are possible on an I2C bus a temporary ID.
(Source: [9]).
Manufacturer Adoption of the
Standard
The list of MIPI members [5] is a who’s who
After receipt of this sort of ‘invisible’ SCL trans- have a glitch filter implemented according to in the world of semiconductor manufactur-
action, the clock generating device can also the specification. ers, from GigaDevice through ST to Solomon
switch its SDA pin or SDA line to push-pull Systech. Virtually all relevant companies are
mode and raise the operating frequency to The HDR modes are initiated by a special on the list. However, if you start looking for
as high as 12.5 MHz. In this sort of full-speed sequence of SCL pulses while the SDA line practically available components, the pickings
mode, a transmission rate of up to 12.5 Mbps is in the idle state. The simplest mode is are very slim. At Mouser, for example, there
can be achieved according to the MIPI I3C HDR-DDR (Double Data Rate), which can are presently only components such as the
specification. achieve speeds up to 25 Mbps. This is done PI3CSW12 from Dialog. As can be seen from
by making each edge of the SCL signal a valid Figure 6, these are generally devices for multi-
Higher transmission rates can be achieved trigger for receiving data. HDR-TSP (Ternary plexing and signal conditioning.
with I3C in one of the three High Data Rate Symbol Pure) mode can achieve speeds
(HDR) modes, but these modes can only be above 30 Mbps. This mode uses both the SCL Renesas has, at least for now, also taken a
used in two special cases. The first special and SDA lines in combination for data trans- similar approach with devices such as the
case is a bus system called Pure I3C Bus, mission. HDR-TSL (Ternary Symbol Legacy-in- IMX3102. In addition, the following state-
consisting exclusively of I3C components, and clusive) mode provides yet another special ment is included in the announcement: “I3C’s
the second is called Mixed Fast Bus and can regime that makes TSP more accommodating 12.5 MHz speeds significantly outpace current
also include I2C components – but only if they for mixed buses. and legacy solutions, such as the I2C 1 MHz

46 May & June 2023 www.elektormagazine.com


On the software front, however, things are Why Not Master and Slave?
more encouraging: a relatively detailed The author, who is generally archcon-
description of the interface driver imple- servative in political matters, prefers the
mented in the Linux kernel is available at [7]. designations ‘clock generating device’ and
‘clock sensing device’. His experience in
How Long Will It Take? teaching generations of students shows
The higher data rate and the ability to trigger that this way of thinking leads to deeper
interrupts without using dedicated GPIO understanding.
inputs may lead to industry-wide adoption
of I3C sooner or later, but the question is
how long this process will take. As there are How Many Devices?
hardly any microcontrollers available now with With regard to the number of devices on
suitable I3C peripherals, the author’s view is a single bus, I3C is more restrictive than
that it could take a while. I2C, probably on account of the higher
Figure 6: I3C hardware presently available is 210640-01 speed as well as the lower capacity of the
primarily limited to signal conditioning (Source: pins to source or sink current. In earlier
[10]). versions of the standard, MIPI said that
Questions or Comments? at most eleven devices per bus would
Do you have any questions or comments be supported. However, this restriction,
speed and analog passive quick switches.” about this article? Contact the author at which originated from a simulation of
[email protected] or the editorial electrical characteristics, is no longer in
If you’re looking for microcontrollers with I3C team at [email protected]. the standard. Of the theoretically possi-
support, the list is very short: the i.MX RT685 ble 27 (128) dynamic addresses, around
from NXP is the only option available, and 90 are available, depending on the bus
there is an application note (AN12797) that configuration.
provides example software. NXP also offers
a soft core (free in some cases), and there is
even a special licence for users who are not
MIPI members [6]. If you are prepared to pay
for soft core intellectual property (IP), provid-
ers such as Silvaco or Arasan Chip Systems
offer turnkey I3C VHDL modules.
RELATED PRODUCTS
If you’re looking for displays with I3C support
(a use case frequently mentioned in the speci-
fication), you won’t find any right now. The
> V. Himpe, Mastering the I2C Bus (Elektor 2011) (SKU 15385)
www.elektor.com/15385
only physical hardware presently available
consists of some accelerometers (BMI263 > V. Himpe, Mastering the I2C Bus (Elektor 2011) (PDF, SKU 16193)
from Bosch and LSM6DSO from ST) and www.elektor.com/16193
the LPS22HH pressure sensor from Bosch.

WEB LINKS
[1] Discussions about I2C: http://www.verycomputer.com/31_b0b5a85949fcce82_1.htm
[2] MIPI I3C web page: https://www.mipi.org/specifications/i3c-sensor-specification
[3] MIPI membership is expensive: https://www.mipi.org/join-mipi
[4] I3C Basic Specification: https://resources.mipi.org/blog/mipi-alliance-delivers-new-i3c-basic-specification
[5] List of MIPI members: https://www.mipi.org/devcon//membership/all-member-directory
[6] NXP soft core IP: https://bit.ly/3qWAvD3
[7] API in the Linux kernel: https://www.kernel.org/doc/html/latest/driver-api/i3c/protocol.html
[8] MIPI I3C white paper: http://bit.ly/2gId6BL
[9] Texas Instruments HDC2010 data sheet: http://www.ti.com/lit/gpn/hdc2010
[10] Diodes Inc PI3CSW12 data sheet: http://www.diodes.com/assets/Datasheets/PI3CSW12.pdf

lektor May & June 2023 47


PROJECT

BlueRC:
IR Remote Control with
Smartphone and ESP32
Adaptive and Universal

By Xin Wang (Germany)

There was a time when


infrared transmitters
on mobile phones were
common, but, that is no
longer the case.
This project offers a
solution: Use your mobile
phone with its Bluetooth
connectivity to control an
ESP32 board that can both
 send infrared commands
Figure 1: WeMos D1 R32
and learn new ones.
ESP32 Wi-Fi / Bluetooth
development board.
I decided that I wanted to be able to control my infrared
devices using my phone. I did some research by compar-
ing several projects on the web. Most of them worked
with predefined codes, meaning that the IR codes had
to be known in advance and stored in an array. I wanted
to build a fully learning remote control that required no
prior knowledge of any proprietary remote control codes.
The codes need to be updated by the circuit in real time
and on the fly.

48 May & June 2023 www.elektormagazine.com


Figure 2: BlueRC V1.1 Android app user interface.

Figure 3: The Keyestudio


The Hardware I added a multiple sensor shield (Figure 3) on top. This Easy Module Shield V1
There are just two main building blocks for this project: shield has a plethora of other sensors, such as a humid- for Arduino. Source:
ity sensor, a buzzer, a potentiometer, a photocell, an flyrobo.in.
> A microcontroller board (Figure 1) with a connected RGB LED, and a couple of buttons — all of which put a
infrared receiver for learning existing codes from lot of versatility in your hands for future home automation
other remotes, and an infrared transmitter for ideas. I’ve used the sensors to display the temperature
performing the main job of sending commands to and humidity in the Android app, but our most important
your TV, set-top box, etc. The board also stores the on-board sensor is the infrared receiver!
learned codes.
> An Android phone to run an app, which just acts as While the shield does have a built-in IR receiver, there is
the user interface for the microcontroller board. The no transmitter, so I had to build my own quick-and-dirty
app provides you with an on-screen remote control driver/transmitter module. It consists of only 3 compo-
interface (Figure 2), which allows you to press the nents — a 3-pin header socket, a BC547 NPN transistor,
buttons you need to control your infrared devices. and an IR transmitter LED, shown very simply constructed
You can also start the learning sequence using a key in Figure 4. After soldering, I plugged the socket header
press in this user interface, but the learning proce- into port pin D7 on the sensor shield, which uses port
dure itself is performed on the microcontroller board.

I chose Bluetooth for communication between the phone


and the IR transmitter hardware, because of its low power
and low latency, when compared with Wi-Fi.

I was looking for a commercially available solution that
would check all the hardware boxes, but unfortunately Figure 4: My DIY infrared
found nothing that was 100% suitable. So, for the micro- driver/transmitter
module.
controller side, I chose an ESP32 board, as it has both
Bluetooth and Wi-Fi. The D1 R32 development board from
WeMos has an Arduino UNO-compatible pin layout and
works well with the Arduino IDE.

lektor May & June 2023 49


Figure 5: The shield


and how I connected
my IR driver/transmitter
module to it. Source:
flyrobo.in.

pin D14 as an output to drive my IR transmitter, while At first, I tried the standard IR library for Arduino. It worked
the shield’s IR receiver uses port pin D27 as an input fine, but is not fully supported on the ESP32, as the ESP32
by default. makes use of a proprietary on-board hardware Remote
Control Transceiver (RMT) with a lot of protocol and
You can see how I hooked it up in the basic schematic modulation logic built-in for IR signals. After much trial
in Figure 5. and error, I finally found a fully working IR library for
the ESP32, IRremoteESP8266, by Ken Shirriff et al [1].
The Software Thank you, Ken.
My software is relatively simple: The ESP32 acts as
Bluetooth server, and an Android app as client. The ESP32 Originally, I wanted to store the IR codes in EEPROM, but
simply awaits Bluetooth messages from the Android app. when I wrote my firmware, I realized that the ESP32 has no
There is minimal Bluetooth communication between the EEPROM at all. However, it does have the ability to save
two devices, as remote control key presses — as well data permanently in flash via the Preferences.h library [5].
as the command to begin the learning sequence (“^”)
— from the Android app are sent to the ESP32 as single Because my original remote control had RC5 coding,
characters. I only implemented the RC5 encoding scheme.

50 May & June 2023 www.elektormagazine.com


You may have to modify the Arduino sketch if your own The IR code for this button will automatically be stored
remote control uses another protocol. in the ESP32’s memory.
4. Repeat steps 1 and 2 for all the buttons you want to
Programming record.
For the WeMos board, download the BlueRC Arduino 5. Close the app by tapping Menu → Exit program.
sketch at [2]. It’s a single .ino sketch that you can upload
using the Arduino IDE. That’s it. You may now enjoy controlling your infrared
devices from your BlueRC device, making use of the app
To set up the Android app, follow these steps: on your Android phone.

1. On your Android device, download BlueRC-app-V1.1.apk For ESP32 troubleshooting, your best bet is to turn it off
from the GitHub page at [3]. You will need to set your and back on again!
phone to allow downloading apps from external sources
(other than Google Play Store). You can see a video of it in action [4] on my YouTube
2. Power up the WeMos board running our BlueRC .ino channel.
firmware. 220103-01
3. Launch the Android app. If Bluetooth is not active, the
app will request permission; tap on Accept.
4. Tap on the “kebab menu” on the top-right, and then
on Connect BT Device. If this is your first time pairing !
with the ESP32, tap Scan for devices and wait for t h is p r o je ct on video z4
Watch dF84O
ESP32BlueRC-Shield to appear under Other Available
t t p s :/ / y o u tu.be/Kb-T
Devices. Tap on this, then confirm the pairing. h
5. In the Status bar at the top, you should now see
connected:ESP32BlueRC-Shield.

Once you’ve paired your hardware, there’s no need to


perform the scan process again — just tap ESP32Blu-
eRC-Shield under Paired Devices in future. Questions or comments?
Do you have technical questions or comments about
With the app installed and working, you can now carry this article? You are welcome to contact the Elektor
out the learning process: editorial team at [email protected].

1. Long-tap on the LEARN button in the UI, and the app


will respond with “Learning begins, please press a
button within 10 seconds...” The Android app then sends
Related Products
the special character “^” to the ESP32, after which the
blue LED on the shield will turn on. > Dogan and Ahmet Ibrahim, The Official
2. On the user interface, tap the button that you want ESP32 Book (PDF, SKU 18330)
to teach the ESP32 board. The phone will send the https://elektor.com/18330
corresponding character to the ESP32, so the ESP32
> Koen Vervloesem, Getting Started with
board awaits the next step. ESPHome (PDF, SKU 19739)
3. Point your old infrared remote control at the ESP32 board https://elektor.com/19739
and press the corresponding button on the remote.

WEB LINKS
[1] IRremoteESP8266 library: https://www.arduino.cc/reference/en/libraries/irremoteesp8266/
[2] BlueRC Arduino sketch for ESP32: https://elektor.link/BlueRCESP32
[3] BlueRC Android app: https://elektor.link/BlueRCApp
[4] The BlueRC system in action: https://youtu.be/Kb-TdF84Oz4
[5] ESP32 Save Data Permanently using Preferences Library:
https://randomnerdtutorials.com/esp32-save-data-permanently-preferences/

lektor May & June 2023 51


MICROCONTROLLERS

Microcontroller
Documentation Explained
(Part 2)
Registers and Block Diagrams

Figure 1: Bit descriptions of registers can seem a little cryptic. (Source: Microchip Technology)

By Stuart Cording (Elektor) Datasheet: First Pages


Now that you know what is included in a datasheet, it is time to start
Regardless of whether you love it or looking at some of the details. Datasheets seem to have a rather
hate it, microcontroller documentation odd way of describing things, and different suppliers create their
descriptions and drawings in different ways. Microchip Technol-
has to be negotiated. In the first part of ogy’s 8-bit PIC16F18877 microcontroller [2] remains our focus, and
this article series [1], we looked at what you should download the datasheet if you want to follow along.
is found in a microcontroller datasheet.
Upon downloading and opening the datasheet, we are confronted
Here, we go deeper and look at how by the first two pages, which provide a brief description of this
users are informed about a device’s microcontroller along with a list of the main features and the
functionality, covering everything from peripherals included. Core features are not stand-alone peripher-
als; these are capabilities that are closely linked to the processing
registers to peripheral block diagrams. core. These cover capabilities such as brown-out circuitry, which
detects when the supply voltage drops below the required level,
and watchdog timers, which reset the microcontroller and are
often used in safety-critical systems.

52 May & June 2023 www.elektormagazine.com


The third page puts a little more meat on the bone, explaining how the STATUS register, which is part of the processor. This register
many of each peripheral we get, and how much RAM, program flash, is composed of bits that are implemented, and some that are not
and EEPROM is implemented. This is complemented by pages four implemented.
to seven, which provide basic packaging information and explain
what functionality is assigned to which pin. The implemented bits are marked with a combination of R and/
or W to indicate whether they can be read or written. After the
The Pin Allocation Tables are a critical element of any microcon- hyphen typically comes a number: “0” or “1.” These indicate the
troller datasheet. With so much capability being packed into each value of this bit after the device has been reset. Some bits may be
die, microcontrollers today have more functionality than they have marked with an x, indicating that the value will be unknown. The
pins. Thus, one of several capabilities (and sometimes more than value of some bits may depend on what caused the microcontroller
one) can be assigned to each pin. On this device, we can see that to come out of reset. If the microcontroller was simply powered
pin RA2 can be used as an ADC input, an analog voltage reference, up, it awoke through a power-on reset (POR). If the power supply
a comparator input, a digital-to-analog converter (DAC) output, or caused a brown-out reset (BOR), this may also result in a different
as an interrupt-on-change pin. In order to provide some flexibility, value in a specific bit. In this example, such “reset-dependent” bits
you may also find that a specific capability can be switched between are marked with q.
one or more pins. The assignment of functionality to pins can be,
as a result, very complex. Unimplemented bits can be a little dangerous. According to this
datasheet, reading the upper three bits should result in a “0.” It
Understanding Register Descriptions is unclear, however, what happens if you were to write to these
Register descriptions are composed of two parts: the name of the bits. The datasheet may provide a general recommendation. If
register and the names of the bits (or groups of bits) within the none is provided, you should probably ensure that any writes to
register. Page 38 of this datasheet describes the functionality of such registers ensure unimplemented bits are cleared to zero.

SIMPLIFIED PIC® MCU SOURCE BLOCK DIAGRAM

Figure 2: Block diagram for clock peripheral, highlighting clock selection multiplexer and controls that turn the clock source off.
(Source: Microchip Technology)

lektor May & June 2023 53


Unimplemented Bits Cleared to Zero
myValue &= 0b00011111; // clear 3 most-significant bits
// (unimplemented bits)
STATUS = myValue; // write 'myValue' into STATUS register

In C/C++, this can be done as follows: processor and the on-chip peripherals. It makes sense to take time to
review its structure, as found on page 110. Normally, this peripheral
myValue &= 0b00011111; // clear 3 most-significant bits is configured once at the start of the application’s code and is never
// = (unimplemented bits) changed. If it is changed, every peripheral may be impacted, from
STATUS = myValue; // write 'myValue' into the sampling rate of the ADC to the baud rate of the serial UART
// STATUS register and CAN interfaces.

Note: it makes sense to provide a comment to explain why this is In this example, we have some external sources (quartz or ceramic
being done to ensure that no-one tries to “optimize” your caution resonator oscillators) and some internal sources. The internal
away at a later date! sources may not be accurate enough (especially with tempera-
ture changes) to act as a reliable source for some interfaces, such
The bar over a bit name indicates that its value is inverted. This as the UART. The datasheet will probably mention this. Otherwise,
is the case for the “Time Out” bit, TO. Upon the occurence of a you need to check the accuracy in the section covering Electrical
time out, which you might expect to be flagged with a positive Characteristics.
response of “1,” the response you are looking for is actually going
to be “0.” Often such negated bits make little sense to the program- In the diagram, marked in orange, we can see that a group of three
mer; you just have to live with them and treat them appropriately bits, COSC<2:0>, in a register most likely related to the oscillator,
in your code. can be used to select between the available clock sources using a
multiplexer. For reasons unknown, only the group of bits is named
Sometimes, a group of bits is required to configure something, such in such diagrams and not the register they belong to. The best way
as the prescaler for a clock source, or the baud rate for a serial inter- to find out which register the group belongs to is to search the
face. Such groups of bits are then named BIT_GROUP<X:Y>, where datasheet PDF — they may be in a register of an unrelated periph-
X names the most significant bit, and Y the least significant bit in eral! Multiplexer diagrams are used frequently in block diagrams
the group. Also, beware: Sometimes one or more bits belonging to where signals can be switched.
the same group may be split across different regions in the same
register, or even across more than one register! The output of this block provides the System Clock, probably to
the processor, and the Peripheral Clock for the peripherals. The
Time to Deal with the Clock datasheet may reference both these terms in the remainder of
The most important part of the microcontroller is its clock periph- the document, especially when discussing any Low Power or Sleep
eral. This decides what will be used as the clock source for the modes. From the sections marked in green, we can already infer that
there is an Idle mode that removes the clock from the peripherals
only, and a Sleep mode that removes the clock from the peripher-
als and the processor.

QUARTZ CRYSTAL OPERATION If a quartz crystal or ceramic resonator is to be used, it is likely


(LP, XT, OR HS MODE) that some guidance is provided on how to construct the circuit
and lay out the PCB (printed circuit board). This is the case here
too (page 112), with two capacitors being required along with an
optional series resistance. The fact that four application notes
on oscillator design accompany this block diagram should serve
as a warning that quartz oscillators require some care in their
implementation.

Beyond Registers and Block Diagrams


Now we have covered the basics of how registers are described
and how to understand the block diagram of the clock peripheral.
We’ve even taken a cursory look at one of the oscillators and the
example circuit diagram for its use with a quartz crystal. In the
Figure 3: Recommended circuit for quartz-crystal-based oscillator. next part of this series, we’ll carry on by looking at another key
(Source: Microchip Technology) peripheral block which needs to be well understood: the reset block.

54 May & June 2023 www.elektormagazine.com


We’ll also search around for all the things that the datasheet doesn’t
cover. If you’re keen to find some resources that ease your entry
Related Products
into the world of microcontrollers, you may want to look at some
of our introductory articles [3] and books. > T. Hanna, Microcontroller Basics with PIC,
230101-01 Elektor 2020 (SKU 19188)
www.elektor.com/19188

> A. Pratt, Programming the Finite State Machine,


Questions or Comments? Elektor 2020 (SKU 19327)
Do you have questions or comments about this article? Email the www.elektor.com/19327
author at [email protected].

WEB LINKS
[1] Stuart Cording, “Microcontroller Documentation Explained (Part 1),” elektormagazine.com:
https://elektormagazine.com/articles/microcontroller-documentation-part-1
[2] 8-bit PIC16F18877 microcontroller: https://microchip.com/wwwproducts/en/PIC16F18877
[3] Tam Hanna, “Programming PICs from the Ground Up,” elektormagazine.com:
https://elektormagazine.com/articles/programming-pics-from-the-ground-up

e-zine
Your dose of electronics

Every week that you don’t subscribe to Elektor’s e-zine is a week


with great electronics-related articles and projects that you miss!

So, why wait any longer? Subscribe today


at www.elektor.com/ezine and also receive
free Raspberry Pi project book!

lektor May & June 2023 55


INDUSTRY

Automating Test
and Measurement
Programming Test Equipment to Do What You Want

By Stuart Cording (Elektor)

Testing can be monotonous and repetitive, and


fault finding is exceptionally challenging. So
why not use the communication interfaces on
test and measurement equipment to make it
easier? Here we explore tools that are easily
controlled using Python without splashing out
on licenses or expensive software.

For most developers, test and measurement (ISO 7637-2). Another common failure mode
equipment sits on the workbench, waiting to related to supply conditions is a voltage that
perform a task. But turn most of those devices slowly rises or falls. Under such conditions,
Figure 1: Two of the EL-R Series bench DC power
around, and you’ll often find a communica- circuits often fall into a brown-out condi-
supplies offer a serial interface (RS-232/virtual
tion interface on the rear. Coupled with the tion from which they cannot recover. Finally, COM using USB) to support test automation.
appropriate software, you’ll gain the power for automated test systems, it helps to have (Source: Aim-TTi)
to control measurements and gather results equipment that can be correctly configured for
for later analysis. This can be exceptionally both voltage and maximum current, especially
helpful when searching for sporadic events when the same setup is used for several differ-
and failures or testing an application over ent products. These bench supplies use low-noise linear
various system parameters. It is also how regulation to provide single, dual, and triple
end-of-line testing and component binning Laboratory power supplies have dropped outputs. They are fanless, relying on convec-
can be automated. significantly in price in recent years. To tion cooling, and range in power from 30 to
compensate for the influx of cheap equip- 130 W. With one or two red LED displays and
Remote Control of Lab Power ment, better-known brands typically expand analog controls, some models also include
Supplies their range of features to compensate, unwill- remote sense terminals. Two models of inter-
A good starting point is the power supply. ing or unable to compete on price alone. It est are the single output EL302P, with RS-232,
If nothing else, most applications require is unknown whether this is the case at Aim and EL302P-USB, featuring USB, both 60 W
power cycling to perform a hard reset. More and Thurlby Thandar Instruments (Aim-TTi) units with 0...30 V and 0...2 A outputs.
advanced testing will see the target applica- in Cambridge, UK, but they do deliver on their
tion operated at the extremes of the allow- promise of “measurably better value.” They The units come with software drivers for
able input supply specification, and it may be offer an extensive range of DC power supplies, the interface. In addition, the utility “PSU
necessary to perform overvoltage tests. This but their entry-level EL-R series (Figure 1) is Sequencer” is provided on the supplier’s
is common in automotive, where pulses of up worth a closer look, especially when toying website [1], allowing user-configured volt/
to 87 V must be withstood for up to 400 ms with the idea of a first automated test setup. current settings to be stepped through

56 May & June 2023 www.elektormagazine.com


Example 1: Simple Python script to acquire PSU ID string
using pySerial
import serial
ser = serial.Serial(’/dev/ttyUSB0’, 9600, timeout=0)
# open serial port
print(ser.name) # confirm port was really used
ser.write(b'*IDN?') # request PSU’s ID strings
response = ser.readline() # collect response
Figure 2: Aim-TTi’s PSU Sequencer software print(response) # output PSU ID string
provides simple, repetitive cycling of voltage and
ser.close() # close port
current settings. (Source: Aim-TTi)

manually or automatically (Figure 2). Addition- must occur, in a specific sequence, to trigger etary software or access to a web server for
ally, pre-prepared sequences can be imported them. Once your team has determined how to configuration. However, a USB class specifi-
from a spreadsheet. trigger the failure, the next stage is configuring cation for test and measurement is available,
the oscilloscope to capture relevant signals known as USBTMC [6]. Much like storage
Python for Power Control that will help determine the ultimate cause. devices, such as USB drives, and human-in-
Developing your own control software, tuned terface devices (HUD), like your mouse and
to your testing needs, is also simple. The Boards such as Arduino and Raspberry Pi keyboard, this class provides predefined
hardware RS-232 interface operates from 600 are great for the rapid development of a test commands suited to interfacing with test and
to 9,600 baud, and the USB interface appears harness that can repeatedly trigger the failure, measurement equipment.
as a virtual COM port. The commands are all using analog outputs and digital signals,
listed in the instruction manual [2], and with a sometimes complemented by a relay or Units such as the B&K Precision 2567B [7], a
bit of planning, it is straightforward enough to MOSFET when needed. They can also provide 200-MHz, 2-GSa/s mixed signal oscilloscope
develop a library that turns all the commands accurately timed trigger signals for an oscillo- (MSO), support this interface. With four analog
into clearly named functions or methods. One scope to ensure the correct portion of relevant channels, a 16-channel digital port, an in-built
option is to use an Arduino and an RS-232 signals is saved for analysis. 50 MHz arbitrary waveform generator, and
transceiver to control the power supply. This advanced triggers, it is simple to configure
has the advantage that other test functions Many oscilloscopes offer USB and LAN inter- using its large 10.1” capacitive touchscreen
can also be integrated, such as signal switch- faces, but some only offer support for propri- (Figure 3). But it’s just as easy via USB.
ing using relays or capturing analog and digital
signals.

Alternatively, Python provides the pySerial


module [3]. With some simple coding
(Example 1), the command interface can
be implemented as a Python module, and
automated control implemented. With some
reading of the documentation, it is also possi-
ble to implement a TCP/IP-to-serial bridge [4].
This functionality is defined in the experimen-
tal RFC2217 [5] memo and allows a remote PC
to configure a serial interface and implement
communication.

Scoping Out Signals


Oscilloscopes can also be remotely controlled.
With their wide range of capabilities, from Figure 3: With a USBTCM-
compliant USB interface, the
signal capture of analog and digital signals to
B&K Precision 2560B Series
FFTs, they can be used for various automated of MSOs are easily automated
tests. For example, some failures are hard to using Python. (Source: B&K
find due to a complex series of events that Precision)

lektor May & June 2023 57


Figure 4: The runt trigger is a clever mechanism for finding pulses Figure 5: The plate-sized Moku:Lab is 12 instruments in one, and can be
that don’t fully rise or fall. (Source: B&K Precision) configured using a Python API. (Source: Liquid Instruments)

Remote Configuration and measurement equipment. The control needed its own display. Thanks to a power-
Again, Python is the preferred programming commands are ASCII strings with various ful FPGA and Ethernet interface, your PC or
language thanks to the USBTMC project [8] by options, as described in the oscilloscope’s laptop forms the user interface. Liquid Instru-
Alex Forencich, which is hosted on GitHub [9]. programming manual [12]. If available, VISA ments has taken the same approach with
The module works on Linux but may require resource strings [13] can also be used. their Moku:Lab [14], an all-singing, all-danc-
the permissions to be appropriately modified. ing laboratory about the size and shape of a
On Windows, both PyUSB [10] and libusb [11] The VID and PID are unique to the product, dinner plate. It offers a range of analog inputs
will need to be installed first. not the individual unit. Thus, if two or more and outputs and is designed to be a lab in
of the same device are attached, they can be a box.
The first steps are relatively straightforward. independently addressed using a third param-
Before starting, the vendor (VID) and product eter, their serial number. This is usually on Recessed into the front are four BNC connec-
ID (PID), two USB-specific reference values a label or can be obtained using the *IDN? tors (Figure 5). The right pair provides the
that identify a USB product, are required. command (Example 2). analog outputs, supporting a sampling rate of
Using Linux, this is easily acquired from the 1 GSa/s per channel at a 16-bit resolution and
command line using lsusb once the device is There isn’t much to differentiate oscilloscopes a bandwidth (-3 dB) of >300 MHz. The left pair
attached. The resultant list provides the neces- these days beyond bandwidth, sampling rate, are the analog inputs, with a bandwidth (-3
sary details. On Windows, these values can be and memory depth. But occasionally, a little dB) of 200 MHz into 50 Ω and a sampling rate
determined via the Device Manager and the feature crops up that is of interest. The B&K of 500 MSa/s per channel at 12-bit resolution.
device’s properties. In both cases, the values Series features a runt trigger (Figure 4), a The internal timebase provides an accuracy
provided are 16-bit hexadecimal. capability that triggers when a signal passes better than 500 ppb. A trigger input is also
one threshold (e.g., high level) but not the provided, along with connectors that enable
All that remains is to import the usbtmc other (e.g., low level). When it comes to failure the synchronization of multiple units. Wired
module in your Python code and use the avail- analysis, every little helps. connectivity is provided via an Ethernet port
able programming interface (API). It is much and USB interface, and a second USB power
like printing text to the screen and evaluat- Headless Test Equipment port is available to charge a tablet. Finally,
ing keyboard input. USBTMC is really just a Red Pitaya broke the mold when it came to there is an SD Card slot and the DC power
wrapper to communicate with capable test test equipment, questioning whether a tool input.

Although the unit has wired interfaces, it is


really designed to be used in conjunction
with an iPad over Wi-Fi (802.11 b/g/n) and
Example 2: Using USBTMC in Python to control a B&K the matching app. Twelve instruments can
be selected via the user interface, ranging
Precision oscilloscope
from the familiar, such as oscilloscope and
import usbtmc spectrum analyzer, to the eclectic, such as
instr = usbtmc.Instrument(<VID>, <PID>, ’ABC123456’) PID controller and laser lock box. The tool
# or, without serial number also functions as a data logger. The size of
instr = usbtmc.Instrument(<VID>, <PID>) your SD card is the limit for data storage up
print(instr.ask("*IDN?")) to 100 kSa/s acquisition, while the internal
# returns ’BK Precision,2567B-MSO,ABC123456,5.0.1.3.9R3’ memory capacity defines it for rates of up
to 1 MSa/s.

58 May & June 2023 www.elektormagazine.com


Of course, like all modern tools, the Moku:Lab
offers a Python API and MATLAB and Example 3: Creating an arbitrary waveform on the Moku:Lab
LabVIEW support. Backed up by numer- in Python
ous examples (Example 3), the device can
also be rapidly integrated into an automated """pymoku example: Arbitrary waveform generator
test harness. It would be well suited to mass (c) 2019 Liquid Instruments Pty. Ltd.
testing RF devices and component binning. (shortened version for Elektor)
"""
Save Time, Improve Accuracy from pymoku import Moku
Test equipment is the eyes of the engineer, from pymoku.instruments import ArbitraryWaveGen
showing what is going on in complex systems. import numpy as np
But they have their limits. By definition, # generate a signal the the Arb Waveform Gen should generate on the output
sporadic events are challenging to track down, t = np.linspace(0, 1, 100) # Evaluate our waveform at 100 points
and a solution can only be proposed for a # Simple square wave (can also use scipy.signal)
cause. API-supported programming inter- sq_wave = np.array([-1.0 if x < 0.5 else 1.0 for x in t])
faces on test and measurement equipment # More interesting waveform. Note that we have to normalize this waveform
are more common today, ranging from simple # to the range [-1, 1]
to refined. And, increasingly, it is the simple-to- not_sq = np.zeros(len(t))
learn Python that is becoming the program- for h in np.arange(1, 15, 2):
ming language of choice. If your measure- not_sq += (4 / (np.pi * h)) * np.cos(2 * np.pi * h * t)
ment challenge is becoming difficult to trigger, not_sq = not_sq / max(not_sq)
requires consecutive changes to complete # Connect to your Moku by its device name
a single round of tests, or is simply dull and m = Moku.get_by_name(’Moku’)
repetitive (leading to operator mistakes), # Prepare the ArbitraryWaveGen instrument
automation is not as complex as you may i = m.deploy_or_connect(ArbitraryWaveGen)
have thought. try:
230046-01 # Load the waveforms to the device.
i.write_lut(1, not_sq)
i.write_lut(2, sq_wave)
Questions or Comments? # Configure on-device linear interpolation
Do you have technical questions or i.gen_waveform(1, period=1e-6, amplitude=1, interpolation=True)
comments about this article? Email the i.gen_waveform(2, period=1e-6, amplitude=2, interpolation=False)
author at [email protected] or finally:
contact Elektor at [email protected]. m.close()

WEB LINKS
[1] PSU Sequencer, Aim-TTi: http://bit.ly/40jGiCQ
[2] EL-R Series DC Power Supplies, Aim-TTi: http://bit.ly/3kWZmXk
[3] pySerial Module: http://bit.ly/3YgSJgZ
[4] pySerial TCP/IP Bridge Example: http://bit.ly/3kTDKem
[5] G. Clark, “RFC 2217 Telnet Com Port Control Option,” Cisco Systems, Inc., October 1997: http://bit.ly/3jcQGM4
[6] “Universal Serial Bus Test and Measurement Class Specification (USBTMC),” USB Implementers Forum, Inc., April 2003:
http://bit.ly/3YbJY7L
[7] Model 2567B-MSO, B&K Precision: http://bit.ly/3kN3rNy
[8] A. Forencich, “Python USBTMC,” July 2014: http://bit.ly/3HMLeZN
[9] A. Forencich, python-usbtmc, GitHub Project: http://bit.ly/3wK4i4r
[10] PyUSB Software: http://bit.ly/3WRFW3l
[11] libusb Software: http://bit.ly/3wLEvIY
[12] “Programming Manual 2560B Series,” B&K Precision, September 2022: http://bit.ly/3WRDYjs
[13] “VISA Resource Syntax and Examples,” National Instruments Corp., May 2022: http://bit.ly/3XK3okh
[14] Moku:Lab, Liquid Instruments: http://bit.ly/3WT6bXb

lektor May & June 2023 59


Elektor infographic
Test and Measurement

Test and measurement solutions are important to and widely used by


professional engineers, students, and makers. Here we present some
informative data about test- and measurement-related topics, including
software testing, system security, the MEMS market, and the global
industrial sensors market.

Keep Testing That Software


Do you work in the software testing Companies to Watch
sector? If so, congratulations: Software Testing Market > Accenture
you are employed in a healthy Billions > Atos SE
$40-billion-plus field. Not a bad gig > Amdocs
at all! According to a recent Global $70 > Cognizant
Market Insights report, the software
$40 > IBM
testing market is poised to grow > Infosys
6% by the year 2030, which means 6% CAGR > Keysight (Eggplant)
you’re likely to have some decent
job opportunities (and perhaps job (Source: Global Market Insights)
security) in the coming years.[1] 2022 2023 2024 2025 2026 2027 2028 2029 2030

What’s in a Test? Need to test some software? Want to debug an application?


Is security important to you? Choose black box or white box!
Before you choose white or black [2] and then start to test,
Black Box White Box consider checking out the following helpful resources!

HELPFUL RESOURCES
</> > S. Cording, “Debugging Microcontrollers Without a Debugger,”
January 17, 2023. https://elektormagazine.com/no-debugger
> S. Cording, “The Full Gamut of Microcontroller Debugging
Techniques,” June 30, 2020. https://elektormagazine.com/
mcu-debug-20
> Functional test: test > Structural test: test > M. Horkan, “A Black-Box Approach to Embedded Systems
app functionality and app infrastructure. Vulnerability Assessment” (Elektor Business 4/2018).
behavior. https://elektormagazine.com/blackbox2018
> Pro programming insights
> Pro programming insights are required. > L. Labbe, “Tracing the Cause of Software Bugs Wirelessly:
Circular Buffer and Webserver on the ESP32,” September 29,
are not required. > Managed by developers. 2022. https://elektormagazine.com/trace-bugs-wireless
> Managed by testers. > Code access is required. > C. Valens, “Secure Communications – An Interview with Luka
> Code access is not Matic,” November 6, 2019. https://elektormagazine.com/
required. secure-comm-19

60 May & June 2023 www.elektormagazine.com


MEMS Market =
The MEMS Market
The Microelectromechanical System (MEMS) market
is growing, with various research firms reporting that
+11% by 2031
the global market is likely to grow at a CAGR between
8% and 11% by 2031, the firm Verified Market Research Key Players
has reported.[3][4] As devices with both electric and > Analog Devices
mechanical functions, MEMS devices have countless Types > Broadcom
applications in a wide range of industries, including
> Actuator > NXP
the industrial measurement equipment, automotive,
consumer electronics, and aerospace. The super-small > Sensor > STMicroelectronics
devices are used for pressure sensing, signal process-
MEMS
ing, data transmission, and much more. “The consumer Market
electronics segment acquired the largest share in 2021,
and is expected to grow at a significant CAGR from 2022 Applications
to 2031 for microelectromechanical system (MEMS) > Automotive Locations/Market Size
market size,” Allied Market Research reported in Septem-
> Consumer Electronics > #1 Asia-Pacific
ber of 2022.[5] If you are fascinated by MEMS technol-
> Healthcare/Medical > #2 North America
ogies, keep an eye on how MEMS chips are being used
in the medical field in microsurgical tools, implants, and > Information Technology > #3 Europe
microneedles for drug delivery.

Making Sense of Industrial Sensors


The global industrial sensors market is poised to reach over $33 indispensable for measurement and test purposes. Industrial sensor
billion by the end of 2027, according to Fortune Business Insights.[6] types include temperature sensors, flow sensors, gas sensors,
Used in a wide variety of Industry 4.0 applications, these sensors are motion sensors, and position sensors.

Top Sensors by Global Industrial Sensors Market


Market Share 2021 Billions

•• 14% Temperature Sensor $33.5

••
11% Position Sensor
39% Pressure Sensor $19.3
7.2% CAGR
36% Image Sensor

2019 2020 2021 2022 2023 2024 2025 2026 2027

WEB LINKS
[1] Global Market Insights, “Software Testing Market Report,” 2022: https://www.elektormagazine.com/GMI-testing-software
[2] L. Nguyen, “Key Differences and Similarities Between Black Box and White Box Software Testing,” Orient Software, 2021:
https://www.orientsoftware.com/blog/black-box-and-white-box-software-testing/
[3] Verified Market Research, “Microelectromechanical System (MEMS) Market Size And Forecast,” 2023:
https://www.elektormagazine.com/vmr-mems-market
[4] Markets and Markets, “Micro-Electro-Mechanical System (MEMS) Market,” 2023: https://www.elektormagazine.com/mandm-mems-market
[5] Allied Market Research, “Microelectromechanical System (MEMS) Market,” 2022: https://www.elektormagazine.com/amr-mems-2022
[6] Fortune Business Insights, “Industrial Sensors Market Size, Share & COVID-19 Impact Analysis,” 2019:
https://www.elektormagazine.com/fortune-sensors
[7] Markets and Markets, “Top 10 Sensors Market by Type (2021-2026),” 2021: https://www.elektormagazine.com/markets-top-10-sensors

lektor May & June 2023 61


BACKGROUND

Overvoltage
Protection
for Safe
Operation
Transient Protection for Non-Isolated
DC/DC Power Modules

By Timur Uludag (Würth Elektronik)

In industrial environments, transient overvoltages


often occur due to an extensive electrical First and foremost, there is not only one possible cause
for a transient on the DC bus that leads to an abrupt
infrastructure. In order to develop an efficient filter rise. The origin of the transient can be a lightning strike
to limit transient overvoltages, many influencing (Figure 1, Part A), in which case we speak of a surge,
parameters must be considered. or it can be generated in the system itself (Figure 1,
Part B). Classically, the 24 V DC bus in the industrial
environment is specified from 19.2 to 30 V (see IEC
Today, many industrial applications run on logic input 61131-2). When it comes to considering transient
voltage levels such as 5 V DC or lower, as shown in overvoltages, other effects must be taken into account.
Figure 1. The power distribution system used to power For example, if the 24 V supply line is installed in paral-
such applications often runs on a DC bus voltage of lel to the control line of a frequency inverter, the pulses
24 V DC. Switching DC/DC converters are commonly are capacitively coupled and the 24 V is oscillating in
chosen to handle the conversion of the higher DC bus the pulse pattern of the frequency inverter.
voltage down to the lower logic voltage level.
Improper and nonexistent surge / transient protection
Figure 1 shows the basic electrical structure of an leads to malfunctioning due to electrical damage to the
industry plant. The separated parts of the applications DC/DC converter, leading to higher system downtimes
are supplied through a DC bus. On site, every separated and costs. For a proper calculation and assumptions,
electrical load is connected via a sub distribution with we have to use a normalized transient such as the
24 V. Non-isolated power modules are implemented surge that is described in the standard IEC 61000-4-5.
to provide the operating voltage of all subsystems.
Filter Concept
Origin of Transients Figure 2 shows the entire immunity filter concept
Transients can be defined as short-term deviations (green), which includes two stages of filtering. One
from a nominal voltage value, which exceeds the stage to clamp the high transient overvoltage during
permissible tolerance range of the nominal voltage a surge event, which can be achieved with transient
in an electrical system. The effects of the transients suppressor components such as unidirectional TVS
are mostly destructive. diodes. For the second stage, a passive LC filter is

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


Figure 1: In industrial environments, typically a DC
bus powers the individual elements of a plant.

recommended, which attenuates the voltages that To make a proper design based on a TVS diode for a
exceed the maximum operating voltage of the DC/ transient protection of the power module, the follow-
DC converter. ing parameters are required.

Immunity Filter Design Limits > VDC supply voltage for the power module
The most critical parameter of a switching regula- > VBR voltage where 1 mA of current is flowing
tor needed for a transient filter design is the input through the TVS diode
voltage. In many cases, there are two different values > IPeak max.peak current flowing through the TVS
given in the datasheet. One is the absolute maximum diode @ VClamp max
input voltage, which, if exceeded, leads to permanent > PDiss max.allowed dissipated power for the TVS
damage to the power module. The other one is the diode
maximum operation voltage, which corresponds to the > VClamp max voltage where the diode carries the
maximum specified input voltage the manufacturer maximum specified current
allows the power module to be used with. For means
of transient overvoltage protection, it is recommended First Immunity Filter Stage
to design the immunity filter so that even in transient Determination of VDC
overvoltage events the power module input voltage For VDC, the determining value for immunity is the
never exceeds the maximum operational voltage limit. maximum DC bus voltage that can be present, not the
For further calculations the 173010535 Sip-3 power nominal value that means 24 V for a 24 V bus. In the Figure 2: Filter concept
module with an absolute maximum input voltage of industrial environment, a 24 VDC bus is specified for for EMC compliance of
MagI3C power modules
Vin = 44 V is used as an example [1]. 19.2 to 30 V. Resultantly, the max is VDC = 30 V.
with immunity and
emission filter.
Immunity Filter Design The selection of the TVS diode for the next steps
In this article, the use of a unidirectional power of calculation is based on the available parts in the 
transient voltage suppressor diode (TVS) is consid-
ered as a protection element for the power module
input. Unidirectional operational behavior means
that the V-I characteristics are nearly the same as that
of a Zener diode. Consequently, the diode is normally
used in reverse direction. Exceeding the component’s
specific breakdown voltage causes the TVS diode to
enter into a conductive state. The clamping voltage
level is then determined by the current flowing
through the component. The following numerical
example provides a simplified, hands-on guide for
establishing a well-estimated filter. The filter estima-
tion enables a quick refinement cycle when conduct-
ing real application tests.

Partner Content lektor May & June 2023 63


product portfolio of Würth Elektronik. The online coefficient αT for this type of TVS of 9.9 × 10-4 1/°C,
catalog shows 2 possible components, the 824541301 this results in a maximum VClamp of 49.84 V at 55 °C.
and the 824551301 [2]. This value will be now the starting point for the dimen-
sioning of the second stage of the immunity filter.
Determination of VBR
VBR is defined as the voltage at which 1 mA of current Second Immunity Filter Stage
is flowing through the TVS diode. This value, here The question now is how to estimate the right filter
35.05 V, is in reality not a fixed value, because this attenuation and how to get the best filter component
is a PN transition and therefore has a tolerance. The values. Starting with the attenuation, the minimum
tolerance is given in the datasheet as ± 5 %. That leads filter attenuation can be calculated with Equation 2.
to a VBR from 33.325 V to 36.8025 V. In this region, the
diode starts its conduction with a current of 1 mA.

However, it is also necessary to know the value at


which the transient voltage should be clamped. This (Instead of the symbol A (attenuation) the formula
is represented by the parameter VClamp max. sign G (gain) is used. A negative gain means an
attenuation).
Determination of VClamp max
This value can be found in the datasheet as well. For Equation 2 considers the resulting clamping voltage
the chosen diode, the voltage is 48.4 V based on a peak level VClamp max of the TVS diode during the surge event
current of IPeak of 31 A, representing a 10/1000 µs pulse. and the maximum operating voltage level VPM_Max of
So far, the calculations have assumed an ideal labora- the chosen converter. The task is to design the filter
tory environment with a controlled ambient tempera- according to Figure 3, where a LC filter circuit needs
ture of 25 °C. However, the reality looks different. Due to be added to the TVS diode. The designer, allowing
to experience an ambient temperature of up to 55 °C for the calculation of a corresponding filter capacitor,
is common for electronic devices such as a TVS diode. can select the inductor value. The reason for this is that
Therefore, the calculation needs to be modified with the filter inductor is in series with the application, and
a temperature factor. therefore its resistance (RDC) causes unwanted losses.
Therefore, the inductor with the smallest possible
Mainly VClamp max and the peak pulse power are RDC value concerning the nominal maximum output
strongly dependent on the temperature. current of the DC/DC converter should be selected. For
this example filter design, a WE - PD2 (744776112) with
Equation 1 shows the temperature effect to VClamp max. an inductance of 12 µH, RDC of 336 mΩ and nominal
rated current of 2.72 A was selected. The DC input resis-
tance of the power module can be determined with the
given input and output voltage, the output current as
Figure 3: Equivalent well as the efficiency during operation. Putting these
circuit for second
For the “standby case” where there is nearly no current parameters together, Equation 3 for the converter
stage immunity filter
calculation. flowing through the TVS diode unless the leakage input resistance can be established.
current of 1 µA the junction temperature (Tj) is nearly
 the ambient temperature. Assuming a temperature

Figure 3 shows the equivalent circuit where the TVS


diode is represented as a simplified voltage source
during surge impulses. The remaining portion of the
circuit diagram for the EMC model consists of two LC
filters for immunity (surge protection) and emission
(EMI attenuation), the input capacitor of the DC/DC
converter and the input resistance of the regulator.

Since this is an indoor application and thus there is


indirect lightning impulse, which is represented by

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


the surge, the following assumptions and calculations
are based on an 8 /20 µs pulse defined in the standard
IEC 61000 - 4 - 5. For further simplification, it is possi-
ble to omit Cf_E and Lf_E since this filter is designed
to suppress disturbances at the switching frequency
of the power module (Figure 4). The power module
switches typically at 520 kHz. The surge is based here on
1 kHz. Looking at the frequency spectrum of the surge
impulse, one can determine that the highest value of The capacitor values are calculated. However, the real 
the noise voltage occurs at a frequency of f = 1 kHz. capacitor is subject to tolerances. The capacitance Figure 4: Simplified
value fluctuates by up to ± 20 %. If the temperature equivalent circuit for
To get the attenuation G of the filter, it is necessary to dependence of the VClamp max is not fully accounted second stage immunity
compare the output voltage to the input voltage of the for, a capacitor with too low a capacitance value may filter calculation.
system (Equation 4). be selected.

Transient Protection and EMI


In order to develop an efficient filter to limit transient
overvoltages, many influencing parameters must
be considered. This is particularly important in an
industrial environment, since transient overvoltages
often occur here due to the extensive electrical infra-
structure. The filter with transient protection enables
efficient protection of the DC/DC converter module
under consideration and simultaneously enables
damping of high-frequency emissions.
With the previously calculated DC input resistance 230180-01
RPM in of the converter, Equation 5 can be used to estab-
lish the necessary capacitor value:
Table 1.

Ambient Filter capacitor


temperature VClamb max value
25 °C 48.4 V 178 µF
55 °C 49.84 V 218 µF
Here Lf represents the immunity filter inductor, RPM
the DC input resistance of the converter, Cin the input
capacitor and Cf_emission the EMI filter capacitor of an
input PI filter structure. The values can be found in the
datasheet of the power module 173010535. Therefore, About the Author
this frequency value is used for the worst-case calcula- Timur Uludag received his Dipl.-Ing. (FH) degree in Mechatronics from the Univer-
tion. Assuming the use of a 12 µH inductor, the calcula- sity of Applied Sciences in Regensburg, Germany. He then worked for several
tion result for the filter capacitor would be Cf = 218 µF. years as a hardware engineer in the field of switched-mode power supplies and
Checking the standard values for capacitors, a value analog circuit design. Since 2015, Timur has been a Senior Technical Market-
of 220 µF (860010775018) is chosen as it is larger than ing Manager at Würth Elektronik eiSos Group in the MagI3C Power Modules
the calculated value. A value less than the calculated business unit. There he specializes in roadmap planning and the market launch
capacitance would not provide sufficient attenuation of new power modules.
of the filter. The final filter selected components are as
follows (from Würth Elektronik):
WEB LINKS
T VS diode = 824541301, L f_I = 744776112, [1] Würth Elektronik data sheets for SIP-3 power modules:
Cf_I = 860010775018 https://www.we-online.com/MAGIC-FDSM
[2] Würth Elektronik data sheets for TVS diodes:
The influence of the temperature on the VClamp max and https://www.we-online.com/WE-TVSP
thus on the value of the filter capacitor, is shown in
Table 1.

Partner Content lektor May & June 2023 65


FEATURE
Figure 1: Wiha’s product range now includes three Volt Detectors,
which differ in terms of price and features.

Wiha
Measuring Equipment
Reliable Electrical Testers and Meters

By Transfer Multisort Elektronik Sp. z o.o. in accordance with the DIN EN 612433 and
VDE 0682-401 standards. They can also
Electrical testing equipment is essential for any technician check continuity in a range of 0 Ω to 500 kΩ.
who doesn’t want to work in the dark. The range of Wiha The mid-range and high-end variants differ
the most. The mid-range model is suited for
measuring equipment here is just the start of the impressive photovoltaic system testing and offers the
range available from Transfer Multisort Elektronik. option of non-contact voltage measurement,
frequency (from 1 Hz to 950 Hz) and resistance
(between 0 Ω and 1999 Ω). On the other hand,
the high-end model is intended for the electro-
Measuring equipment is a set of tools which can detect voltage from a distance. In other mobility sector and can measure frequencies
may prove useful both in maintenance words, you don’t need to touch any danger- of between 40 Hz and 400 Hz.
workshops in large modern factories and in a ous surfaces.
DIY-enthusiast’s garage. As the name suggests, Digital Multimeter
measuring equipment is intended for measur- Wiha’s product range now includes three Volt Digital multimeters (Figure 3) are examples
ing distinct properties of electrical devices and Detectors, which differ in terms of price and of the most common measuring equipment.
installations. However, it may also be used for features. The base model is equipped with a Their popularity can be attributed to the fact
estimating environmental conditions. Thanks single LED that informs the user of voltage that they can measure multiple electrical
to such tools, it is much easier to detect a fault detection in the range of 90 V AC to 1000 V AC. properties and are easy to use.
in a malfunctioning device or check whether a The other two devices indicate voltage detec-
newly assembled circuit works properly. tion using an LED and an audible signal. What This product category includes two slightly
is more, the high-end variant is equipped with different meters. The more basic model,
While looking for the right measuring equip- a flashlight, and it can detect a wider voltage WIHA.45218, can check continuity in a range
ment [1], it is worth checking out the range of range (between 12 V AC and 1000 V AC) than of up to 30 Ω and detect resistances of up to
Wiha products [2]. This German manufacturer the base model. In addition, the high-end 40 MΩ. What is more, the device can measure
provides tools of impeccable quality, precision, variant, in contrast to the mid-range devices, voltages of between 0 V and 600 V (for both
and reliability recognized all around the world. is ATEX-certified. Therefore, it can be success- alternating and direct current), measure
This is evidenced in the number of prizes the fully used in explosion risk zones. current of between 40 mA and 10 A AC/DC,
brand receives every year for its innovative and frequencies of up to 5 MHz. Additionally,
ideas, design, and customer service. Now, their Two-Pole Voltage and
product range has been expanded to include Continuity Tester
measuring equipment. Another device that may prove useful in a
workshop is the two-pole Voltage and Conti-
A non-contact voltage detector (Figure 1) nuity Tester (Figure 2). The device can be
is considered to be a must-have for every used for testing electrical installations and
electrical engineer and technician. With such control cabinets.
a product, you can check whether a circuit is
Figure 2: The Voltage and Continuity tester can
charged with electricity. It’s incredibly safe to All three available testers have a measuring check continuity in a range of between 0 Ω and
conduct tests with such tools because they range of 12 V to 1000 V AC or 12 V to 1500 V DC, 500 kΩ.

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


Figure 3: The WIHA.45218 Figure 4: With a Wiha Figure 5: The Socket Tester Figure 6: The Phase Rotation
Digital Multimeter can clamp meter, you can ensures easy and quick Indicator is a perfect solution
measure voltages in the measure current of socket testing. for maintenance workshops.
range of 0 V to 600 V. up to 400 A AC/DC.

the tool is equipped with a HOLD function to 1500 V at direct current. Additionally, the
and an automatic range measurement setting. tool can measure current at up to 400 A AC/
DC, frequency at up to 5 MHz, and resis-
The other multimeter, WIHA.45215, is a bit tance at up to 40 MΩ. The product has also
more advanced. It can check circuit conti- been equipped with TrueRMS, HOLD, and
nuity in a range of up to 30 Ω and detect Min / Max / Avg functions. What is more,
resistances of up to 200 MΩ. In addition, it the tool has an integrated flashlight and can
can measure voltages of between 0 V and be used, for instance, in photovoltaic system
1000 V AC/DC, measure current ranging testing and the electromobility sector. Figure 7: The result of the Continuity Tester is
from 40 mA to 10 A AC/DC, and frequencies indicated by an LED and an audible signal.
of up to 60 MHz. Moreover, the product has Mains Socket Tester
TrueRMS, HOLD, and Min/Max functions. It The WIHA.45220 is an interesting example of a
also offers the option of non-contact voltage mains Socket Tester (Figure 5). With this tool, meter is connected to the motor, the LEDs will
measurement, as well as automatic and you can test various types of sockets. Depend- indicate the direction of rotation and inform
manual measurement range setting. ing on the result of the test, the three LEDs on the user of an incorrect phase sequence. Such
the front panel will light up in a preset config- a rotational field indicator is a must-have for
Wiha Clamp Meter uration. The product can detect, for instance, maintenance workshops.
A clamp meter (Figure 4) may be useful when whether the L/N cables have been connected
you need to measure current without making the other way around, but also a phase loss or Continuity Tester
physical contact with a conductor. To test a lack of earthing. Such equipment may prove Even the best electrician can make a mistake
cable, you only need to place it between the immensely useful for electricians. while putting together an electrical installa-
clamps, and the meter will show you the value tion. To find the fault, you can use a Conti-
of the current. Due to this feature, such tools Rotational Field Indicator nuity Tester (Figure 7). The tool is intended
have gained a lot of popularity among electri- (Phase Sequence Tester) for professionals and offers two measuring
cal engineers and technicians. Phase sequence is crucial in three-phase ranges (up to either 10 Ω or 500 Ω, respec-
motor systems. An error in the sequence may tively). The test is compliant with the CAT II
The manufacturer offers a professional clamp cause damage to the motor and an undesir- 400 V standard. Continuity is indicated by an
meter, the WIHA.45219. With this device, able production line stoppage. A device that LED and a loud, audible signal. The manufac-
you can check continuity in a range of up to can help you check whether phases have turer claims that the signal can be heard in
30 Ω and detect voltages ranging from 0 V been connected in the correct order is the another room or even on another floor.
to 1000 V at alternating current, and from 0 V Phase Rotation Indicator (Figure 6). When the 230192-01

WEB LINKS
[1] Measuring instruments: https://tme.eu/dk/en/katalog/measuring-instruments_100164/p,wiha_248/
[2] Wiha products: https://tme.eu/dk/en/linecard/p,wiha_248/
[3] Article source: https://tme.eu/dk/en/news/library-articles/page/51790/wiha-measuring-equipment/

Partner Content lektor May & June 2023 67


BACKGROUND

Figure 1: The Moku:Lab has two analog


inputs and outputs and features a
groove in the top of the housing for use
as a tablet stand.

Automating Testing and


Collaborating on Test Results
By Stuart Cording for Mouser Electronics
as an App. Packaged in a circular housing,
When it comes to testing complex applications, it is 20 cm (7.9”) in diameter and 4.4 cm (1.")
a few go-to tools are essential, such as these high, making it simple to find it a home on
even the busiest lab bench. A groove across
sampling devices of the range available from the top also functions as a stand for your
Mouser Electronics. iPad. Data, settings, and screenshots can
be shared directly to Dropbox and other
cloud services or sent by emails in addition
to using the internal memory.
Today’s applications are becoming increas- budgets for measurement tools or a profes-
ingly complex, not only to develop, but sional HIL setup. Recessed into the front are four BNC
also to test. Increasingly, test automation connectors. The right pair provides the
is needed even during research and devel- Ultimate Measurement analog outputs, supporting a sampling rate
opment to tackle those niggling, sporadic Flexibility and Headless Test of 1 GSa / s per channel at a 16-bit resolu-
issues that you can’t nail down. Test runs Recently, there has been significant growth tion and a bandwidth (-3 dB) of > 300 MHz.
overnight or over the weekend demand test in headless measurement equipment, The left pair is for the analog inputs, with a
and measurement equipment that is flexi- devices that rely on software running on bandwidth (-3 dB) of 200 MHz into 50 Ω and
ble and that can be programmed to execute laptops, computers, or tablets to display a sampling rate of 500 MSa / s per channel
a multitude of test cases. The measure- measurement results. These typically rely at 12-bit resolution. The internal time base
ments must then be stored for evaluation on field-programmable gate array (FPGA) provides an accuracy better than 500 ppb
to support the hunt for that annoying bug! system-on-chip (SoC) devices coupled (Figure 1).
with high-speed analog front-ends and
Thankfully, the range of test and measure- digital-to-analog converters (DAC). The At the rear, further BNC connectors are
ment equipment with automation and FPGA enables users to reconfigure the tool available for an external 10 MHz reference
result-sharing capabilities is growing. on-the-fly, enabling their use as an oscillo- clock input and a 10 MHz output. These
High-end suppliers continue to broaden scope at one moment, as a signal analyzer enable the signals captured by multiple
the number of features on offer and can the next, and then as a PID loop control- Moku devices to be synchronized with one
ensure calibrated results with their certi- ler. Additionally, thanks to masses of inter- another. A trigger input is also provided.
fication programs. Then there is a range of nal storage, they are also ideal for logging Next to these are an Ethernet port, a USB
new names. These suppliers often focus on measurements, be it a burst over a milli- interface, a USB power port (to charge a
providing unparalleled levels of measure- second or continuous logging over days. tablet), an SD card slot, and the DC power
ment flexibility coupled with support for input. Connectivity via Wi-Fi (802.11 b/g/n)
integration into hand-built hardware-in- The Moku:Lab from Liquid Measurement is also supported.
the-loop (HIL) testing solutions. This is ideal [1] is just such a reconfigurable hardware
for research and development teams that platform, offering 12 different instruments. Among the 12 supported instruments are
need to test and iterate their design rapidly Software is provided for Windows and the common ones you’d expect, along with
but don’t have access to five or six-figure Mac OS desktops/laptops and for the iPad tools that simultaneously use the inputs

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


Figure 2: The
Moku:Lab FIR Filter
Builder interface
clarifies what is
happening in the
signal path while
providing simplicity
of configuration.

and outputs. These include a PID control- automated testing and data logging, all of and cold spots. Teledyne FLIR is well-known
ler with two fully configurable paths and which are supported with examples hosted in the field of visual temperature measure-
an FIR Filter Builder for finite impulse on GitHub [3]. A robust and straightforward ment, with its products supported by a
response filters with up to 14,819 coeffi- two-channel data logging application for wealth of software to simplify data analy-
cients (Figure 2). A Laser Lock Box is also Python requires only a few lines of code sis, collation, and collaboration. Equipment
included that utilizes the Pound-Drevel-Hall (Figure 3). such as the MR265 [4] (Figure 4) features
[2] technique to stabilize laser frequency Multi-Spectral Dynamic Imaging enhance-
— something used in gravitational wave Long-Term Testing of Thermal ment [5] (MSX®), which improves image
detectors, time measurement, and atomic Issues clarity over traditional infrared imaging
physics. Sometimes, you may wish to investigate tools. The unit achieves this by combining
long-term self-heating or heat dissipation a 160 × 120 (19,200 pixels) thermal camera
Application programming interfaces (API) for your device’s housing. In such cases, coupled with a 2 MP visual camera. Due to
are provided for MATLAB, LabVIEW, and infrared cameras can be a huge help, their lower resolution, cameras relying on
Python, providing many ways to implement enabling you and your team to pinpoint hot thermal image sensors alone tend to deliver
a very fuzzy image.

Pictures created with such tools can be so


poor that it can be impossible to under-
stand the image’s content without knowl-
edge of where the image was taken. MSX®

Figure 3: Example simple data logger capturing the signals from the two analog inputs written in Figure 4: Thermal cameras such as the Teledyne
Python for Moku:Lab. FLIR MR265.

Partner Content lektor May & June 2023 69


Figure 5: Without
MSX® (left) the
labeling on this
connection panel is
missing. With MSX®
(right) the labeling
is clear, and the
overall image quality
is significantly
improved.

couples the thermal output with a high-con- Where supported, dual streaming can also On-unit results are displayed on the 2.8",
trast image from the visible-light camera be enabled, allowing both visible light and 320 × 240-pixel color TFT.
(Figure 5). Together, the visible detail in radiometric video storage of the target
the image becomes clearer and the thermal being measured. Automated Measurement with
measurement more coherent. Traditional Lab Equipment
The MR265 offers a 9 Hz measurement While highly configurable, headless
These cameras are also supported by the update rate and measures temperatures measurement equipment is attractive in
FLIR Thermal Studio Suite [6] that can of 0 °C to 100 °C (32 °F to 212 °F) for objects some situations, the need to purchase an
collect both individual images and stream- at a distance of greater than 10 cm. Further- extra tablet or laptop to display the results
ing video. Deltas and formulas can be applied more, this unit also supports moisture may discount such tools. And, sometimes,
to provide image analysis, while measure- measurements of 7% to 100% via an what you know is quite simply better. The
ment alarms can be defined when required, in-built pinless measurement sensor or B&K Precision 2560 B Mixed Signal Oscil-
and results are easily shared with colleagues. separately available ball and pin probes. loscope series [7] doesn’t disappoint in this

Figure 6:
The B&K Precision
2569B-MSO offers
four 350 MHz
channels and a
16-bit digital logic
analyzer.

70 May & June 2023 www.elektormagazine.com Partner Content


respect, with a large 10.1" capacitive touch- provides a selection of projects that resolved. Results are also easily shared as
screen coupled with soft-touch buttons and support USBTMC devices in Python [9]. log files via cloud files sharing services,
rotary knobs. And, at only 111 mm deep When combined with the 2560B Series email, or the equipment supplier’s cloud
(4.4"), it doesn’t consume a vast amount of Programming Manual [10], it is possible to platforms. This allows teams to pull in
real estate on the bench. develop scripts (Figure 7) that automate skilled colleagues anywhere in the world
data capture and logging and decoding of to review and evaluate results.
The top-of-the-range 2569B-MSO model serial data, perform measurements, or even
offers four channels of 350 MHz bandwidth define masks for pass/fail boundary testing 230189-01
inputs and a 16-channel digital port of signals.
(Figure 6). The unit also integrates a
50 MHz waveform generator that supports Test, Test, and Test Again
a Bode plot function. Also included are While working at the bench is the highlight
advanced triggering options such as edge, of most development engineers’ days, About the Author
slope, pulse, and video (including HDTV), searching for intermittent failures with an Stuart Cording is a
along with serial bus decoding for the unclear cause is a time-sapping endeavor. freelance journalist,
common interfaces used in embedded Thankfully, much of today’s test and who writes (among
systems. Other serial interfaces, such as measurement equipment, such as the others) for Mouser
CAN FD, FlexRay, I2S, MIL-STD-1553B, and devices covered here, can be coupled with Electronics. He specialises in video content
SENT, can be purchased as upgrades. software to implement automated testing and is focused on technical deep dives and
or data logging. Due to the simplicity and insight. This makes him particularly inter-
Remote control and data capture are flexibility of these tools, simple scripts or ested in the technology itself, how it fits
supported via the USB and Ethernet inter- test procedures can be created in moments, into end applications, and predictions on
faces. For USB, a USBTMC Test & Measure- often with open-source software, to test an future advancements. Mouser Electron-
ment Class driver is needed. The National assumption. And, once the cause of failure ics is an authorised semiconductor and
Instruments NI-VISA product is recom- has been found, such tests can be saved and electronic component distributor focused
mended [8], but there are alternatives used as part of continuous integration (CI) on New Product Introductions from its
if you’re willing to look around. GitHub testing to ensure that the failure remains leading manufacturer partners.

Figure 7: USBTMC USB support can be found in open-source projects. This code, written in Python,
accesses the oscilloscope based upon its VID and PID to acquire its name and serial number.

WEB LINKS
[1] The Moku:Lab from Liquid Measurement: https://bit.ly/3FI0BAW
[2] Pound-Drevel-Hall technique: https://en.wikipedia.org/wiki/Pound%E2%80%93Drever%E2%80%93Hall_technique
[3] Liquid Instruments GitHub: https://github.com/liquidinstruments
[4] MR265 : http://bit.ly/3Zb4OUK
[5] Multi-Spectral Dynamic Imaging enhancement: https://flir.com/globalassets/industrial/instruments/flir-msx-tech-note.pdf
[6] FLIR Thermal Studio Suite: https://flir.eu/products/flir-thermal-studio-suite/
[7] B&K Precision 2560 B Mixed Signal Oscilloscope series: http://bit.ly/40tFNW7
[8] National Instruments NI-VISA product: https://ni.com/en-gb/shop/software/products/ni-visa.html
[9] USBTMC devices in Python: https://github.com/python-ivi/python-usbtmc
[10] 2560B Series Programming Manual: https://bit.ly/40lx6gi

Partner Content lektor May & June 2023 71


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

Source: Shutterstock / Olha Birieva


From Life’s
Experience Building Blocks
A few years ago, I got into a heated discus-
sion with a person who had just completed
High-Level Electronics a Master’s degree in Information Science.
He certainly had some strange ideas, and it
looked like arrogance and a disdainful attitude
By Ilse Joostens (Belgium) were part of the university curriculum during
his course of study. According to him, there
Around 15 years ago, my employer asked me to build was no room in informatics for anything
a panic alarm, because some employees felt unsafe. having to do with firmware, microcontrol-
lers, or anything else from the ‘low-level’
After a bit of market research with disappointing realm, which he disdainfully relegated to
results, I decided to put together something wireless. the realm of electromechanics. He probably
“That will never work, you should just buy something reacted this way to hide his lack of knowl-
edge of the subject. He was a champion of
ready-made,” said one of my technically oriented operating systems and high-level program-
acquaintances scornfully when I casually mentioned ming languages [1]. I don’t begrudge him his
the subject. ideas, but the prospect of having to wait for
the start-up process of a full Linux system
or similar when I switch on my coffee maker,
before it decides to start heating the water,
It cost me blood, sweat and tears, but I radio protocol libraries online, and Arduino is not pleasant.
managed to do it despite the naysayers, with boards had not yet conquered the world. This
the help of assembly language and Manches- illustrates perfectly the current trend of wanting Convenience is what people want, but it looks
ter coding. At that time, you couldn’t find any to get quick results with minimum effort. like the urge to do everything at a higher

72 May & June 2023 www.elektormagazine.com


level has also made its way into the world of existing software and breakout boards during
electronics. I’m an old-school type and I design the development phase, but that’s mainly to
most of my circuits with discrete components, explore something, to learn something, to
but what I see online and in Elektor Labs [2] try out something, or to avoid the need to
is more and more projects consisting of just immediately design a circuit board with tiny
a small single-board computer and a number SMD components. Furthermore, modules and
of separate ready-made modules, with most breakout boards can make a valuable contri-
of the functionality provided by software. bution in the educational environment, both
And, usually this software also consists of a for advanced users and for beginners — young Source: Shutterstock / Sinisa Botas
mishmash of bits of open-source code and or old — getting acquainted with the wonder-
libraries plucked willy-nilly from the internet. ful world of electronics. A variety of advanced
It looks like everyone is perfectly happy if all kits, some of which look literally like building
this does more or less what was intended, blocks, are a good example of this — a sort of board from Uncle Ali, several times, but I’m
but, to me, this way of working looks more high-tech version of conventional electronics not yet desperate enough to consider that.
like playing with building blocks than devel- experimenter kits.
oping truly sound products. Recently, I spent Sometimes there are good reasons to use a
a bit of time experimenting with ChatGPT [3] Hot Glue ready-made board, but things get really bad
[4], a new chatbot based on artificial intelli- A guitarist friend always claims that the life of when commercial companies resort to this
gence. Apparently, this program can spit out a musician consists of 3% inspiration and 97% sort of ‘spider web’ design. Last year, I was
complete descriptions of electronic diagrams perspiration, and I think the same is true for asked to have a look at a small medical device
and source code upon request. It’s anyone’s electronics. You may have an excellent idea, with a bad USB connector. After getting the
guess whether this is all correct, but it’s but if the inside of your design looks like a enclosure open with some difficulty, it turned
certainly very easy this way. spider’s web of small PCBs that are only held out (much to my surprise) to contain a cheap
together by a rat’s nest of multicolored wires, Arduino Nano clone and an equally cheap little
I’m not totally opposed to the use of ready- it makes a very unprofessional impression, not board with an I2C pressure sensor. The two
made boards and open-source software. I’d be to mention whether the random collection of were connected by small jumper wires held in
the first to admit that I sometimes make use of software will work reliably under all conditions. place with hot glue, or ‘hot snot’ [5] as David
It wouldn’t be the first device where the user Jones so graphically calls it on EEVblog. The
interface is not really right, or the buttons do associated app was also nothing to get excited
strange things. about in terms of complexity or functional-
ity. And all that went for a price of several
If you work this way, you acquire less basic hundred euro — pure profit-seeking or a lack
knowledge of electronics and there is a large of knowledge, or both? I leave it up to your
chance that you do not (really) understand imagination.
what the open-source library does or exactly Translated to English by K. Cox — 230034-01
how it works. What’s more, with this approach,
you also incur a risk because your product Editor’s note: This article is written by an
is critically dependent on the availability of electronics professional, and we appreciate
the modules you use, and software updates that Ilse is always talking frankly about her
can also unexpectedly break things. The perspective. However, we encourage all our
tendency to design things with modules is readers to set their electronics projects on our
further encouraged by the massive availabil- Elektor Labs platform, regardless of in which
ity of low-cost boards from Asia. Now that I’m stage they are. Prototypes made of building
suffering a bit from the component shortage, blocks, simple project sketches and even bare
Source: Shutterstock / jivacore I have received the suggestion to use a little ideas are welcome!

WEB LINKS
[1] Wikipedia: Programming language: https://en.wikipedia.org/wiki/Programming_language
[2] Elektor Labs: https://elektormagazine.com/labs
[3] OpenAI: ChatGPT research release: https://chat.openai.com
[4] OpenAI: Getting Started with Codex: https://help.openai.com/en/articles/6195637-getting-started-with-codex
[5] EEVblog: Sony Boombox REPAIR and Teardown: https://youtu.be/8ToVCAhLg8A?t=487

lektor May & June 2023 73


PROJECT

Energy Logger Measuring and Recording Power Consumption

By Georg Luber (Germany)

There are many potential


applications where a continuous
record of the generation or
consumption of electrical energy
makes sense. Just think of the energy
consumption of certain circuits in
the house or the energy supplied
by a balcony power plant or a larger
photovoltaic system. There are ready-
made solutions for recording, but
you can also build a suitable logger Figure 1: The finished energy logger with meter and power supply unit,
installed in a small plastic distributor.
yourself.

The logger presented here uses a meter with an S0 power circuits or also the yield of photovoltaic systems
output to record electrical power consumption. to be measured and “logged” or recorded using the
Suitable meters are available for less than €20 (e.g., electronics described here.
at Amazon, eBay or directly from the Far East). This
allows the energy consumption of connected mains After all, what was it that microcontrollers were
invented for? Pretty much for this kind of applica-
tion. Before the computer age, recording energy
consumption or generation over time would have
been difficult and virtually impossible for home
Features
use. Thanks to inexpensive microcontrollers with
> Accurate and safe due to meter with S0 interface and electrical all their great capabilities, not only is digital logging
isolation. no problem today, but even fancy things like a Wi-Fi
> Configurable acquisition of up to five 5 meters. connection and more become possible. What the
> Buffering of data in FRAM to protect the SD card. energy logger can do can be found in the Features
> Recording to SD card in CSV format. box. An impression of the finished solution is given
> Time resolution: 5 minutes. in Figure 1, showing the combination of meter and
> A separate file is saved per day. logger, including power supply units, installed in a
> Display of individual and aggregated data (current and previous day in plastic distributor box.
kWh).
> Display of Wi-Fi field strength and number of µC resets (start counter). Circuit
> Download of data via FTP. Thanks to the microcontroller, the circuit of the
> OTA: Update capability via Wi-Fi. energy logger (Figure 2) is quite simple. On the left
> Development environment: VSCode with PlatformIO. side, there are a number of optocouplers for electrical
isolation, through which the data from the meter’s S0

74 May & June 2023 www.elektormagazine.com


Galvanic +3V3
D1...D5 = 1N4148 +3V3
Isolation
IC1...IC5 = SFH617G
R9
R11 SD Card Module
300Ω

100Ω
1 4 +3V3
D5 R8 R7 R6 R5 R10
IC5 LED1
1
GND

10k

10k

10k

10k

10k
2
+3V3
3
+5V
4
2 3 CS
1 30 5
R1 EN D23 MOSI
2 29 6
300Ω VP D22 SCK
S0-Interfaces 1 4 3 28 7
D1 VN TX0 MISO
IC1 4 27 8
D34 RX0 GND
5 26
S0-1 D35 ESP WROOM D21
6 25
D32 D19
7 24
S0-2 2 3 D33 D18
FRAM Module
8 23
D25 D5 +3V3
R2
9 22
8k x 8
S0-3 300Ω D26 TX2
1 4 10 21
D2 D27 RX2 8
IC2 11 20 VCC
S0-4 D14 D4 7
12 19 GND
D12 D2 6
13 18 /HOLD
S0-5 D13 D15 5
14 17 SCK
2 3 GND GND 4
RST BOOT 16 MISO
+6V5 R3 15 3V3 3
VIN MOSI
300Ω 2
1 4 USB /CS
D3 1
IC3 +3V3 /WP

PS S0 2 3
PS Sec.
R4
+6V5 300Ω +5V
1 4
D4

GND IC4 GND

2 3

220079-006

interface are sent to the corresponding inputs of the DC/DC converter and a voltage regulator would also Figure 2: The circuit of
microcontroller. These are interrupt-controlled to have been possible, but this would not really make the energy logger is
make sure that no pulse is lost. I used an inexpensive things easier nor cheaper. quite simple.
ESP32 module because it has enough computing power
and also a Wi-Fi interface. On the right side, there Data Storage and Transmission
are two memory modules — a slot for an SD card for As already mentioned, using two memory modules is
mass storage and an additional FRAM module, which not a luxury. The S0 interfaces can sometimes deliver
temporarily buffers the data of 5 minutes in order to several pulses per second. If the measured values were
reduce the number of write cycles to the SD card. collected in the internal memory of the microcontroller,

Since the circuit is so simple, I built it on a bread-


board. As you can see from the two light blue blocks,
two separate power supplies are provided for safety
reasons. For the S0 interfaces on the left, 6.5 V is suffi-
cient. The rest of the circuit is powered by a 5 V power
supply (right). A load capacity of 0.5 A each is suffi-
cient. For the purpose of electrical isolation, the two
GND lines of the power supplies must not be connected
under any circumstances. Furthermore, below the
optocouplers –— between their inputs and outputs —
all copper must be removed over a distance of at least
4 mm. Figure 3 shows how this is supposed to look. 

The electrical isolation by means of two separate power Figure 3: The copper on
supplies also allows that the ESP32 to be connected to the bottom side of the
breadboard between
the USB interface of a PC (e.g., to allow future updates
the inputs and outputs
to be sent to the installed controller). Instead of using of the optocouplers was
two power supplies, a solution with only one power removed with a small
supply with a higher current load plus an isolating cutter.

lektor May & June 2023 75


 even withstand quadrillions of write cycles. Every five
minutes, the data collected in FRAM is transferred
Figure 4: The data to the SD card. This means just over 100,000 write
structure becomes visible
operations per year, and since an SD card has many
when importing a CSV
file into a spreadsheet. memory cells, it can be operated for quite a few years
without any problems.

data could be lost during a reset. On the other hand, In addition, the number of restarts of the logger is
writing them immediately to an SD card would recorded to the FRAM, allowing you to check at any
massively shorten the card’s service life. With only time how often a reset was triggered. Furthermore, a
one value per second, 31.5 million write cycles would new file is created on the SD every day, and the data of
occur per year. However, the memory cells of an SD this day is saved to it. In order to save memory space,
card reach the end of their life after only 1,000 to the recording is only started if one of the meter values
3,000 write cycles. Even a high-capacity card would has changed since midnight. If the energy logger is
therefore almost certainly show defects before a year used to record power consumption, this feature is
has passed. actually superfluous. However, if the energy produc-
tion of a solar system is monitored, it is useful that the
To avoid this, a stable buffer is provided. The exter- recording only starts after sunrise (i.e., when the first
nal FRAM module used here has a storage capacity electricity is generated).
of just 8 kB, but that is easily enough to collect quite
a few values. The biggest advantage of FRAM is that Data Structure and More
it can be written to at least 1010 times, depending on Figure 4 shows a section of a spreadsheet where
the manufacturer — typically, such a memory can the data has been imported in CSV format. Cell A1
contains the date and time the file was created. Row 2
then contains the last values of the previous day as the
new starting point. The first change of a meter value
occurred at 05:55 (cell A3). From row 5 on, the new data
of this day follows. The columns contain the data of
the individual meters. Each row has a time difference
of five minutes to the next row. The data is recorded
on each day until midnight. Every day, a new file is
created. The amount of energy can then be calculated
from the difference between the counted values using
the pulse value of the meters (e.g., 0.5 Wh/pulse). The
CSV format is economical and suitable for importing
into any spreadsheet like Excel, OpenOffice/LibreOf-
fice Calc or Numbers on the Mac. The data can then
be further processed to your liking.

On the SD card, the data is stored in a temporal folder


structure. At the top level, there are folders for each
year, each of which contains subfolders for the months,
and these then contain the files for the individual days.
Figure 5 shows the structure.

In this example, the values of five meters are recorded


as integers (see Figure 4). Thanks to the CSV format,
relatively little memory is required for this. This results
in a few kilobytes per meter per day.

Figure 5: The folder structure by year, month and day.

76 May & June 2023 www.elektormagazine.com


The transfer of data from the logger to a PC is done via
FTP. Common FTP clients such as FileZilla are suitable
for this. Since the logger is integrated into the home
network via Wi-Fi, this method is probably the simplest.

I created the source code for the ESP32 using the


PlatformIO IDE for VSCode [1]. The code is available
for free download on the web page of this article [2].

The following data must be customized in the main.cpp


file: Starting at line 30, the SSID and the password of
the Wi-Fi network must be entered. The username and
password for FTP are specified in line 813. By default,
“esp32” is entered as the username and password. Of
course, the FTP client also needs the IP address of the
energy logger. This address is output via the USB inter-
face after a reset. Ideally, however, you should config-
ure your router so that the energy logger is always
assigned the same IP address.

Built-In Web Interface


The current data and the total value of the day and the
previous day are displayed using the integrated web
server. The server hosts two pages. One page shows
the current power per meter as well as the total of
all connected meters. In addition, the total energy
of the day and the previous day is displayed in kWh.
Figure 6: The integrated web interface Figure 7: If you append “/about” to the IP
The other page shows the field strength of the Wi-Fi displays the measurement results. address or click on Info, you will get this
network and the number of restarts of the logger. information.

Figures 6 and 7 are screenshots from a smartphone.


As you will notice immediately, I do not use the energy
logger to measure consumption, but to monitor my
photovoltaic system, which has five inverters. There-
fore, I have adapted the labels of the individual values
to my intended use. But you can easily change this in
the software as needed. When connecting to the IP
address in the browser, you get the display of Figure 6.
By appending “/about” to the address or by clicking
on the Info button, Figure 7 appears.

One more note about the Wi-Fi connection: If you


install the energy logger in a metal housing, you will
almost certainly get reception problems.

OTA
Once the energy logger is built into a housing and
installed, you will probably not want to remove
the electronics again in case of a software change.

Figure 8: Updates of both the firmware and the data


structure are possible via Wi-Fi.

lektor May & June 2023 77



laws apply to work on the fuse box. In Germany, you
Figure 9: Four meters must be registered with the network operator as a
of type DDS5188 in trained electrician for this purpose. Also, work on
operation. external sub-distributors connected to the fuse box
is only allowed for a skilled electrician with the appro-
priate training and knowledge.

Translated by J. Starkmuth — 220079-01

Therefore, the data logger can be updated “Over The About the Author
Air” (i.e., via Wi-Fi). The complete software as well Georg Luber is a trained electrician who studied
as the file system — the web pages with JavaScript electrical engineering and worked for many years in
and the CSS file — can thus be reloaded if necessary. the fields of electrical safety and electrical installa-
tion. He has worked nationally and internationally in
If you want to do that, you enter the IP address with standardization committees (DKE/VDE, CENELEC,
appended “/update”. Figure 8 shows how this looks IEC and ISO). Another focus of his work was build-
like in my case. I implemented the OTA capability ing automation, particularly KNX. Georg Luber is
with the help of Ayush Sharma’s library [3]. involved in the development of software and electron-
ics projects in these areas.
A Simple Circuit
The circuit is so simple that a parts list is actually
unnecessary. Besides the ESP32 development board, Questions or Comments?
which is available everywhere, important components Do you have questions or comments about this article?
are an SD card slot, which is available on inexpensive Contact Elektor at [email protected].
breakout boards, and the FRAM module — also conve-
niently available on breakout boards. Since breakout
boards are available with different pin assignments,
you should not pay attention to the pin numbers, but
to the pin designations when connecting. For the SD
Related Products
card module, MOSI may be connected to DI or SI and
MISO to DO or SO. The meters can be any inexpensive > ESP32-DevKitC-32D (SKU 18701)
model for DIN rail mounting with an S0 interface. The www.elektor.com/18701
DDS5188 type I used (Figure 9) is easily available and
very inexpensive.
> PeakTech Stromzange 4350 (SKU 18161)
www.elektor.com/18161

While it should go without saying that you must


exercise the necessary care when working with mains
power, a note should be allowed: Different national

WEB LINKS
[1] PlatformIO for VSCode: https://platformio.org/platformio-ide
[2] Article web page: https://www.elektormagazine.com/220079-01
[3] OTA library by Ayush Sharma: https://github.com/ayushsharma82/ElegantOTA
[4] ESP32 projects: https://randomnerdtutorials.com/projects-esp32

78 May & June 2023 www.elektormagazine.com


REVIEW

Assembling the
4tronix M.A.R.S.
Rover Kit
By Clemens Valens (Elektor)
The M.A.R.S. rover comes as a kit of parts, but doesn’t
Inspired by NASA’s Mars rovers, Curiosity and require any soldering. The kit is self-contained, includ-
Perseverance, the M.A.R.S. rover from 4tronix ing tools, although I preferred to use my screwdrivers
instead, as they fit better.
is an autonomous vehicle designed to drive
around on rough terrain on Earth instead of There are two versions of the kit: Raspberry Pi Zero and
on Mars. Indeed, in this case M.A.R.S. doesn’t BBC micro:bit. I tried the Raspberry Pi version. Note that
the Raspberry Pi Zero or BBC micro:bit aren’t included,
refer to the planet, but is an acronym for and neither are the four AA batteries. For the Raspberry
Mobile Autonomous Robotic System. Pi, you will also need a microSD card.

An additional keypad is available from the 4tronix


•E
r lab lekto website [1], but I didn’t try it. The Raspberry Pi
to
version of the rover allows mounting a Raspberry
k

r la
Ele

Pi camera on the ultrasonic transducer mast, but I


b

TESTED didn’t try that either.


ab
Ele

to The box containing the kit is surprisingly compact


rl

to
k

r la
b • Ele k
(18 cm × 16 cm × 8 cm) but quite heavy
(600 g) and filled to the brim with
plastic bags containing parts. A
manual is not included. Detailed
assembly and programming
instructions are available on the
4tronix website, so you will need a
computer with an internet connection
to assemble the rover.

The assembly instructions are quite clear and


detailed. Assembling the rover isn’t difficult, but
there are some fiddly things like screwing on the
motor mounting brackets without the nuts falling
out or fixing some of the lock nuts or connecting the
motors. However, do pay close attention to the orienta-
tion and positioning of certain parts like the bogies and
the servos, as it’s easy to get it wrong, and then you’ll
have to do it again. This happened to me a few times.

lektor May & June 2023 79


A Few Assembly Tips
Assembling the rover took me about two hours due to
a few mistakes I made. Here are a few tips:
> Get some real screwdrivers (Figure 1).
> There are three 18 mm-long screws that go through
circuit boards. Make sure to tighten them well
before fixing the part on the other side with a lock
nut, as it may get loose otherwise when you have
to adjust the nut to make the attached parts rotate
smoothly.
> All the servo connectors are oriented the same way.
They’re clearly labeled, and the servo wires are

color-coded (Figure 2). Brown is GND and yellow is
Figure 1: Bring your own SIG (signal). Writing down the number of each servo
screwdrivers. (SVx) is practical for when you run the servoTest
program.
> The ultrasonic transducer mast can run into its
servo wires if the wires aren’t folded down enough.
> After connecting the servos, you can wrap their
wires around the servo bodies to tidy things up a bit.
On the other hand, leave the wheel motor wires free
to avoid them blocking the movements of the rocker
arms (Figure 3).
> It isn’t required to chop off the protruding ends

of the servo arms, as it makes the rover only look
slightly neater.
Figure 2: All the servo
connectors are oriented Add the Brains
the same way, they’re After assembling the rover, I mounted a Raspberry Pi Zero
clearly labeled, and the
servo wires are color
2 W on top of it. I used a microSD card with the Raspberry
coded. Brown is GND, Pi Buster OS installed. This had been used in another
yellow is SIG (signal). project, so the Raspberry Pi could already connect to
my Wi-Fi network, and SSH access was enabled too.
To save batteries, I powered the Raspberry Pi over USB
to download and install the software to make the rover
run. Again, the instructions on how to do this are clear
and detailed, but online only [2].

I also tried a Raspberry Pi Zero instead of a Zero 2 W


and found it to work in the same way. The advantage of
using a Zero 2 is, of course, that it boots much faster.

The Raspberry Pi doesn’t power the rest of the rover —


you need the batteries for that. So, if you see an error
 message complaining about the I2C bus when trying the
examples, but you’re sure you enabled it on the Raspberry
Figure 3: The bogey on
the rocker arm should Pi, then check the On/Off switch and your batteries. A
rotate with hardly any blue LED indicates whether the rover is powered on
friction. or not.

I measured a current consumption of about 400 to


500 mA when the rover is driving with the motorTest
script, and about 200 mA when idle.

80 May & June 2023 www.elektormagazine.com


in Video:
This review utu.be/
https://yo 85oc
Np8ZQQd

Programming the Rover


When developing your own programs for the rover [3],
it’s probably best to do as much as possible with the
Raspberry Pi powered over USB to save batteries and 
only switch the rover on when trying things out.
Figure 4: Once
assembled, the M.A.R.S.
I have tried all the examples provided by 4tronix [2] and rover becomes almost
found everything to work without any problems. I didn’t unstoppable.
do any programming myself. Note that, for some reason,
using the rover’s RGB LEDs requires administrator privi-
leges, so any script using them must be run with sudo.
Extending the Kit
The rover is quite impressive when driving over obsta- The main PCB has four extra mounting holes that can
cles (Figure 4). It doesn’t go very fast, but the rocker be used to attach extensions and there are plenty of
arms allow the robot to navigate obstacles as if they connections left for adding more servos (BTW, the spare
weren’t even there. parts bag in my kit contained an extra servo).

Almost Unstoppable I didn’t find a schematic, so I don’t know if the servo


The 4tronix M.A.R.S. rover kit is a high-quality kit that looks connectors can be used for something else. There are
pretty cool once assembled, thanks to its decorative print also two I2C extension connectors available to which you
and PCB features. It measures 20 cm × 18 cm × 16 cm, can connect sensors, for example.
so it’s a bit bigger than the box it comes in. Assembling 220107-01
the robot is straightforward as everything fits perfectly
(which is pretty rare) and the instructions are clear and
detailed. Using it is easy as well, and the examples and
test programs install and run without any problems.

Once assembled with the software installed, the rover is


Related Products
ready to drive around and becomes almost unstoppable.
> 4tronix M.A.R.S. rover (SKU 19996)
Some programming knowledge is required, of course, www.elektor.com/19996
but that’s why you got it in the first place, didn’t you?

WEB LINKS
[1] M.A.R.S. rover assembly: https://4tronix.co.uk/blog/?p=2112
[2] Programming M.A.R.S. Rover on Raspberry Pi Zero (inc v2): https://4tronix.co.uk/blog/?p=2409
[3] MARS-Rover [GitHub]: https://github.com/4tronix/MARS-Rover
[4] “Assembling the 4tronix M.A.R.S. Rover Kit” — this review [video]: https://youtu.be/Np8ZQQd85oc

lektor May & June 2023 81


PROJECT

Parking Disk
with E-Paper Display
An Innovative Digital Replacement

By Antonello Della Pia (Italy)

A parking disk is a traditional


accessory known by most
motorists. This project presents
a digital version based on an
e-Paper display. The design has
special features, such as setting
the arrival time with a single
button, a message in a choice of
four languages, and an on-demand
display of the current time and Figure 1: Basic operating principle of the e-Paper display
(1 upper layer, 2 transparent electrode layer, 3 transparent micro-capsules,
date, ambient temperature, and 4 positively charged white pigments, 5 negatively charged black pigments,
6 transparent oil, 7 electrode pixel layer, 8 bottom layer, 9 light, 10 white,
battery level. 11 black). (Source: https://en.wikipedia.org/wiki/E_Ink)

The evolution of the automotive sector, from the point of view The E-Paper Display
of integrating electronic technology into vehicles, has reached A relatively recent invention (1996), e-ink (electrophoretic ink)
extremely high levels. Virtually every functional aspect is optimally technology, generally referred to as e-Paper [1], owes its success
managed by sophisticated sensors, digital interfaces, microproces- mainly to its use in eBook readers, the portable devices that offer an
sors and related software. In the cockpit of what can now be consid- electronic alternative to traditional books, thanks to its paper-like
ered ‘computers on wheels,’ however, it is still easy to find an indis- reading experience and perfect visibility even in high light condi-
pensable instrument, often made of humble cardboard and operated tions. However, the unique feature that has led to the spread of this
manually. This is the Time Disk, a device required to indicate the technology in other areas is the ability to maintain the display of
start of parking in regulated areas. Over the decades, this accessory information for a long time even in the absence of a power supply,
has remained almost unchanged — made of cardboard, plastic or allowing the realization of devices that potentially require power
other more noble materials — and only recently have some digital only for the duration necessary to update the screen (refresh).
models appeared on the market. The one proposed in the article Typical applications, increasingly popular in retail outlets, are
uses a modern e-Paper display with some special features, such as electronic labels and price tags, often difficult to distinguish from
setting the arrival time with a single button, a message in a choice paper ones, which can be updated when necessary, even remotely
of four languages, and the on-demand display of the current time using wireless technologies. To better understand how electronic
and date, the ambient temperature, and the battery level. ink works, Figure 1 helps us.

82 May & June 2023 www.elektormagazine.com


VCC VCC
R2

Display e-Paper
10k
C2 C3

BUSY

GND
VCC
RST

CLK
DIN
DC
CS
100µ 100n
R1 16V J3
VCC
330Ω

1
R11 2
3
4
5
6
7
8
C1 VCC
20 7 21
SW1 AVCC VCC AREF
100n 1

1k
/RES
C4 R4 R5
23 14
PC0 PB0

10k

10k
24 15
470n PC1 U1 PB1
VCC 25 16
PC2 PB2
R6 26 17
PC3 PB3
1 7 27 18
10k

32kHz SDA PC4 PB4


2 U2 8 28
PC5 PB5
19
VCC SCL
3 6
INT/SQW VBAT ATmega328P-PU ICSP
R10 4 5 2 13
RST GND PD0 PD7 MISO 1 2
330Ω

3 12
DS3231M PD1 PD6 SCK 3 4 MOSI
C5 4 11
PD2 PD5 RST 5 6 GND
5 6
SW2 PD3 PD4
100n
R3 R12 J2
GND X1 X2 GND

330Ω
5k6

D1 8 9 10 22
VCC 8MHz
X1
BZ1
D2
SS34 BAT1

R7 R8 BLUE
F1
3V6 40mA
3k3

5k6

250mA
NiMH

D
Q1

J1
USB micro

D3 G
1 IRLD024

2 Q2
S
3 RED

4 BC546B R9
100Ω

230012-002

Figure 2: Schematic
diagram of the circuit.

In the simplest, black-and-white display version, positively (white) libraries for the various development platforms, and often fragmen-
and negatively (black) charged pigments are suspended in a liquid tary and insufficient information and support from the manufactur-
contained in microspheres representing pixels. Due to the polariza- ers themselves. Despite this, by choosing among the best supported
tion created by an appropriate electric field, the pigments, attracted products and stubbornly applying ourselves as Makers, it was possi-
by the charge of opposite sign (electrophoresis), position themselves ble to achieve a result that I believe could be interesting. Let us
to create black or white pixels, composing the desired image. At this therefore continue with the analysis of the circuit diagram, shown
point, even if the electric field is removed, the pigments remain in in Figure 2.
position until a new charge is applied. Visibility, from the partic-
ularly wide angle, is achieved by reflection from ambient light, Schematic Diagram
and in the absence of this, a special light source is required. Inter- An ATmega328P [2] microcontroller was chosen to manage the
estingly, however, under direct sunlight, the screen update does display, the same as the one used in the Arduino UNO board, given
not take place correctly. On the basis of this operating principle, the availability of a versatile library specific to this platform. The
numerous types of displays have been realized, even large and MCU operates at a clock frequency of 8 MHz, thanks to the external
full-color ones, which are, however, still very expensive. At the same ceramic resonator, and is normally in a power-saving state (SLEEP_
time, the affordable offer of smaller, black-and-white, grayscale or MODE_PWR_DOWN), to ‘wake up’ only if the display needs to be
limited-color displays by specialist retailers has increased. On the updated. The DS3231M [3] Real-Time Clock (RTC) integrated circuit,
other hand, the interest of DIY enthusiasts in these components on the other hand, remains active at all times, capable of maintain-
has not increased as much, from what I have been able to see on ing, as long as it is powered, the date and time with an accuracy
the Internet. In my opinion, the reason for this is to be found in of ±5 ppm (±0.432 seconds/day). Other notable features include
various critical points, which also became apparent during the a temperature sensor, a dual alarm and extremely low current
development of this project, due to factors such as the excessive consumption, in the order of microamps (µA) in the configuration
number of models, versions, sizes, drivers and color combinations used, Single Supply (VBAT Only). It communicates with the microcon-
on the market, the lack of well-documented and easy-to-implement troller via an I2C interface and dedicated library. The SW2 button

lektor May & June 2023 83


Figure 3: Example of info and parking screens.

(blue in the prototype) ‘wakes up’ the MCU, which can thus receive Practical Realization
data on the current time and show it on the display, together with The prototype of the Parking Disk was made as usual on a proto-
the message ‘TIME OF ARRIVAL’ and the ‘P’ logo, before returning type board, as can be seen in Figure 4. Of course, this is only one
to sleep mode. A short beep from the buzzer confirms the operation of many possibilities; by using SMD components and a special
of the button while the blue LED D2 remains lit for the duration of printed circuit board, one could probably achieve a smaller size,
the event. SW1 (red in the prototype), on the other hand, produces slightly larger than the display. The battery and buzzer are located
a hardware reset of the ATmega328P, followed immediately by the under the e-Paper module, while the eight-pin connector of the
display of a screen showing the ‘P’ logo, the battery symbol and same is obtained from a section of male and female strip contacts.
voltage, the ambient temperature, the current time and date, and the The integrated circuits are socket-mounted, and a readily available
language selected for the message, as per the example in Figure 3.

The same screen is automatically displayed every 24 hours (at the


desired time, thanks to the RTC alarm function) in order to perform
a complete refresh of the display, recommended by the manufac-
turer, and to check the battery status and the correct operation
of the entire system. Therefore, we can define SW2 as “parking
button” and SW1 as “info button.” Resistors R1 and R10, with capac-
itors C1 and C5, help to suppress any noise due to bouncing of the
button contacts, whereas R2, R4, R5, R6 are pull-up resistors. C2,
C3 and C4 are the usual power supply bypass capacitors of the ICs.
R11 limits the current drawn by the reset terminal of the specific
display used. JP2 is the connector to the display, while JP1 allows
the upload of firmware by connecting a USBasp programmer. Due
to the low current consumption, the power supply for the proto-
type is provided by a small 3.6 V Ni-MH rechargeable battery with
40 mAh capacity. The circuit formed by Q1, Q2, R8, R9 is a constant-
current regulator with low voltage drop, which limits the charging
current to about 6 mA, a value that this type of battery can withstand
without any inconvenience even if the expected 14...16 hours of
charging are exceeded. A micro-USB socket allows the connection
of a common 5 V charger, via a resettable protection fuse, while
D1 diode prevents the ‘backflow’ of current from the battery. LED
D3 indicates that the device is charging. However, we will go into
the power supply topic in more detail later. Figure 4: A view of the prototype, component side.

84 May & June 2023 www.elektormagazine.com


Figure 5: The e-Paper module utilized in the project with its “customized”
connector. (Source: Waveshare)

adapter was used for the DS3231M, in an SO-8 housing. Maximum


freedom for the choice of an enclosure, as long as it is equipped,
of course, with a transparent window!

As far as the e-Paper module is concerned, as already mentioned,


it is sometimes difficult to find our way around in the very wide Figure 6: Solder side of the prototype.
range of apparently similar components on offer. The one used
in the prototype is visible in Figure 5. It is a Waveshare 2.9-inch
diagonal, black and white, 296 x 128 resolution [4]. It has a built-in
logic level converter and supports partial refresh, an indispens- motivated by the search for higher safety and reliability in the
able feature in this project. Models other than this one may not not always optimal conditions of use on a vehicle. Compared, for
guarantee the same results I obtained, or may require modifica- example, with Li-Ion batteries, the albeit remote danger of explo-
tions to the firmware or wiring diagram. Also to be considered is sion is null and even the performance at low temperatures is better.
the permitted operating temperature range, which in this case Standard charging is certainly slower, but easier to handle. In any
extends from 0 to 50°C. case, given the minimal currents involved and the operating voltage
of the circuit, which can vary between 3.3 V and 5.0 V without
Figure 6 shows the soldering side of the prototype, on which D1 any problems, a solution involving three AAA alkaline batteries
diode (SMD type) and the micro-USB charging connector are also in series should also be considered, eliminating the need for the
located. charging circuit and still being able to rely on a duration that is
likely to exceed the car’s! Quantifying accurately the ‘consumption’
Coming back to the subject of power supply, the choice of a recharge- of increasingly popular battery-powered devices that alternate
able Ni-MH battery, not quite a recent technology, is mainly between periods of activity and pauses in power-saving mode (also
referred to as sleep-mode, power-down, hibernation, low-power)
is not straightforward; unfortunately, inserting a multimeter in
series with the power supply and taking a current reading is not
enough. The basic calculation to be performed in order to obtain
the average value of the current drawn, and thus an estimate of
battery life, can be represented with the following pseudo-formula:

where IAVG represents the average current, ION the activity current,
ISBY the stand-by current, TON the activity time and TSBY the stand-by
time.

I ‘captured’ the trend of the active current with the oscillo-


scope (see Figure 7) by detecting the voltage drop at the ends
of a low-value precision resistor in series with the power supply,
obtaining, with acceptable approximation, the figure of 10 mA for
a time of 7.5 seconds, which represents the duration of a display
Figure 7: Pattern of the current drained by the circuit. cycle. The quiescent current, measured with a digital multimeter

lektor May & June 2023 85


Figure 8: Flowchart of the firmware.

voltage, temperature variations and other


factors — at an average current of 0.008 mA
could ideally power the circuit for approxi-
mately 40 /0,008 = 5.000 h (i.e., more than
200 days or at least six months)! Realisti-
cally, even a duration reduced to half would
be a good result. Convenient online appli-
cations are now also available for this type
of calculation. I provide a link to one that I
have found to be among the most effective
and practical [5].

The Firmware and Its


Functionality
In this project, the source code [9] is written
with the Arduino IDE 1.8.19 and requires,
for proper compilation, the installation of
the Arduino core MiniCore v2.1.3 and some
specific libraries. The core used allows a
more efficient and versatile management
of the ATmega328P microcontroller and
above all optimizes the memory usage of
the compiled code, which comes to occupy
31,264 of the 32,768 bytes of program
memory (Flash) and 1,501 of the 2,048 bytes
of dynamic memory (SRAM), almost at the
limit of this MCU’s possibilities.

It should be noted that this project is not


feasible, even by trial and error, with an
Arduino Uno board, since part of the latter’s
memory is used by the bootloader to allow
direct programming, while for the ‘barebone’
microcontroller we use an external USBasp
programmer. Speaking of memory, the
keyword PROGMEM appears several times in
the listing, referring to the byte arrays of the
instead, amounts to as little as 3 µA. Assuming we will be using bitmap and text character strings, which are read-only data. By
the parking disk four times a day, plus the refresh cycle, we get a declaring these arrays as PROGMEM, functions can access these
total uptime of 7.5 x 5 = 37.5 seconds and a rest time of (24 x 3600) data by reading them directly from Flash memory, without first
- 37.5 = 86,362.5 seconds over 24 hours. We therefore obtain: copying them into the much smaller SRAM, which then remains
available for ‘dynamic’ execution of the program. The DS3231M 1.0.6
library is used for communication with the integrated real-time
clock (RTC), while the GxEPD2 1.3.6 library, supported by the GFX_
Root 2.0.0 graphics library, has been chosen for the basic manage-
ment of the e-Paper display.

The latter must be overwritten with the one supplied with the
project, which has modified fonts. The GxEPD2 library is a massive
A 40 mAh battery — leaving aside for the sake of simplicity the piece of work and unfortunately lacks a structured documentation,
reduction in capacity due to self-discharge, a drop in nominal which is to be found instead in the code of the available examples,

86 May & June 2023 www.elektormagazine.com


which are very numerous, but at first glance daunting due to their In order to simplify the firmware and the circuit, avoiding the
apparent complexity, which is then discovered to be due to the addition of further buttons, the programming of the date and time
attempt to extend compatibility to as many display models as possi- is carried out at the same time as the sketch is loaded, by means of
ble. I have therefore attempted to do a summary job, extrapolating a special line of code inserted in the setup() routine.
only the functions and definitions necessary for the type of display
used in the project. These can be found in the file Waveshare_29_ DS3231M.adjust(DateTime(2022, 03, 02, 19, 10, 00));
BW_avr.h, while the file ParkBitmap128x128.h contains the array of
bytes, obtained by means of a special converter [6], representing the
bitmap image of the parking logo (capital P inscribed in a square
with rounded corners, size 128 x128 pixels, black/white). These files,
available for download, reside in the sketch folder, together with
the main source code file Disco_Orario_e-Paper.ino, in which there
are also links to the core and library sites, extensive comments on
the code, and other indications that I found useful. I advise readers Component List
interested in the details of the listing to examine it by opening it Resistors (0.25 W, 1%)
with the Arduino IDE (or their favorite editor). Instead, here I would R1, R10, R12 = 330 Ω
like to illustrate the operation of the program in a more descriptive R2, R4, R5, R6 = 10 k
manner, with the help of the flowchart in Figure 8. R3, R8 = 5.6 k
R7 = 3.3 k
Keeping in mind that the circuit is always connected to the battery, R9 = 100 Ω
the first time it is switched on (Power-Up), the initialization operations R11 = 1 kΩ
and the setup() function are executed, with the activation of an
Interrupt, and then the loop() is executed. Capacitors
C1, C3, C5 = 100 nF, 50 V polyester or multilayer ceramic capacitor
At the start of the loop, the ambient temperature is checked. If it C2 = 100 µF, 10 V electrolytic capacitor
is not within the expected range, an acoustic and luminous alarm C4 = 470 nF, 50 V polyester or multilayer ceramic capacitor
signal is emitted, then the microcontroller is placed in maximum
energy-saving mode (SLEEP_MODE_PWR_DOWN). Otherwise, Semiconductors
the loop() continues by initializing the display, showing the ‘P’ Q1 = IRLD024 Logic-level gate drive MOSFET
logo, battery status, current date and time, temperature and the Q2 = BC546B
language selected for the incoming message, showing what we D1 = SS34 Low Drop Schottky diode
can call info mode, after which the display is ‘hibernated’ (again D2 = Blue LED 3 mm, Hi-Bright
for energy saving), the MCU switched off and the loop() aborted. D3 = Red LED 3 mm, Hi-Bright
From this state, the microcontroller can be ‘woken up’ (Wake Up) U1 = ATmega328P-PU
by a hardware reset (with the SW1 button) or by an Interrupt, an U2 = DS3231M RTC, SO-8 Package
event generated in this case by the RTC’s daily alarm function or
by the SW2 button. If the resumption is caused by the reset or the Miscellaneous
alarm, the loop() restarts from the beginning and always ends in Y1 = 8 MHz Ceramic Resonator
info mode. On the other hand, if the microcontroller is reactivated BUZZER = Piezo-Electric Buzzer
via SW2, the loop() restarts, initializes the display, shows the logo SW1, SW2 = N.O. Push-button
and if the button was pressed and immediately released, shows the F1 = Re-triggerable fuse (polyfuse) 250 mA
arrival message and the current time, in what we will call parking X1 = Micro-USB Socket type B
mode. Keeping SW2 pressed, on the other hand, will display the JP1 = 6-pin ICSP PCB Connector, M
messages in the four languages in succession. Simply release the JP2 = 8-pin PCB Connector M/F
button when the desired one appears, and the setting will be stored DISPLAY = e-Paper Display 2.9 inches B/W, (see text)
in EEPROM until the next change. The current time will then appear, BAT1 = Ni-MH 3.6V Battery, 40 mAh (3 x V40H)
and the cycle will always end in parking mode. An example of the 28 pin DIP Socket
screenshots can be seen in Figure 3. We have seen how the current 8 pin DIP Socket
date and time are provided and maintained by the RTC DS3231M SMD – DIP8 for SO-8 Adaptor
integrated circuit, which must still be programmed after the first Prototyping Board
application of the supply voltage and in case the supply voltage fails.

lektor May & June 2023 87


The format to be used is of the type “YYYYY,MM,DD,hh,mm,ss”. Questions or Comments?
Once you have entered the correct data, you can load the sketch, Do you have technical questions or comments about this article? You
check the date and time, comment out the line (add the double slash are welcome to contact the author at [email protected]
at the beginning) and reload the sketch, this is to avoid the clock or the Elektor editorial team at [email protected].
reverting to its initial settings at every reset. To achieve sufficient
accuracy, simply measure the time it takes to upload the code, say
30 seconds, and then start the first upload 30 seconds in advance.
With a few tries, a synchronization per second can be achieved at
... no cost! The daily refresh time is also set from code, simply by About the Author
entering the desired time. Ever since childhood, Antonello Della Pia was
attracted to electricity and electronic devices.
Finally, a note on the method used to measure the battery voltage. It He holds an “Electrical Engineering Techni-
is often found on the Internet, with some variations, and Microchip cian” high-school diploma. Antonello has
itself documents it in its own note [7]. The ‘trick’ is to set, via the always cultivated and developed his passion
appropriate registers, the internal reference voltage (1.1 V) as the for analog and digital electronics. Currently, he plays around with
ADC’s input value and the voltage to be measured (VCC) as the refer- microcontrollers and programming, trying to improve his computer
ence. Any change in VCC will change the ADC reading, allowing the skills. Antonello likes to develop and propose projects that are as
voltage value to be calculated with enough accuracy. original as possible and — as he hopes — interesting as well.

Final Considerations
Although offering features of undoubted interest, which make it
particularly suitable for the project presented, e-Paper technology
also has certain limitations, the most obvious of which is the
low refresh rate. The model used here performs the complete
Related Products
refresh cycle in 2 seconds and the partial refresh in 0.3 seconds.
These values cannot therefore compete with other display types > Waveshare 2.9” 3-color E-Ink/E-Paper Display Module
in the visualization of rapidly changing images, graphics and text. (SKU 18776)
Finally, as I often say, beyond the actual usefulness of the proposed www.elektor.com/18776
object, I hope that you have found some interesting ideas to elabo-
> Ynvisible Segment E-Paper Display Kit (SKU 20143)
rate and reuse with the attitude of a Maker, and that this article www.elektor.com/20143
has triggered your desire and curiosity to experiment with e-Paper
displays!
230012-01

WEB LINKS
[1] Electronic Paper (Wikipedia): https://en.wikipedia.org/wiki/Electronic_paper
[2] ATmega328P Datasheet: https://www.elektormagazine.com/atmega328p-datasheet
[3] DS3231M Datasheet: https://datasheets.maximintegrated.com/en/ds/DS3231M.pdf
[4] Waveshare - 296x128, 2.9inch E-Ink display module: https://www.elektormagazine.com/waveshareeink
[5] Battery Life Calculator – Online Calculator: https://www.omnicalculator.com/other/battery-life
[6] BitmapToByteArrayConverter: https://www.briandorey.com/post/bitmap-byte-converter-for-e-ink-display
[7] Measure VCC/Battery Voltage Without Using I/O Pin on, Microchip: https://www.elektormagazine.com/vcc/battery
[8] Basic operating principle of the e-Paper display: https://www.elektormagazine.com/bwcapsules
[9] Source code: www.elektormagazine.com/230012-01

88 May & June 2023 www.elektormagazine.com


PROJECT

eCO₂
Telegram bot
Air-Quality Measurement with Telegram Notification

By Peter Neufeld (Germany)


Highly integrated sensor technology, a modern microcontroller and
Determining indoor air quality does some BASIC programming make it possible, with very little techni-
not always require highly accurate cal effort, to use this eCO2 monitor and its various display modes to
indicate poor air quality in four ways:
and expensive measuring devices.
A simple indicator plus limit-value > Local NeoPixel LED(s) as visual air quality indicator
monitoring can already be very > Web interface for local devices with a web browser
> Manual query via the Telegram messenger app
helpful if you simply want to know > Telegram alert message sent to a dedicated Telegram user
when it’s appropriate to ventilate an
intensively used room. Such a device The Hardware
The simple circuit in Figure 1 is based on a CCS811 eCO2 sensor and
becomes even more useful when its an ESP32 SoC module. The air quality is indicated by one or more
simple local display is complemented NeoPixel LEDs. A single push-button switch is connected to an input
with an alert output to a Telegram pin. The sensor and the SoC communicate via a two-wire I2C bus. The
NeoPixel display uses only one data line at GPIO27, no matter whether
account on your smartphone. a single LED dot or a matrix is addressed.

Figure 1: eCO2 Telegram bot with an M5Stack Atom matrix and CCS811, including internal circuitry (image source: AMS data sheet).

lektor May & June 2023 89


While almost any ESP32 module with exposed I2C pins is suitable for
this job, I recommend either an ATOM Matrix or an ATOM Lite, both
from M5Stack. The reason is that these handy devices combine an
ESP32-PICO-D4 with an antenna, and either a NeoPixel matrix or a
single NeoPixel dot, as well as a push button and some more compo- Figure 2: Easy soldering of the two modules on perfboard.
nents, all in a small and shapely protective case. That way, the sensor
and ESP32 module are almost all the hardware needed to build the
device on an ordinary perfboard. To do this, plug the CCS811 and
the ATOM into the appropriate female and male connectors, respec-
tively, and make the few necessary connections with circuit wire, as
shown in Figure 2. The bottom side of the through-plated perfboard
is insulated with adhesive tape. > Displaying this status via the built-in NeoPixel matrix or the color
of the single NeoPixel LED.
The circuit is powered via the ESP32 module from a USB power supply > A web interface displays the eCO2 value and the category via a
(5 V with a maximum of 500 mA), either via USB C, the HY2.0 Grove browser over the (W)LAN.
connector, or the lower socket connectors. > The status and eCO2 value can be queried manually via Telegram,
as our program includes a Telegram bot and fetches incoming
The CCS811 eCO2 Sensor user commands from the Telegram server.
The CCS811 sensor cannot measure the CO2 content directly! It calcu- > A Telegram warning message is automatically sent to the
lates the equivalent CO2 content (eCO2) by measuring the tVOC (total last Telegram chat_id when the air quality is in the red zone
volatile organic compounds), where the main source of these volatile (Figure 3).
organic compounds is the air exhaled by humans. > The baseline of air quality can be stored manually by pressing
the front button of the Atom module or by an incoming Telegram
This inexpensive type of sensor, called Metal Oxide Semiconductor command.
(MOS), seeks a relative baseline for “good air” by determining the best
air condition over an extended period of time and then assuming that
the sensor is in fresh, unpolluted air with 400 ppm of CO2 at that time.
But: The sensor does not store this value by itself.

In addition, the sensor’s sensitivity can change over time, and under
different environmental conditions such as temperature and humidity.
So, to provide reliable eCO2 readings, the sensor requires:

> a single burn-in time of more than 48 hours and


> a minimum run-in period of approx. 20 minutes after each cold
start.

The data sheet [1] contains more detailed information on the gas sensor.

The Software
The program was developed with Annex32, a BASIC interpreter for
ESP32 [2]. After installing the interpreter in the ESP32 module’s flash
RAM via an installation program and a serial USB interface, the inter-
preter and its development environment run entirely on the ESP32.
Only a Chrome or Firefox browser is needed to load, edit, test and
(automatically) run the BASIC script. The minimum required Annex32
version is V1.435, as this includes CCS811 and Telegram messenger
support. The online help [3] for Annex32 is a very useful introduction
to this BASIC interpreter. The main tasks of the BASIC code are:

> Initializing the CCS811 and obtaining the eCO2 value once per
second.
> Classifying the eCO2 status of the ambient air as GREEN,
YELLOW, or RED. Figure 3: Warning message: The air is really bad!

90 May & June 2023 www.elektormagazine.com


Program excerpt: web page output
'#################################################
MAKE_WEBPAGE:
'-------------
'create the autorefreshing html page with dynamic
'display values and matching colors
A$ = ""
A$ = A$ + "<H1>eCO2 " + LOCATION$
A$ = A$ + "</H1>"
A$ = A$ + "Time :" + textbox$(T$) + "<br>"
A$ = A$ + "eCO2: " + textbox$(STR_eCO2$) + "<br>"
A$ = A$ + |<span style="color:| + COND_COL$ + |">|
A$ = A$ + "<H1>Condition: "+ CONDITION$+ "</H1>"
A$ = A$ + "</span>"
cls
autorefresh 1000
html A$
return
'#################################################

The Telegram bot routine regularly queries the Telegram servers for Figure 4: Control via the Telegram bot.
incoming commands. It then responds to these commands, as shown
in Figure 4:

> /e returns the eCO2 value and the category [GREEN | YELLOW |
RED].
> /s saves the baseline value in /baseline.txt.
> /r restores the base value from /baseline.txt.
Related Products
> /i returns the local IP settings of the module.
> [Any other character] does the same as /e. > M5Stack AtomU ESP32 Development Kit (SKU 20184)
https://elektor.com/20184
Your Own Telegram Token
In order to use the Telegram features in the BASIC program, you must
> ESP32-PICO-Kit V4
Without headers: https://elektor.com/18423
first create your own Telegram bot by following the BotFather instruc- With headers: https://elektor.com/20323
tions at [4] in your Telegram app. This will give you your personal
Telegram token and a bot name. Important: You must include these > Dogan and Ahmet Ibrahim: The Official ESP32 Book
two pieces of information in the BASIC program to set the appropri- (PDF)
https://elektor.com/18330
ate variables.

The use of Annex32 BASIC, the current version of which you can always
find in the Annex RDS forum [5], certainly has at least the advantage
of being easy to read —even for inexperienced programmers — and
also to be adaptable to your own needs. For a better understanding of
the functions, the code [6] is nevertheless abundantly provided with
comments. This script must be pasted into Annex32’s web-based editor WEB LINKS
and saved to the ESP32 module as an auto-run file (/default.bas). [1] CCS811 data sheet: https://bit.ly/2qQKqKu
[2] AnnexToolKit 1.1 including release 1.48.22:
Translated to English by J. Starkmuth — 210566-01 https://bit.ly/3Gtf8RS
[3] Annex32 WIFI RDS Help Version 1.48.2:
https://bit.ly/3Gwhdg9
Questions or comments? [4] BotFather on Telegram: https://t.me/BotFather
Do you have technical questions or comments about this article? [5] Annex RDS forum: https://bit.ly/3VBTRK2
Then please contact the author by email at [email protected] [6] The Project on Elektor Labs:
or the Elektor editorial team at [email protected]. https://www.elektormagazine.com/labs/eco2-telegram

lektor May & June 2023 91


With Ton Giesberts
(Elektor Labs staffer)

Behind the Scenes of


DIY High-End Audio
Elektor’s Ton Giesberts Interviewed on the Fine Art of Analog Design

By Jan Buiting (Elektor) assembly less and less attractive. Electron- a multimeter will only get you so far. I am
ics has shifted to software development at a really content to have been able to use the
Meet the man behind the rapid pace. Microprocessor boards have been AP analyzer for many years. What matters,
Elektor Fortissimo-100 popular for a long time, but even building though, is how and what you measure. In
them is less attractive than buying ready- other words, know what you are measur-
power amplifier and many made modules, especially in recent years. ing! Without good experience and the right
other top-notch audio The software then determines the applica- conclusions, using that AP can accomplish
projects: Elektor Labs staffer tion, although obviously with some external little. You don’t learn that in a day.
(analog) components such as sensors etc.
Ton Giesberts. Jan: What are your main sources of
Jan: How is your work organized these inspiration for new designs, compo-
days, and what lab instruments and tools nents, and techniques?
Jan: Tell us briefly about your technical do you usually work with? Do you use a Ton: For novel designs, the oldies are very
background, your experience, and how simulation program for your designs? good sources of inspiration. You can find
and when you joined Elektor. Ton: Now that I work for a different depart- plenty of them on the internet. The devel-
Ton: After my studies, I was approached ment within Elektor [Books, Kits and Pillar opment of bipolar power transistors, for
almost instantly by an employment agency Products - Ed.], there are other tasks I have to example, has not been idle. So, what’s wrong
“to come over for a chat.” They offered me spend time on. These tasks frequently aren’t with picking up an old design again, tweak-
several jobs, including one at a school. That about developing new circuits or processing ing it here and there, and using up-to-date
did not appeal to me, but I did like a job at a raw material supplied to us directly. They are components to give it a new lease on life?
publisher of a technical monthly, located in about checking and obtaining components,
Beek. As a subscriber, I knew this could only supporting colleagues, and much more. Like Jan: Your work seems focused primarily
be Elektuur. I had already built several circuits most electronic engineers, I use a multime- on analog electronics possibly combined
from the magazine, and, after a job interview, ter and an oscilloscope most frequently. Of with digital stuff, but limited to “side
I first worked in the lab for a few months course, a couple of lab power supplies and a assistance.” How do you weigh the
through the temp agency before I was hired function generator are indispensable, not relative significance of analog and
permanently. Elektuur was just looking for forgetting an audio analyzer. In addition to digital within your designs?
someone who wanted to do analog engineer- a plain soldering iron, I use a reflow oven and Ton: I continue to like the bog-standard
ing, so that suited me just fine. hot air to solder SMDs. For prototype photo- logic series, also as drivers or in combina-
graphy, I have a small setup in the attic to take tion with analog circuits. But, I have come
Jan: Outside your profession, what are properly exposed photos. I’ve preferred to to appreciate that microcontrollers make
your favorite pastimes or hobbies? use Micro-Cap for simulation ever since the your design cheaper and smaller as far as
Ton: Electronics was and still is my pastime. DOS days. the hardware goes, while software makes
I also design some things outside of work. I a project more versatile. Programming has
like to read and watch documentaries or a Jan: We hear you own an Audio Preci- never been attractive to me; analog technol-
good movie. sion Analyzer. How do you like working ogy seems more tangible, but that may be
with an instrument that many audio an illusion. If I do use a microcontroller, it’s
Jan: Over the years, how have you seen enthusiasts can only dream of ? one from the AVR family, and then program-
the craft of “electronics” and its practice Ton: Without a good analyzer, designing ming with BASCOM is still doable even for
change? high-end audio circuits is almost impossi- me. Occasionally, it’s even a fun and welcome
Ton: Over time, the use of wired components ble. Of course, and thankfully, measurement change, sort of. Nowadays, it can be even
has decreased. I suppose the emergence and data aren’t everything, but they’re great to easier with tools such as CircuitPython and
standard use of mostly SMD parts made home reveal imperfections. An oscilloscope and a Raspberry Pi Pico.

92 May & June 2023 www.elektormagazine.com


Jan: You contributed to the long list of
high-end audio amplifiers that made
Elektor famous. Which ones were the
most renowned, and which one do you
like best?
Ton: One of the first ones I worked on was
the LFA-150 [1] (though not my design) and
its derivative, the LFA-50-OA [2], and then transistors such as the MAT02 and MAT03 from a switching power supply are higher
the Medium-Power AF Amplifier [3], then are no longer produced, and the small and there is some RF ripple. But, this is
moving on in time, the Audio Drive, an ampli- versions in SMD fell short in performance. beyond hearing range and duly suppressed
fier with modest power. The Medium-power So, I turned to the good old BC546B and by the amplifier. To still meet the needs of
HEXFET Amplifier [4] with its successor, the BC556B, which do allow a very fast ampli- those interested in the amplifier, I consid-
IGBT Power-Amp [5] (using the same PCB) fier to be made running at a higher supply ered making an analog regulator. But, it had
with special IGBTs developed for audio, as voltage. Of course, people now prefer Miller to remain modest as well as easy to repro-
well as power amplifiers for active subwoofers compensation, but I wanted to change the duce at home. Unfortunately, today’s design
and various active speaker systems. Later still, original concept as little as possible. I only work is quite a challenge due to poor, late, or
the Crescendo Millennium Edition amplifier used ThermalTrack power transistors for the even “zero” availability of components. Soon,
[6], and the ClariTy 2x300W Class-T ampli- output stage, which allowed me to attempt you’re forced to compromise and that’s why
fier [7]. More recently, a 200W Class-D Audio a symmetrical bootstrap, first in a proof-of- the design uses old timers such as TIP35C
Power Amplifier [8]. The Q-Watt Audio Power concept. This worked surprisingly well, bring- and TIP36C — still made by several manufac-
Amplifier [9], and, of course, the Fortis- ing a larger output swing within reach. For turers and available off the shelf at several
simo-100 [10] and many more large and small better selection of the BC trannies in the kit, distributors.
amplifiers. The Medium-Power AF Ampli- they were used in as many places as possible,
fier was tested and favorably reviewed by a including the current sources of the differen- Jan: How and where do you see yourself
German audio magazine at the time, and tial amplifiers. To keep the power in check, working on electronics one year from
that’s perhaps why I prefer it, but I don’t really collector resistors are needed which in turn now?
want to pick a favorite. force the use of a stabilized supply voltage, Ton: I expect to be doing more or less the
among others. same thing as and now, but the world is in
Jan: Your Fortissimo-100 amplifier turmoil and predicting now what the future
was developed modestly through the Jan: We read on Elektor Labs that a holds is total guesswork.
Elektor Labs website, Jumpstarted great, linear power supply is in the making 220603-01
and sold even better after its “official” especially for the Fortissimo-100. What
publication in Elektor Magazine. Tell is the reason for this? That SMPS800RE
me about the design and publication switching power supply is just fine, isn’t
process. Where were the stumbling it?
blocks? Ton: For some, the use of a switching supply
Related Products
Ton: I was asked to design another new is profanity and absolutely “no go.” But,
power amplifier. I was thinking mainly of there are good versions nowadays, specifi- > Elektor Fortissimo-100 Power
the Medium-Power amp and followed that cally designed for audio. One of these is the Amplifier Kit (SKU 20273)
concept far, apart from the output stage. SMPS800RE. It also makes the whole power https://elektor.com/20273
The problem was (and is) that large dual supply part nicely compact. Sure, noise levels

WEB LINKS
[1] “LFA-150: A Fast Power Amplifier,” Elektor, 11/1988: https://elektormagazine.com/magazine/elektor-198811/47463
[2] “LFA-50-OA,” Elektuur, 10/1991: https://elektormagazine.nl/magazine/elektor-199110/37655
[3] “Medium-Power AF Amplifier,” Elektor, 10/1990: https://elektormagazine.com/magazine/elektor-199010/32233
[4] “Medium-Power HEXFET Amplifier,” Elektor, 12/1993: https://elektormagazine.com/magazine/elektor-199312/32952
[5] “IGBT power-amp,” Elektuur, 6/1995: https://elektormagazine.nl/magazine/elektor-199506/38437
[6] “Crescendo Millennium Edition,” Elektor, 4/2001: https://elektormagazine.com/magazine/elektor-200104/16985
[7] “ClariTy 2x300W,” Elektor, 6/2004: https://elektormagazine.com/magazine/elektor-200406/17714
[8] “200W Class-D Audio Power Amplifier,” Elektor Labs, August 10, 2016:
https://elektormagazine.com/labs/200w-class-d-audio-power-amplifier-150511
[9] “Q-Watt Audio Power Amplifier,” Elektor, 9/2013: https://elektormagazine.com/magazine/elektor-201309/23330
[10] “Fortissimo-100 High-End Amplifier,” Elektor, 11/2022: https://elektormagazine.com/magazine/elektor-280/61057

lektor May & June 2023 93


HOME LAB

HomeLab Tours
Work in Progress...
Figure 1: This ping-pong ball floats in or on a water jet.

By Ilse Joostens (Belgium) and Eric Bogers (Elektor)


The annoying thing was that every time the ping-pong
Ilse Joostens is no stranger to our loyal balls were hit, all weapons had to be unloaded (of
Elektor readers — not only as the author course) and someone had to place new ping-pong balls
in the air stream. That’s where the idea was born to
of the column “From Life’s Experience,” feed ping-pong balls through a tube at the push of a
but also as a master of vintage Nixie and button, but no one had any idea how that would work
VFD tubes. The Corona pandemic with its mechanically because the idea is, of course, that the
balls should come out one by one. I then sketched a
lockdowns and other sufferings has not left draft on a piece of paper, but ultimately I did nothing
her untouched either, as the story below with the idea.”
describes.
Meanwhile, Ilse had established herself as an independent
electronics designer, specializing in vintage electronics
The origins of the device that features in this episode of components such as Electrontubes, Nixies and vacuum
"HomeLab Tours..." goes back many years. We let Ilse do fluorescent displays (VFDs). There was a very practical
the talking: reason for this — many things were already designed,
and even then the competition from China* was already
“About 20 years ago, I was living as a single in Dender- strong. The choice for a niche market was then obvious.
monde and looking for joining an association to
engage in activities. By coincidence, there was a shoot- “Thanks to COVID-19, I became quite bored; my
ing society near my apartment; I became a member.” shooting society was also closed for the time being.
In order to practice a bit at home, I decided to buy a few
“Regularly, what was called ‘fun shooting,’ involved air-pressure and airsoft guns. It was also a welcome
shooting ping-pong balls floating on compressed air. pastime during the lockdowns.”

* During the COVID-19 crisis, the Chinese acquired virtually all remaining stocks of Russian Nixie tubes.
That is one of the reasons why Elektor’s six-digit Nixie clock is no longer available.

94 May & June 2023 www.elektormagazine.com


Figure 2: The ping-pong


ball container.

Due to a lack of Nixie tubes and Plexiglas (also a result up to 11 ping-pong balls, but a supply through a funnel
of COVID-19), Ilse wanted to change direction in terms of in the container is possible in addition to a longer tube.
electronics, but it had to be something special. And that’s A rotating plastic cam causes the ping-pong balls to
where the idea with the ping-pong balls came around the roll out from the container one by one. With each
corner again, with the idea of shooting them at home back-and-forth movement of the cam, one ping-pong
with air guns. Something similar can be seen at fairs: at ball is released while the remaining balls are automat-
Figure 3: This
shooting stalls where you can shoot at ping-pong balls ically blocked. The cam is held in a basic position by a mechanism ensures that
floating on water jets (Figure 1). tension spring with the cam being moved by a minia- the balls enter the air
ture servo using a string (see Figure 3).” stream one by one.
“Currently, I have only built an operating mechanical

prototype. As for the airflow, I used a 9BMC24P2G001
blower from Sanyo Denki. It is not a cheap one, unfor-
tunately, but it delivers a solid airflow and can be
easily controlled in speed by a PWM signal. This is
convenient because by modulating the airflow, we
can cause the ping-pong ball to move up and down
irregularly to make it a bit more challenging target.
Using a removable cabinet that also serves as a buffer
bin and a powder funnel from a chemical wholesaler,
a powerful constant airflow is generated. Any debris
(bits of projectiles) cannot enter the blower in this way,
and you can open the bottom of the cabinet to clean it.”

“The ping-pong balls are stored in a slanting container


made of a Plexiglas tube (diameter 50 mm, inner
diameter 44 mm, Figure 2). Gravity causes them to roll
in the direction of the airflow; there are no restrictions
on the size of the container. The prototype can contain

lektor May & June 2023 95


“Such a mechanism could also be the basis of a Basically, you can use any kind of shooting equipment
Nespresso capsule machine. Something with several to aim at the ping-pong ball — even a bow and arrow.
tubes next to each other. You then select which It is important, however, to use the cheapest possible
capsules you want and they drop into a tray at the ping-pong balls as they will not have an extremely long
bottom where you can take them out. I have been life; preferably, they should also have a contrasting colour.
thinking about this idea for some time, but I haven’t
done anything specific yet.” “Immediately after building the mechanical part, the
issues with a shortage of parts started. The blower is
The ball that rolls out of the container [1] then enters the currently no longer available (at least not in the short
airflow above the opening of the powder funnel and is term) so an alternative should already be found for
then catapulted into the vertical Plexiglas tube. Two strips that. As for the rest of the electronics, it is not that
of felt are adhered in the tube to prevent the ball from critical as basically only two miniature servos need
‘rattling’ in the tube. This can happen when the ball keeps to be controlled and another PWM signal should be
quickly moving in the tube while the air flows between generated for the blower. At the moment, the project
the ball and the wall of the tube. is on hold, partly due to the war in Ukraine. I find it
less appropriate to release a shooting game with all
“If the vertical tube were open at the top, the ping-pong the misery on TV and in the media.”
balls would be launched upwards without getting
caught in the airflow. Maybe that’s an idea for a table “Currently, I am not sure how to proceed and whether
tennis ping pong ball dispenser? To prevent the this project has any potential. At least a remote control
launching of the ping-pong balls, there is a slide at would be required. With each press of the button,
the top of the tube that is also controlled by a minia- you would get a new ping-pong ball, possibly with
ture servo (Figure 4). The ping-pong balls now shoot an indicator of the remaining stock of balls. For the
up to the top of the tube until the slide. When the latter, you could add IR reflection sensors on the
slide then slowly opens, the ball moves up a little and container tube. Other additional options could be a
then dances up and down for a while until it remains choice between floating or ‘launching’ the ball [2] or
stable on the airflow [2]. From then on, the blower can a choice of whether or not to modulate the blower.”
be modulated with a PWM signal to make the ball’s
behaviour a bit more unpredictable. In practice, the “What I would like to know is whether there would be
ball floats about 15 to 20 cm above the end of the slide. any interest in this, and any suggestions and requests
I also tried experiments without a vertical tube, but for additional (or different) functionality. In principle,
then the ball was less stable and regularly fell out of it should be possible to offer a kit with mechanical
the airflow.” parts, as everything can be easily cut by laser and glued
together. Only the electronics are and will remain an
issue at least until mid-2023.”

210591-01
Figure 4: This slide
prevents the balls from
being launched.

Questions or Comments?
Do you have technical questions or comments regar-
ding this article? Send an email to the editors of Elektor
at [email protected].

WEB LINKS
[1] Video 1 – Ping-Pong Ball Launcher: https://youtu.be/gTmytGPtHfQ
[2] Video 2 – Floating Ping-Pong Ball: https://youtu.be/iH6_5-zcddw

96 May & June 2023 www.elektormagazine.com


lektor May & June 2023 97
ELEKTOR BOOKS

RFID
Tag Reading
and RFID
Door Lock
Sample Projects from the Elektor
Arduino Experimenting Bundle

By Dogan Ibrahim (United Kingdom)

RFID stands for Radio-Frequency Identification RFID technology utilizes electromagnetic fields to transfer data over
— a wireless technology covering devices for short distances. RFID systems are used mainly in security applica-
tions. For example, they can be used to open a door exclusively by a
security, access, and goods tracking purposes. person having the correct RFID tag.
In essence, an RFID system includes an RFID
reader and one or more tags. Both hardware The RFID reader supplied with the Elektor Bundle mentioned above
(comprising a book and a kit of parts) is known as the ‘RC522 Module’
devices are contained in a versatile kit of (Figure 1). It has the following specifications:
parts aimed at Arduino experimenting and
backed by a specially written guide. In this > Operating frequency: 13.56 MHz
> Operating voltage: +3.3 V
article, as an example of embedded project > Operation with both SPI bus and I2C bus
development from the ground up, Elektor
guide author Dogan Ibrahim explores RFID
technology and gets help from “our mutual
friend,” the Arduino UNO.

Editor’s Note. This article is an excerpt from the 238-page Elektor


Guide: Arduino Uno Experimenting Kit - Programming & Projects.
The Guide is part of the Elektor Arduino Experimenting Bundle. The
excerpt from the Guide was formatted and lightly edited to match
Elektor Magazine’s conventions and page layout. Being an extract from
a larger publication, this article may refer to discussions elsewhere
in the Guide. The Author and Editor have done their best to preclude
such instances and are happy to help with queries. Contact details Figure 1: RFID reader and tag.
are in the Questions or Comments? box.

98 May & June 2023 www.elektormagazine.com


The RFID reader comes with pin headers which must be soldered to > Download the rfid-master.zip file to a folder. You can find it in
the sockets at the edge of the reader before it can be used. the support archive file for the book posted on the Elektor Store
website [1].
Project 1: Finding the Tag ID > Start the IDE.
In this project, you will learn to display the Tag ID of the supplied tag > Click Sketch → Include Library → Add .ZIP Library.
in Arduino Serial Monitor. > Browse to the saved .zip file and click Open
> You can now start to use the library.
Block Diagram: Figure 2 shows the block diagram of the project,
which is pictorial rather than abstract/functional. The RFID reader library offers many functions that can be seen
by unzipping the library file. The most important library functions
Circuit Diagram: The connections between the UNO development include:
board ports and the RFID reader module are as follows:
mfrc522.PCD_Init() Initialize the RFID reader
RFID Reader Pin Development Board Port mfrc522.PICC_IsNewCardPresent()) Look for an RFID reader
SDA 10 module
SCK 13 mfrc522.PICC_ReadCardSerial()) Select the RFID reader
MOSI 11 to use
MISO 12 mfrc522.uid.uidByte[] Return the Tag ID in an
array
IRQ not used
mfrc522.PICC_HaltA() Stop reading (Halt PICC)
GND GND
RST 9 The program DumpInfo from the Arduino IDE can be used to deter-
3.3 V 3.3 V mine your card’s Tag ID of your card. The steps are:

Figure 3 shows the circuit diagram of the project. Be careful not to > Start the IDE.
connect the supply voltage pin to +5 V. > Click File → Examples → MFRC522 → DumpInfo.
> Compile and upload the program to the development board.
Program Listing: Before using the RFID reader, you have to add the > Start Serial Monitor.
RFID library to your IDE. The name of the library is MFRC522, and the > Place the white tag on top of the reader and keep it there until the
steps to add it are as follows: data display stops in Serial Monitor.

Figure 2: Tag reader project block diagram. Figure 3: Tag reader project circuit diagram.

lektor May & June 2023 99


The Tag ID is also displayed under the heading Card UID in Figure 4.
In this project, the Tag ID is: 23 F0 58 A7.

Project 2: RFID Door Lock Access Control with


Relay
In this project, the RFID reader and the supplied relay (also contained
in the kit – Ed.) are both connected to the development board. It
is assumed that a secure door entry is operated with a relay under
protection of an RFID system. The door can be opened by holding an
authorized tag card near the RFID reader. The relay is activated for
15 seconds, then deactivates, so the door is closed.

Block Diagram: Figure 5 shows the project’s block diagram. Again,


images of the real boards are used rather than a theoretical or abstract
Figure 4: Tag memory data dump. representation with functional blocks.

Circuit Diagram: The circuit diagram is shown in Figure 6. As opposed


to other ‘switching’ projects in the book (not discussed here), a relay
Now, you should see data displayed similar to that shown in Figure 4. is added to Port 2.
This is the card’s 1 KB of memory and its Tag ID. The 1 KB memory is
organized into 16 sectors (0 through 15), where each sector is further Program Listing: Listing 1 shows the program developed for the
divided into four blocks (0, 1, 2, 3). Each block can store 16 bytes of RFID-controlled door lock, named RFIDLock. At the beginning of the
data (0 through 15). Therefore: program, the SPI and MFRC522 libraries are included. The Valid Card
ID is stored in the ValidCard string, and RELAY is assigned to Port 2.
16 sectors × 4 blocks × 16 bytes = Inside the setup() function, RELAY is configured as the output and is
1,024 bytes of data on card (i.e., 1 KB) deactivated. The SPI bus and the MFRC522 are also initialized.

The third block of each sector (i.e., the top block) is called the Sector
Trailer, and it contains the Access Bits. These control the read/write
access to the remaining blocks in the sector. Therefore, only the bottom
three blocks (i.e., blocks 0, 1, and 2) of each sector are available for
user data storage. This means that you have 48 bytes (3 × 16 bytes)
per 64-byte sector for your use.

Block 0 of sector 0 is known as the Manufacturer Block/Manufac-


turer Data, and it includes the manufacturer data and the tag’s ID.

Figure 5: Access control project block diagram. Figure 6: Access control project circuit diagram.

100 May & June 2023 www.elektormagazine.com


Listing 1. RFIDLock Program Developed for the Project.
//----------------------------------------------------------------------
// RFID LOCK SYSTEM
// ================
//
// In this program, the RFID card reader is used with a relay. The relay
// is only activated if an authorized tag is placed near the reader. The
// relay stays ON for 15 seconds and then turns OFF. The Tag ID of the
// authorized valid card in this example is: 23 F0 58 A7
//
// Author: Dogan Ibrahim
// File : RFIDLock
// Date : May, 2022
//----------------------------------------------------------------------
#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance
String ValidCard = “23F058A7”; // Valid Tag ID
String TagID = “”;
int RELAY = 2; // RELAY at port 2
byte i;

void setup()
{
pinMode(RELAY, OUTPUT); // RELAY is output
digitalWrite(RELAY, LOW); // Deactivate RELAY
SPI.begin(); // Initiate SPI bus
mfrc522.PCD_Init(); // Initiate MFRC522
}
void loop()
{
if (!mfrc522.PICC_IsNewCardPresent()) // Look for card
{
return;
}

if (!mfrc522.PICC_ReadCardSerial()) // Select the card


{
return;
}
TagID = “”;

for (i = 0; i < 4; i++) // Read 4 byte Tag ID


{
TagID.concat(String(mfrc522.uid.uidByte[i], HEX));
}

TagID.toUpperCase(); // Convert to upper case


mfrc522.PICC_HaltA(); // Stop reading
if(TagID == ValidCard) // Valid card?
{
digitalWrite(RELAY, HIGH); // RELAY ON
delay(15000); // Wait 15 seconds
digitalWrite(RELAY, LOW); // RELAY OFF
}
else
digitalWrite(RELAY, LOW); // RELAY OFF
}

lektor May & June 2023 101


The rest of the program runs inside the main program loop. Here, the
program waits until a card is placed near the reader, at which point
it is selected and a for loop is formed to read the 4-byte Tag ID into
variable TagID. Afterwards, TagID is compared with the authorized
Tag ID in ValidCard. If there is a match, the user is authorized, and
the relay is activated for 15 seconds. If the card is not valid, the relay
remains deactivated. This process is repeated forever.

Figure 7, finally, shows the project built on the breadboard.


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

Figure 7: Access control project built on a breadboard.

Related Products
> Arduino Uno Experimenting Bundle (SKU 20340)
Consists of:
• Elektor Guide: Arduino Uno Experimenting Kit -
Programming & Projects (238 pages)
• Makerfabs kit of parts including a genuine Arduino Uno R3.

www.elektor.com/arduino-uno-experimenting-bundle

WEB LINK
[1] Software Archive for Bundle: https://elektor.com/arduino-uno-experimenting-bundle

102 May & June 2023 www.elektormagazine.com


PROJECT

Oscilloscope
Current Probe for RF
RF Current Measurements Made Easy

By Roberto Visentin (Italy)

Do you need to
measure the antenna
current of your HF
transmitter? Or, like I
do, the primary current
of your Tesla coil?
These projects require
some preliminary
Figure 1: A closeup photo of my RF current probe.
considerations. Here
are some design
guidelines and a real- In many cases, current measurements to high frequencies, which are really straight-
without a DC component are useful. The most forward to build. The formulas presented are
world example. common is the case of CTs (current transform- valid also for AC mains units.
ers) for AC mains. This article is about the
design of current transformers for medium Probe Principle
The probe in Figure 1 is designed to measure
up to 50 A peak in a frequency range from
7 kHz to tens of MHz. The schematic in
Figure 2 is quite simple: the wire whose current
Ix
must be measured is passed through the toroid,
FT 82-43 which is an ordinary Amidon FT 82-43 core
that performs well up to at least 50 MHz.
Probe
5x 1Ω, 1/4W The secondary winding consists of ten turns of
wire evenly distributed over the core. If avail-
able, use a medium-gauge stranded wire, but
this is not mandatory. Due to the ratio of 1:10
turns, the maximum current in the second-
ary is 5 Ap.

Secondary is 10 turns
The secondary side is loaded with 0.2 Ω, which
evenly distributed was realized by a parallel connection of five
20385-007
1 Ω resistors. At a peak current of 5 Ap, the
peak voltage across these resistors is 1 Vp,
Figure 2: My RF current probe’s simple circuit. which is very convenient for measurements

lektor May & June 2023 103


with an oscilloscope. For a sinusoidal current, the 50 Ω load with the 0.2 Ω incorporated in Finally, RL should be greater than the second-
the average power dissipation at the resistors the probe (total resistance becomes 0.1992 Ω, ary wire resistance.
is R·I2 = R·Ip2 / 2 = 2.5 W or 0.5 W per resistor. giving a scaling factor of 50.2 A/V).
A continuous sinusoidal current of 50 Ap can In my case, I chose 0.2 Ω so that I could get
be measured only with 0.5 W or larger resis- What must be avoided is attaching the scope 1 V at 5 A (50 A on the primary), which adds
tors. But, if the waveforms are pulsed or very probe directly to resistors using the clips 2 mΩ to the circuit under test.
short measurements are made, ¼ W resis- and skipping the BNC connector, because
tors will do. That was my choice because I when measuring high RF currents, even the The number of secondary turns, n, determines
wanted to keep the design compact for better minimum unshielded loop in the probes will the current ratio. In case of a high-frequency
RF performance. OK, I also have to admit that add artifacts to the measurements. CT, this number must be kept low to avoid
these were the resistors I had on hand… self-resonance caused by stray capacitance
Calculations together with high inductance. In the case of
Usage The design of the current transformer is not mains CTs, the frequency is quite low (50 or
Figure 3 shows typical usage with a scope complicated, but some electromagnetic formu- 60 Hz), and therefore n = 1000 is a common
probe, using a BNC adapter for scopes. The las are necessary. First, about the load resis- value. Powers of 10 are common, so that the
device can also be used with a direct coaxial tor RL, which should be as small as practi- current conversion ratio is simple, but other
cable connection to the scope input, because cally possible in order to minimize the power values are possible.
1 Vp is ideal for scope 1× operation: In this loss introduced, because the circuit under
case, using a short cable is recommended measurement will “see” at least R·n2, where The highest usable frequency for a toroidal
to avoid reflections in the band of interest, 1:n is the turns ratio (1:10) and R is the sum of ferrite CT depends on the:
because the coax will be mismatched on both RL (0.2 Ω) and of the secondary wire resis-
sides. Even better, the coaxial cable can be tance (some mΩ). As already said, it is very > performance of the ferrite material;
terminated at its characteristic impedance on important that the secondary side is evenly > self-resonance of secondary winding;
the scope side: Many modern scopes offer the wound, as otherwise the circuit under test will > resistor inductance (resistor itself and
ability to set the input impedance to 50 Ω, so present some stray inductance in series. On connections).
this is particularly easy. In this specific case, the other extreme, if we choose too low a value
one has to remember that the measurement for RL, we’ll also have a very small voltage A design such as mine can easily work for
will be slightly off-scaled, due to the parallel of to measure, causing noise on the traces. up to several tens of MHz if a suitable ferrite,
such as material 43 from Amidon/Fair-Rite,
is used. High permeability cores used for EMI
suppression can be used as well, but only up
to much lower frequencies. Low permeabil-
ity cores used for power chokes and high-Q
inductors are not recommended, because their
inductance per turn is too low, which affects
the following point.

The choice of ferrite core also has an impact on


the lowest usable frequency, for two reasons:

> In order to get good measurements,


we’ll want the reactance of the second-
ary to be much greater than R, because
it also acts as a load. Since reactance
is X = 2π·f·L, this affects the lower
frequency end. In practice, we’ll want
X > 10·RL at the lower end.
> We must avoid saturation of the core,
which happens at high current and low
frequency. Saturation of ferrites happens
for field B = 0.25…0.3 T, but in order to
avoid nonlinear phenomena, we must
stay below 0.2 T at the maximum current
Figure 3: RF current probe in practical use. and minimum frequency.

104 May & June 2023 www.elektormagazine.com


The design can be improved by adding an
electrostatic shield that avoids this capaci-
GND
tive coupling: In practice, the primary wire
is passed inside a small piece of metal tube
(typically copper or brass) connected to the
output GND of the secondary, as shown in
Figure 4. This doesn’t alter the magnetic
linkage, but acts as an electric field blocker.

Conclusion
This example of an RF current transformer
together with the most important design crite-
ria proves that this matter is less complex than
it initially seems. I hope that the consider-
ations and formulas presented here are useful
in simplifying the handling of toroidal cores,
as well as serving as a basis for your own
developments.
Figure 4: Probe improved with electrostatic shield. 200385-01

About the Author


Roberto Visentin is a recently-retired
For both reasons above, low usable frequen- and replacing I with the absolute value of the electronic engineer who worked on
cies with a small number of turns and a high AC magnetizing current abs(I) = V / (2π·f·L). If electronics and control systems for marine
current tend to require large cores. The key V and n are fixed in previous design phases, applications and underwater robotics.
core parameters are AL , the inductance per the only way of reaching a lower f is adopting Still working as a freelance consultant, he
turn, generally expressed in nH/n2 for RF a larger S, namely a larger toroid again. enjoys finding more time to develop hobby
cores, and the core cross-section S, which projects in his home electronic laboratory.
can be easily computed from core dimen- In my case, Vp = 1 V, n = 10, S = 24.6 mm2 (pay
sions. In case of the Amidon FT 82-43 core, attention to use correct units), so we have
AL = 470 nH/n 2 and the cross-section is B < 0.2 T for f > 3.2 kHz, which is fine again, Questions or comments?
24.6 mm2 (easy to compute from outer diame- at least for my application. It may be confusing Do you have questions or comments
ter, inner diameter and height). that current doesn’t appear in the calculation: about this article? Contact Elektor at
actually, it is hidden behind V, because we [email protected].
The inductance of 10 turns is therefore know that 1 V corresponds to 50 A.
470 nH × 102 = 47 µH (remember, induc-
tance depends on n 2). If we accept that Improvements
X = 10·R ≈ 10·R L = 2 Ω, by reversing the Capacitive coupling between primary and
reactance formula we get f > 6.8 kHz as the secondary windings can disturb measure-
lower cutoff frequency. This may be acceptable ments at the highest useful frequencies, or
or not, depending on the application, and a even at moderate frequencies if the primary
larger core, having a greater AL, will have conductor is subject to a high RF voltage.
a lower cutoff. In my case, for measuring a
musical Tesla coil, I was interested in frequen-
cies greater than 500 kHz, so this core was fine.

Regarding saturation, we have the fact


Related Products
that in the sinusoidal regime, the magni-
tude of field B (magnetic flux density) is > OWON SDS1102 2-channel oscilloscope (100 MHz) (SKU 18782)
abs(B) = Vp / (n·2π·f·S), where Vp is the peak https://elektor.com/18782
voltage across the winding. This expression
can be derived by equaling the two expres-
> OWON XSA810 Spectrum Analyzer (1 GHz) (SKU 19714)
https://elektor.com/19714
sions of magnetic-linked flux Φc = L·I = n·B·S

lektor May & June 2023 105


REVIEW

• Elek
r lab to
to

r la
Ele

b
TESTED

ab
Ele to

rl
k r la to
b • Ele k

Not for the Faint-Hearted:

Robot Arm Kit


With Raspberry Pi Pico and MicroPython

By Clemens Valens (Elektor) What Is It?


The 6 DOF Robot Arm with Raspberry Pi Pico [1] is a robot arm
A robot arm that can move in controlled by a Raspberry Pi Pico microcontroller board. DOF is
many directions and pick up short for Degree(s) of Freedom, which, in the case of a robot arm,
relates to an articulation. The arm reviewed here has six of them,
objects thanks to six articulations allowing it to move in six different places independently of the
is a fun toy to play with, and even others. Each DOF translates to a servo.
more so when it is easy to control
The robot arm is controlled by a Raspberry Pi Pico board mounted
with MicroPython running on a on a small extension board (Figure 1) that provides the connections
Raspberry Pi Pico. With this kit to the servos, the power supply, a buzzer, and a push button. The
you can build a powerfull all-metal Pico, or rather the RP2040 MCU on it, is intended to be programmed
in MicroPython, but this is, of course, not an obligation. However,
arm yourself. the driver and examples are written in MicroPython.

Everything Is Included
The robot arm comes as a self-contained kit of parts (Figure 2).
Besides a computer to do the programming on and a micro-USB
cable, nothing else is required. A 5 VDC, 6 A power supply is included.

Figure 1: A Raspberry Pi Pico board controls the six servos of the robot arm. Figure 2: The 6 DOF robot arm comes as a complete kit of parts.

106 May & June 2023 www.elektormagazine.com


A power cord is included too, but with a US-style plug, so, depend-
ing on where you live, you may need to replace it or add an adapter
(as I did). There is even a little screwdriver, but I prefer to use my
own tools.

There are quite a few parts and even more nuts and bolts, but not all
are used. Except for the acrylic baseplate and the steel arm bone, all
the parts are made from aluminum. When it’s put together properly,
you don’t end up with a wiggly plastic toy but a with strong, solid
metal arm. Even though everything is made of aluminum, the
assembled arm weighs 1.3 kg (without the power supply). Figure 3: The arm can hold a tool, but I wouldn’t trust it with one.

Educational Tool
The 6-DOF robot arm is mainly an educational tool to teach
programming in MicroPython. It is a fun object that can move in
many ways, and it can pick up small items like its own power supply
(approx. 6 cm × 4 cm × 8.5 cm). As a demo video [2] shows, you can,
for instance, use it to play the Towers of Hanoi game. The robot
is not suited for industrial applications or high-precision tasks. It
does have a grip, but I wouldn’t trust it with a tool in it (Figure 3).

Things You Might Want to Know First


Assembling the arm is not for quitters. The manual [3] (not
included, for you to find without any hints on where to look) is in
Chinese only, and, on top of that, is unclear and incomplete. There
is also a short assembly animation video [4], but it is incomplete as
well. Yet, you can do it with a bit of patience and common sense, as
it is not a very complicated design. The only complex part, the grip,
is pre-assembled (Figure 4). However, there are a few things that
you need to know in advance (and that I found out the hard way):
> Be prepared to take things apart, so you can assemble them
again in the right way. Building it twice will probably give the
best results.
> Start at the bottom, i.e. the baseplate with the rotating Figure 4: The grip is pre-assembled — you only have to mount the servo on it.
platform, and work your way up.
> The large bearing of the rotating base is in three parts. I
noticed a slight difference in spinning quality between
the two possible assembly configurations, but ultimately,
it doesn’t seem to matter at all as it functions merely as a
deadweight.
> Use the two red YF-6125MG servos first (Figure 5). The kit
includes three of them (one spare), but the manual and video
use them everywhere. These servos are the strongest and can
carry the most weight, and therefore should go on the bottom
part of the arm.
> Make sure all the servos are in their mid-position before
mounting them. For the black MG 996R servos, you can
do this manually/visually with a kind of servo pointer/arm
(included in the kit). The red YF-6125MG servos, however, do
not have end stops, so you can’t see when they are in their
middle position. I therefore ended up using the Pico for
zeroing the servos on the fly, i.e. while assembling the arm.
This may sound complicated, but is actually rather easy to do.
I would even suggest beginning the assembly by setting up Figure 5: The YF-6125MG servos are powerful and should carry most of the
the MicroPython development environment and trying to run weight of the arm.

lektor May & June 2023 107


the demos while connected to unmounted servos [5]. Once
you understand how to control the servos from MicroPython,
you can zero them and mount them in the arm.
> In all subassemblies, the servo goes in last. They are generally to
be fixed with the screws with the gasket (the Mexican hat type).
> Make sure to tighten everything well, as it is difficult to do
once the arm is assembled.
> The grip is pre-assembled and wiggly, so I tightened
the self-locking nuts a bit. The result was that the servo
controlling the grip burnt out, as the grip had apparently
become too tight to move (even though I could move it
manually). Luckily, the kit includes two spare servos.
> There is no wiring diagram, there are six servos, and the servo Figure 6: Clamping the robot arm to the bench allows for safer
connection header has eight positions. Fortunately, it is color experimenting.
coded, so getting the polarity right is easy. Connect the servos
starting at the bottom. The lowest servo (the rotating base,
‘0’ or ‘A’ in the software) connects to GPIO16, the highest (the
grip, ‘5’ or ‘F’ in the software) goes to GPIO21. The software
allows remapping of the GPIO pins, and the spinning direc-
tion of each servo can be defined too, so you have some
freedom here to correct things.
> The baseplate has many holes, but not for attaching the Pico
board or the power supply.
> Make sure the power supply outputs 5 V before connecting it
to the arm. The output voltage can be adjusted from approxi-
mately 4.5 V to 6.5 V.

Be Careful!
Do not naïvely assemble the arm and run the demo without having
tested every servo first. The arm may spin around and move wildly,
swiping things from the bench or hitting you in the face. Its servos
are powerful! I managed to make the arm snap its own 4-mm-thick
baseboard due to a servo pushing down on the bench instead of
going up. The red YF-6125MG servos move especially fast, so watch
out. I therefore strongly recommend fixing the arm to the bench
(Figure 6) or to a heavy plate, and keep the space around it clear.

Also note that the red YF-6125MG servos do not have end stops and
may go the wrong way around to reach their target position. This
may happen when the arm is folded down and then powered up. I
therefore also highly recommend stretching the arm to its upright
position before switching on the power; see Figure 7.

Not for the Faint-Hearted


The 6 DOF Robot Arm with Raspberry Pi Pico from Makerfabs [6]
is not a kit for the faint of heart. Assembling it properly requires
patience and perseverance. Even though the arm is quite easy to
use, thanks to its driver and demo written in MicroPython, it should
be tamed step by step or accidents may happen. Its servos are fast
and strong, and the arm is 44 cm long when fully extended (50 cm
including the rotating base). Bolting it down to the floor in the
center of a square meter void of any objects is highly recommended.
You don’t want it to smash your laptop or swipe your coffee mug
off the table, do you?
220232-01 Figure 7: Upright is the safest starting position.

108 May & June 2023 www.elektormagazine.com


Questions or Comments?
Do you have technical questions or comments about this article?
Related Products
Email the author at [email protected] or contact Elektor
at [email protected]. > Makerfabs 6 DOF Robot Arm with Raspberry Pi Pico
(SKU 20130)
www.elektor.com/20130

> Elektor Raspberry Pi Pico Experimenting Kit


(SKU 19834)
www.elektor.com/19834
in Video:
This review utu.be/
https://yo DPq0
yb54d4v

WEB LINKS
[1] 6 DOF Robot Arm at Elektor: https://www.elektor.com/makerfabs-6-dof-robot-arm-with-raspberry-pi-pico
[2] Demo video: https://youtu.be/8dB1W6Jd07g
[3] Assembly guide [Zip file]: https://www.makerfabs.com/desfile/files/Raspberry-Pi-PICO-6-DOF-Robot-Arm.zip
[4] Assembly video: https://youtu.be/NqL9n3avBbY
[5] MicroPython driver and example: https://github.com/Makerfabs/PICO_Merchanical_Hand_Driver
[6] Makerfabs website: https://makerfabs.com/raspberry-pi-pico-6-dof-robot-arm.html

Genius
The only autonomous wheel in the world.
Innovation that transforms anything into an
autonomous mobile robot with simple set up.

Smart navigation Omnidirectional movement

State of art
Remote access via App
sensor technology

Flexibility to adjust
In-process charging
your payload

more details at www.wheel.me

lektor May & June 2023 109


ETHICS IN ACTION

Source: P. Haring-Kuipers — made with DALL-E


using the prompt “AI working on a painting”.

filters, neurochemistry and a whole host of other


things all influencing our thinking. AI can compute
more data much faster than we can, but it does not do
so in the same way. Human intelligence takes years
to become self-aware, to cultivate emotional under-
standing, and to take the creative leaps that might
result in anything artistic. AI will not develop in the
same way if we just give it time or more compute. We
are shaping AI.

It’s All You


Data mining is used to build better models that
might behave as we do. It may be less obvious with

Generative AI
ChatGPT [2], but this AI is trained on you too. On all
of us. Massive bodies of text and our written inter-
actions from all over the Internet are used to train
the linguistic model that is core to ChatGPT. If you
want to know more about these underlying linguis-
tic models, I recommend you listen to ”Speaking of
Who Made This Anyway? Intelligence“ by Hannah Fry [3] — an episode of her
DeepMind podcast series.

By Priscilla Haring-Kuipers (The Netherlands) One of the problems of the model is that it is unwit-
tingly racist, aggressive, and downright horrible. It
It’s all about AI. DALL-E and ChatGPT — both by is trained on the Internet and has no built-in value
OpenAI — have mesmerized many and landed system on which to judge content. How does it acquire
such values? Humans. Badly paid computer workers
generative AI in society. that spend their days looking at immoral text and
images and label them accordingly. So that the model
might learn to recognize bad content and stop produc-
ing it [4]. Moderation of social media content also uses
A Is for Art this process. That the model is getting better means
The biggest debate surrounding visual generative AIs hours of humans correctly labelling content as ‘rape’,
like DALL-E [1] is about the art that the AI trained on ‘racist content’, ‘child abuse’, ‘violence’ and the like.
without asking the original artists. For humans, we Much of the intelligence in AI is our own.
are fine with being inspired by art. We are even okay
with beginning artists copying art as a starting point, ChatGPT is also often factually wrong. Stack Overflow
but the general idea is that you then move into making banned the use of ChatGPT for now because, “The
original work. Why can’t a system use online artwork primary problem is that while the answers which
this way? One reason is that this wasn’t a general ChatGPT produces have a high rate of being incor-
consideration when the artist put their art online. They rect, they typically look like they might be good, and
did not make their art available for training, and no the answers are very easy to produce.”[5] Because the
one asked them if they could use their art this way. AI is giving information in a conversational style, we
The rules were suddenly changed on them, and now tend to process the information easier and judge it as
we have to all figure out together what we accept as more likely to be true if we judge it at all. For your next
the new rules and how they should be applied. interaction with ChatGPT, I would like you to keep in
mind that you are talking to the median of the inter-
Another reason is that AI is not inspired by art; it is net and trust it accordingly.
building a dataset on which it is training a model. We
understand intelligence mostly through the lens of AI Needs UBI
our own experiences, and expect AI to work in much We could take the sting out of this ongoing automa-
the same way as human intelligence does. This is not tion of work by providing everyone with a Universal
the case. We are multi-modal beings with direct and Basic Income. Just give everyone enough money to
indirect processing, associative learning, emotional live on. No strings and no questions.

110 May & June 2023 www.elektormagazine.com


Generative AIs do not threaten the creativity of an
artist; it threatens their way of gathering an income.
I might use AI to make visuals to go with this article
instead of my usual license-free stock photos or public
domain visuals, but I would never let an AI write it. I
want to write. However, my publisher might decide
that it is more economical to prompt an AI to write
ethical articles and not want to pay me for doing this
anymore. This matters a lot less if my house and health
do not depend on it.

Make no mistake; there is no profession safe from


AI. Visual artists, writers, lawyers, programmers
and engineers are all going to have part of our work
replaced with generative AI in the nearby future. We
might be able to use AI as a tool and happily focus on
what we are intrinsically motivated to do if our liveli-
hood is safe. Universal Basic Income would provide us
with the safety to try and divide work between what
humans do best and what AI does better.

When we can view AI as a helpful tool, it becomes


clear that what belongs to us humans is the moment
of decision. The decision to apply (or not) whatever the
AI outputs. Perhaps the decision to evolve the prompt
or change the parameters and make the AI try again.
Deciding on what to do with the AI’s output also makes
it our responsibility. In a car, in a medical setting, and
when sharing information with others.
230048-01

ChatGPT flowchart. Aleksandr Tiulkanov is an AI researcher.

About the Author


Priscilla Haring-Kuipers writes about technology from The World Ethical Electronics Forum
a social science perspective. She is especially inter- The World Ethical Electronics Forum (WEEF) inspires
ested in technology supporting the good in humanity global innovators with open discussions and publica-
and a firm believer in effect research. She has an MSc tions about ethics and sustainable development goals.
in Media Psychology and makes This Is Not Rocket Visit worldethicalelectronicsforum.com for inspira-
Science happen. tion and to participate.

WEB LINKS
[1] OpenAI, DALL-E 2: https://openai.com/dall-e-2/
[2] OpenAI, “ChatGPT: Optimizing Language Models for Dialogue,” November 30, 2022:
https://openai.com/blog/chatgpt/
[3] H. Fry, “Speaking of intelligence,” DeepMind: The Podcast (S2, Ep2), January 25, 2022:
https://youtu.be/21JSKHR7KWw
[4] B. Perrigo, “OpenAI Used Kenyan Workers on Less Than $2 Per Hour to Make ChatGPT Less Toxic,”
January 18, 2023: https://time.com/6247678/openai-chatgpt-kenya-workers/
[5] Stack Overflow, “Temporary Policy: ChatGPT Is Banned,” December 5, 2022:
https://meta.stackoverflow.com/questions/421831/temporary-policy-chatgpt-is-banned

lektor May & June 2023 111


lektor store
www.elektor.com

The Elektor Store


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

Elektor Archive 1974-2022 (USB Stick)


5 Elektor Decades (’70s, ’80s, ’90s, ’00s, and ’10s)
on a USB Stick.
This handy USB stick (32 GB, USB 3.0) is loaded with
all the Elektor magazine English editions (as PDFs)
from 1974 to 2022. Elektor engineers, authors, and
editors aim to inspire you to master electronics and
computer technology by presenting professionally
designed circuits that are easy to build.

Price: €199.95
Special Price: €99.95

www.elektor.com/20372

Microcontrollers Hands-on Course


for Arduino Starters (Bundle)
This microcontrollers hands-on course for
Arduino starters shows how you can realize
your own projects with a microcontroller
even without much experience in
electronics and programming languages.

Price: €109.95
Special Price: €94.95

www.elektor.com/20440

112 May & June 2023 www.elektormagazine.com


Arduino Giga R1 WiFi The CAN Bus Companion
+
FREE CAN Module

Price: €89.95 Price: €37.95


Member Price: €80.96 Special Price: €29.95

www.elektor.com/20436 www.elektor.com/20405

SDRplay RSP1A – 14-bit Whadda WTS100


SDR Receiver (1 kHz to 2 GHz) Soldering Starter Set

Price: €139.95 Price: €49.95


Member Price: €125.96 Member Price: €44.96

www.elektor.com/20421 www.elektor.com/20426

lektor May & June 2023 113


Hexadoku
Puzzles with an Electronic Touch

Traditionally, the last page of Elektor The Hexadoku puzzle employs digits in the hexadecimal range 0
through F. In the diagram composed of 16×16 boxes, enter digits
Magazine is reserved for our puzzle with an such that all hexadecimal digits (that’s 0–9 and A–F) occur once
electronics slant: Welcome to Hexadoku! only in each row, once in each column, and in each of the 4×4 boxes
Find the solution in the gray boxes, submit it (marked by the thicker black lines). A number of clues are given in
the puzzle, and these determine the starting situation.
to us by email, and you automatically enter
the prize draw for one of five Elektor Store Correct entries received enter a prize draw. All you need to do is
vouchers. send us the digits in the gray boxes.

SOLVE HEXADOKU AND WIN! PARTICIPATE!


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

PRIZE WINNERS
The solution of the Hexadoku in edition 3-4/2023 (March & April) is: F13AB.
Solutions submitted to us before April 15th were entered in a prize draw for 5 Elektor Store Vouchers.
The winners are posted at elektormagazine.com/hexadoku.
Congratulations, everyone!

The competition is not open to employees of Elektor International Media, its subsidiaries, licensees and/or associated publishing houses.

114 May & June 2023 www.elektormagazine.com


PROTEUS
DESIGN SUITE
Design Quality Assurance
Constraint Driven
Design
Flexible and scalable
Zone Inspector
rule system
Full support for design Analyze plane coverage and
rule rooms stitching
Manufacturing Grid view of plane
solder mask rules configurations
Live display of
Edit plane settings and
violation areas
draw order

Dedicated
Reporting
Module
Tables automatically
populate with design
Pre-Production data
Checklist
Compliance status for
diff pairs and length
Set of board tests
matched routes
before Gerber Output
Make custom
Includes placement, reports with data
connectivity and object tables
clearance testing
Generate reports
Completely independant from templates
code for clearance checks

[email protected]
+44 (0)1756 753440

lektor May & June 2023 115


Development tools
in one location
Thousands of tools from hundreds
of trusted manufacturers

Choose from our


extensive selection at
mouser.com/dev-tools

116 May & June 2023 www.elektormagazine.com

You might also like