Elektor Mag - 2022-01+02

Download as pdf or txt
Download as pdf or txt
You are on page 1of 116

£9.95 | €10.95 | $12.

95

+4V5 511 JANUARY & FEBRUARY 2022


ELEKTORMAGAZINE.COM
SI
NCE 1961

*
S2

1 Driving Motors BWD

with H-Bridges
WD

p. 6

K3 D7
D5
D3
D1 K1 FOCUS ON

Motor
M1 Control
Versatile Servo M In this edition

Tester
> DIY Master Power Switch for the Lab Bench
> The Raspberry Pi Zero 2 W GoesK4Quad-Core D8
D6 > The Elektor Lab Team
D4
K2 p. 73 > Sound Card for the Raspberry Pi Family
D2
> Practical Neurons
> Inside an Open-Source Processor
ELEKTOR INDUSTRY

Large
> Motor Control Complexity Simplified
> Impressions from the World Ethical
Electronics Forum
and
21 0491much
-004
more!
Electric Motors
p. 52

Raspberry Pi as a KVM ESP32 with RISC-V Core Autonomous Vehicle with


Remote Control p. 22 Getting Started with the p. 59 2D Lidar Remote Control Over p. 36
Software in Practice ESP32-C3 Bluetooth
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!

What can you expect?


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

Elektor Magazine,
English edition
Jens Nickel
Edition 1/2022 International Editor-in-Chief, Elektor Magazine
Volume 48, No. 511
January & February 2022

ISSN 1757-0875 (UK / US / ROW distribution)

www.elektor.com
www.elektormagazine.com

Elektor Magazine, English edition


Motor Control and More
is published 8 times a year by
We know from surveys that most Elektor readers are also professional electronics engineers.
Elektor International Media They work in development, purchasing, or sales of components and devices. We have
78 York Street therefore always been a magazine that has defied the usual division into hobby and profes-
London W1H 1DP sional electronics. After all, many a professional developer has drawn valuable inspiration
United Kingdom from our playfully presented projects. And in times when makers are founding their own
Phone: (+44) (0)20 7692 8344 companies or are being courted by the development departments of large semiconductor
companies, the old black-and-white thinking is probably finally obsolete.
Head Office:
Elektor International Media b.v.
PO Box 11 A few years ago, we launched our Industry Special (first under the name “Elektor Business”).
NL-6114-ZG Susteren Here you could find out first-hand what the development departments of the manufac-
The Netherlands turers had just brought to market. There were also interesting overview articles on the
Phone: (+31) 46 4389444 latest trends in the industry (e.g., by Stuart Cording). The engineer was on the road for
us at trade shows and had an excellent connection to many experts who provided him
Memberships:
with background information.
Please use London address
E-mail: [email protected]
www.elektor.com/memberships In 2022, starting with this issue, we will return to a uniform concept and integrate the
interesting articles from the industry into Elektor magazine. With a stronger focus on one
Advertising & Sponsoring: main topic — without sacrificing coverage of the entire spectrum of electronics in our
Raoul Morreau issues — we can cover different areas more comprehensively and in depth.
Phone: +31 (0)6 4403 9907
E-mail: [email protected]
In this issue, we begin with a focus on “Motor Control.” On pages 6, 52, and 73, you’ll find
two basic articles by Mathias Claußen and Thomas Scherer, as well as (of course!) a circuit
www.elektor.com/advertising project on the subject. And on the Industry pages Stuart Cording shows in another article
Advertising rates and terms available on request. how motor controls can be simplified.

Stay curious!
Copyright Notice
The circuits described in this magazine are for
domestic and educational use only. All draw-
ings, photographs, printed circuit board layouts,
programmed integrated circuits, disks, CD-
ROMs, DVDs, software carriers, and article texts
published in our books and magazines (other
than third-party advertisements) are copyright
The Team
Elektor International Media b.v. and may not be International Editor-in-Chief: Jens Nickel
reproduced or transmitted in any form or by any
Content Director: C. J. Abate
means, including photocopying, scanning and
recording, in whole or in part without prior writ- International Editorial Staff: Eric Bogers, Jan Buiting, Stuart Cording, Rolf Gerstendorf,
ten permission from the Publisher. Such written Dr Thomas Scherer, Clemens Valens
permission must also be obtained before any Laboratory Staff: Mathias Claussen, Ton Giesberts, Luc Lemmens, Clemens Valens
part of this publication is stored in a retrieval Graphic Design & Prepress: Giel Dols, Harmen Heida
system of any nature. Patent protection may
Publisher: Erik Jansen
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
Elektor is a member of FIPP, an organization that has “grown over almost 100 years to
projects based upon or from schematics,
descriptions or information published in or in include media owners and content creators from across the world.”
relation with Elektor magazine.

Elektor is a member of VDZ (Association of German Magazine Publishers), which


© Elektor International Media b.v. 2022
“represents the common interests of 500 German Consumer and B2B publishers.”
Printed in the Netherlands

lektor January & February 2022 3


S2

THIS EDITION
BWD
Volume 48, No. 511
S1 January & February 2022
FWD

Driving Motors
with H-Bridges
An Introduction to DC, Stepper, K3 D7
andD1Brushless Motors
D5
D3
K1

6
M1

M
K4 D8
D6
D4
K2

Regulars
D2

FOCUS
3 Colophon
52 Large Electric Motors
72 productronica Fast Forward 2021 Winners Basic Principles and Useful Information
Exciting Technologies and Creative Solutions -004 (Part 2)
68 Create GUIs21
with Python
0491
92 Starting Out in Electronics Spy Name Chooser
We Are Not Yet Done with the Coil
82 Understanding the Neurons in Neural Networks (Part 3)
96 Err-lectronics Practical Neurons
Corrections, Updates and Readers’ Letters
87 Inside an Open-Source Processor
110 Ethics Sample Chapter: Lattice and Xilinx FPGA Results
Poverty and Electronics
102 BattLab-One
114 Hexadoku Measure and Optimize the Battery Life of IoT Devices
The Original Elektorized Sudoku

Industry
Features 44 Notes From the 2021 World Ethical Electronics Forum
FOCUS
FOCUS
46 Motor Control
6 Driving Motors with H-Bridges How the Complexity of Motor Control Is Simplified
An Introduction to DC, Stepper, and Brushless Motors
16 The Elektor Lab Team
Our Approach, Preferred Tools, and More
28 IQaudio Codec Zero
The lektor Team
A Sound Card for the Raspberry Pi Family Our Approach, Preferred Tools, and More
31 The PiKVM Project and Lessons Learned
Interview with Maxim Devaev (Developer, PiKVM)
40 The Raspberry Pi Zero 2 W Goes Quad-Core

16
4 January & February www.elektormagazine.com
The Raspberry Pi Protect Yourself
Zero 2 W and Others!
DIY Master Power Switch
Goes Quad-Core for the Lab Bench

40 64

Projects Next Edition


22 Raspberry Pi as a KVM Remote Control Elektor Magazine Edition 3-4/2022 (March & April 2022)
Pi-KVM Software Test As usual, we’ll have an exciting mix of projects, circuits, fundamentals
and tips and tricks for electronic engineers and makers. We will focus
36 Autonomous Vehicle with 2D Lidar
on Embedded Development.
ESP32 Pico Interprets Data from the Lidar Module
59 Getting Started with the ESP32-C3 RISC-V MCU
From the contents:
64 Protect Yourself and Others!
DIY Master Power Switch for the Lab Bench > Workshop: RISC-V Core on FPGA
FOCUS > Buffer Board for the Raspberry Pi 400
73 Versatile Servo Tester > 4-Bit and Other Low-Cost Controllers
Check Behavior When There’s No Datasheet > Spring Collection of Raspberry Pi RP2040 Boards
> Portable Temperature- and Humidity-Measuring Device
78 Modbus Over WLAN (Part 2)
> Audio Measurements with USB Audio Interface
Software for the Modbus TCP WLAN Module
> WinUI 3: A New Graphics Framework for Windows Apps
98 Color to Sound > Over-the-Air Updates for Arduino and ESP
How to Read Out a Color Sensor via I2C > NB-IoT in Practice
106 Simple Earth-Leakage Tracer And much more!
Testing Isolation of Mains Supply
Elektor Magazine edition 3-4/2022 covering March & April 2022 will
be published around March 10th, 2022. Arrival of printed copies with
Elektor Gold Members is subject to transport. Contents and article
titles subject to change.
Simple Earth-
Leakage Tracer
Testing Isolation
of Mains Supply FOCUS ON

106 Motor
Control
lektor January & February 2022 5
background

Driving Motors
with H-Bridges
An Introduction to DC, Stepper, and Brushless Motors

Motor
Control

Source: shutterstock.com

By Mathias Claußen (Elektor)

Motor control is required in many applications — not only for fans


and ventilation systems. Conveyors, pumps, and 3D printers are also
equipped with motors that cannot be simply operated in on-off mode.
Motor power and rotation direction also need to be controlled. To make
make this an easy introduction, here we only consider conventional DC
motors, stepper motors, and low-power brushless motors.

6 January & February www.elektormagazine.com


Figure 1: The Basic Kit for Raspberry Pi Pico Figure 2: Type 28BYJ-48 stepper motor for 5 V DC.
with a DC motor. (Source: Kuongshun) (Source: Geekcreit)

The circuits shown in this article are intended to illustrate the individ- can press momentary switch S2 to engage relays K3 and K2. Then
ual sections and serve as starting points for your own designs, not current will flow into the negative terminal of the motor and out of
as finished designs that you can copy directly. First, let’s look at a the positive terminal, and the motor will run backwards. Note that
simple DC motor. In this case, it is a motor with a rated operating you should never press both momentary switches (S1 and S2) at the
voltage of 3 V to 6 V and a maximum operating current of 1 A. Motors same time. If relays K1 and K2 or relays K3 and K4 were engaged at
of this sort are included in many starter kits, such as the Basic Kit the same time, a large short-circuit current would flow through the
for Raspberry Pi Pico [1] (Figure 1). In the latter case, the supply relays and could damage them severely.
voltage is 5 V, as provided by a standard USB port. Some starter
kits also include a stepper motor or offer it as a low-cost additional From Slow to Fast
purchase. The 28BYJ-48 [2] (Figure 2), which can be powered from Using the H-bridge, we can now control the rotation direction of
5 V, is a common type. the motor. However, we are not yet able to control the motor speed.
Switching relays under load, especially with DC, considerably short-
Forwards and Backwards ens their life expectancy. In addition to the drawback of shortened
Let’s look at the circuit shown in Figure 3. Relay K1 acts as a switch lifetime with a large number of switching cycles, relays are neither
to power the motor on or off. The relay is controlled by momen- compact nor energy-efficient.
tary switch S1, so that the current required by the motor only flows
through the relay, not through the switch. Diode D1 is a snubber The first logical improvement is to use semiconductor devices. Let’s
diode and is there to prevent voltage spikes over the relay coil when look at a layout with NPN and PNP transistors. Figure 5 shows the
the switch opens. modified circuit diagram. Here the relays have been replaced by a
pair of PNP transistors (T1 and T3) and a pair of NPN transistors (T2
When momentary switch S1 is pressed, the relay K1 engages and the and T4). The drive circuitry has also changed. Now switch S1 pulls
motor M1 can start running. When momentary switch S1 is released, the bases of T1 and T2 to ground through the current-limiting resis-
the relay drops out and the motor is no longer supplied with power. tors R1 and R2 when the switch is closed, or ties them to the supply
The windings of DC motors can also generate voltage spikes, the voltage through R5 when the switch is open. Switch S2 performs
same as relay coils. Here diode D2 acts as a snubber diode for the the same actions for transistors T3 and T4.
motor to prevent the motor from generating an undesirable voltage
spike when it is switched off. With this circuit it is only possible to In the quiescent state of the circuit with switches S1 and S2 open,
run the motor in the forward direction. But what if you also want to the supply voltage is applied to resistors R1 to R4 through resistors
run the motor backwards (e.g., to drive a winch)? Then you have to R5 and R6. This means that transistors T1 and T3 are cut off and
modify the circuit so the motor can run backwards. therefore have very high impedance (in the megohm range). By
contrast, transistors T2 and T4 are driven into conduction by their
An H-bridge is a good option for this. An example is shown in Figure 4. base currents and therefore have low impedance. As a result, both
The name is based on the structure in the circuit diagram. The motor ends of the motor are connected to ground and no current flows
is connected in the middle of the H. If you press momentary switch through the motor.
S1 (motor forwards), then relays K1 and K4 will engage to allow
current to flow into the positive terminal of the motor and out of What happens now if switch S1 is closed and switch S2 is open?
the negative terminal. If you want the motor to run backwards, you Then resistors R1 and R2 will be tied to ground, so transistor T2 will

lektor January & February 2022 7


+5V +4V5

S1 S1 S2
ON FWD BWD

D1 K1

D1 K1 D3 D5 K3 D7

M1
D2
M1
M

D2 K2 D4 D6 K4 D8
210491-005

Figure 3: Motor control


with relays.
210491-004

Figure 4: H-bridge with relays.

no longer have any base current because the base and emitter are motor needs to be operated with a higher voltage or the MCU can
at the same potential. Transistor T1, by contrast, will be conducting only tolerate 3.3 V on its I/O pins (as with the Raspberry Pi), the
because current can flow from the emitter to the base. As a result, circuit has to be modified a bit.
the positive supply voltage is applied to one terminal of the motor
while the other terminal is tied to ground, so the motor can start The result is shown in Figure 7 with two additional transistors (T5
running. If switch S1 is open and switch S2 is closed, then transistor and T6) driven by the PWM signals through base resistors. Thanks to
T3 will be conducting and transistor T4 will be cut off. In this case these transistors, it is possible to use MCUs that operate with a supply
the motor also starts running, but in the other direction. voltage lower than the voltage for the DC motor. Here it should be
noted that the PWM signals are now inverted. If a voltage is applied
But what if you want to be able to control the motor speed, for example to transistor T5 or T6, this transistor is driven into conduction and
using a microcontroller? Instead of the switches, you can use two pulls the inputs of transistors T2 and T1 or transistors T3 and T4 to
pins of a microcontroller. These are marked PWM_A and PWM_B ground. This must be taken into account in the drive signals from the
in Figure 6. If you want the motor to run forwards or backwards, MCU, since forwards and backwards are swapped now.
you simply have to set these pins High or Low as appropriate. If you
also want to control the speed, you can use pulse width modulation There are drawbacks to using PNP and NPN transistors in this appli-
(PWM). This way the speed is determined by the duty cycle (the cation. They need base currents, which means they consume energy,
On time relative to the period) of the PWM signal, and the direc- and the frequency of the PWM signal is limited. Switching between
tion depends on whether a pulse waveform is output on PWM_A the high-impedance and low-impedance states is not instantaneous,
or PWM_B. This layout is designed for a 5 V supply voltage, so the so there are switching losses. Furthermore, at the moment when T1
outputs of the MCU must be able to handle 5 V signal levels. If the and T2 or T3 and T4 change states, there is a brief interval in which

+5V

R5 R6

T1 T3
D3 D5
R1 R3

M1

M
T2 D4 D6 T4
PWM_A R2 R4 PWM_B

210491-010

Figure 5: H-bridge with NPN and PNP transistors. Figure 6: Driving with PWM signals from an MCU.

8 January & February www.elektormagazine.com


M
+4V5

R5 R6

T1 T3
D3 D5
R1 R3

M1

M
T2 D4 D6 T4
R2 R4

T5 T6
PWM_A R7 R8 PWM_B

210491-009

Figure 7: Driving with 3.3 V signals.

both transistors of the pair are conducting. This allows a higher between the gate and the source must also be taken into account.
current to flow directly from the supply voltage to ground. This also If this voltage is exceeded, the FET will be damaged. With an NMOS
increases the power dissipation and can even lead to early failure. FET, the voltage on the gate must be more positive than the voltage
on the source to drive the FET into conduction. For T2 and T4, this
H-Bridges with FETs means that they are in the high-impedance state when the gate is
To avoid some of the drawbacks of bipolar transistors, a good choice pulled to ground, and they start to conduct when a positive voltage
is to use field effect transistors (FETs). They can achieve higher (relative to ground in this case) is applied to the gate.
switching frequencies and have lower power dissipation. All of the
H-bridges described above have the problem that the transistors can Diodes D4 to D6 are still present in Figure 8, but they are not needed
generate transient short-circuit currents, and this problem needs to when FETs are used because the body diodes of the FETs serve the
be eliminated. The H-bridge shown in Figure 8 is therefore built with same purpose. The FET symbol in Figure 9 for T1–T4 clearly shows
FETs that can be driven individually. the body diode as a component of the FET structure. This means
that diodes D4 to D6 can be omitted, resulting in the circuit diagram
Here T1 and T3 are PMOS FETs, while T2 and T4 are NMOS FETs. in Figure 10.
With a PMOS FET, the FET is cut off (high impedance) when the
voltage difference between the gate and the source is close to zero. If you only have a 5 V supply, couldn’t you simply connect PWM_A
In order to drive a PMOS FET into conduction (low impedance), to !PWM_A and PWM_B to !PWM_B? In theory, this is possible,
the voltage on the gate must be more negative than the voltage on but it would lead to even worse transient short-circuit currents than
the source. For T1 and T3, this means that when the gate is pulled with bipolar transistors. As a mental experiment, let’s suppose that
to ground, the FET conducts. The maximum permissible voltage PWM_A and !PWM_A are connected. With 5 V applied to T1 and

+5V

T1 S S T3
PWM_A D3 D5 PWM_B

G G

M1
D D
M
T2 D D T4
D4 D6
PWM_A PWM_B
G G

S S

210491-001

Figure 9: FET symbol with body


Figure 8: H-bridge with FETs. diode.

lektor January & February 2022 9


+5V

S S
PWM_A T1 T3 PWM_B
counterparts. This means higher power dissipation, especially with
G G
relatively high currents. Figure 11 shows a circuit with two half-bridge
driver ICs (ON Semiconductor NCP5901B) and a layout with four
M1
D D
M
NMOS FETs. There are no blocking capacitors in the circuit diagram;
D D
T2 T4
capacitors C1 and C2 are part of the charge pump of the NCP5901B.
PWM_A PWM_B
G G But why does the half-bridge driver IC need a charge pump? Here T1
S S
and T3 are NMOS FETs, which as previously described need a gate
voltage higher than the source voltage in order to start conducting. In
210491-002
the case of T1 and T3, this means that the voltage on the gate must be
higher than the supply voltage of the H-bridge. A charge pump is used
Figure 10: Circuit diagram without snubbing diodes.
to achieve this. Figure 12 shows the internal functional block diagram
of the half-bridge driver IC. There you can see the dead time gener-
ation function to prevent shot-through, which is labelled ‘Anti-Cross
Conduction’.

This allows an H-bridge to be built from discrete components using


T2 as the initial condition, T1 is conducting and T2 is cut off. Now FETs suitable for the use case concerned. Currents greater that 25 A
we pull PWM_A and !PWM_A to ground. The 5 V signal drops to can also be handled this way with H-bridges. If you are looking for a
0 V, but not straight away. Instead it declines gradually, over a time more compact solution for lower currents, you can also opt for a fully
interval in the nanosecond range. In this process there is a point integrated solution.
where both FETs are conducting: T2 is not yet completely cut off
and T1 is already conducting. In this situation both FETs have a resis- The STM L298N, which is fitted on many low-cost motor driver
tance on only a few ohms, resulting in a short-circuit current directly boards (Figure 13), provides two complete H-bridges. It does not
through T1 and T2. This is called ‘shot-through’, and it is undesirable have integrated FETs, but does have integrated bipolar transistors. It
in H-bridges because the components can be severely damaged. You can drive up to 4 A at 46 V. A glance at the block diagram (Figure 14)
are therefore strongly advised to not try to connect the two signals. reveals a very familiar structure. MCUS with 3.3 V signal levels are
Some PWM units of advanced MCUs offer the option of generating certainly suitable for driving the L298N. The module is available from
signals suitable for driving H-bridges and are able to insert suitable mail-order dealers for around €3 to €6 (£2.60 to £5.20 or $3.50 to $7.00).
dead times to avoid shot-through conditions. The Infineon IFX9201SG is distinctly more compact. It can drive up to
6 A and has integrated protection circuitry and diagnostic functions,
H-Bridge Driver ICs as can be seen in Figure 15. It costs approximately €4 (£3 or $4.20)
You can have the MCU generate dead times to ensure that T1 and per device. It would be so easy to design a DC motor driver with this
T2 are never conducting at the same time, or you can use a suitable device, but as of 1 September 2021 it is not expected to be available
H-bridge driver IC. The above-mentioned H-bridge with two NMOS until mid-2022, like so many other semiconductor devices. If you are
FETs and two PMOS FETs has the disadvantage that the conductiv- looking for a ready-made H-bridge for motor control, you should have
ity of the PMOS FETs is at least a factor of 10 worse than their NMOS a look at the Cytron motor driver boards [3] in the Elektor Store.

+5V +5V

C1 T1 D D T3 C2

G G
NCP5901 NCP5901
M1
1 8 8 1
PWM_A BST DRVH S S DRVH BST PWM_B
2 7 M 7 2
PWM IC1 SW SW IC2 PWM
3 6 6 3
EN GND T2 D D T4 GND EN
4 5 5 4
EN_A VCC FLAG DRVL DRVL FLAG VCC EN_B
G G
9 9

S S

210491-003

Figure 11: Four NMOS FETs with driver ICs.

10 January & February www.elektormagazine.com


M

Figure 12: Internal block diagram of the ON Semiconductor Figure 13: L298N module as a dual H-bridge.
NCP5901B (source: ON Semiconductor).

Stepper Motors, Step by Step inside there is a rotor, consisting of permanent magnets and toothed
As the name says, stepper motors do not simply run, but instead rings made of soft iron. The rotor consists of a set of windings arranged
move in incremental parts of a full rotation. They are not intended so that the rotor always move one step at a time.
for high speeds in continuous operation, but they can perform incre-
mental motion with high torque. In most households, stepper motors In terms of drive, the most common stepper motors have two poles.
are most likely to be found in ink-jet printers. There they are used to Other pole counts are also possible, but are not considered here. In
move the print head or transport the paper. A stepper motor operates terms of structure, there are two types of this sort of stepper motor:
with a defined step size (increment of a full rotation), so it is very unipolar and bipolar. We will look at these below.
easy to calculate the exact position of the print head. Some of us
may also remember the sound of stepper motors in diskette drives, Unipolar Stepper Motors
where they were used to move the read/write head. As an example of a stepper motor, here we use the 28BYJ-48 shown
in Figure 2, which can be found in many starter kits. This small
But how do you drive a stepper motor, and why does it move in unipolar stepper motor additionally has a gear unit with a 63.68395:1
steps? Stepper motors are available in various forms: reluctance reduction ratio. The motor has a step size of 11.25°, so the number
stepper motors, permanent magnet stepper motors, and hybrid of steps for a full rotation of the gear unit output shaft is 2037.8864,
stepper motors. Here we consider hybrid stepper motors, which or approximately 2038 steps per rotation (rounded up). Five wires
have become established in many applications because of their good are needed to connect the motor: A, B, C, D, and the supply voltage.
torque characteristics and large number of steps per rotation.
Driving a unipolar stepper motor is very easy, and with a motor of
Figure 16 shows the structure of this kind of stepper motor. On the this size this can be done with a ULN2003, available from a variety

Figure 14: Internal structure of the L294N (source: STMicroelectronics).

lektor January & February 2022 11


Figure 15: Internal
block diagram of the
Infineon IFX9201SG
(source: Infineon).

of manufacturers. The ULN2003 contains seven Darlington transis- sizes defined by the National Electrical Manufactures Association
tors, as shown in the block diagram in Figure 17. Snubber diodes are (NEMA). NEMA 17-03, for instance, designates the size of a type of
also integrated in the IC, making it quite suitable for driving inductive stepper motor that is produced and/or sold by a variety of compa-
loads. Figure 18 shows a circuit with a ULN2003, which can be used nies. The NEMA17-03 stepper motor from Joy-IT [5] is one example
to drive a 28BYJ-48 stepper motor. In addition to full step mode, the (Figure 19). A ULN2003 is not sufficient to drive this type of stepper
28BYJ-48 can be operated in half-step mode. According to the data motor, which requires two H bridges in the drive circuit. An L298N,
sheet, this is the recommended drive method. The sequence of the as previously mentioned for DC motors, provides two H-bridges in
drive signals for clockwise rotation is listed in Table 1. To make a step a single package and is used as a stepper motor driver in the circuit
in the backwards direction, you have to run through the sequence in Figure 20. As these H-bridges are made with bipolar transistors,
in reverse. Unipolar stepper motors have become rare now because snubber diodes are required at the outputs. The sequence in Table 2
they can deliver only about half as much torque as a bipolar stepper must be performed to generate one step in the clockwise direction.
motor of the same size. However, this is offset by the very simple
driver stage with a ULN2003. If you want, you can modify a 28BYJ- Unlike unipolar stepper motors, in this case the complete winding
48 stepper motor for bipolar operation. To learn how, read jangeox’s is used, instead of only half with a centre tap. This enables higher
blog post [4]. Then the stepper motor will be able to generate more torque than with a unipolar stepper motor of the same size. Driving
torque, but it will need a different driver. with H-bridges is very easy, and highly integrated drivers such as
the MP6500 from MPS or the TMC2300-LA from Trinamic make this
Bipolar Stepper Motors even easier. They contain part of the control logic that performs the
Bipolar stepper motors, which are installed in most 3D printers, have step sequences. The MCU only specifies the desired direction (clock-
only four leads. For these stepper motors there are standardised wise or anti-clockwise) and supplies a pulse for each desired step.

Table 1: Sequence for one step.

Step/ Orange Yellow Pink Blue


colour
1. 1 0 0 0
2. 1 1 0 0
3. 0 1 0 0
4. 0 1 1 0
5. 0 0 1 0
6. 0 0 1 1
7. 0 0 0 1
8. 1 0 0 1
Figure 16: Structure of a stepper motor (source: Microchip)

12 January & February www.elektormagazine.com


+5V

M
Red

ULN2003 9
Pink
CD+
Orange
1 16
Pink I1 O1
2 15
Orange I2 O2
Yellow
3
I3
IC1 O3
14 M1
4 13 M
Blue I4 O4
5 12
I5 O5
6 11
I6 O6 Yellow
7 10
I7 O7 Blue
GND

8
210491-007

Figure 17: Internal structure of the ULN2003 Darlington


array (source: STMicroelectronics). Figure 18: Circuit diagram with ULN2003 and stepper motor.

The nice thing about stepper motors is that they have high torque rotor are possible: internal and external. Some brushless motors have
and do not need any brushes or commutators to carry the current integrated Hall sensors to determine the position of the rotor; motors
to the rotor, as with DC motors. with only three leads do not have this form of feedback. They require a
bit more complicated circuitry and more computation. For sensorless
Brushless DC Motors types of brushless DC motors, the AVR444 application note [6] is a good
If you combine the properties of a DC motor with the torque and low starting point for learning more about the subject.
maintenance of a stepper motor, you get a brushless DC motor. Brush-
less DC motors are ideal for drive tasks in a wide variety of applications. Figure 21 shows the structure of a brushless DC motor with an
In conventional DC motors, brushes provide a path for current to flow external rotor. In this case the external rotor is a permanent magnet.
into the rotor windings. With every rotation, these brushes wear and Inside the rotor there are six windings arranged in three pairs. Each
distribute conductive dust inside the motor, so the brushes of DC motors pair is wound such that one winding forms the north pole and the
must be replaced at regular intervals and the motors may need to be other the south pole when current flows through them. The poles
cleaned. Brushless DC motors do not need this sort of maintenance, and of the rotor tend to align with a pair of windings in which current is
they deliver high torque in a small package. However, driving brushless flowing. Figure 22 shows how the rotor is pulled by the magnetic
DC motors is complicated, and faulty drive can lead to damage. For field of the windings, causing it to rotate. However, only one of the
this reason, here we only give a very brief introduction to the theory of three pairs of windings is used at a time, so there is room for improve-
driving brushless DC motors. ment. When winding pair A is attracting the permanent magnet in
the first step, winding pair C can be used to repel the permanent
The structure of a brushless DC motor is very similar to that of a stepper magnet. In this way two windings contribute to the rotary motion,
motor. It has a stator (the non-moving part) and a rotor. Two types of increasing the torque and therefore the performance of the motor.

Table 2: Sequence for a bipolar stepper motor.

A B C D
1. 1 1 0 0
2. 0 1 1 0
3. 0 0 1 1
4. 1 0 0 1

Figure 19: Joy-IT NEMA17-03


stepper motor (source: Joy-IT).

lektor January & February 2022 13


+5V

9 4 D1 D3 D5 D7

5V VS
5
A A
7
B B
10 IC1 M1
C C Q1 2
12
D D
Q2 3 b a

6 M
INH1 13
11 Q3 c d
INH2 14
L298N Q4
1
SENSE1
15
SENSE2
D2 D4 D6 D8
R1 R2
GND
8

210491-006

Figure 20: L294N as a stepper motor driver. Figure 21: Structure of a brushless DC motor.

Figure 23 shows the rotation with two driven windings. The drive marked in Figure 23. If a voltage is applied between A and B, the voltage
signals must have the right timing. between the two windings can be sensed over winding C. At the point
in time when a voltage is applied between A and B, a timer is started
The windings are driven by three half-bridges. You have already learned and the voltage on winding C is monitored. When the voltage reaches
about these in the section on DC motors. The circuit in Figure 24 shows half the supply voltage of the motor, the rotor has travelled half of the
the theoretical layout of these three half-bridges, which are also available rotation distance between two winding pairs. This time can then be
as ICs from various manufacturers. In order to drive the motor, suitable used to calculate when the next windings should be driven and with
signals must be supplied to the inputs A, B and C. The NCP5901B has which polarity. As a result, the permanent magnet is kept in motion by
a voltage divider at each input, which biases the input pin to 2.0 V when the rotating magnetic field.
it is not being driven by the MCU. In the range between 1.3 V and 2.7 V,
the NCP5901B switches to diode emulation, which means free-wheel- The speed of the motor can be controlled by PWM signals, which must
ing mode, so the winding is not connected to ground or to the supply be applied accordingly to inputs A, B and C of the driver IC. The hardware
voltage of the motor. This allows the back electromotive force (BEMF) used in application note AVR444 is the ATAVRMC100 evaluation kit,
to be measured later in order to determine the rotor position. whose description and schematics can be found on the Microchip web
page [7]. More information is also available in application note AN1946
Assuming that the rotor is rotating and no Hall sensors are installed in from ST [8] and application note AN12435 from NXP [9]. Driving brush-
the motor, the BEMF of the non-driven winding can be utilised. This less DC motors requires a bit more software than with stepper motors
allows the position of the rotor to be determined, or more precisely the or simple DC motors. Rotor position detection, internal signal filtering
point in time when the rotor has travelled far enough that it is positioned and signal conditioning by the software make driving less intuitive than
between two winding pairs. The three winding pairs A, B and C are with conventional DC motors.

Figure 22: The rotor is pulled by a magnetic field.

Figure 23: The rotor is driven by two of the three winding pairs.

14 January & February www.elektormagazine.com


+5V +12V ADC_A

C1 T1 D

R1
G
NCP5901
1 8
BST DRVH S
2 7
A R2
PWM IC1 SW
3 6
EN GND T2 D
4 5
VCC FLAG DRVL

An H-Bridge for All Seasons 9


G

H-bridges are an important basis for DC drives, regardless of whether S

they are for stepper motors, motors with brushes or brushless motors. +5V +12V ADC_B

You do not necessarily need to build them with discrete components; for
relatively small motors and low currents, you can use ready-made ICs C2 T3 D
M1 A
if available. Driving brushless motors is more difficult, and you should R3
B C
consider whether you want to acquire experience in building control-
G
NCP5901
1 8
lers for brushless motors or would instead be satisfied with ready-made BST DRVH S
2 7
B PWM IC2 SW

solutions. However, knowledge of the underlying theory certainly doesn’t


R4 3 6
EN GND T4 D
4 5
VCC FLAG DRVL
hurt. 9
G

210491-01 S

+5V +12V ADC_C


Contributors
Concept and text: Mathias Claußen
Editor: Jens Nickel
C3 T5 D

R5
Translation: Kenneth Cox NCP5901
G

Layout: Harmen Heida and Giel Dols 1


2
BST DRVH
8
7
S

C R6
PWM IC3 SW
3 6
EN GND T6 D
4 5
VCC FLAG DRVL

Questions or Comments?
G
9

Do you have technical questions or comments about this article?


S

210491-008

Email the author at [email protected] or contact


Elektor at [email protected]. Figure 24: Brushless DC motor with three half-bridges.

RELATED PRODUCTS

> Geekcreit 5pcs 5V Stepper Motor with ULN2003 Driver > Cytron 10Amp 7-30 V DC Motor Driver Shield for Arduino
Board Dupont Cable (SKU 19783) (SKU 19063)
www.elektor.com/19783 www.elektor.com/19063

> Cytron 3Amp 4-16 V DC Motor Driver (2 Channels) > E-book: Power Electronics in Motor Drives (SKU 18517)
(SKU 18999) www.elektor.com/18517
www.elektor.com/18999
> Book: Motors for Makers (SKU 18194)
> Cytron 25Amp 7-58 V High Voltage DC Motor Driver www.elektor.com/18194
(SKU 19062)
www.elektor.com/19062

WEB LINKS
[1] Basic Kit for the Raspberry Pi Pico: https://www.elektor.com/basic-kit-for-raspberry-pi-pico-pico-included
[2] 28BYJ-48 stepper motor: https://www.elektor.com/geekcreit-5pcs-5v-stepper-motor-with-uln2003-driver-board-dupont-cable
[3] Cytron H-bridge motor driver boards: https://www.elektor.com/catalogsearch/result/?q=cytron%20driver
[4] Jangeox blog: http://www.jangeox.be/2013/10/change-unipolar-28byj-48-to-bipolar.html
[5] Joy-IT NEMA 17-03: https://joy-it.net/en/products/NEMA17-03
[6] Microchip AN AVR444: https://www.microchip.com/en-us/application-notes/an8012
[7] ATAVRMC100 Hardware User Guide: https://ww1.microchip.com/downloads/en/DeviceDoc/doc7551.pdf
[8] STM AN1946: https://www.st.com/resource/en/application_note/cd00020086-sensorless-bldc-motor-control-and-bemf-
sampling-methods-with--st7mc-stmicroelectronics.pdf
[9] NXP Semiconductors AN12435: https://www.nxp.com/docs/en/application-note/AN12435.pdf

lektor January & February 2022 15


background

The Team
Our Approach, Preferred Tools, and More

By Jens Nickel (Editor in Chief) uncover all the details of a project, includ-
ing the source code, whether it was a new
There are many electronics magazines around project from one of our engineers or it was
the world, but most of them just report on new from an enthusiastic reader’s home lab.
Why has this been Elektor’s approach? Our
developments and applications. Elektor is different. reasoning is clear. We want our readers
With our in-house Elektor Lab team of engineers, to be able to build the same projects, and
we are constantly developing, refining, and testing we invite them to modify, improve, and
expand everything we publish. Whether
electronic projects and products. you are a professional engineer or a
weekend maker, we want you to under-
stand how everything works. So, it is not
For six decades, Elektor magazine has electronics workbench for soldering, reverse an overstatement to say that Elektor has
featured a healthy mixture of theory and engineering, programming, and tinkering. been one of the long-time leaders in the
practice. It is in our DNA. It all started Elektor also maintains a useable electron- open-source movement!
more than 60 years ago with electronics ics workspace in its HQ that is stocked with
enthusiast Bob van der Horst who was handy lab equipment, components, and Most Elektor readers and community
bored by dry datasheets and theoretical engineering tools. Lab team members can members will also recognize that there is
articles full of formulas and diagrams. pop into the workspace at any time to test no strict line between our Lab engineers and
Instead, he wanted to publish a magazine designs or collaborate on projects. editorial team. All the engineers in the Lab
with circuits that readers could build and (Clemens Valens, Luc Lemmens, Mathias
modify [1]. From those early days, most The actual team comprises engineers of Claussen, and Ton Giesberts) are writing
of the circuits and projects were built and various ages, backgrounds, and personali- articles, and all the editors including me and
tested before they were published in Elektor ties. From the very beginning, the Lab has Content Director C. J. Abate also have fun
magazine. And as a result, the Elektor Lab included analog guys interested fiddling contributing ideas and input to Lab projects.
quickly became famous. The work of the around for months on big circuits as well
Elektor Lab continues to this day. Curious as programming enthusiasts interested As we kick off 2022, we encourage everyone
about the status of the Elektor Lab in 2022? contributing fresh ideas. To put it simply, to get to know the Elektor Lab team. On
Read on and join us! we have a diverse crew. these pages, you will find a short presenta-
tion about the Elektor Lab team members
What Is the Elektor Lab? Some magazines only report about kits or and some of the platforms and tools that we
The Elektor Lab is both a location and a new products. Not Elektor! We do much use. We invite you to contribute your ideas,
team. Each Elektor Lab member has a home more. We have always endeavored to feedback, projects, and articles!

16 January & February www.elektormagazine.com


The Elektor Lab Team

Based in
Germany

Based in
France

Clemens Valens is an engineer who manages the Elektor Mathias Claußen started as a trained IT systems electronics
Labs online platform. He holds a BSc in Electronics and an MSc in technician and earned a BSc in Electrical and Information
Electronics and Information Technology. Clemens started working Engineering and a MSc in Microelectronic Systems. After this,
for Elektor in 2008 as Editor in Chief of Elektor France, and he has he worked as a project engineer for embedded development
also worked as an editor for Elektor UK/US and ElektorMagazine. and focused on ARM Cortex-M-based architectures and real-
com. Later, Clemens was head of Elektor’s design labs in the time operating systems. Mathias joined Elektor in 2018 as part
Netherlands, Germany, and India. Today, he is Elektor’s creative of the Elektor Lab team focusing mainly on software. Today, it is
technologist responsible for the Elektor Labs community website more than just software development in the background. Mathias
where electronics enthusiasts can publish their work and interact writes articles about hardware and software development, creates
with peers from all over the world. Besides contributing own videos for Elektor TV, and more. Want to learn about his home
projects and other articles to the magazine, he is also producing workspace? You can read about it online at Elektor [2]. You can
regular videos for Elektor TV and moderating webinars. His main see some of the instruments and tools Mathias is using for many
interests are sound generation and signal processing. daily tasks there.
Based in
Netherla the
nds
Luc Lemmens started working Ton Giesberts started
for Elektor in March 1990 after his working at Elektuur (now called
studies at the Technical University Elektor) after his studies when
the
Based in nds Eindhoven. At the time, he also they looked for someone with an
Netherla published Elex, an electronics affinity for audio. Over the years,
magazine aimed primarily at the he has worked mainly on audio
novice electronics hobbyist. Luc projects. Analog design has
designed and edited projects always been his preference. Of
for both magazines. He has course, projects in other fields
many interests, which means of electronics are part of the
that he knows a little about a job. One of Ton’s mottos is:
lot of topics in electronics. Of “If you want to have it done
course, he has also written or better, do it yourself.” For
edited software in a wide range example, a PCB design: for
of programming languages — and, especially in his early days an audio project with distortion
at Elektor, in assembly language. Nowadays, he usually limits figures on the order of 0.001%, a good layout is
himself to the Arduino IDE, which is perfect for most simple crucial!
projects. Over the years, Luc has also written and translated
technical text and even Elektor books. In his spare time, Luc likes
to play with pinball machines, especially repairing and restoring
both modern electronic machines and electromechanical ones
(with relays and stepper units).

lektor January & February 2022 17


Recent Elektor Lab Projects and Products
The Elektor Lab team has prepared for collaboration with our partners.
many electronics projects for Elektor. The end result might be an article (or
Sometimes a design is developed article series) or product that is sold
entirely by the Elektor Lab. Other in the Elektor Store. Below is a list
times, our Lab team members adapt of just a few successful Elektor Lab
projects from external designers. projects from recent years.
And sometimes ideas are outsourced

Clocks Audio DAC for Raspberry Pi New LCR Meter 50 Hz - 2 MHz


Electronic clocks have always been popular
with the readers of Elektor magazine. Also
because they are the devices par excellence
to give old displays a new application, as in
the 6-digit Nixie Clock [3] and the Pinball
Clock [4].

The LCR Meter 50 Hz - 2 MHz is a high-pre-


cision device for testing and measuring
passive components. It can compete with
Raspberry Pi boards have audio outputs, — and even beat! — commercially avail-
but if you want real high-quality sound, able equipment [8].
an external high-end Digital-Ana-
log-Converter is needed, like this board
[6] designed by our audio wizard Ton Book
Giesberts. Mastering Microcontrollers Helped by
Arduino

DIY LiPo Supercharger Kit

Weather Station with ESP32

Need a rechargeable LiPo power supply kit


for 5 V and 12 V output? Check out the kit
the Elektor Lab developed in cooperation
with GreatScott! [7] Clemens Valens’s book, Mastering Micro-
controllers Helped by Arduino, will familiar-
ize you with the world of Arduino and you
Buy an affordable, complete set of weather will learn how to program microcontrollers
station sensors and add state-of-the-art in general. Some of the proposed projects
electronics and software to build your own include a car GPS scrambler, a weather
weather station [5]. station, an infrared remote manipulator,
and PID controller.
210545-01

18 January & February www.elektormagazine.com


Elektor Needs You!

In contrast to a lot of other magazines, articles and other and critical feedback! You also have the chance to get
interesting content does not flow one-way from Elektor to you. It backers for your project (please see the Elektor Jumpstarter
also goes the other way around. We encourage our growing textbox). On the Elektor Labs platform, ideas and questions
worldwide community of engineers and makers to contribute are welcome!
ideas, tutorials, tips and tricks, circuits and projects.
2) You can send your article/project to the editorial team
Can you teach others about a certain subdomain of by mail: [email protected]. You don’t have to have a
electronics or software? Have you developed a nice ready-made article text, but a circuit diagram and a short
electronics project? Do you have special area of technical description is a must to let us know what you have in the
expertise? Our readers may be very interested in that. works. Of course, we will not uncover any details of your
project without your ok!
There are 2 ways to share tips, tutorials and projects:
Elektor editors and Lab team members review all the
1) You post something on Elektor Labs (see Elektor Labs contributions during our weekly internal meetings. If we
textbox). Here you can immediately get in touch with other select your article to be published in print or online, we will
readers, maybe on the other side of the globe, to get positive let you know, and we will discuss the next steps with you.

Elektor Jumpstarter

Elektor Labs Platform Elektor Jumpstarter is


Elektor’s take on crowdfunding.
The Elektor Labs online The online platform is intended
platform was developed for to help innovators like you turn
engineers, makers, and your electronics projects into
students who are passion- products.
ate about electronics. It is a
place where you can share To apply, simply post a project
your projects, participate in at Elektor Labs and then click the Jumpstarter button. It will
those posted by others, and then be evaluated by Elektor. When a project is accepted, the
discuss project develop- community can start backing it.
ment and electronics. Elek-
tor Labs is open to every- Backing a project does not involve any money. Instead, when
one; the only requirement is someone "backs" a project, it indicates their interest in having
a free Elektor ID. the chance to purchase the final product if the Jumpstarter
campaign reaches its goal (i.e., a certain production quantity
Now in its tenth year, Elektor at a predefined price). If the campaign succeeds, Elektor will
Labs has gathered more than 10,000 active users who have produce the product and put it in the Store for anyone to buy.
posted more than 2,000 projects and countless comments.
The online platform is much more than just a free space In short, at Elektor Labs, our motto Design, Share, Sell really
where you can show off your skills. Not only can our team of comes to life.
electronics specialists assist you in successfully completing
your project, but we can also help if you wish to turn it into www.elektor-labs.com
a product to be sold in the Elektor Store. And, as every www.elektormagazine.com/jumpstarter-info
project posted at Elektor Labs is evaluated by our editorial
team, Elektor Labs is also the place for posting an article
proposition for Elektor Magazine.

www.elektor-labs.com

lektor January & February 2022 19


Open-Source Design Tool: KiCad If a small board is
needed but is not
available via an Elektor-
partner collaboration, we
will offer the CAD files for
free. Each reader can adapt the PCB or use it as it is, and order it
via a PCB production service. We recommend
www.elektorpcb4makers.com and www.elektorpcbservice.com,
which we offer in cooperation with our partner Eurocircuits.

Elektor @ GitHub
Elektor loves open-source solutions, so the Elektor Lab team
members tend to use open-source tools. One example is
KiCad, which we use (besides Altium and Eagle) to design
schematics and PCBs. KiCad is free to use, open-source and
runs on all three major operating system. This enables you
to share your work with others so that they can also adapt or
modify your creation as needed.

You can find online articles and videos about KiCad at the
Elektor site: www.elektormagazine.com/tags/kicad

Elektor PCBs
Elektor readers are used to finding green drawings of (mostly
small) PCBs in the magazine. As a service for many years, The Elektor Lab uses the Elektor Labs platform (www.
almost all these PCBs were available in our Store for people elektormagazine.com/labs) to host its own projects and
who wanted to find and solder the components themselves. projects from external authors. You will find the files (software
From most of these naked PCBs, we only sold a few pieces, and hardware) required for the projects there.
and these figures have even decreased in the last years. We
have to face the fact that the electronics world is changing. It For larger projects that are continuously developed,
makes no sense to develop a microcontroller or a small audio managing the different versions can become confusing.
amplifier board (just to name two examples) from scratch This is where GitHub comes in, which brings a version
and produce it in small quantities for (too) high prices. Today, management system so you can easily revert to a specific
makers and professionals alike are used (and are even state or track changes made. GitHub also offers several other
expecting) to getting inexpensive modules with at least the advantages, such as experimental alternate versions, issue
most important components — as SMD blocking capacitors trackers for suggestions and comments, or community-
or pull-up resistors — already integrated. Time is money, so supplied patches in the form of pull requests.
most electronic developers want out-of-the-box prototyping
solutions. They expect to open the box, connect everything, Therefore, we will offer more and more software and also
and start working. CAD data for download on GitHub (https://github.com/
ElektorLabs). The corresponding web link can be found at the
However, this doesn’t mean that we do not sell any PCBs end of each project article.
or kits anymore! We focus on the most promising and
interesting projects, where we really invented something For GitHub beginners, Clemens Valens from the Elektor Lab
original which can’t be ordered for a few bucks everywhere. has created a video tutorial at on Elektor TV:
For these projects, we have set up collaborations with www.youtube.com/watch?v=X5e3xQBeqf8.
partners who are experienced at producing small and
also larger quantities when needed. Two of these partners
are Eurocircuits and SIMAC (Joy-IT).

20 January & February www.elektormagazine.com


Follow Us on Social Media

Elektor Lab members and editors are easily accessible on


social media. Feel free to follow us and reach out on Twitter,
Facebook, and YouTube.
YouTube
Twitter ElektorTV: https://www.youtube.com/user/ElektorIM
Mathias Claussen: https://twitter.com/elektormathias
Clemens Valens: https://twitter.com/clemens_elektor Facebook & Instagram
Elektor: https://twitter.com/Elektor Elektor Labs (FB): https://www.facebook.com/ElektorLabs/
C. J. Abate: https://twitter.com/elektor_us Elektor Labs (IG): https://www.instagram.com/elektorlabs

WEB LINKS
[1] “Elektor @ 60”, ElektorMag May/June 2021 : http://www.elektormagazine.de/210025-01
[2] “An Elektor Engineer’s Workspace for Embedded Software Development”, Elektormagazine.com: https://www.elektormagazine.
com/articles/elektor-workspace-embedded-software-development
[3] 6-digit Nixie Clock: https://www.elektormagazine.com/magazine/elektor-146/58526
[4] Pinball Clock: https://www.elektormagazine.com/magazine/elektor-88/42431
[5] Weather Station with ESP32: https://www.elektormagazine.com/magazine/elektor-70/42351
[6] Audio DAC for Raspberry Pi: https://www.elektormagazine.com/magazine/elektor-201707/40496
[7] DIY LiPo Supercharger Kit: https://www.elektormagazine.nl/labs/diy-lipo-supercharger-kit-by-greatscott
[8] New LCR Meter 50 Hz - 2 MHz: https://www.elektormagazine.com/magazine/elektor-159/59096

Advertisement

available-to-ship-delivering-more-185x124mm-5mmbleed-en.indd 1 25/11/2021 08:43

lektor January & February 2022 21


project

•E
r lab lekto
to

r la
Ele

b
TESTED

ab
Ele
Raspberry Pi as a
to

rl
to

k
r la
b • Ele k

KVM Remote Control


Pi-KVM Software Test
By Mathias Claussen (Elektor)
of hardware, makes it possible to avoid long
KVM stands for keyboard, video, mouse, and whoever trips to a site. It is also possible to remotely
has access to it can remotely control a computer. Using operate devices and measuring instruments
the clever Pi-KVM software and a Raspberry Pi 4, you that were never intended for this purpose
by the manufacturer. Figure 1 illustrates the
can inexpensively control a PC and other devices via use of Pi-KVM for remote control of a PC.
the Internet without having to install software on the A machine could be remotely maintained as
remotely controlled computer. Pi-KVM also enables the shown in Figure 2.

provision of virtual disks, so that a computer can not only The Pi-KVM Alternative
be controlled and maintained remotely, but a complete There is remote maintenance software, isn’t
reinstallation is possible. there? If you are using a Raspberry Pi or
a PC, you will surely have used a tool like
VNC, AnyDesk or TeamViewer. Besides
During the pandemic, I received information through dozens of installation steps with a these, there are quite a few other solutions
that my parents still had computers running mixture of phone call and video chat can for remote maintenance and control. All these
Windows 7 (some were even Windows XP) easily imagine that such a thing is not a good solutions are inexpensive or even free of
at their house. Because of the security gaps, idea for an operating system installation and charge for the private user. To help someone
which can no longer be fixed, these computers data backup. Remote access is what’s needed. set up new software or create social media
urgently needed to be updated. Unfortunately, And that’s exactly what is made possible with posts, something like this is a quick and easy
an update was not enough for these machines. a Raspberry Pi as a KVM remote control. solution. However, these helpers all require
They required a complete reinstallation, but a running operating system with an Internet
driving there was not an option, because of At this point in the text, you can replace connection.
the pandemic and more than eight hours of parents with customers, computers with
driving time. machine controls, and new installation with But what if the computer no longer boots or
error analysis. A pair of eyes with which one can no longer establish a network connec-
Anyone who has ever tried to guide someone can look at a system remotely, independent tion? Or if the operating system has to be

22 January & February 2022 www.elektormagazine.com


Figure 1: Remote support with Pi-KVM on remote PC.

reinstalled? That’s the point at which someone


with appropriate expertise needs to be on site
to get the operating system to boot again and
establish a network or Internet connection.
This also applies to reinstalling an operating
system. Figure 3 shows the BIOS message
of a PC that could not find bootable media.

Pi-KVM works independently of the computer


to be controlled and transmits the video image
that the graphics card outputs via the network Figure 2: Remote maintenance of
to a second system that only needs to run an a machine with Pi-KVM.
HTML5-capable web browser. There, not only
the image output of the remotely controlled
computer can then be displayed; the mouse
movement and keyboard inputs are also
returned to the computer to be controlled. This
allows you to remotely control the computer
as if you were sitting in front of the computer’s
screen, mouse and keyboard. Figure 4 shows
the BIOS message of the PC now comfortably
in the browser of a remote computer. Access
to the BIOS (as shown in Figure 5) can also be
conveniently controlled via a remote browser,
so it is not absolutely necessary to be near
the PC.

Virtual Disks
Something that gets complicated over Figure 3: Error message at boot.
longer distances (usually 2 m is enough) is
the insertion of USB bootsticks, or rotating
data media such as DVD or CD. You could
send a bootstick to the PC to be controlled
remotely and hope that someone onsite will
insert it correctly. Pi-KVM offers the option of
virtual disks (i.e., it can emulate a USB stick
or a USB-CD-ROM drive). To do this, you
can simply upload and mount the appropri-
ate disk image via a browser. Figure 6 shows
the virtual disk menu. Currently, CD emula-
tion is limited to ISO files, so they must not
be larger than 2 GB. For ISO files larger than
2 GB (Figure 7), hybrid ISOs must be avail-
able (i.e., those that could also be written to
a USB stick). These can then be used with
the Flash emulation type and appear as USB Figure 4: Error message in the browser with Pi-KVM.
mass storage.

lektor January & February 2022 23


Figure 5: BIOS settings remotely. Figure 6: Virtual disks. Figure 7: ISOs over 2 GB as mass storage.

Figure 8: Data flow with HDMI-CSI bridge.

Figure 10: Raspberry Pi 4 2 GB version.

Figure 9: Data flow with HDMI-USB dongle.

An Affordable, Open-Source The Necessary Hardware HDMI capture dongle can be ordered for a
Solution The hardware needed for the Pi-KVM is quite few Euros from relevant mail-order compa-
Doesn’t something like Pi-KVM already exist? simple: nies. Even though the price of these dongles
The functions provided by a Pi-KVM are also may be tempting, they have some limitations
offered by other devices from other manufac- > A Raspberry Pi Model 4 (2 GB RAM or in terms of stability or supported resolutions.
turers, but usually much more expensive than more) (Figure 10) The HDMI-to-CSI bridge is the more stable
the Pi-KVM solution and with closed-source > One Micro SD card (16 GB and compatible choice.
firmware. With these devices some comfort recommended)
functions are then also subject to an extra > One USB power supply (5 V/3 A) For the connection between the Raspberry
charge. The Pi-KVM comes as an open-source > Optional housing Pi 4 and the computer to be controlled, the
project and can be assembled with common > HDMI to CSI Bridge or USB HDMI USB-C port of the Raspberry Pi 4 is used in
hardware. In the end, you have to budget about Capture Dongle (Figure 11) USB OTG mode. This allows the Raspberry
€100 for the DIY solution. > A USB Y-cable (Figure 12 and Figure 13) Pi 4 to behave like a keyboard, mouse or
mass storage device towards a PC. For
There are two ways to build a Pi-KVM, one While the first three components should be this, the Raspberry Pi 4 is connected to the
with an HDMI-CSI bridge and one with a available or easy to get for most readers, the computer with a USB-A to USB-C cable
USB-HDMI dongle. Figure 8 and Figure 9 last three are a bit more difficult to get. For and would also be supplied with power
show the data flow through the Raspberry Pi 4 the HDMI-to-CSI bridge (Figure 14 shows via this. Since 3 A @ 5 V is required here,
with the respective solution. At this point, we two available variants), on the other hand, you stable operation cannot be guaranteed, so
would like to present the required components have to search a bit for a European source an additional power must be provided by a
and give a few hints about how to build them. or resort to one from the Far East. A USB power supply unit.

24 January & February 2022 www.elektormagazine.com


Figure 11: HDMI-to-CSI bridge and USB- Figure 12: USB A-Y cable.
Figure 13: USB-A to USB-C cable.
HDMI capture dongle.

Figure 14: Two variants of the HDMI-to- Figure 15: Assembled adapter board. Figure 16: Two robust USB-B sockets.
CSI bridge.

Figure 17: Micro SD card with 16 GB Figure 18: Finished setup with HDMI-to-CSI
memory. Figure 19: Finished setup with HDMI USB dongle.
bridge.

Since the USB-C port is used in OTG mode, you own risk. You can find a component list and Hardware Assembly
could feed 5 V into the Raspberry Pi 4 via the the circuit diagram at the end of the article. If the CSI-to-HDMI bridge is used, it is unfor-
40-pin header. However, these 5 V would then tunately a bit more difficult to find a suitable
also supply power to the computer connected Software Installation case. Either someone has already built such a
to the USB-C port. This is something that quite You can download the Pi-KVM software from case or you have to help yourself with a little
a few computers do not like and acknowledge the developer’s homepage [2]. An SD card FreeCAD and a 3D printer. For this article, the
with malfunctions. One solution is to use a with 16 GB memory (Figure 17) is recom- parts are therefore installed using flying wires.
Y-cable that splits the data and the power supply. mended for the installation. If an HDMI-to-
CSI bridge is used, the Raspberry Pi 4 v2 For the setup with HDMI-to-CSI bridge, you
So that two USB cables do not have to be platform image can be used for the HDMI-to- need a corresponding board and a Raspberry
soldered together to fit, the Elektor Lab has CSI bridge; if a USB-HDMI dongle is used, Pi camera cable. A suitably prepared SD
routed a small circuit board (Figure 15). Two use the HDMI-USB dongle image for the card with the latest image for Pi-KVM must
USB-B sockets (Figure 16) allow one connec- Raspberry Pi 4 v2 platform. be inserted into the Raspberry Pi 4 and the
tion to a power supply and one connection to HDMI-to-CSI bridge connected to the camera
a computer without feeding 5 V backwards. The downloaded file must be unzipped with a port. The USB-Y cable must be connected to
Both sockets have in common that a LED program like 7-Zip and then written to an SD the USB-C port of the Raspberry Pi 4. With
signals the presence of the 5 V bus voltage. card with a tool like the Raspberry Pi Imager. this, the Pi-KVM is ready for use (Figure 18).
The board is available as a KiCAD project and This completes the basic installation and you
can be downloaded from the Elektor GitHub can start assembling the hardware. If you want For the variant with HDMI USB dongle, this
repository [1]. However, the board has not yet to take a look at the source code, you can do must be connected to one of the USB 2.0 ports
been tested extensively, so rebuild at your so in the GitHub repository [3] of the Pi-KVM. of the Raspberry Pi 4B. If you use one of the

lektor January & February 2022 25


blue USB 3.0 ports, the shown USB dongle mouse and keyboard can now be operated take a look at the PI-KVM homepage. There
is not recognized (Figure 19). remotely. they are working on a finished HAT for the
Raspberry Pi 4 and a matching case. Pi-KVM
First Test Run Figure 21 shows the web interface with the and its developers are currently funded by
Once all parts have been assembled and, if desktop of the remote Raspberry Pi, taken donations through Patreon or Paypal. If you
possible, stowed away in a housing, nothing with the HDMI-to-CSI bridge. Figure 22 like the project, the developer would surely
stands in the way of the first test run. I used a shows the same scene, although an HDMI-to- appreciate some recognition.
second Raspberry Pi 4 as a test object, which USB dongle was used here. The image quality 200523-01
has been doing its job as a camera on my has decreased and green edges are visible
desk for some time (Figure 20). (The article as artifacts.
about the Raspberry Pi 4 camera can be found Contributors
in Elektor Sep/Oct 2021 [4].) The Raspberry For additional configuration and options, it Design and text: Mathias Claußen
Pi 4 running Pi-KVM is connected to a wired is worth taking a look at the Pi-KVM homep- Editor: Jens Nickel
network. age or the GitHub repository. Besides mouse Layout: Harmen Heida
and keyboard, a mass storage is available as
After the first start of Pi-KVM, it takes a already mentioned. The Raspberry Pi 4 with
moment because the partition is adjusted Pi-KVM can emulate either an optical drive or Questions or Comments?
to the size of the SD card. If this process is a USB stick. To do this, the appropriate image Have technical questions or comments
finished, Pi-KVM tries to get an IP address via can be copied to the Raspberry Pi 4 via the about this article? Email the author at
DHCP. It might be necessary to check in the web interface (Figure 23). [email protected] or contact
router or DHCP server which IP the Pi-KVM Elektor at [email protected].
got. With a web browser the interface of the Outlook
Pi-KVM can then be called. With the Pi-KVM software and a few inexpen-
sive components, you can turn a Raspberry
After booting, you can log in to the interface Pi 4 into a remote control for computers
with the user name admin and the password and other equipment that can be operated
admin. Under the item KVM the screen of with a mouse and a keyboard. If you don’t
the second Raspberry Pi 4 appears and both want to assemble the components yourself,

RELATED PRODUCTS

> Raspberry Pi 4 B (4 GB RAM) (SKU 18964)


www.elektor.com/18964

> Raspberry Pi HDMI to CSI-2 Adapter Board (supports up


to 1080p25fps) ( 19707)
www.elektor.com/19707 Figure 20: Raspberry Pi camera
(Elektor Sep/Oct 2021 [4]).

WEB LINKS
[1] KiCad files on GitHub: https://github.com/ElektorLabs/200523-Raspberry_Pi_4_with_PiKVM
[2] PiKVM Homepage: https://pikvm.org/
[3] PiKVM Github Repository: https://github.com/pikvm
[4] Mathias Claußen, “Imaging and Video-Streaming with a Raspberry Pi 4,” ElektorMag 9-10/2021:
www.elektormagazine.com/200582-01

26 January & February 2022 www.elektormagazine.com


COMPONENT LIST
Resistors (0.25 W) Semiconductors
R1,R2,R3 = 100 k D1,D2 = LED RED 5 mm
R4,R5 = 1 k
Others
Figure 21: Desktop of the Raspberry Pi camera captured with HDMI-to-
Capacitors K1,K2 = Connector USB B CSI bridge.
C1,C2,C3 = 100 n K3 = Connector USB A
PCB = 200523-1 V1.0

Figure 22: Desktop of the Raspberry Pi camera recorded with HDMI


1 2
USB dongle.
D2
VBUS D– K1
GND D+
USB_B
RED
5 4 3

R5 R1
C1
100k
1k

100n
K3 USB_A

1
VBUS
2
D–
3
1 2
SHIELD

D+
4
D1 VBUS D– K2 GND

GND D+
USB_B 5
RED
5 4 3

R4 R2 R3
C2 C3
100k

100k
1k

100n 100n

200523-005

Figure 23: Mass storage emulation on the web interface.

lektor January & February 2022 27


review

IQaudio Codec Zero


A Sound Card for the Raspberry Pi Family

By Mathias Claußen (Elektor Lab)

Looking for a small and compact sound card for a Raspberry Pi?
Check out the IQaudio Codec Zero, which has a Zero form factor.

Figure 1: IQaudio Codec Zero (Source: Raspberry Pi Foundation). Figure 2: Contents of the IQaudio Codec Zero package.

If you only need a digital sound output via HDMI, you don’t need Zero can be found on the page [1] of the Raspberry Pi Foundation.
a sound card. A sound card becomes interesting if you want to
output analog audio in good quality or if you also want to process IQaudio Codec Zero: Almost Plug & Play
analog signals with the Raspberry Pi. The A and B models of the The IQaudio Codec Zero has an EEPROM according to the
Raspberry Pi still have a 3.5-mm jack connector that can output Raspberry Pi HAT specification, so a Raspberry Pi should automat-
analog audio; however, the quality is not the best and not really ically recognize the board and set it up appropriately. On a
suitable for listening to music. Raspberry Pi 3B+, this works fine; the current Raspberry Pi OS
(32 bit) recognizes the board and sets it up appropriately. Figure 4
The IQaudio Codec Zero (Figure 1) offers an integrated 1.2 W ampli- shows the IQaudio codec in the sound settings. However, there
fier for an 8 Ω speaker, an integrated MEMS microphone and an are still a few steps necessary that are not directly described in
analog AUX input and output with line level. This makes projects the IQaudio Codec Zero manual.
such as a smart speaker, a VoIP phone, or a custom jukebox quite
easy to implement. Figure 2 shows the hardware and the included First, the output volume should be reduced to a minimum. After
mounting hardware. The heart of the IQaudio Codec Zero is the the internal audio codec of the Raspberry Pi has been deactivated
DA7212 from Dialog Semiconductor. Figure 3 shows the blocks and according to the instructions, the IQaudio now remains in the
signal routing within the DA7212. The IC is a 24-bit codec with up system as the default sound card. If a terminal is opened now,
to 96 kHz sample rate. Integrated is a 5-band equalizer as well as an a speaker test can be started with speaker-test -t wav -c 1.
ALC and a noise gate. The documentation for the IQaudio Codec However, the speaker remains mute. It is necessary to adjust a

28 January & February 2022 www.elektormagazine.com


Figure 3: Block diagram of the DA7212
(Source: Dialog Semiconductor).

Figure 4: IQaudio Codec Zero settings.

few parameters in the Advanced Linux Sound Architecture (ALSA)


settings. The fastest way is to reload the provided settings from
IQaudio. To do this, a Git repository is cloned via terminal with
git clone https://github.com/iqaudio/Pi-Codec.git. In
the terminal change to the created folder Pi-Codec and execute
the command sudo alsactl restore -f IQaudIO_Codec_
Playback_Only.state. After that, speaker-test -t wav -c 1
should make a front left sound from the speaker. From now on
all sounds will be output via IQaudio Codec Zero. A quick and
easy installation!
Figure 5: AUX In and Aux Out connected.
Microphone, AUX-In and AUX-Out
With the built-in microphone, the Raspberry Pi can record audio.
This way, a smart speaker can be realized — e.g., with voice2json
[2]. Or you can use the Raspberry Pi in conjunction with Edge
Impulse [3] to record data. The MEMS microphone on the board sudo alsactl restore -f IQaudIO_Codec_AUXIN_record_
won’t win any awards in the “recording quality” category, but it and_HP_playback.state
does its job. If you are unhappy with the sound, you can connect
an external microphone. The predefined .state files in the cloned You can also see the AUX Out on the picture, which allows the
Pi codec folder help to get the appropriate settings for recording IQaudio Codec Zero to act as a feed to an amplifier or active
via microphone. Using sudo alsactl restore -f IQaudIO_ speakers.
Codec_OnboardMIC_record_and_SPK_playback.state selects the
microphone as the recording source. For a test recording, arecord New Life for an Old Radio
--device=hw:1,0 --format S16_LE --rate 44100 -c2 test. Something that has been on my to-do list for too long is an old
wav can be used in the terminal to start a test recording with Philips radio (Figure 6 and 7). All that’s left of the interior is the
the microphone and end it with CTRL+C. This can then be played speaker, and there’s room for new hardware. Inside, a low-power
back with aplay test.wav. If you want to connect an external Raspberry Pi would do well, but an amplifier is needed for the
audio source, you can solder suitable jacks to the IQaudio Codec speaker. It’s a good thing that the IQaudio Codec Zero has an
Zero. Figure 5 shows AUX In with RCA jacks. To select AUX In as integrated 1.2-W amplifier, so that a small office can be sounded
recording source, you have to type the following in a terminal: wonderfully.

lektor January & February 2022 29


Figure 6: Old housing of a radio. Figure 7: There is only one speaker left.

For music playback, anything can be used that outputs sound in


the direction of ALSA under Linux. But if the MPD or a special
distribution like Volumio will be used, is not decided yet. I don’t
have a completely finished concept for the radio yet, but one of
WEB LINKS
the hurdles, a codec with a small amplifier, is already out of the
way. So, with time, the inner workings will fill up piece by piece [1] IQaudio Codec Zero:
with hardware. There is still a lot to do and plan for this project. www.raspberrypi.org/products/iqaudio-codec-zero/
[2] Voice2Json: http://voice2json.org
[3] M. Claussen: Image Processing with the Nvidia Jetson
A Solid Base Nano (Part 2) - Image Recognition Using Edge Impulse,
The IQaudio Codec Zero offers Aux IN, Aux Out as well as an Elektor 11-12/2021 : www.elektormagazine.com/210318-B-01
integrated microphone and can drive a small speaker with 1.2 W. For
the price of about €20, this is a compact solution that can be used
on a Raspberry Pi Zero as well as on a Raspberry Pi 3B or Raspberry
Pi 4B. For streaming players, VoIP phones or smart speakers, the
IQaudio Codec Zero provides a solid base. If you want to experi-
ment with audio and streaming on the Raspberry Pi and Linux, RELATED PRODUCTS
you should consider the IQaudio Codec Zero.
210535-01
> IQaudIO Codec Zero - Sound Card for Raspberry Pi Zero
(SKU 19541)
Questions or Comments? www.elektor.com/19541
Do you have technical questions or comments about this article?
Email the author at [email protected] or contact Elektor > Raspberry Pi Zero WH (with pre-soldered header)
at [email protected]. (SKU 18567)
www.elektor.com/18567

> Raspberry Pi 3 B+ (SKU 18452)


Contributors www.elektor.com/18452
Text and pictures: Mathias Claußen
Editors: Jens Nickel and C. J. Abate > Raspberry Pi 400 - Raspberry Pi 4-based PC (EU) +
Layout: Giel Dols FREE GPIO header (SKU 19431)
www.elektor.com/19431

30 January & February 2022 www.elektormagazine.com


interview

The PiKVM Project


and Lessons Learned
Interview with Maxim Devaev (Developer, PiKVM)
By Mathias Claußen (Elektor Lab)

PiKVM software is a Raspberry Pi 4-powered tool for remotely accessing a PC, server or other
machine over a network connection. We were able to ask the developer of the PiKVM a few
questions about his project.

Figure 1: UI of PiKVM.

The PiKVM software [1] makes it possible to turn a Raspberry Pi 4 — all that is needed on the side of the controlling computer
into an inexpensive remote control for other computers. Locally, is a web browser. The PiKVM project (UI shown in Figure 1) is
the Raspberry Pi is connected to the computer to be controlled. open-source and the cost of the required hardware is less than
It grabs the monitor image and emulates a USB mouse, keyboard €100 for the DIY version, a fraction of commercial products.
and flash drive. The signals are then made accessible via the This raises a few questions that we put to the developer of the
Internet by the PiKVM software [2] running on the Raspberry Pi PiKVM, Maxim Devaev.

lektor January & February 2022 31


So, I took the self-education route and got a job as a software devel-
oper. I worked, I worked, I worked, I improved, and some time later I
landed in Yandex (Russian Google of sorts). There I settled down for
nine whole years. I was developing distributed systems, solving big
infrastructure monitoring and management problems and all that
jazz. It might not be the most interesting thing, but it is what it is.

Claußen: How did you come up with the idea to start the PiKVM
project?

Devaev: It’s a funny story, actually. One time I went to visit my


parents 1400 kilometers from home. My home server, which I
always keep on, died as I was eating my mom’s cake. I was annoyed
and had to ask my friend to go to my place and reboot it, and decided
to buy a KVM over IP after that. I went online, and saw … $500?
Seriously? What’s in that thing to cost $500? And then I read some
reviews and realized that those $500 get you an overpriced piece of
hardware paired with awful buggy proprietary software with licens-
ing restrictions. And there were no good devices on the market:
they were all equally bad. I don’t know what got me, but I decided I
was not going to pay that amount of money as a matter of principle.
If you want something good, do it yourself. And the rest is history.

Claußen: Why did you use a Raspberry Pi for the project?

Devaev: Raspberry Pi just came in handy. It was fresh to the market


Figure 2: Prototype of PiKVM using a Raspberry Pi 1 and was a perfect fit for a small embedded system. Basically it could
(Source: Maxim Devaev).
have been any other ARM computer, but the price, prevalence and
great manufacturer support played a crucial role. I didn’t want
to spend any time debugging noname devices, creating custom
kernels, etc. — so, Raspberry Pi allowed me to focus on my task.

Besides Raspberry Pi, I needed a video capture device and a way


Claußen: Let’s begin with your background. Tell us about how to emulate a keyboard (no mouse in mind at that point). At that
you became interested in electronics. Did you study at university? time, there was no cheap VGA capture devices on the market, so I
went for a little hack: I used an RCA-USB dongle that was usually
Devaev​: Sure, but it would be wrong to call me an electronic special- used to digitise old VHS tapes, and fed analog video from a cheap
ist. I know how to hold a soldering iron, of course, and I can design VGA-RCA converter (Editor’s note: see Figure 2). Video quality
a simple wiring diagram and assemble it without burning the whole was horrible but good enough to set up BIOS and use a console. As
thing. But I’m mainly a software engineer. Electronics is my second- for the keyboard, I bought a PS/2 to USB converter and emulated
ary and far less developed skill. PS/2 signals using GPIO. It was cheap, primitive, but it worked.
Eventually, I threw all this hardware away and went for a popular
I became interested in technics when I was a child and I have been HDMI bridge for video and switched my PS/2 converter for an
reading a lot of different science and tech literature since. Getting Arduino with custom software.
my first PC affected the contents of my bookshelves a lot, of course,
as they became much heavier with all the computer science books.
Claußen: How did the appearance of the Raspberry Pi 4 influence
A couple years later, when it was time for me to choose univer- the project?
sity, I went for information security, but abandoned shortly after,
as the curriculum disappointed me. Russian higher education is Devaev: Besides better performance and a way to improve video
very formal: it’s often more important that you don’t fail the dozen quality, Pi 4 had two USB controllers. I could use one to emulate a
accompanying humanitarian subjects. keyboard and a mouse on kernel level which allowed me to ditch

32 January & February 2022 www.elektormagazine.com


variants.
Figure 3: HDMI to CSI Bridge in two
Figure 4: HDMI to USB Dongle.

the Arduino. I also managed to build a virtual CD drive so I could I manned up and wrote to the RFBProto (de facto VNC standard
remotely reinstall an OS on the server. It was a moment when description) and TigerVNC repository maintainer with a proposal:
PiKVM came before most of the existing commercial devices in let’s create new encoding, it would be great for users with low
price and functionality. bandwidth. We discussed details for a long time and finally came
up with a format that suited us all. Then I went to IANA and asked
them to register this new VNC extension. I was worried they would
Claußen: Did you start the PiKVM as a part-time project or hobby? say no, as they already had a registered format with no description,
but they went for it and explained that it was legacy from a propri-
Devaev: It was a pet project of sorts. I enjoyed doing it, humour- etary client. Lo and behold, we’re developing an official TigerVNC
ing my perfectionism. I never thought anyone besides me would patch for a first ever open source H.264 over VNC extension. The
need it until I stumbled upon a similar half-abandoned project on beta version is running smoothly! It might be very new, but some
GitHub (DIY-IPMI). Its author had followed the same route, but VNC clients and servers are already interested in implementing it.
they dropped it on the proof-of-concept stage. I became excited. I
began advertising my project and committing like crazy, solving one The moral of the story is: Don’t be afraid to communicate with other
issue after another, adding more and more features and spending projects, even if they seem monumental. And one other thing: even
thousands of hours on the project. It was great to see how many one person can push forward development of the whole protocol;
people began using my software. I had been developing only small you just have to dream big.
utility scripts or heavy enterprise software before.

Claußen: Did the appearance of the 10$-USB-HDMI dongle help


Claußen: Are there lessons learned from this project that you to push the PiKVM project?
would like to share with other developers?
Devaev: It depends. Before the USB dongle I used an HDMI-CSI-
Devaev: Okay, here’s a story. Web interface is a main way to use bridge (Figure 3) that had many advantages. Surely, the USB
PiKVM, but there’s a self-developed VNC server as an alternative. dongle (Figure 4) played a big role in popularising PiKVM as it was
That’s cool, right — use a VNC client to set up BIOS! I used MJPEG really cheap, but I always advised against using it due to hardware
to transfer video both for web and VNC. It’s a simple but very problems: it’s not very stable.
bandwidth-ineffective format. For the browser, I could use H.264
and WebRTC, but for VNC there was no way to use full-fledged Many people reported buying it and regretting afterwards, as
differential encoding. they often saw a blank screen and couldn’t do anything about it.

lektor January & February 2022 33


Devaev: I’m not very good at writing documentation,
so many people help me with that. Some write recipes
and scripts, come up with and describe new ways to use
some of the PiKVM features. Some create bug reports
and give me remote access to their hardware for me to
debug problems. And the most important thing of all:
when the number of users became really big, it became
impossible to reply to every single person on Discord [3],
so active users helped me onboard new users and now
only reach out to me when they can’t solve a problem
themselves. I’m very thankful for those people, as I can
now dedicate all my time to writing software.

Sometimes there are people who bring in patches with


new features or bug fixes, but there are not many of
those people yet, and I’m virtually the only PiKVM
developer at the moment. I’m planning to hire some
Figure 5: PiKVM v3 HAT (Source: Maxim Devaev) [5].
people to help me with software full-time when we
start selling devices. So if you buy our hardware, you
will sponsor the development of open source software.

A USB dongle is a black box: you have no idea how it works, and Claußen: If someone likes to support your work, what would be
if something goes wrong, you can’t fix it. The bridge, on the other the best way in doing that?
hand, is much more open and almost all video processing is done
by the kernel and my software. Devaev: Besides donations, help is appreciated with things we
can’t handle on our own yet. Some of those problems are outlined
in our GitHub issues [4].
Claußen: The PiKVM is an open-source project that can (currently)
be used free of charge. How is its development financed? You now
seem to work full time on the project. Claußen: Are there any plans to commercialize your work?

Devaev: I would lie if I said I had a long-term vision, a plan and Devaev: Right now my main source of income are donations. I’m
understanding of the market. It all started last year, when I quit often told I could sell a commercial license to the PiKVM software
my job to take a break and to think about my career. I continued with advanced features, but I don’t want to do that for two reasons.
working on PiKVM as a hobby. The community was growing and I Firstly, PiKVM has direct access to the hardware and I wouldn’t trust
thought it would be great if PiKVM became my main job, and I’ve such a thing if it wasn’t open source. Secondly, a paywall would inevi-
seen some open-source projects whose authors made a living at it. tably lead to someone forking your open software and developing
It was a win-win situation: I would be doing what was really inter- pro features for free, getting part of your community to themselves.
esting to me, and users would get high quality software for a small
donation. As a test, I set up Patreon and announced I was accepting The other way to monetize, which will soon become primary, is
donations now, as I was now without a job and ready to improve selling my own hardware (PiKVM v3 HAT) (Figure 5]), you can
PiKVM upon request (in case you needed a certain feature quickly). use instead of that DIY version to get more stability and additional
To my surprise, several months later, I began making some profit. hardware features. But I don’t plan to abandon PiKVM DIY and force
It was way less than my previous salary, but considering I stopped users to buy the v3. I don’t pursue wealth at any cost, just enough
spending money on trips to the office, started getting enough sleep, money to feed me and my cat.
and even lost some weight, it was a fair trade. Users were also happy,
as it could now be half an hour between finding a critical bug and
a fix, and I was adding new features in a matter of days. Claußen: Can you tell us a bit about your hardware, the PiKVM
v3 HAT?

Claußen: How is the community supporting your project besides Devaev: To DIY a PiKVM, you have to use your hands and option-
helping you to afford full-time development? ally a soldering iron. I decided to make it a bit easier for the user, as

34 January & February 2022 www.elektormagazine.com


well as to improve hardware stability of this version and add some Claußen: Do you have any other projects in development? Can
features that are hard to DIY. Although I came up with the original you share some details about what you are working on?
concept of the device, I couldn’t develop a completely custom board
(this is a separate magic that I don’t own), so I invited my friend with Devaev: uStreamer, I guess. It was created for PiKVM, but it’s a
hardware skills to work with me on this project. Our PiKVM v3 HAT totally separate component many people use as a server for webcam
has a built-in server power controller, a video capture device, a USB video. (It’s used as a capture device in PiKVM.) I wrote it from
switch (to emulate plugging a cable out, it’s sometimes useful), and scratch as an alternative to MJPG-Streamer to fix the performance
a serial port (to connect to a server or console in a rack), clock for problem. Now uStreamer is the fastest specialised MJPEG/H.264
precise logging — all on one board. Basically, it’s a solution that’s video service, and I’m really proud of that.
better and cheaper than all the $500 ones you have on the market.
You don’t have to take my word on it: you can look up v3 reviews
on YouTube. And soon everyone will be able to buy it. Claußen: Maxim Devaev, thank you for the interview. Those who
are now heading to the Kickstarter campaign [5], we have some
good news. The campain was more than successful. This means
Claußen: Also, you have an enclosure for the Raspberry Pi 4 and you will be able to order the PiKVM v3 HAT in an online store soon.
your add-on — that is made from metal. Was there a reason not to Also have a look at the Elektor Store [6] as our purchase team is
use plastic? We read on Discord that it is easier to build in Russia currently working to be able to offer you also some PiKVM v3 HATs
something out of metal than rubber or plastic. in the near future.
210405-01
Devaev: That’s true. The metal enclosure came out more heavy,
sturdy and much cheaper than a plastic one. Those who ordered
v3 HAT on Kickstarter could get this case for free. Then it will be Questions or Comments?
sold in online stores. And we also have a free drawing of the case Do you have technical questions or comments about this article?
for 3D printing, if you like to work with your hands. Email the author at [email protected] or contact Elektor
at [email protected].

Claußen: Will your kit be available for customers to be ordered


from stores outside of Russia?

Devaev: The first batch should be available in the USA shortly. The
second batch will be available worldwide in autumn 2021.

RELATED PRODUCTS
Claußen: What plans for the PiKVM do you have for the future?

Devaev: We will continue developing both software and hardware. > Raspberry Pi HDMI to CSI-2 Adapter Board (supports up
We plan to implement 1080p 60Hz capture (you can’t do that now to 1080p25fps) (SKU 19707)
due to Pi 4 restrictions) and create a secure solution for cloud access www.elektor.com/19707
for users without an open external IP address.

WEB LINKS
[1] M. Claußen, “Raspberry Pi as a KVM Remote Control”, Elektor 1-2/2022: http://www.elektormagazine.com/200523-01
[2] Pi-KVM Homepage: https://pikvm.org/
[3] Pi-KVM on Discord: https://discord.com/invite/bpmXfz5
[4] Pi-KVM GitHub issues: https://github.com/pikvm/pikvm/issues
[5] Pi-KVM v3 HAT on Kickstarter: https://www.kickstarter.com/projects/mdevaev/pikvm-v3-hat
[6] Elektor Store: http://www.elektor.com

lektor January & February 2022 35


project

Autonomous Vehicle
with 2D Lidar to
r lab
• Elek
to

r la
k
Ele

b
O R IGINAL

Ele

ab
to

rl
to

k
r la
b • Elek

ESP32 Pico Interprets Data


from the Lidar Module

By Clemens Valens (Elektor Labs)

Lidar enables robots and other self-driving vehicles


to detect obstacles around them without touching,
project
providing much more freedom of movement. To Watch this eo!
get a feel for this technique, I built a simple remote- on vid
controlled cart and let it drive around in my livingroom.

Lidar is an acronym for light detection and and traffic control towers on airports. 3D lidar ant. An ideal black body cannot be seen by
ranging. Lidar is like radar, except that it uses exists too and is used for instance by planes a lidar as it does not reflect any light at all.
light instead of radio waves. The light source to create three-dimensional renderings of
is a laser. A lidar sends out light pulses and the surface of the earth below them. For this Connecting the Lidar
measures the time it takes for a reflection project, a 2D lidar is used. For my experiments, I used the X4 from
bouncing off a remote object to return to Ydlidar (Figure 2). It features a range of up
the device. As the speed of light is a known Basically, a 2D lidar is nothing more than a to 10 meters and an angular resolution of 0.5°
constant, the distance to the object can be rotating 1D lidar. Instead of rotating both the (for distances up to 50 cm). It has an infrared
calculated from the travel time of the light laser and detector, it is often easier to shine laser with a wavelength of 785 nm. This device
pulse (Figure 1). the light on a rotating mirror. By sending out rotates the laser and detector assembly; it
light pulses periodically 360° can be covered does not use a rotating mirror.
Two-Dimensional Lidar and a distance map with the lidar at the center
Lidar can be one-dimensional (1D), like laser can be created. The X4 lidar outputs distance data as a
distance meters. It can also be two-dimen- continuous serial stream at 128,000 baud.
sional (2D), much like the radars used by ships Note that the reflectivity of objects is import- It is also controlled over this serial link. You

36 January & February 2022 www.elektormagazine.com


d = 0.5 • t • c [m]

Figure 1: This is how you calculate distances. t is the travel time of the light pulse in Figure 2: The YDLIDAR X4 is a low-cost 2D lidar with
seconds and c is the speed of light in m/s. The factor 0.5 corrects the fact that the pulse more than enough range and precision to make a robot
must travel to the object and back and therefore travels twice the distance. move around without bumping into objects.

can start and stop scanning by sending it


simple commands. You can also request some
information about the device. The motor is
controlled separately with two extra wires, one
for on/off and one for speed. This means that
this lidar can also work in one-dimensional
mode when the motor is not turning.

I connected the serial port and the motor


connections to an ESP32 Pico Kit (Figure 3).
To save power, I only used the lidar motor on
its lowest speed, which is about 400 rpm. The
lidar then consumes approximately 400 mA.
Figure 3: The ESP32 Pico Kit is used as the brains of the autonomous
Parsing Lidar Data vehicle. The motor drivers and DC-DC converter are generic modules
For programming the ESP32 Pico Kit, I used available online.
the Arduino IDE. After writing a function to
parse the lidar data, I had to check my inter-
pretation of the data. The X4 development
manual is not very clear about how to do this
and specifies two levels of detail. The second
level provides better angle resolution, but
involves many inverse tangent calculations,
which are computationally intensive. There-
fore, I first tried naïve interpretation.

I placed the lidar on a table inside a rectangu-


lar enclosed space and let it scan for a while.
After stopping it, I made it spit out an averaged
360° scan on a serial port as comma-sepa-
rated values (CSV) that I loaded into Excel.
With the radar chart function, I could display
it (Figure 4). The result looked a lot like my Figure 4: Microsoft’s Excel let me quickly check my interpretation of the
rectangle and the distances were correct too, lidar data. The short horizontal line at 400 mm (and the shadow behind
and so I didn’t bother to try to improve the it) is due to my laptop recording the decoded lidar data.
quality by adding inverse tangent calculations.

lektor January & February 2022 37


Figure 5: Bottom view of the vehicle. The motor
assembly and motor driver board were once obtained
from Landzo.com but are no longer available.

Figure 6: Top side of the vehicle showing


the ESP32 Pico Kit and the Lidar.

Build a Little Robot multiple control surfaces (Figure 7). One of degree. This table is then searched for the
As a next step, I built a simple remote-con- these is a gamepad, which was perfect for my 10-degrees-segment that has the highest
trolled cart on which I mounted the lidar. application. It is really easy to use and it let averaged distance (the width or aperture of
The cart has two motorized wheels in the me control the cart with my phone. 10 degrees is a rather arbitrary value). The
center and a stand-off on either end. I glued center degree of this segment is the direc-
ping-pong balls cut in half to the standoffs A Pathfinding Algorithm tion the cart should take. To achieve this, the
to improve sliding behaviour. Everything is My goal was to program the cart so that cart will turn so that the center degree, the
mounted on a sheet of double-sided copper it would drive around all by itself without direction, moves to zero degrees. We now
FR4 PCB material. The wheels with motors, bumping into objects like furniture and things. have a classic control algorithm that tries to
the motor driver board and the power supply, A popular approach is to let the cart run around minimize an “error” (Figure 8).
a 3S 11.1 V Li-Po battery, are mounted on the and back up or steer away when it comes too
bottom side (Figure 5). The ESP32 module close to an object, but this requires the cart to First Test Run
and the lidar are mounted on the top side make decisions. I wanted something simpler. To my great surprise, on its first run with this
(Figure 6). The plate is grounded and shields There are many examples of simple algorithms simple algorithm the cart managed to move
the ESP32 module from the noisy motors. that result in complex behaviour, for instance through our living room without bumping into
The center of the lidar is in the center of the the way a flock of birds stays together [2], and obstacles (Figure 9). It circled our couch and
mounting plate. The wheel axe too is in the I wanted something like that. passed through narrow passages without diffi-
center. This simple car can spin around and culties. The cart does not have any knowledge
is pretty agile and manoeuvrable. My idea was to make the cart always move of its environment or itself, like its dimensions.
in the direction of the greatest distance as Also, I hadn’t tried to optimize anything. All
Add Remote Control Over reported by the lidar. To avoid making it run parameters like forward- and turning speed
Bluetooth in circles, it only looks forward, in the range and search angle were just set to values that
As a remote control, I used the free and of -90° to +90°. Implementing this rule was I thought might be reasonable.
open-source Dabble library [1], which provides quite easy. For every scan, a table is updated
Bluetooth control for the ESP32 and Arduino with the average distance for each degree. The Bluetooth remote control turned out to be
together with a smartphone app featuring Therefore, the table has 360 entries, one per very handy for confusing the cart or to help

38 January & February 2022 www.elektormagazine.com


Figure 8: The robot cart avoids obstacles
thanks to a simple error-minimizing
control algorithm.

Figure 7: Trying out the Dabble-based smartphone


remote control on the test bench.

Figure 9: Go cart, go! Watch the video


[4] to see how smooth it moves.

it out difficult situations. Also, it can be used


to adjust parameters on the fly. Contributors
Idea, Design, Text and Photographs:
Now, as I am not into optimizing at all, I am more Clemens Valens
a proof-of-concept kind of person, I stopped at Editor: Jens Nickel, C. J. Abate RELATED
this point. If you want to have a play yourself, Layout: Giel Dols PRODUCTS
you can find the links to the code below. There
are many possibilities for improving this design,
> ESP32 Pico Kit (SKU 18423)
www.elektor.com/18423
and it is still a long way from an autonomous Questions or Comments?
vacuum cleaner or lawnmower, but the obtained Do you have technical questions or > YDLIDAR X4 (SKU 18601)
results are very encouraging. The software for comments about this article? Email the www.elektor.com/18601
this project, an Arduino sketch for the ESP32, author at [email protected]
can be donwloaded from [3]. A video is available or contact Elektor at [email protected].
at [4] with a bonus at [5].
210399-01

WEB LINKS
[1] Dabble: https://thestempedia.com/product/dabble/
[2] Flocking behavior: https://en.wikipedia.org/wiki/Flocking_(behavior)
[3] ESP32 Arduino sketch for this project: https://github.com/ClemensAtElektor/Lidar-controlled-autonomous-vehicle/
[4] Watch this project on video: https://youtu.be/BmNelv_gR9Q
[5] Lidar-based parking light by Rob Reynolds from SparkFun: https://youtu.be/KRfidalgJx8

lektor January & February 2022 39


review

The Raspberry Pi Zero 2 W


Goes Quad-Core
By Mathias Claußen (Elektor Lab)

The Raspberry Pi Zero with its ARM11 core is now getting a bit long in the tooth, and its
performance for many applications could be described as marginal.
Fortunately, the Raspberry Pi Foundation fairly recently announced a
much anticipated upgrade, the Raspberry Pi Zero 2 W. What does this
latest Raspberry Pi bring to the table?

Figure 1: The Raspberry Pi Zero W. Figure 2: The Raspberry Pi Zero 2 W.

h a V id e o about the Linux-capable computer, powered by a single-core SoC, which we


Watc Pi Zero 2 W
on
Raspberry Tube
first saw fitted to the original version of the Raspberry Pi 1 (introduced
You five years earlier). The speed of ongoing processor development is
dizzying. From today’s perspective, the 10-year-old ARM11 single-core
processor is looking decidedly elderly, although it still does the job
in many applications. Users have been crying out for a replacement
offering better performance and lower power consumption.
The Raspberry Pi Zero W (Figure 1) is a popular small development
platform costing only around €10. With the necessary peripherals, it In the fall of 2021, the Elektor Lab engineers were lucky enough to get
works as a standalone computer, but it’s small and flexible enough our hands on a pre-release Raspberry Pi Zero 2 W (Figure 2). It was a
for embedded applications such as a media player, camera, or as nice opportunity to see what Eben Upton and the Raspberry Pi team
a simple controller device. When introduced in 2017, it was a small had been working on.

40 January & February 2022 www.elektormagazine.com


Table 1: Specifications
> Broadcom BCM2710A1, 4-core Cortex-A53 (ARMv8)
64-bit SiP @ 1.0GHz
> 512MB LPDDR2 DRAM
> VideoCore IV GPU
> IEEE 802.11.b/g/n Wireless LAN, Bluetooth 4.2/BLE
> 40-pin GPIO-Header
> Mini-HDMI-Port
> Micro-USB 2.0 OTG Port
> CSI-Camera-Port
> Micro-SD-Slot
> Micro-USB Power in (5 V DC/2.5 A)
> Composite Video and Reset-Pin test points

Figure 3: Raspberry Pi Zero 2 W and in the background the Raspberry Pi


Zero W.

A Drop-In Replacement specifications can be found in Table 1. Essentially, the quad-core engine
Nothing has changed about the board’s physical and its connectors. from the (five-year-old) Raspberry Pi 3 A/B+ has been shoehorned into
Figure 3 shows a Raspberry Pi Zero W and a Raspberry Pi Zero 2 W, side the Raspberry Pi Zero form factor and runs with a clock speed of 1 GHz.
by side. All accessories and enclosures for the original Pi Zero can still Anyone hoping for a Raspberry Pi 4-based Zero might feel a tinge of disap-
be used with this new board without any issue. As with the Raspberry Pi pointment but no doubt this will appear sometime in a future upgrade.
Zero W, we have two micro-USB ports, the usual 40-pin connector, and
a mini-HDMI output. One of the two USB ports is again a USB OTG to The Raspberry Pi 3A+ uses a BCM2837B0 clocked at 1.4 GHz. In the
which USB accessories can be connected via an adapter — or with which case of the RP3A0, this uses a BCM2710A1 that in the Zero 2 W is
the Raspberry Pi Zero 2 W itself can become a USB device. As usual, a clocked at 1.0 GHz. The lower clock rate reduces energy consumption
micro SD card is used for booting. A higher read speed smoothens the and heat generation. Further optimizations of the energy consump-
Raspberry Pi Zero 2 W’s operation. Figure 4 shows the underside of the tion for the Raspberry-Pi-3-based systems are in the pipeline, as
board which again has no mounted components. Figure 5 shows the Eben Upton revealed during his interview [1]. The use of a SiP from
topside of the Raspberry Pi Zero 2 W, where we can see the wireless the Raspberry Pi 3 series means that there is already a stable and
chips now have shielding, and the SiP labeled RP3A0-AU is the obvious broad software base available for use on the Zero 2 W. SD card
upgrade. The outline of this new SiP is only slightly larger than the one images for the Raspberry Pi 3 will boot on the Zero 2 W without any
fitted to previous Raspberry Pi Zero models. further tweaking.

The RP3A0-AU SiP Some of the important questions I put to Eben were: How has the power
The RP3A0 label on the SiP indicates ‘RP’ for Raspberry Pi, and ‘3’ for consumption changed? Can I still use my previous power supplies?
the SiP generation (i.e., it has a Raspberry Pi 3 at its core). The exact What new features are available and what about its performance?

Figure 4: A view of the underside of the Raspberry Pi Zero 2 W. Figure 5: The Raspberry Pi Zero 2 W component side.

lektor January & February 2022 41


Smaller and Less Power Hungry though the clock rate is the same as earlier versions of the Zero. In
Low power consumption is a key feature of the Raspberry Pi Zero the Raspberry Pi 3B+, the same processor runs 400 MHz faster.
series. This is achieved using a minimalist approach to the board’s
design and choosing well-established and proven chipsets. Energy The 512-MB RAM also offers ample space for some applications, but
consumption of the Raspberry Pi Zero 2 W is around 2.5 W maximum you can’t expect the Raspberry Pi Zero 2 W to be a replacement for a
with active HDMI output and Wi-Fi link. Most computer USB ports fully-fledged desktop. It gets a bit clunky loading web pages with only
can supply up to 0.5 A at 5 V, which allows the board to be powered 512 MB RAM to play with. For this a Raspberry Pi 4B or Raspberry Pi
from a PC’s USB port without the need for an external mains adapter. 400 would be a better choice and offer significantly more computing
With the desktop idling, it draws around 0.7 W and other operational power; the strengths of the Raspberry Pi Zero 2 W lie in other areas.
modes will reduce the power consumption even more. For comparison,
a Raspberry Pi 3B+ draws around 2 W in idle mode, which is signifi- A Modest But Welcome Upgrade
cantly more. Under load, the Raspberry Pi 3B + clocked at 1.4 GHz This latest Raspberry Pi Zero 2 W is a welcome addition to the Zero
reaches around 4.4 W. family. The SiP from the Raspberry Pi 3 is admittedly already five years
old, but it is a proven platform and represents a significant upgrade
Its compact outline enables the Raspberry Pi Zero to be used in a wide to the Raspberry Pi Zero’s processing power. It enjoys good software
variety of applications, from web radio to mobile game consoles or support and its four-core Raspberry Pi 3 SiP will allow many existing
simple control systems. The new Raspberry Pi Zero 2 W is also ideal software applications to run on the Zero’s more compact board outline
as a server for home assistants; its lower energy consumption means and benefit from its lower power requirements.
that it has less of an impact on the environment than the larger models.
The Zero’s form factor also opens up new possibilities in areas like
2.4 GHz Wi-Fi and Bluetooth automation, retro-gaming, or media players. You will find it to be a
The Raspberry Pi Zero 2 W supports 2.4 GHz Wi-Fi in accordance more economical option for projects where a Raspberry Pi 4 is too
with 802.11 b/g/n. Bluetooth and BLE 4.2 are also provided. Wi-Fi expensive or too power hungry.
in the 5 GHz band is still reserved for its larger siblings such as the 210536-01
Raspberry Pi 4 B or Raspberry Pi 3 B+.

First Boot Contributors


When it comes to booting the original Raspberry Pi Zero W, it’s usually Project and Text: Mathias Claußen
a good opportunity to go and grab a coffee, by the time you get back Editor: Jens Nickel
everything should be stable and ready to go. With the Raspberry Translation: Martin Cooke
Pi Zero 2 W however, the same process takes around 30 seconds Layout: Giel Dols
when loading a current version of Raspberry Pi OS (32 Bit) without
any optimization to the boot loader. The system is then ready for use
just like a Raspberry Pi 3. If you already use an original Raspberry Pi Questions or Comments?
Zero, you will for sure have an OTG adapter (Figure 6) to connect a Do you have any questions or comments about this article? Email
mouse and keyboard. The four cores of the author at [email protected] or contact Elektor at
the Zero 2 W provide a noticeable [email protected].
increase in throughput, even

RELATED PRODUCTS

> IQaudIO Codec Zero – Sound Card for the Raspberry Pi


Zero (SKU 19541)
www.elektor.com/19541
> Retroflag GPi – Game Boy case for the Raspberry Pi
Zero (W) (SKU 19273)
www.elektor.com/19273
> ZeroDock – Prototyping Dock for the Raspberry Pi Zero
(SKU 19760)
www.elektor.com/19760
Figure 6: A USB-OTG adapter.

42 January & February 2022 www.elektormagazine.com


Project Idea: Wi-Fi camera with
motion detection Project Idea: Multimedia Player
One of the most popular add-ons to the Raspberry The Raspberry Pi Zero 2 W is ideally suited for use
Pi Zero is a camera module to make a Wi-Fi as a small media player. Together with the IQaudio
enabled camera. The boot time of the setup is however quite Codec Zero HAT, it becomes a small streaming
long and the CPU quickly reaches its limits when it comes device for audio. Distributions like Volumio are so easy to use,
to motion detection. Live streaming can suffer from dropped everything is optimally supported, since the RPi zero 2 W is
frames and a certain degree of image latency. These effects essentially a Raspberry Pi 3. The MPD (Music Playing Deamon)
are not evident when the same camera and software config- can also be installed on the RPi Zero 2 W and operated on
uration are run on the full size Raspberry Pi 2 and later, more various devices with one of the various front ends. Using it as
powerful, versions. a Wi-Fi stick with Kodi is also not a problem.

The extra processing power of the Raspberry Pi Zero 2 W should


resolve the dropped frames and latency issues and make it
a good compact platform for use as a webcam with motion
detection and live streaming.

Project Idea: USB printer and


scanner server
An old printer can be reborn as a network (in
some cases wirelessly) attached device. Using the
Raspberry Pi’s USB port it’s possible connect the printer to a
network. Depending on the manufacturer and model, this may
require a little configuration work, but the printer can continue
to be operated in its own network with fewer security gaps. This Project Idea: Debugger for the
even applies to scanners and printers that can no longer be RP2040 and other MCUs
used with current Windows or MacOS versions [2]. The option to use a Raspberry Pi as a network-com-
patible debugger is somewhat overlooked in the
CUPS and SANE are the classic representatives for printing documentation from the Raspberry Pi Foundation. While working
and scanning under Linux. A printer sharer can be set up in on the articles for the release of the Raspberry Pi Pico, we carried
connection with Samba. SANEWinDS enables Windows clients out our first experiments with a Raspberry Pi Zero as a Wi-Fi-en-
to access a scanner via the network, so that several computers abled debugger. The setup does require some manual tweaking
can access the scanner. and adjustment of the configuration, but the result is an inexpen-
sive Wi-Fi-enabled debugger, not just for the Raspberry Pi Pico,
The Raspberry Pi Zero 2 W can also be used as a scanner - but also a wide range of Cortex-M MCUs.
using the GPIOs and a few Scripts you will be able to handle
complex processing of documents.

WEB LINKS
[1] M. Claussen, “A Decade of Raspberry Pi: An Interview with Eben Upton,” Elektor Industry 03/2021:
www.elektormagazine.com/210464-01
[2] Web UI frontend for scanner: http://github.com/sbs20/scanservjs
[3] Elektor TV: The Raspberry Pi Zero 2 W

lektor January & February 2022 43


ethics

Notes From
the 2021
World Ethical
Electronics Forum
By Priscilla Haring-Kuipers (The Netherlands)

The first World Ethical Electronics Forum — which took


place online and live at productronica on November 18,
2021 — inspired global innovators in electronics with an
open discussion about ethics and Sustainable Development
Goals (SDGs).

On the November 18, 2021, almost 200 WEEF 2021 Speaker Snapshots > Margot Cooijmans of the Philips
people came together virtually and physi- Let’s take quick look at what some of the Foundation discussed how to provide
cally to be involved in the first World speakers covered at the WEEF 2021 event. health tech to “under serviced regions.”
Ethical Electronics Forum (WEEF), which You can watch all of the WEEF talks online This cannot be done by dumping
was organized by Elektor and Elektronik at Elektor TV [2]. donated tech as this has no lasting
Praxis during productronica 2021 in health effects.
München. Among the speakers and partic- > Professor Dr. Stefan Heinemann
ipants of this industry-driven get- together opened WEEF with his keynote, > Dirk Akemann of SEGGER spoke of a
there was a sense that the time is right to “A Focus on SDGs in Electronics.” In “friendly licensing” approach where
see what we can do to make electronics this excellent talk, he encouraged their products are free to use for
more ethical. In the past decade, more electronic businesses to “do more” private, educational and prototyping
people have been thinking about ethical than the current legislation demands. purposes.
issues in electronics. Many have been He stated that good morals are good
discussing the different facets of our business and not to believe the > Felix Plitzko from AISLER is striv-
industry and applying ethical practices in naysayers. ing to “make hardware less hard” and
their own businesses. Now the time seems promised to make carbon neutral PCB
ripe to share these thoughts and practices > Dr. Paula Palade spoke on how we production available in the future. He
with the industry as a whole and to learn might establish policy around the is currently investigating this together
from each other. design and use of self-driving cars. She with the Frauenhofer institute.[3]
is working on a European project to
F 2021! >
Watch WEE
draft the first guidelines. The Brenner family (Johannes Brenner
and Markus Brenner) joined to talk
> Amir Sherman (Edge Impulse) about how integrating mindfulness at
pointed to the opportunity of using the core of your business, rather than
machine learning in smaller hardware chasing profit, sets you up to take good
to combine real life metrics with care of the people in your organisation.
advanced modelling.

44 January & February www.elektormagazine.com


More WEEF
Of course, we should not be satisfied with talking alone. If we are > Who do you want to be in the WEEF Index?
to be ethical in electronics, we must also take action. This was the > What should be in the WEEF manifesto?
first edition of WEEF, and this is to be a yearly event. The second > What are the important ethical questions in your practice?
WEEF is already planned for November 2022. Between now and
then, we will be working on a WEEF Index featuring most the ethical Please follow the conversation and participate at
people/companies in electronics, as well as a WEEF manifesto. www.elektormagazine.com/weef.
We would love your input on the following questions and more: 210645-01

WEB LINKS
[1] WEEF Webpage: https://www.elektormagazine.com/weef
[2] ElektorTV, “World Ethical Electronics Forum 2021”: https://youtu.be/ELpxR6SuLb8
[3] A
 ISLER, “AISLER Plans to Ship the First World-Wide Carbon Neutral Circuit Board in 2022,” November 18, 2021:
https://www.elektormagazine.com/news/aisler-plans-to-ship-first-world-wide-carbon-neutral-circuit-board-in-2022

lektor January & February 2022 45


ELEKTOR INDUSTRY

M t r Control M M

How the Complexity of Motor Control Is Simplified

Mounted centrally is an armature on a rotor


shaft featuring the windings. These connect
Motor to a commutator on the rotor shaft. Carbon
Control brushes, typically part of the cap fitted to
the stator’s can, enable electrical energy to

M
By Stuart Cording (Elektor) be applied to the windings (Figure 1). The
position of the commutator on the shaft
The electric motor continuously reinvents is critical for ensuring optimal efficiency.
itself to meet new application requirements Ideally, the commutator-brush position,
from electronic toys and home appliances to known as the commutating plane, must
enable the magnetic field generated by the
power tools and electric vehicles. However, rotor windings to be at right angles to the
equally important are the diverse range of stator’s magnetic field. However, during
electronic control solutions that go hand- operation, this plane moves due to distor-
tions in the stator’s magnetic field. For
in-hand with the motor to meet the needs simplicity, a commutating plane is selec-
of such applications. Integration has been ted that provides the highest efficiency at
key, ensuring that the full performance of a specific rotation speed.
the motor can be attained. In the 1970s, the With the motor’s commutation solved
integrated H-bridge revolutionized home mechanically, only speed and direction of
electronics, such as video cassette recorders. rotation need to be implemented electrically.
If only speed adjustment is required, a pulse-
Today, highly optimized microcontrollers with width modulated (PWM) signal together
dedicated motor-control capabilities ensure with a suitably dimensioned power device,
efficient operation using brushless motors. such as a MOSFET, is all that is required
(Figure 2). Most microcontrollers (MCU) also
feature a timer block that, once configured,
can generate a PWM signal without regular
interaction from the processor. An N-chan-
Small permanent magnet brushed DC view, even if they are not the most efficient nel MOSFET as a low-side switch is preferred
motors are found almost everywhere. option on the market. Such motors remain in such cases, as the gate can typically be
Often termed fractional horsepower (FHP) in regular use except for applications requi- driven directly in low-power applications.
motors, the majority sold provide motion ring continuous operation, such as pumps Should high-side switching be needed, an
control in automotive and home appli- and fans, that have moved to more efficient N-channel MOSFET must be used together
ances. Thanks to the increase in comfort brushless motor technology. with a MOSFET driver to generate the requi-
features, cars have augmented their electric red gate voltage [1].
motor-powered features beyond windscreen Controlling Basic Brushed DC
wipers and fans to include electric mirrors, Motors Monitoring Speed and
window openers and sunroofs, doors, and Simple permanent magnet DC motors Controlling Direction
adjustable seats. The DC motors used are construct their stator from a can within For speed control, the control loop used
simple to control, from an electrical point of which typically two magnets are found. requires the current rotation speed of

46 January & February www.elektormagazine.com


M

the motor shaft. One approach is to use a


sensor, such as an optical detector, together
with a slotted wheel attached to the rotor. In
a digital control system, the period between
signals from the optical detector can be
converted into motor rotations per minute
(RPM). Most MCUs also have an input block
that can capture timer values on a signal’s
rising and falling edge. Their resolution
depends on the clock speed of the timer and
should be high enough to provide usable
data at the highest rotation speeds. The Figure 1: The component parts of a fractional horsepower DC motor. The commutator is clear to
see on the rotor shaft by the armature coils. (Source: ShutterStock/Pixel Enforcer)
output of this block feeds into a propor-
tional-integral-derivative (PID) control
algorithm [2] that modifies the mark-space
ratio of the PWM to maintain the setpoint
for the motor’s speed (Figure 3).

Such rotor-mounted sensors often prove


to be too expensive for the application
being built. Instead, the back-EMF of the
motor, which is proportional to its speed,
can be used and offers more than enough
accuracy for most applications. During
the phases of the PWM control where the Figure 2: PWM generator based upon an operational amplifier.
power switch is off, the back-EMF can be
measured directly at the motor’s terminals.
Since most microcontrollers also feature an
analog-to-digital converter (ADC), this is
typically very economical. Hardware imple-
mentation of this approach only requires
a couple of resistors to limit the voltage to
the input range of the ADC. More complex
is the software implementation. The ADC
measurement has to be synchronized
with the shutting-off of the MOSFET and
requires an additional short delay to allow
Figure 3: Output from a sensor attached to the motor’s rotor can be used to capture timer values.
the voltage to settle (Figure 4). For MCUs
These are combined with the speed setpoint and passed to the PID to regulate motor speed. (Source:
designed with motor control in mind, there Microchip Technology)
will probably be a hardware link that can
be established between the PWM output 1.00 m
s/ Auto 2 1.06 V
and ADC trigger, as well as a delay block, Spike Vbemf = Vcc -Vs
allowing this measurement approach to
Vcc = 5.0 V Vbemf = 0.7 V
be automated.
Motor
Terminal Vs = 4.3 V
With the elements for motor speed control
in place, all that remains is to handle
the direction of rotation. The H-bridge
PWM
(Figure 5) uses four power switches that Output
allow the polarity of the supply applied to
the motor terminals to be swapped (either
Q2 and Q3, or Q1 and Q4). Shorting the
motor terminals via the upper or lower Figure 4: After the MOSFET switches off, a small spike appears at the motor’s terminals. ADC measurements
pair of switches can be used as an electrical must wait until the back-EMF has achieved a steady-state. (Source: Precision Microdrives)

lektor January & February 2022 47


ELEKTOR INDUSTRY

brake to slow the rotor speed. Speed control ters. These provide feedback on shorts to tely, such MCUs are not well known for their
is again implemented using a PWM signal the supply or ground, open load conditions, math performance. This makes it tricky to
to one or both MOSFETs. However, it should or undervoltage. If desired, speed and direc- implement a PID controller that responds
be noted that there is potential for a short tional control can be switched to control promptly to changes in the speed setpoint
circuit if both high- and low-side MOSFETs via SPI rather than the direction and PWM or load variations. To tackle this, some PIC
are engaged simultaneously. input pins. The risk of an unintentional MCUs feature an integrated PID accelerator
short circuit of the H-bridge is thus elimi- block (Figure 6) with a 35-bit accumula-
Most major silicon vendors offer highly nated, and further protection features, such tor, such as Microchip’s PIC16F1619. Using
integrated H-bridge solutions, simplifying as over-temperature and overcurrent, are the standard s-domain PID controller
its use and offering a host of protection included. Those looking to quickly proto- equation, three constants — K1, K2, and
features and diagnostics. The IFX9201SG type a design can acquire the H-Bridge Kit K3 — are written to the module’s registers
[3] from Infineon is one such device, targe- 2Go [4] that integrates with Infineon’s DAVE before writing the desired setpoint and
ting currents of up to 6 A for motor control software development environment. engaging the PID calculation module. The
in industrial applications. The device can be PID module reduces the number of clock
controlled using general-purpose I/Os and Optimizing the PID Controller cycles required to 9 from around 1,000 for
a PWM signal, allowing motor speed and The selection of an MCU that meets the a software PID on the same MCU [5].
direction control. In parallel, an SPI inter- desired price point for the application can
face provides access to the diagnostic regis- often result in an 8-bit device. Unfortuna- The Advantages of BLDC and
PMSM
While the simplicity of FHP DC motors
is attractive, increasingly other design
factors, such as efficiency, acoustic noise,
and increased power density are pushing
applications towards brushless DC (BLDC)
motors and permanent magnet synchro-
nous motors (PMSM). When driven
optimally, BLDC and PMSM are much more
efficient and, with their electrical windings
in the stator, heat dissipation is simpler.

BLDC and PMSM motors can be thought


Figure 5: H-bridge circuit with table describing how switch operation controls direction. Shorting the of as inside-out FHP DC motors. The coils
motor terminals is also possible to implement an electrical brake. (Source: Microchip Technology) used for commutation are wound onto

PIDxSET PIDxK1

Kd
Difference Z0 Multiplier
K1 = K + K T +
p i
T
PIDxIIN
2Kd
PIDxK2 K2 = -K -
+ +
p T
+ +
PIDxZ1 Multiplier Adder Accumulator PIDxOUT
Kd
+
K3 =
PIDxK3 T

PIDxZ2 Multiplier
210523-006-94 KD

Figure 6: The PID block from the PIC16F1619 together with the equations to calculate the three standard constants used. (Source: Microchip Technology)

48 January & February www.elektormagazine.com


M

the stator, the motor’s housing, while the


magnet is wrapped around the rotor. This
makes for light rotors with little inertia.
However, there are no mechanics for imple-
menting the commutation, which leaves
this task to the development engineer. The
key difference between the two motor types
is that BLDC motors generate trapezoidal
back-EMF and have simpler commutation
demands than PMSM motors, which use
a sinusoidal commutation and generate
a sinusoidal back-EMF. PMSM motors are
also quieter in operation.

The windings are typically implemented in


a star formation. Six half-bridges are then
required to energize the coils of a BLDC
motor in a six-step pattern that applies Figure 7: BLDC motor with star formation windings and the commutation steps for a
power to two of the three (Figure 7). A single electrical rotation. Mechanical rotation may require several electrical rotations.
(Source: Microchip Technology)
magnetic field results that rotates around
the stator, a field that the rotor simply has
to follow and results in the desired mecha-
nical rotation. Reversing the order of the
commutation pattern causes the rotor to
change direction. While this simple model
of BLDC functionality makes operation
clear, in reality motors are typically wound
in a manner that requires several electrical
rotations before a full mechanical rotation
is achieved.

Sensorless Determination of
Rotor Angle
The next challenge is determining the
position of the rotor to ensure the next
commutation point is output at the correct
moment in time. Many BLDC motors integ- Figure 8: The back-EMF from the open phase can be measured and used to determine
angular rotation, avoiding the need for a Hall or other sensor. (Source: Microchip
rate Hall sensors that indicate the rotor Technology)
angle to a reasonable level of accuracy. The
rising and falling edges of such sensors can
be linked to many MCUs with edge-trigge-
red interrupts, allowing the correct drive of As already stated, sensors add to the cost of While the theory seems simple, the practi-
the motor coils to be implemented simply the bill-of-materials and there may simply cal implementation is exceptionally
in interrupt routines. Such signals can be no place to accommodate them. Like challenging. Firstly, motors do not generate
also be captured into a timer/counter to brushed DC motors, BLDC motors also back-EMF at a standstill, requiring an appro-
determine the rotational speed and feed generate back-EMF. However, in these ach for spinning them up to a speed where
the input of a PID controller. Motor speed devices, this signal can be used to deter- an algorithm has enough back-EMF signal
is also controlled using PWM outputs. So, mine rotor position. As the back-EMF of to measure. Next, the code required to
while the commutation of such motors the undriven phase crosses the zero-cross evaluate the back-EMF data and apply filte-
falls upon the shoulders of the responsible threshold (half of the current supply ring can have a significant execution time.
development engineer, the approach is not voltage), the rotor angle can be determined This can mean switching between different
that different from using their brushed DC by measuring the time between these algorithms and commutation approaches
counterparts. zero-crossing events (Figure 8). as the motor changes between lower and

lektor January & February 2022 49


ELEKTOR INDUSTRY

Software Hardware Conventional


MCU
Software Hardware (Vector Engine) Hardware Toshiba MCU

Speed Control Current Control


Vd
ref Idref + Coordinate Space
+ PI Trans-
PI - formation
Vector PWM PWM
Inverter PM
- + Trans- Correction Generator motor
PI (Fixed
formation
Iqref - Vq
Coordinates)

1 Shunt
Trigger Trigger
Phase SIN sin Generator
0 Generation
Timer COS cos

= + *T
PWM

Ia
Id Coordinate
Trans- 3 Phase Input AD Ib
Calculation formation 2 Phase Correction Converter
n (Rotating Conversion Ic
Iq Coordinates)
Angular Velocity Estimation 210562-009-94 KD

Figure 9: Highly integrated motor control modules, such as Toshiba’s Advanced Vector Engine Plus, enable quasi-autonomous permanent magnet motor
control. (Source: Toshiba Electronics Europe)

higher speeds. Suppliers of intelligent BLDC module that is tightly coupled with the
motor control solutions have solved many PWM and ADC modules (Figure 9). Inside
of these issues, enabling a new motor to be the A-VE+ module, the complete three-
attached and ‘learned’ by attaching it to a With so much phase to two-phase and reverse Clarke/
motor controller with little input required Park transformations are implemented
from the design engineer. complexity, leaders in hardware, requiring only a PI control-
in motor control are ler and angular velocity estimation in
Implementing Sinusoidal Motor software and some housekeeping. The rest
Control focusing on simplifying of the time, the modules operate together
PMSM motor control algorithms have their solutions so quasi-autonomously.
an additional layer of complexity. These
demand that the PWMs of the MCU are that developers can Driving Innovation in Motor
modulated continuously to generate concentrate on creating Control
a sinusoidal output that energizes the With so much complexity, leaders in motor
motor windings. Such control approaches differentiating features control are focusing on simplifying their
use field-oriented control (FOC), using the in their applications. solutions so that developers can concen-
three-phase windings’ currents to deter- trate on creating differentiating features
mine the current rotor angle. Using Clarke/ in their applications. According to Jonas
Park transformations, this control method P. Proeger, Director Business Manage-
aims to maintain a 90° angle between the ment at Trinamic, now part of Analog
rotor and stator magnetic fields at all times, manufacturers have developed dedicated Devices (Figure 10), the core themes they
thus achieving maximum torque at all hardware modules that automate much see revolve around improving efficiency,
times. of the complexity. One family of devices reducing noise, and increasing intelligence.
are the TXZ4A+ MCUs from Toshiba [6]. Efficiency improvements are needed to
While such complexity can be imple- These Arm® Cortex®-M4 devices feature support the growing raft of battery-operated
mented in software on some MCUs, many an Advanced Vector Engine Plus (A-VE+) autonomous vehicles, such as Autonomous

50 January & February www.elektormagazine.com


M

Questions or Comments?
bipolar stepper motor [8]. The resultant Do you have technical questions or
reduction in ripple current also lowers the comments about this article? Email the
power dissipation in the motor. The final author at [email protected].
growth area is in intelligent motors, where
industrial installations require ‘self-aware’
motors. Such motor solutions contribute Contributors
to the growing use of artificial intelligence Design and text: Stuart Cording
at the system level by delivering real-time Editing: C. J. Abate
data from the very edge of the factory floor. Illustrations: Patrick Wielders
Layout: Giel Dols, Harmen Heida
Power Is Nothing Without
Control
It is easy to develop the perception that
Figure 10: Jonas P. Proeger, Director Business everything is moving to BLDC and PMSM
Management at Trinamic, now part of Analog
motors. However, this is not the case.
Devices. (Source: Analog Devices)
There remain plenty of applications
where traditional FHP DC motors remain
fit for purpose. And, with the wealth of
H-bridge motor drivers and low-end MCUs
Mobile Robots (AMR), used in logistics. with clever peripherals on offer, it is clear
The motors used are also changing, with that the semiconductor industry still sees
higher power densities and weight savings plenty of potential too. However, as appli-
resulting in lower inductance motors. As a cations target ever-higher efficiencies,
result, the motor control algorithms have move to battery operation, or require close
to change with the control loops opera- to silent operation, engineers will need to
ting at up to 100 kHz. Devices such as their get to grips with BLDC and PMSM. While
TMC4671 [7] achieve this using dedicated many of the techniques used to control
hardware, displacing alternative approa- DC motors still apply, there are plenty of
ches requiring DSP or FPGA performance. pitfalls surrounding the finer aspects of
the controller implementation. A sound
Silent operation is another growing requi- basis in the theory remains helpful and
rement, offering a perception of higher enables motor control solutions to be
quality compared to alternative products debugged. But, to save time, it makes sense
RELATED
with their grinding motors and gearboxes. to draw upon the experience of experts in
PRODUCTS
Here Jonas highlights their stealthChop this dynamic field and review the highly
technology that uses a voltage-control- integrated silicon solutions the market > E-book: Power Electronics in Motor
led chopping technique to reduce audible has to offer. Drives (SKU 18517)
noise by up to 10 dB in conjunction with a 210562-01 www.elektor.com/18517

WEBLINKS
[1] C. Valens, “How to Choose Between High-side and Low-side Switching,” Elektor, August 2019: https://bit.ly/3H38uA5
[2] “Understanding PID Control, Part 1: What Is PID Control?,” The MathWorks, Inc., May 2018: https://bit.ly/3CZfcor
[3] Infineon IFX9201SG Product Page: https://bit.ly/3CZfEmD
[4] Infineon H-Bridge Kit 2GO Product Page: https://bit.ly/3ww91FZ
[5] D. Hou, “PID Control on PIC16F161X by using a PID Peripheral,” Microchip Technology Inc., 2015: https://bit.ly/3DbGCHy
[6] Toshiba TXZ4A+ Series MCUs: https://bit.ly/3bXUSId
[7] Trinamic TMC4671 Product Page: https://bit.ly/3bWO2CA
[8] B. Dwersteg, “stealthChop Performance (qualitative),” TRINAMIC Motion Control GmbH & Co. KG, February 2018:
https://bit.ly/3CZgxvt

lektor January & February 2022 51


background

Large
Electric Motors
Basic Principles and
Useful Information

Motor
Control
By Dr Thomas Scherer (Elektor)

Electric motors come in all shapes and sizes and have found use in a vast range of
applications for many decades. With the foreseeable widespread replacement of internal
combustion engines by electric drive trains in vehicles, electric motors will soon be seen as
the primary way to create mechanical motion. That alone makes them worth a closer look.

Electric motors can be found wherever electrical energy is to be Motor Types and Some Rules of Thumb
turned into mechanical energy of whatever kind. They have many As mentioned above, this article will not look a lower-power motors,
advantages over internal combustion engines and other non-elec- in particular the types of motor (shaded-pole, capacitor-run, stepper
trical methods for producing mechanical energy such as water and servo motors) that are commonest at lower power levels. We
mills and windmills. Principal among these are small footprint, will also not consider linear motors, although they are commonly
low weight, long service life and high efficiency. In larger machines, used in hard disk drives for head positioning, and, at rather higher
efficiency can be considerably more than 90%. The tiniest examples power, in other types of actuator. High-power linear motors (in the
can be found in luxury non-mechanical watches. At power levels up megawatt range) are also outside our scope: their military appli-
to 100 W, we find the conventional ‘universal’ motors, and special cations (e.g., in railguns) to accelerate projectiles require highly
variants such as stepper motors, servos, shaded-pole motors, small specific drive techniques, and we will not delve into this exotic
synchronous and induction motors and the increasingly popular subject.
brushless DC (BLDC) motors are widely found. An article by Mathias
Claussen elsewhere in this issue of Elektor [1] describes how to drive Instead we will confine ourselves to the four types of motor listed in
smaller motors, and my article from three years ago [2] discusses Table 1. In practice these cover more than 90% of application cases
motor drive techniques in general. Below we will be concentrating at power levels from under 1 kW to tens or hundreds of megawatts.
primarily on the principles behind the larger motors increasingly In principle each motor type could equally well be made in small or
found not just in appliances (e.g., vacuum cleaners and washing large versions, but because of their different electrical and mechan-
machines), but also in electric vehicles and, most importantly, in ical characteristics, each is differently suited to particular appli-
industry (e.g., in machine tools). cation areas, with considerable differences between each type.

52 January & February 2022 www.elektormagazine.com


Table 1: Types of larger electric motors.
Type Characteristics
A mechanical commutator creates an alternating field; many variants, series-wound and shunt-
Universal motor
wound; high start-up torque.
Passive rotor (no slip rings); rotor slips behind stator field; protection against high inrush current
Three-phase induction motor
(star-delta switching or variable frequency drive) required.
Permanent or electric excitation field required; rotor moves synchronously with rotating field; can
Three-phase synchronous
use variable frequency drive; can be operated as a generator; can be configured with internal or
motor
external poles.
Variant of synchronous motor with electronic commutation; suitable for drive trains; very reliable;
BLDC motor
permanent magnets often used in low- to medium-power applications.

It is interesting to see what myths about electric motors still circu-


late among engineers not specialized in the field. For example, take
the excessively idealized proposition that at start-up (that is, at a Figure 1: Principle of operation
speed of 0 rpm) electric motors would in theory have an ‘infinite’ and construction of a simple
permanently-excited electric
torque. The ‘in theory’ part is where it goes wrong: in the absence motor. At the top of the stator
of extreme current, extreme magnetic fields, negligible winding is the north pole and at the
resistances, hyper-stable metals and pie-in-the-sky drive electron- bottom the south pole. The
ics, such a thing is impossible. Back down on Earth, all these param- rotor is an electromagnet
eters have their practical limits; all we are left with from the myth which is powered via a
commutator made from a
is the rule of thumb that (most types of) electric motors can indeed slip ring and carbon brushes.
offer a high starting torque if their drive circuit and power supply (Image credit: Michael Frey,
are suitably designed. In electric vehicles this characteristic has CC 3.0 [3])
the advantage, compared to internal combustion engines, that a
multi-ratio gearbox (be it manual or automatic) can in general be
dispensed with. That improves the reliability and simplicity of
the drive train and reduces its weight: this last aspect is import-
ant even though the savings are more than offset by the weight of
a large battery pack.
difference is 0 V then the maximum possible rotational speed has
A further rule of thumb will come in useful for anyone not famil- been achieved: the tiny residual current that flows is just enough
iar with the subject: in an electric motor the correlation between to compensate for friction losses.
torque and operating current at a given load is highly linear, because
the current that flows is proportional to the magnetic field gener- Principles of Operation
ated in the windings; this is proportional to the resulting magnetic The historically earliest, and indeed the simplest, form of motor is
attractive or repulsive force, which in turn correlates with torque. the permanent magnet motor shown in Figure 1. The rotor consists
of an electromagnet mounted on a bearing so that it can turn. The
And another, somewhat more rough-and-ready, rule of thumb is black dot in the middle represents the axis of rotation and the
that the maximum possible unloaded rotation speed (ignoring grey ring the bearing. The applied DC voltage is passed through
mechanical considerations) depends on the power supply voltage. a commutator comprising a slip-ring with copper contacts and
Why? When an electric motor is turning it creates what is called a brushes made of carbon. The polarity of the voltage applied to
‘back EMF’ which, ignoring construction aspects, is broadly propor- the electromagnet, and hence of the magnetic field, thus depends
tional to rotational speed. The term ‘EMF’ (electromotive force) was on the position of the rotor. If the polarity of the applied voltage
historically used to describe a voltage generated by a motor; by ‘back is reversed, the direction of rotation will also reverse. It is also
EMF’ we mean a voltage induced by the rotation of a motor which clear that this type of motor can act as a generator if its rotor is
tends to oppose the voltage from its power supply. If we neglect mechanically driven: in this case a pulsed DC signal will appear
inductances and losses, the resulting effective voltage across the at its connections. If the commutator is dispensed with then the
motor’s windings is the difference between the applied voltage and machine becomes an AC generator; and by applying an AC voltage
the back EMF. The resulting current depends almost exclusively we have a single-phase synchronous motor design which, however,
on this difference and the ohmic resistance of the windings. If this is not really practical because it has problems starting up.

lektor January & February 2022 53


Figure 2: Idealized behaviour of
torque as a function of rotational
speed for various types of electric
motors, compared to three types
of internal combustion engines.
(Image credit: Dr. Thomas Scherer)

From this simple motor design we can derive practically all other become not only costly, but also very large and heavy. In the classical
motor types. If the permanent magnet of the stator is replaced by universal motor the field winding in the stator is connected in series
a winding (creating another electromagnet) then the resulting with the rotor winding, forming what is known as a series-wound
design is known as a ‘universal’ motor. If the motor is equipped motor. The main advantage of the series-wound universal motor
with multiple phases, then we can build induction, synchronous over the less widely used shunt-wound motor (not illustrated),
and BLDC motors which employ an electrically-generated rotat- where the stator winding is connected in parallel with the rotor
ing field. The simple motor has poor coasting properties when no winding, is that it has a very high starting torque.
voltage is applied, since the field lines of the permanent magnets
always give rise to a braking effect. Separately excited motors exhibit Both variants can be operated either from DC or AC supplies.
this problem to a lesser degree. Designs optimized for AC operation at high rotational speeds
use a core for the stator and rotor consisting of a stack of metal
The various principal characteristics of these motor types are sheets isolated from one another in order to reduce losses due to
shown (in idealized form) in Figure 2, including a comparison with eddy currents and hysteresis. Changing the polarity of the applied
current designs for internal combustion engines. The contrasting voltage during operation does not affect the direction of rotation in
behaviours of torque as a function of rotational speed are particu- either design. To achieve this, it is necessary to reverse the polar-
larly noteworthy. This comparison is far from exhaustive, and all the ity of either the stator winding or the rotor winding, but not both
various characteristics have a significant influence on the suitabil- simultaneously.
ity of various types of motor in different application scenarios.
Larger universal motors (in the kilowatt range) have a high starting
The Universal Motor current, and so, in order to protect the motor itself (and to prevent
Figure 3 shows the universal motor, invented over 117 years ago, its fuses from blowing!) a start-up controller is used. In the simplest
which is the closest design variant to the simple motor shown in case this initially powers the motor via a series resistor to reduce
Figure 1. Here we simply replace the permanent magnet by a further the inrush current. After a short period of time, or when a certain
winding which acts as an electromagnet. The advantages of the rotational speed is reached, power is applied directly to the motor
universal motor show themselves most in high power designs, connections. Not only must the value of the series resistor be chosen
where the permanent magnets required in the simpler design according to the particular operating conditions, but also its load
rating must be sufficient to cope with the integral of the current
curve over the start-up period. The required start-up resistor can
end up being rather physically large, and special constructions, or
even devices such as liquid rheostats, can be used. For very large
Figure 3: Principle of operation universal motors a single resistor is not sufficient: instead, several
and construction of a universal resistors are used in series. As the rotational speed reaches a series
motor, where the permanent of thresholds, these resistors are short-circuited one by one. The
magnet of a simple motor is
replaced by an electromagnet.
simplest form of start-up protection controller is the time delay
(Modifications from Figure 1: shown in Figure 4. More intelligent approaches measure the
Dr. Thomas Scherer) rotational speed, shorting the protection resistors as required,
possibly in conjunction with slowly raising the operating voltage
gradually using an electronic controller.

54 January & February 2022 www.elektormagazine.com


Figure 4: Simple start-up
protection circuit using a series
resistor to limit inrush current.
As mentioned above, universal motors can be run from an AC or
a DC power supply. The rotational speed when loaded and under
no-load conditions depends on the construction of the motor and
the applied voltage. The output power under load and rotational
speed can can therefore be controlled using a PWM drive. If such
a PWM drive circuit is already available, then it is easy to use it in
conjunction with the existing microcontroller that controls it to
provide start-up protection. This can be done by starting opera-
tion using a PWM signal with a very low mark-space ratio, and
then increasing it gradually. If the motor should be stalled because
of an excessive load, or even in the case of simple overload, it is
possible for very high and potentially destructive currents to flow.
It is therefore recommended to monitor not just the rotational
speed of the motor but also the drive current, especially for larger
motors. In simple cases this latter protection can take the form of a
thermal overcurrent cutout. If the speed falls below the minimum
threshold or if the current exceeds an upper limit then the motor is
switched off, protecting the motor itself, its drive electronics, and
any machinery that it is powering. Such protection has the advan-
tage over simply blowing a fuse that power will not be interrupted
to other machines on the same supply lines.

As the name implies, universal motors are used in a wide range


Figure 5: Rotor of a typical single-phase universal motor. The
of applications from household appliances, drills and other tools number of contacts on the commutator corresponds to the
starting from under 100 W to motors in electric locomotives and windings and to the number of poles. (Image credit: Sebastian
EMUs rated in the megawatts, powered from either DC or AC. Stabinger, CC 3.0 [4])

The simple variant shown in Figure 3 suffers from uneven torque


as a function of rotational position. More sophisticated designs
are therefore naturally the rule. Single-phase multiple-pole
designs with a variety of different stator and rotor constructions
are common (see Figure 5) with various kinds of compensation
windings which affect not just the torque behaviour but also the Figure 6: Diagram of the
amount of brush sparking. In turn, this also affects the reliability of construction of a three-phase
the commutator and other properties. Looking at the relationship induction motor (internal rotor).
between torque and rotational speed in Figure 2, we can see that The rotor consists of a ‘squirrel
cage’ with short-circuited
at a given voltage the speed varies with the load. To stabilize the
windings. (Image credit: Dr.
speed an active control loop is required, along with a speed sensor. Thomas Scherer)

The Induction Motor


The induction motor, whose basic construction is illustrated in
Figure 6, has some decisive advantages in comparison to the
universal motor. The most important of these is the complete
absence of a commutator: apart from the bearings the design is
wear-free and hence extremely reliable. Larger induction motors
are almost invariably three-phase designs, and multi-pole designs Figure 7: Cut-away
of this type give a steady torque over each rotation. The popular induction motor rated
in the low kilowatts.
internal rotor design, as pictured, uses the rotating magnetic field
The stator windings
of the stator: under load, the rotor turns slightly slower then the and the short-
stator field and this induces a current in its windings, and hence circuited rotor can
also a magnetic field. The corresponding back EMF in turn induces easily be seen. (Image
an increased current flow in the rotor winding: hence the term credit: S. J. de Waard,
CC 3.0 [5])
‘induction motor’. Figure 7 shows a cut-away induction motor
rated in the low kilowatts. The number of poles in the design deter-
mines the nominal rotational speed of the motor: doubling the

lektor January & February 2022 55


and the amount of slip depends on the load, but is nevertheless
closely coupled to the speed of rotation of the field (and hence the
frequency of the AC supply). As the load on the motor is increased
Figure 8: A small variable
frequency drive for
a threshold is eventually reached after which the torque falls off
induction motors rated sharply. The motor then stalls and the current rapidly increases.
at a few kilowatts. This The usable range of rotational speeds can be adjusted (either higher
electronic switching or lower) over a considerable range by powering it via a variable
circuit allows the frequency drive (see Figure 8). Such drives are particularly popular
rotational speed to be
set. Larger versions are
in industrial machines.
also available, offering
more advanced functions. Larger induction motors require a high current at start-up: up to
(Image credit: C. J. Cowie, a factor of 10 more than the nominal current during operation.
CC 3.0 [6]) There are various ways to reduce the inrush current. In simpler
cases, up to say 11 kW, a star-delta switch (Figure 9) is used: the
current, and hence power draw, in the star wiring configuration is
one third of that in the delta configuration. The switchover from
star to delta configuration is typically made once the motor has
reached at least 75 % of its rated speed. Care must be taken that
the load is not too great during the start-up period so that the stall
torque threshold is not reached. When using a variable frequency
drive this precaution is not necessary as the drive frequency and
hence the speed can be increased gradually at start-up.

Because of their extreme robustness and high efficiency this


kind of motor can be found in machines of all kinds in industrial
production as well as in electric vehicle drive trains. Tesla uses
compact high-speed induction motors with a reduction gearbox
in their current models, achieving the required very wide range
of rotational speeds using a clever motor control system combin-
ing current and speed monitoring circuits. The use of electronic
Figure 9: Star-delta protection switching. This offers a simple way to control by and large overcomes the most significant disadvantage
prevent large inrush currents at motor start-up.
of the motor, that the speed is closely coupled to the frequency of
the AC supply. If the rotor is turning faster than the rotating stator
field, then the induction motor functions as a generator: this can
allow for energy recovery which is important both in vehicles and
number of poles halves the motor speed at a given frequency of in fixed machines.
the three-phase supply.
Synchronous and BLDC Motors
As can be seen from the plot in Figure 2, the induction motor has Essentially a synchronous motor is a universal motor operated from
a very steep torque curve and the rotor always rotates at just under a three-phase supply. In one popular design the rotor winding is
the rotation rate of the applied field. This is known as ‘slipping’, supplied via separate slip rings: in contrast to the universal motor
a commutator is not required and so the rings are unbroken and
hence friction is reduced. Figure 10 shows one design; it is also
possible to fit permanent magnets to the rotor, removing the
need for slip rings entirely. For larger fixed motors the separately
excited design illustrated is more economical and more reliable
Figure 10: Diagram of the from a thermal point of view: permanent magnets can easily be
construction of a simple three-
damaged by even brief exposure to high temperatures. There are
phase synchronous motor. The
rotor can instead be fitted with also designs with an external rotor, where the interior part is fixed
permanent magnets to avoid and the external rotor is fitted with permanent magnets, obviating
the need for a commutator. the need for slip rings. These types have a long service life and are
(Image credit: Dr. Thomas maintenance-free. As can be seen from the plot of torque against
Scherer)
rotational speed, the speed remains constant and is rigidly coupled
to the speed of the rotating field. The rotor does not slip under load;
instead, it lags by a phase angle relative to the rotating field by an

56 January & February 2022 www.elektormagazine.com


Figure 11: Principle of electronic commutation for a BLDC motor. Figure 12: Stator of a 2 kW BLDC wheel hub motor with external
Each half-bridge driver receives a pair of complementary drive rotor. The four-pole windings and laminations can easily be seen, as
signals with an appropriate phase delay. can the location of the Hall effect sensors used to detect the angular
position of the rotor. (Image credit: Dr. Thomas Scherer)

amount that depends on the load. Like the other types, this kind The torque-versus-speed characteristic is also superior. If a PWM
of motor can be operated as a generator. Synchronous motors are controller is added, the no-load rotational speed can be adjusted by
made with multiple poles to give a more steady torque over each changing the mark-space ratio of the control signals. If the PWM
rotation; here also the number of poles is inversely proportional signal is regulated using the supply current as a reference signal,
to rotational speed. the current will correlate very linearly with torque at a given load
and speed.
The big advantage of the synchronous motor is hinted at by its
name: it is possible to achieve very precise, constant and load-in- Both types of motor, over a wide range of power ratings, are used in
dependent rotational speed without a controller. Since, unlike in fixed machines. BLDC motors are in general better suited to vehicle
a universal motor, the slip rings are unbroken and the excitation drive trains because of the possibility of building commutator-free
energy is relatively small, the carbon brushes experience very little solutions and because of the sophisticated degree of control that is
wear. If permanent magnets are used in the rotor then it is possible available. A special variant is the ‘wheel hub motor’ (see Figure 12)
to construct extremely robust motors in small form factors. One which is frequently used in electric bicycles and other low-to-me-
disadvantage is that it can be relatively difficult to start the motor: dium power drive applications. These motors feature an external
for this reason larger synchronous motors sometimes include an rotor assembly, usually fitted with permanent magnets. The large
extra rotor winding that is short-circuited, so that the motor can number of poles results in a low rotational speed and high torque.
be brought up to speed as if it were an induction motor. At start-up Torque is constant as a function of rotational position and reliability
the same protection techniques can (and, in some cases, must) be is excellent. However, for higher-power applications, the necessary
used as in the case of the induction motor, including the protection permanent magnets are both expensive and heavy. A wheel hub
features offered by modern variable frequency drives. motor therefore represents a considerable unsprung mass, which
impairs ride comfort. It is for this reason that electric vehicles more
The rotating field in the stator windings of a synchronous motor can usually employ high-speed and compact induction motors which
be generated by driving the windings from a DC power source using drive the wheels via flexible couplings.
three half-bridge drivers, rather than from a three-phase AC power
supply (see Figure 11). The half-bridge drivers are electronically Moreover...
controlled to create the three-phase waveform, just like in a variable Even though electric motors are in widespread use and seem likely
frequency drive. The result is called a brushless DC (or BLDC) motor. to supersede all other motor technologies, there are still a few things
In this case we need a sensor to detect the angular position of the to be aware of when using them. Today’s electric motor designs
rotor, and we use this information to clock the half-bridge driver are very refined and there does not seem to be scope for further
circuit. This forms a quasi-synchronous motor that autonomously significant innovation. However, there will doubtless be many
creates its own rotating field and whose rotational speed depends evolutionary optimizations: these will come not only from improve-
on the supply voltage and on the load. In contrast to the univer- ments to existing materials and to construction and manufac-
sal motor the construction is straightforward, and if permanent turing technology, but also, most importantly, from intelligent
magnets are used then the motor is practically maintenance-free. electronic control. Power semiconductors are improving all the

lektor January & February 2022 57


Table 2: Top 20 manufacturers of electric motors (as of the market. The total turnover of all electric motor manufactur-
2019) [8]. ers in 2020 was some $150bn [7], and analysts expect the market
to grow at 6% per annum over the coming years. Table 2 lists the
Ranking Manufacturer Country
twenty biggest manufacturers: firms based in the USA dominate,
1 Siemens Germany but the market leader is a German company. If you are looking
2 Toshiba USA for something a little out of the ordinary, you will need more than
3 ABB Switzerland just a knowledge of the basic principles: be prepared to get deeply
involved in the nitty-gritty of the subject!
4 Nidec Motor Japan
210555-01
5 Rockwell Automation USA
6 Ametek USA
7 Regal Beloit USA Contributors
Author: Dr Thomas Scherer
8 Johnson Electric Hong Kong
Editor: Jens Nickel
9 Franklin Electric India Translation: Mark Owen
10 Allied Motion USA Layout: Giel Dols
11 Faulhaber Germany
12 General Electric USA
Questions or Comments?
13 Danaher Motion USA If you have technical questions or comments on this article, feel
14 WEG Brazil free to e-mail the Elektor editorial team at [email protected].
15 maxon motor Switzerland
16 TECO Westinghouse Taiwan
17 Hitachi Japan
18 Lincoln Electric USA RELATED PRODUCTS
19 Piela Electric USA
20 Dumore Corporation USA > SmartPi 2 – Smart Meter for Raspberry Pi (including
three current probes) (SKU 18165)
www.elektor.com/18165
time, becoming faster and more efficient, and computing power is > Current Probe for SmartPi 2 (SKU 18167)
becoming ever cheaper. That means that complex algorithms can be www.elektor.com/18167
implemented, improving the efficiency of the overall combination
of the electromechanical motor and the electronic control system. > PeakTech 4350 Clamp Meter (SKU 18161)
www.elektor.com/18161
In the end the choice of an electric motor for a particular appli-
cation is always a quest for the optimum trade-off among a large
number of factors. Making that choice demands a lot of know-how,
and customers look to the manufacturers of electric motors for
high-quality support and specialist advice. There are hundreds of
such manufacturers, and it is difficult to obtain a clear overview of

WEB LINKS
[1] M. Claussen, ‘Motor Drive using H-Bridges’, Elektor January/February 2022: https://www.elektormagazine.com/210491-01
[2] T. Scherer, ‘Electric Motor Control’, Elektor January/February 2019: https://www.elektormagazine.com/magazine/elektor-70/42362
[3] Simple electric motor: https://commons.wikimedia.org/wiki/File:Animation_einer_Gleichstrommaschine.gif
[4] Rotor of a universal motor: https://commons.wikimedia.org/wiki/File:Kommutator_universalmotor_stab.jpg
[5] Cut-away induction motor: https://commons.wikimedia.org/wiki/File:Rotterdam_Ahoy_Europort_2011_(14).JPG
[6] Variable frequency drive: https://commons.wikimedia.org/wiki/File:Small_variable-frequency_drive.jpg
[7] The market for electric motors: https://www.grandviewresearch.com/industry-analysis/electric-motor-market
[8] Ranking of electric motor manufacturers: https://blog.technavio.com/blog/top-20-electric-motor-companies

58 January & February 2022 www.elektormagazine.com


review

Getting Started with the


ESP32-C3 RISC-V MCU
By Mathias Claußen (Elektor)

Curious about Espressif’s ESP32-C3?


A single-core, cost-effective alternative to
the ESP8266, the ESP32-C3 uses the open
RISC-V instruction set architecture.
Let’s take a look.

The ESP32-C3 from Espressif has been eagerly awaited. It


has just one core humming away at its heart instead of the
usual two cores in ESP32-based controllers. This core,
however, uses the free and open RISC-V instruction set
architecture which competes with ARM-based control-
lers widely used for IoT applications. I recently took a
look at the ESP32-C3 and the ESP32-C3-DevKitC-02 to
see how it performed in the lab. Let’s review what I learned.
Figure 1: The ESP32-C3
Anyone following the me on Twitter (@ElektorMathias) [1] DevKitC-02.
might have noticed a couple of ESP32-C3 DevKits sitting on my
desk. Followers of our Lab Notes in June 2021 [2] will also be aware that
software support for the ESP32-C3 is still a work in progress. The devel-
opment kit under the spotlight in this review is fitted with the revision
2 version of the ESP32-C3 chip. These preliminary versions come with https://raw.githubusercontent.com/espressif/arduino-esp32/
an A4 errata sheet (printed on both sides) listing the problems which gh-pages/package_esp32_dev_index.json
have so far been identified. Which installs the 2.0.0-rc1 version.

Amongst other things, the revision 2 suffers from insomnia — that is, Purchasers of dev kits based on the ESP32-C3 should be supplied
it draws a high level of power in deep sleep mode, and the USB/JTAG with the latest rev.3 version of the chip, as can be read in the forum
serial adapter in the chip doesn’t function. The more recent revision 3 entry at ESP32.com [4]. The preliminary rev.2 buggy version was only
version should have these problems resolved, as I noted on Twitter [3]. fitted to a limited numbers of the first dev kits supplied.

The Espressif ESP-IDF repository supporting the ESP32-C3 is also The ESP32-C3 DevKitC-02
a work in progress and may contain bugs. Since Arduino support is First, we will take a look at the ESP32-C3 and the DevKitC-02 (Figure 1).
based on it, any bugs will migrate onto this platform too. At the time The ESP32-C3 chip is effectively a successor to the Espressif ESP8266
I am writing this article, the Development Release of the Arduino microchip. Like the ESP8266, it also uses a single core processor
Support Package will need to be installed in the Arduino IDE you are which can be clocked at up to 160 MHz and has a 2.4-GHz BGN Wi-Fi
running. To do this, enter the following link under Preference in the communications chip with full TCP/IP stack implementation. But the
Additional Boards Manager URLs: similarities with the ESP8266 end there. The ESP32-C3 includes many

lektor January & February 2022 59


> RISC-V CPU clocked at 160 MHz
> 400 KB SRAM ( 16 KB Flash Cache )
> Integrated 2.4 GHz Wi-Fi (BGN)
> Bluetooth LE 5.0
> Crypto Hardware Accelerator
> 22 programmable GPIOs
> 2 x 12-Bit SAR ADC
> 3 x SPI (supports SPI, Dual SPI, Quad SPI and QPI)
> 2 x UART (supports RS232, RS485 IrDA up to 5 MBd)
> 1 x I2C (up to 800 kbit/s)
> 1 x I2S
> RMT (remote control peripheral devices)
> TWAI (CAN 2.0 b compatible / ISO 11898-1)
> PWM
> Internal USB/JTAG adapter

Figure 2: Block diagram of the ESP32-C3. Table 1: ESP32-C3 specs.

A block diagram of the controller functions is given in Figure 2 and


shows a clear inheritance from the ESP32 device, with a specifi-
cation overview in Table 1. With its 384 kB of RAM, the ESP32-C3
offers almost five times more RAM space than the ESP8266 (80 kB).
The main component which distinguishes the ESP32-C3 from all
other ESP32 or ESP8266 chips is the processor core. While its
predecessors use the Tensilica L106 or LX6/LX7 [5] RISC proces-
sor, the ESP32-C3 has a RISC-V CPU. This means that compilers
and other programs from the RISC-V toolchain can be used with
this core. Improvements to these compilers and the corresponding
tools will thus benefit users of the ESP32-C3. It is not necessary
for the community to set about creating a toolchain as it was when
the ESP8266 was first introduced.

The DevKitC-02A board includes a USB-to-serial converter as well


as a WS2812-compatible RGB LED. A detailed circuit diagram of the
Figure 3: Both sides of the ESP32-C3-DevKitC-02. board can be found at [6]. Figure 3 shows both sides of the board.

A Different Take on Blinky


The WS2812-compatible RGB LED installed on the board is controlled
using a serial communication protocol so that we can’t get away by
more of the peripherals associated with the ESP32 which is Espressif’s just setting an I/O pin to turn the LED on. Fortunately, the Adafruit
successor to the ESP8266. In addition to Wi-Fi, the ESP32-C3 includes NeoPixel library contains routines that work with this type of LED. If
BLE 5.0 and Bluetooth Mesh communications. It also employs the it is not already installed, you can add it to your Arduino IDE in the
useful GPIO matrix, so that almost any function can be assigned to normal way. The code in Listing 1 makes the RGB LED flash red. You
almost any pin. Figure 2 shows the block diagram of the ESP32-C3, don’t need to make any special tweaks to the code for it to run on the
which includes a USB serial/JTAG adapter. ESP32-C3. Uploading the code is just as easy as it is with an ESP32.

60 January & February 2022 www.elektormagazine.com


Thanks to the I/O matrix, WS2812 LEDs can
also be used with other pins. Listing 1: Blinky
/* This sample needs the Adafruit NeoPixel library */
Read the Chip Type and Version #include <Adafruit_NeoPixel.h>
With ESP32 chips, it is possible to read out #define PIN 8
information stored on-chip showing its basic #define NUMPIXELS 1
properties. Listing 2 shows this informa- Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
tion read out via the serial interface running
void setup() {
at 115200 baud (communication at 9600
pixels.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
baud, with chip revision 2 using the built-in
pixels.clear(); // Set all pixel colors to ’off’
USB-to-serial converter outputs garbled
}
characters). Here you will be able to read which
version of the chip is fitted to your ESP32-C3 kit.
void loop() {
When you see the list of known bugs associated
delay(1000); // wait for a second
with revision 2, you will be glad when you can pixels.setPixelColor(0, pixels.Color(255, 0, 0));
confirm the chip version fitted is not affected. pixels.show();
delay(1000); // wait for a second
Porting ESP32 Projects pixels.setPixelColor(0, pixels.Color(0, 0, 0));
Some of the most useful features of the pixels.show();
ESP32-C3 are its built-in Wi-Fi and BLE }
communication capabilities. Together with
SPIFFS or the LittleFS file system to manage
web pages and other data on the ESP32, it
makes the platform ideal for a wide range of Wi-Fi applications. Those will also run on the ESP32-C3, and since FreeRTOS is working in the
working with an older 1.X version of the Arduino IDE will need to install background here too, you can make use of all the advantages and
a patched plugin [7] for uploading files to the ESP32 file system. The disadvantages that it brings, as with an ESP32.
original version by me-no-dev [8] does not work with the ESP32-C3.
Since the ESP32-C3 is currently only supported in a developer branch
As an example, we have used the code [9] which builds an ESP32 of the ESP32 chips in the Arduino framework, not all IDEs fully support
Mini-NTP server [10]. This can provide the time of day via NTP in its own the chip yet. As the framework matures, we can expect the support
network and is written for the Arduino-Framework. After a few tweaks level to improve.
to the pin assignments, the code can be compiled without problems
and uploaded to the ESP32-C3. This basic example shows that a lot of A Single-Core Solution
existing code and knowledge from the ESP32 will be directly portable The ESP32-C3 is a single-core, cost-effective alternative to the ESP8266
to the ESP32-C3, so even newbies to RISC-V environments shouldn’t and has many of the peripherals found on the ESP32. The integrated
find the transition too daunting. Most of the existing ESP32 examples USB/serial and JTAG adapter makes it easy to exchange files and

WEB LINKS
[1] @ElektorMathias on Twitter: https://twitter.com/ElektorMathias/status/1386623477604626433
[2] Elektor lab notes June 2021: www.elektormagazine.com/news/elektor-lab-notes-june-2021
[3] Tweet about USB Serial / JTAG support on ESP32-C3: https://twitter.com/ElektorMathias/status/1392475706647584776
[4] Forum Thread concerning ESP32 C3 revisions: https://esp32.com/viewtopic.php?t=21040
[5] Wikipedia - Cadence Tensilica Products: https://en.wikipedia.org/wiki/Tensilica
[6] ESP32 C3 DevKitC-02 circuit diagram:
https://dl.espressif.com/dl/schematics/SCH_ESP32-C3-DEVKITC-02_V1_1_20210126A.pdf
[7] ESP32 Data uploader for Arduino IDE (patched version): https://github.com/lorol/arduino-esp32fs-plugin/releases
[8] ESP32 Data uploader for Arduino IDE: https://github.com/me-no-dev/arduino-esp32fs-plugin
[9] Github Repository Mini NTP Server with GPS: https://github.com/ElektorLabs/180662-mini-NTP-ESP32
[10] Mini NTP Server with GPS at the Elektor Lab: www.elektormagazine.com/labs/mini-ntp-server-with-gps
[11] Materials for this article: https://bit.ly/3CD6iNs

lektor January & February 2022 61


data via USB. You can even start debugging code (as long as nothing will be in a good position to begin writing and testing code now for
unforeseen occurs in revision 3 of the chip). this environment. Listings of the Arduino sketches used here can be
found on our GitHub page [11].
Thanks to the Arduino framework, existing code can be reused with 210466-01
the ESP32-C3 and the generous amount of RAM and Flash allows
larger projects to be considered. Looking to the future, we are sure
to see a whole slew of third-party ESP32-C3 boards begin to appear
via European outlets, it will be interesting to see what new features
these boards will offer. Anyone with an ESP32-DevKitC-02 at home

Listing 2: Read the chip information


/* From the IDF documentation at https://github.com/espressif/esp-idf/components/esp_hw_support/include/
esp_chip_info.h */
/*
typedef enum {
CHIP_ESP32 = 1, //!< ESP32
CHIP_ESP32S2 = 2, //!< ESP32-S2
CHIP_ESP32S3 = 4, //!< ESP32-S3
CHIP_ESP32C3 = 5, //!< ESP32-C3
CHIP_ESP32H2 = 6, //!< ESP32-H2
} esp_chip_model_t;
// Chip feature flags, used in esp_chip_info_t
#define CHIP_FEATURE_EMB_FLASH BIT(0) //!< Chip has embedded flash memory
#define CHIP_FEATURE_WIFI_BGN BIT(1) //!< Chip has 2.4GHz WiFi
#define CHIP_FEATURE_BLE BIT(4) //!< Chip has Bluetooth LE
#define CHIP_FEATURE_BT BIT(5) //!< Chip has Bluetooth Classic
#define CHIP_FEATURE_IEEE802154 BIT(6) //!< Chip has IEEE 802.15.4
typedef struct {
esp_chip_model_t model; //!< chip model, one of esp_chip_model_t
uint32_t features; //!< bit mask of CHIP_FEATURE_x feature flags
uint8_t cores; //!< number of CPU cores
uint8_t revision; //!< chip revision number
} esp_chip_info_t;
*/

void setup() {
Serial.begin(115200);
}

void loop() {
delay(5000);
Serial.println(“esp_chip_info()”);
Serial.println(“----------------------------------------------------------------”);
esp_chip_info_t info;
esp_chip_info(&info);
Serial.print(“Chip Model: “);
switch(info.model){
case 1:{
Serial.println(“ESP32”);
}break;
case 2:{
Serial.println(“ESP32-S2”);
}break;

62 January & February 2022 www.elektormagazine.com


Questions or Comments?
Do you have any technical questions or comments about this article? RELATED PRODUCTS
Email the author at [email protected] or contact the
Elektor team at [email protected].
> ESP-C3-12F-Kit Development Board with Built-in 4 MB
Flash (SKU 19855)
Contributors www.elektor.com/19855
Text and images: Mathias Claußen
Editors: Jens Nickel and C. J. Abate
Layout: Giel Dols

case 4:{
Serial.println(“ESP32-S3”);
}break;
case 5:{
Serial.println(“ESP32-C3”);
}break;
case 6:{
Serial.println(“ESP32-H2”);
} break;
default:{
Serial.print(“Unknown Chipmodel”);
Serial.println(info.model);
}
}

Serial.print(“Featues :”);
if(info.features&CHIP_FEATURE_EMB_FLASH){
Serial.print(“ Embedded Flash “);
}
if(info.features&CHIP_FEATURE_WIFI_BGN){
Serial.print(“ WiFi(BGN) “);
}
if(info.features&CHIP_FEATURE_BLE){
Serial.print(“ BLE “);
}

if(info.features&CHIP_FEATURE_BT){
Serial.print(“ BT CLassic “);
}
if(info.features&CHIP_FEATURE_IEEE802154){
Serial.print(“ IEEE802.155.4 “);
}
Serial.println(“”);
Serial.print(“Cores: “);
Serial.println(info.cores);
Serial.print(“Chip Revision: “);
Serial.println(info.revision);
Serial.println(“----------------------------------------------------------------”);
Serial.println();
}

lektor January & February 2022 63


project

Protect Yourself
and Others!
DIY Master Power Switch for the Lab Bench

By Philippe Le Guen (France)

When unattended, is your


electronics workspace
safe for visitors? You may
know what you are doing,
but what about family
members and friends? Will
they get electrocuted when
they accidentally touch
something? Avoid all risks
with this master bench
power switch!

Why did I find it necessary to make my lab


bench safer? There are several reasons,
although some are quite personal. First of all, I
wanted to be able to switch on and off all the
equipment on the bench — instruments as
well as devices under development or repair Figure 1: The circuit is split in two
— with a simple flick of a switch. Furthermore, separate devices, the control box
I do not want the bench to be automatically (left) and the power stage (right).
The control box also has an
repowered after a power failure or (accidental) additional keylock master switch.
power cut. Power must be reapplied manually
in such cases.

The third reason is that after my son left


home, I have installed my little lab in his
former bedroom where it is accessible to my
grandchildren. As their tiny hands explore and

64 January & February 2022 www.elektormagazine.com


12V AC
L N PE
J1

X3 X4
D1
1 1
S1 R6
T1 LD1 2 2 390Ω
1N4007 3 3
BC516
4 4
R1 R2 R3 R4 K1
5 5
100k
10k

2k2

820Ω
6 6 1/L1
IC1
1 6 MOC3041M A1
ZD1 C1
S2 TRI2 S
BTA08-600 A2
100µ
A2
BZX55C15
25V
S3 ZC G A1 2/T1
A
TRI1
2 4
G BT169
K
R5
390Ω
200475-002

L N PE

Figure 2: The left part of the circuit, the control box, is powered from the right part, the power switching stage.

Editor’s note: Switching off the N conductor to disconnect from the mains does not make sense in all cases and is also not allowed, since
the energy stored in a switched-off (for example inductive) consumer can in this case not flow away via the N conductor. For this reason,
only a single-pole contactor is shown in the circuit diagram. If you still want to switch off the N conductor, a contactor with a leading/
lagging N contact should be used.

touch everything they can, I wanted to protect switch are housed in a small polycarbonate The Low-Voltage Supply
the bench power supply with a key. Power off case. I chose this enclosure because I already The cable transports the 12-VAC supply
should remain possible in all cases. had it, and because it fits perfectly in my lab. voltage for the control box and its output
signal. The AC voltage is rectified by D1
Specifications I don’t have a reference for the keylock switch and filtered by C1. A 15-V Zener diode (ZD1)
For extra safety, I wanted the control circuit as it was scrounged off something. It should protects against overvoltage.
to be low voltage (12 V) with the power stage be a non-momentary type, lockable in both
galvanically isolated by an optocoupler. All positions. You can refer to [1] for inspiration. The 12-VAC power supply used to be a 12 VDC
this had to be a DIY electronic system, easy to power adapter until its rectifier died. Today
build and repair thanks to the use of standard The power stage is housed in a small DIN it is nothing more than a transformer with
components only. rail enclosure fixed on one of the rails of the Class II insulation. A 12 VDC supply will work
electrical switch board. It is assisted by K1, a too. In this case D1 would serve as a protec-
I could very well have used one of these 230-V, 20-A contactor for off-peak rates. This tion against polarity inversion. C1 provides
commercially available no-volt-release (NVR) allows switching on the bench manually (with filtering. Of course, nothing prevents you from
safety switches as used on machine tools, but ‘s‘ inside K1) in case of failure of the control increasing its value to make the circuit less
I wanted to design it myself and furthermore, circuit (you never know what happens). sensitive to noise and glitches.
I wanted it to fit inside the electrical switch Besides, I had one lying around.
board that I installed in my lab for this reason. Thyristor Memory
The complete circuit is shown in Figure 2. The On state — after pressing the green
A Design in Two Parts The control box is located at some distance pushbutton S3 — is memorized by means
I designed a simple electronic system using from the contactor and its interface, and the of a thyristor (TRI1), which drives Darlington
only standard components (Figure 1). The two are connected by a cable with RJ11-type transistor T1 and optocoupler OK1. The pulse
green and red pushbuttons for switching the plugs on both ends. I used standard Cat 5 produced by the pushbutton through resistor
bench on and off together with the keylock Ethernet cable for this. R1 causes TRI1 to conduct, which will remain

lektor January & February 2022 65


in this state until its load current (through R2) the current is zero. The two resistors R5 and
R3
* disappears. This is possible by either applying R6 have the recommended values as found
22k

R2
a negative pulse to its gate or by removing its in the datasheet of OK1.
2k2 supply. The latter method was easily imple-
mented with the red Off pushbutton. No Snubber Circuit
A
R5 Using a triac with an inductive load such as
When TRI1 is conducting, the base of T1 is a motor or relay normally requires a protec-
10k

T2 pulled to 0 V and so it conducts too. R3 polar- tive snubber circuit, typically consisting of a
BC557B izes T1, while R2 limits the current flowing low-value RC network placed between the two
through the thyristor. The LED LD1 and the anodes of the triac. This is not needed here
S3 G T3 LED of OK1 both turn on, switching on triac because TRI2 is a so-called snubberless type.
BC547B
TRI2 that in turn activates the power relay.
R4 The current through the LEDs is limited by Your trained eye will have noticed the absence
R4 to about 10 mA. of fuses and circuit breakers. In fact, the power
10k

stage input comes from a 30-mA differential


K
When the red pushbutton (S1) is pressed, switch while the output of the power relay
TRI1’s supply voltage disappears. TRI1 blocks has a circuit breaker. But maybe I was wrong
200475-020
immediately, which makes T1 block too. The to do so. Nothing prevents you from adding
current through OK1 stops flowing and triac fuses, of course.
TRI2 stops conducting, deactivating the power
Figure 3: A PNP/NPN transistor pair relay in the process. Note that S1 must be a Now With a Pseudo-Thyristor
can replace the thyristor. normally-closed (NC) type. I also propose a second version of my project,
which does not use thyristor TRI1, but a pair
Optocoupler OK1 only switches during the of PNP/NPN transistors of type BC557B and
zero crossing of the AC mains voltage, when BC547B instead. Together with two 10 kΩ

Figure 5: The power stage is built into a DIN rail module. The black
thing is the RJ11 connector to which the control box is connected.
Figure 4: The insides of the control box. The small
circuit board can be fixed next to the pushbuttons
with a drop of hot glue.

66 January & February 2022 www.elektormagazine.com


bias resistors these two transistors form a
pseudo-thyristor (Figure 3). RELATED PRODUCTS
On power-up, both are blocked. T1 is also
blocked and no current flows into optocou- > PeakTech 2240 AC Power Source (SKU 19315)
pler OK1. When the On pushbutton is pressed, www.elektor.com/19315
T3 starts conducting and pulls the base of T2
close to 0 V. Now T2 starts conducting too and
> Fumetractor with LED Light (SKU 19092)
www.elektor.com/19092
applies a positive voltage to the base of T3,
keeping it open even when the pushbutton is
released. The current is limited by R2 and R5.
As before, a current of about 10 mA will start
to flow into OK1 via T1 as it has also become
conductive. Power-off is again achieved by
pressing the Off pushbutton.
to host the power stage including the
This second circuit functions exactly as the optocoupler and the triac (Figure 5). It
first one built around a real thyristor. Person- also provides the 12-VAC supply for the
ally, I prefer the thyristor due to its simplicity. control box on an RJ11 socket. I did not Contributors
On the other hand, in the second version there use a heatsink for the triac because of Idea, design, text & illustrations:
is no need to use a Darlington transistor for T1 the low current. Philippe Le Guen
and it may be replaced by a BC557B. If you Schematic drawing: Patrick Wielders
do so, also lower the value of its base bias I did not design any printed circuit boards for Editor: Clemens Valens
resistor to 22 kΩ. I used a BC516 because I this project, I simply used a set of perforated Layout: Giel Dols
couldn’t find my bag of BC557s in my drawers, prototyping boards bought somewhere online.
even though they are rather well organized. The assembled circuit board can be fixed with
a little hot glue inside its enclosure.
Construction Questions or Comments?
As mentioned before, I used two enclosures to Always keep in mind that you are working Do you have technical questions or
house the system that I divided into two parts: with the mains, so please be very careful! comments about this article? Contact
The pins of the triac are quite close to each Elektor at [email protected].
> An almost square polycarbonate enclo- other!
sure with dimensions 82 x 80 x 55 mm
(Bopla M210, see Figure 4). This enclo- Safety Matters
sure hosts the two pushbuttons and The system presented in this article is simple
the keylock switch together with the and practical to use and makes your bench
low-voltage control electronics. The a lot safer, so why not build one for your own
control box fits snuggly under one of my lab? The bill of materials can be downloaded
two desks. The pushbuttons are accessi- from [2].
ble at all time from any of them. 200475-01
> A 17.5-mm-wide DIN Rail enclosure

WEB LINKS
[1] Keylock switch examples: https://www.mouser.com/datasheet/2/140/KO-345961.pdf
[2] Design files, datasheets & BoM: https://www.elektormagazine.com/labs/4209
[3] Author‘s website: https://www.pleguen.fr/index.php/securiser-sa-paillasse

lektor January & February 2022 67


tutorial

Create GUIs with Python:


Part 02

Spy name chooser


Make an interactive GUI application

S
o far in this series, you’ve learnt how
Figure 2
to customise your GUI with a variety of
different options. It’s now time to get
into the really interactive part and make a GUI
application that actually responds to input from the
user. Who could resist pushing a big red button to Figure 2 You now have a button
generate a super secret spy name?
Laura Sach Since you already know how to create an app, why Underneath the Text widget, but before the app
MAKER

not go ahead and create a basic window and add displays, add a line of code to create a button.
Laura leads the some text if you like? Here is some code to get you
A Level team at started, and this code also includes some comments button = PushButton(app, choose_name,
the Raspberry
Pi Foundation,
(the lines that start with a #) to help you structure text="Tell me!")
creating resources your program:
for students Your code should now look like spy1.py. Run it and
to learn about
# Imports --------------- no button will appear, but you’ll see an error in the
Computer Science.
from guizero import App, Text Shell window:
@CodeBoom
# Functions ------------- NameError: name 'choose_name' is not defined

# App ------------------- This is because choose_name is the name of a


app = App("TOP SECRET") command which runs when the button is pressed.
Most GUI components can have a command
# Widgets --------------- attached to them. For a button, attaching a
title = Text(app, "Push the red button to command means “when the button is pressed, run
find out your spy name") this command.” A GUI program works differently
Martin to other Python programs you might have written
MAKER

O’Hanlon # Display --------------- because the order in which the commands are run in
app.display() the program depends entirely on the order in which
Martin works in the user presses the buttons, moves the sliders, ticks
the learning team
Run this code and you should see a window with the the boxes, or interacts with whichever other widgets
at the Raspberry
Pi Foundation, text (Figure 1). you are using. The actual command is almost always
where he creates the name of a function to run.
online courses,
projects, and
Add a button
learning resources.
Let’s go ahead and add a button to the GUI. Add Create a function
PushButton to your list of imports so that you can Let’s write the function choose_name so your button
@martinohanlon
use buttons. (Be careful to use a capital B!) has something it can do when it is pressed.
Look at your program and find the functions
section. This is where you should write all of the
functions which will be attached to GUI widgets, to
keep them separate from the code for displaying the
widget. Add this code in the functions section:

def choose_name():
Figure 1 Displaying
the text in a window
Figure 1 print("Button was pressed")

68 January & February 2022 www.elektormagazine.com


DOWNLOAD
spy1.py THE FULL CODE:
> Language: Python 3 magpi.cc/guizerocode

001. # Imports ---------------


Figure 3 002. from guizero import App, Text, PushButton
003.
Figure 3 Text is output to the Shell window 004. # Functions -------------
005.
006. # App -------------------
Your code should now look like spy2.py. The button 007. app = App("TOP SECRET")
will now appear (Figure 2). If you press the button, 008.
009. # Widgets ---------------
it may appear that nothing has happened, but if you
010. title = Text(app, "Push the red button to find out your spy name")
look in your Shell or output window, you will see 011. button = PushButton(app, choose_name, text="Tell me!")
that some text has appeared there (Figure 3). 012.
013. # Display ---------------
Instructing your function to first print out some 014. app.display()
dummy text is a useful way of confirming that the
button is activating its command function correctly
when it is pressed. You can then replace the print

spy2.py
statement with the actual code for the task you
would like your button to perform.
Inside your choose_name function, type a # symbol
in front of the line of code that prints “Button was > Language: Python 3
pressed”. Programmers call this ‘commenting out’,
and what you have done here is told the computer
001. # Imports ---------------
to treat this line of code as if it were a comment, or 002. from guizero import App, Text, PushButton
in other words you have instructed the computer to 003.
004. # Functions -------------
ignore it. The benefit of commenting a line of code 005.
out instead of just deleting it is so that if you ever 006. # App -------------------
want to use that code again, you can easily make 007. app = App("TOP SECRET")
008.
it part of your program again by removing the # 009. # Widgets ---------------
symbol. 010. title = Text(app, "Push the red button to find out your spy name")
011. button = PushButton(app, choose_name, text="Tell me!")
012.
Add some names 013. # Display ---------------
On a new line, add a list of first names. You can 014. app.display()
choose the names in your list and there can be as
many names as you like, but make sure that each
name is between quotes, and the names are each This tells the program that you would like to use a
separated by a comma. A collection of letters, function called choice which chooses a random item
numbers, and/or punctuation between quotation from a list. Someone else has written the code which
marks is called a string, so we say that each name does this for you, and it is included with Python for
must be a string. you to use.
In your code for the choose_name function, just
first_names = ["Barbara", "Woody", below your lists of names, add a line of code to
"Tiberius", "Smokey", "Jennifer", "Ruby"] choose your spy’s first name, and then concatenate
it together with the last name, with a space in
Now add a list of last names as well: between. Concatenate is a fancy word that means

last_names = ["Spindleshanks", "Mysterioso",

Big red button


"Dungeon", "Catseye", "Darkmeyer",
"Flamingobreath"]

Now you will need to add a way of choosing a At the moment, your button is not big or red! You used properties in part one
of this tutorial series to change the appearance of your text on the ‘Wanted’
random name from each list to form your spy name.
poster, so can you use the properties of the PushButton widget to change the
Your first job is to add a new import line in your background colour and the text size?
imports section: Note that it may not be possible to change the colour of a button on macOS,
as some versions of the operating system will not allow you to do so, but you
from random import choice should still be able to alter the text size.

lektor January & February 2022 69


Figure 4

spy3.py
Figure 4 Outputting a spy name
> Language: Python 3
‘join two strings together’ and the symbol in Python
001. # Imports ---------------
002. from guizero import App, Text, PushButton
for concatenation is a plus (+).
003. from random import choice
004. spy_name = choice(first_names) + " " +
005. # Functions -------------
006. def choose_name(): choice(last_names)
007. #print("Button was pressed") print(spy_name)
008. first_names = ["Barbara", "Woody", "Tiberius", "Smokey",
"Jennifer", "Ruby"]
009. last_names = ["Spindleshanks", "Mysterioso", "Dungeon", Your code should now resemble spy3.py. Save and
"Catseye", "Darkmeyer", "Flamingobreath"] run it. When you press the button, you should see
010. spy_name = choice(first_names) + " " + choice(last_names)
011. print(spy_name)
that a randomly generated spy name appears in
012. your console or Shell, in the same place where the
013. # App ------------------- original “Button was pressed” message showed up
014. app = App("TOP SECRET")
015. before (Figure 4).
016. # Widgets ---------------
017.
018.
title = Text(app, "Push the red button to find out your spy name")
button = PushButton(app, choose_name, text="Tell me!")
Put the name in the GUI
019. button.bg = "red" That’s good, but wouldn’t it be nicer if the spy name
020. button.text_size = 30 appeared on the GUI? Let’s make another Text
021.
022. # Display ---------------
widget and use it to display the spy name.
023. app.display() In the widgets section, add a new Text widget
which will display the spy name:

name = Text(app, text="")


03-spy-name-chooser.py When you create the widget, you don’t want it to
display any text at all as the person won’t have
> Language: Python 3
pressed the button yet, so you can set the text to
"", which is called an ‘empty string’ and displays
001. # Imports ---------------
nothing. Inside your choose_name function,
002.
003. from guizero import App, Text, PushButton comment out the line of code where you print out
004. from random import choice the spy name.
005.
006. # Functions ------------- Now add a new line of code at the end of the
007. function to set the value of the name Text widget
008. def choose_name(): to the spy_name you just created. This will cause the
009. #print("Button was pressed")
010. first_names = ["Barbara", "Woody", "Tiberius", "Smokey", Text widget to update itself and display the name.
"Jennifer", "Ruby"]
011. last_names = ["Spindleshanks", "Mysterioso", "Dungeon",
name.value = spy_name
"Catseye", "Darkmeyer", "Flamingobreath"]
012. spy_name = choice(first_names) + " " + choice(last_names)
013. #print(spy_name) Your final code should be as in 03-spy-name-
014. name.value = spy_name
015. chooser.py. Run it and press the button to see your
016. # App ------------------- spy name displayed proudly on the GUI (Figure 5).
017. You can press the button again if you don’t like
018. app = App("TOP SECRET")
019. the name you are given, and the program will
020. # Widgets --------------- randomly generate another name for you.
021.
022. title = Text(app, "Push the red button to find out your spy name")
023. button = PushButton(app, choose_name, text="Tell me!")
024. button.bg = "red"
025. button.text_size = 30
026. name = Text(app, text="")
027.
028. # Display ---------------
029.
030. app.display()
Figure 5 Figure 5 The finished
spy name chooser

Editor's note: This article originally appeared in MagPi magazine. Elektor publishes the Dutch, French, and German editions of MagPi.

70 January & February 2022 www.elektormagazine.com


The official Raspberry Pi magazine

£10
for 3 issu
es
You also
recieve
a FREE bo
your chooi k of
ce
From an ap
proved se
lection

SUBSCRIBE magpi.cc/freebook CALL 01293 312193


J006477 - £10 for three issues half page advert.indd 1 13/10/2021 11:16

Grrr. Got stuck?


You love our Elektor print projects but need help or
have an idea, question or comment about an article?

No worries. Elektor engineers, editors and


community members are also active on social
media.

You can find us here:

www.elektor.com/TW www.elektor.com/Insta

www.elektor.com/FB www.elektor.com/YT www.elektor.com/LI

lektor January & February 2022 71


productronica
Fast Forward 2021
Winners
Exciting Technologies and Creative Engineering Solutions

By Clemens Valens (Elektor)

productronica fast forward 2021, the start-up platform


powered by Elektor, offered innovative companies a unique
opportunity to present their technologies to the worldwide
electronics community. Here are the winners!

€50,000 Elektor marketing budget


ioTech Group — Based in Jerusalem, Israel, ioTech
develops new technologies for additive mass manufac-
turing and multi-material printing.
www.elektormagazine.com/news/
FIRST PRIZE
iotech-group-productronica-fast-forward-2021

As it remained long unclear if productronica 2021 was €25,000 Elektor marketing budget
going to take place as a real, live tradeshow or not, the Reedu GmbH & Co. KG — Reengineering Education
only way forward was online. Therefore, instead of pitch- aka Reedu aka re:edu from Münster, Germany is known
ing in front of a live jury and audience, the 2021 produc- for senseBox and openSenseMap.
tronica Fast Forward Award candidates from countries SECOND PRIZE www.elektormagazine.com/news/
such as Hungary, Germany, Israel, and France had to reedu-gmbh-co-kg-productronica-fast-forward-2021
record their presentations and submit them online.
Supplementary information about each electronics-re-
lated start-up was provided in the forms of business €15,000 Elektor marketing budget
plans and pitch decks. Pozi Development Ltd — Pozi from Budapest, Hungary
provides full visibility in manufacturing and logistics,
After watching the pre-recorded elevator pitches and and identifies and eliminates lean waste throughout the
studying all the documentation, the productronica Fast THIRD PRIZE entire supply chain.
Forward jury — which included Benjamin Klingenberg www.elektormagazine.com/news/
(NCAB Group, Platinum Sponsor of the event), Elektor pozi-development-ltd-productronica-fast-forward-2021
engineering and editorial representatives — selected
three winning start-ups.
The winning three start-ups were chosen by the jury because of their high commer-
Watch the cial potential and the quality of their teams, two important criteria for a start-up
pFFWD ceremony! to grow into a successful business. Congratulations to the winners!

Going to electronica 2022?


The Fast Forward Award is planned to roll again at electronica 2022
(https://electronica.de/de/) in Munich in November of this year. Hopefully, things
will be back to normal by then and we’ll see you there in person!
210658-01

72 January & February www.elektormagazine.com


project

Versatile Servo Tester


Check Behavior When
There’s No Datasheet

Motor
Control

By Marcelo Maggi (United States)

Knowing the precise behavior of a servo, particularly when the datasheet is not available, is
fundamental to make sure that the end application will have the expected performance. This
is even more relevant nowadays, with the proliferation of all sorts of servos varying in price,
quality, and performance.

The general definition of servomechanism, or servo, describes a Features and Specifications


device used to provide control of a desired operation using feedback. Modes: manual (low and high resolution) and automatic (low and
In electronics, and particularly when considering electromechanical high speed).
actuators, a servo is a device that generates a mechanical motion Minimum pulse width: adjustable by software.
controlled by an electrical pulse. Maximum pulse width: adjustable by software.
Center position: can be adjusted manually.
Examples of such servos can be found in various fields; for the Minimum step/pulse resolution: 1 µs.
purpose of this description, I will focus the attention on those used Maximum step: adjustable by software.
in radio‐controlled models, since they are extremely popular and Signal period: fixed at 20 ms.
widely used, not just for models but for hobbies in general. There Pulse stability/accuracy: crystal controlled.
are several types of servos, analog and digital, with plastic or metal Power supply: 4.5 to 6.0 V.
gears, with or without ball bearings, etc. However, all share one thing

lektor January & February 2022 73


the ‐90 and +90 degrees rotation from the center point at 0. Regarding
Pulse Width Servo Position the direction, it could follow the pulse clockwise or counterclockwise,
depending on the manufacturer.

The pulse amplitude, in volts, is usually the same as the servo power
supply; the most common supplies are 4.8 V and 6.0 V, although
nowadays other amplitudes are possible, from 3.7 V up to 14 V and over.

Period
Why a Servo Tester?
While the manufacturer’s datasheet gives all the specifications of the
servo in terms of maximum displacement, speed, dead band, etc., the
Figure 1: Servo control pulses. datasheet is not always available. And this is particularly true for the
wide range of low-cost servos currently available on the market. In
many cases, although some data may be available, testing the actual
performance may give quite different results. At the end of the day,
what matters is the actual performance of the servo you will use, not
in common: they can be controlled by the same electrical signal, for its theoretical behavior.
all practical purposes.
Designing a Servo Tester
This signal consists of pulses, of variable width, spaced by a fixed period A simple servo tester is something very easy to build, and there are
of time (Figure 1). The fixed period is usually 20 milliseconds (ms), plenty of examples on the web. Suffice to say that with a 555 (very
and the pulse width is what effectively controls the servo rotation. The popular integrated circuit) and a few other components, you can create
center position is set at 1500 microseconds (µs) for most servos, while an analog servo tester. However, if you want to measure the servo
the extreme positions could reach up to 500 µs on the lower end and behavior in a precise way, and with visual indication of the pulse being
2500 µs on the upper end. Usually these extremes correspond with sent to control it, a slightly more complex approach is required. One

+3V3

R8 R9
10k

10k

R3 11
A
U3 CAI3461AH
1 150
R11 7
VDD 16 150 B
RC0 R6 4
15 150 C
19 RC1 R4 2
RA0 14 150 D
18 U2 RC2 R1 1
RA1 7 150 E
17 RC3 R5 10
RA2 6 T1 150 F
4 RC4 R10 5
RA3/MCLR 5 150 G
3 RC5 10k 3
RA4/CLKOUT 8 DP DIG1 DIG2 DIG3 DIG4
2 RC6
RA5/CLKIN 9 CC1 CC2 CC3 CC4
RC7
12 9 8 6
U1 Q1
R2
PIC16F1829-I/P
1k 2N3904
13 Q2
RB4/SDA1 R7
12
32MHz RB5/SDA2 1k 2N3904
11 Q4
C5 C6 RB6/SCL1 R13
10
RB7/SCL2 1k 2N3904
VSS Q3
18p 18p C1 R12
20 X1 X2 1k 2N3904
100n

+4V5...6V

+4V5...6V LP2950-3.3 +3V3 R15 R14


10k

D5
1k

U4
J5 3 3 J4
1N4007
C2 C3 C4 Q5
2 2
DC IN OUT
1 10 100n Figure 2: Circuit
1 10V 10V 2N3904 1 schematic diagram.
200491-004

74 January & February 2022 www.elektormagazine.com


step above the simple 555 tester would be one with precise control Please note that the capacitors of the microcontroller’s oscillator circuit
of the pulse width, including a display showing this value. Cheap are missing in this PCB design; apparently the author’s servo tester also
versions can be found on the web, but they have one disadvantage: works like a charm without C5 and C6. The capacitors can easily be added
most parameters are already programmed and cannot be changed on the copper (bottom) side of the board, you may need to scratch the
by the user. Wouldn’t it be great to have a fully customizable servo soldermask off the GND-plane. But of course, you can also download the
tester, in which the user has full control of all the parameters to create design files and add the two capacitors to the PCB.
the desired signal, including manual and automatic testing features?
Software
This is exactly that: a fully programmable unit that allows the user to Probably the most important part of this design is the software; here
control all signal parameters, featuring manual and automatic modes, is where the precision and the versatility lie. The program runs in a
with a clear and intuitive user interface.

Hardware
The full circuit schematic is shown in Figure 2. The external connec-
tions are shown in the lower part; to the left is the power input (J5 COMPONENT LIST
– DC IN), which can be connected to the ESC of the RC model, or
Resistors Semiconductors
to any power supply capable delivering the required current for the
R1,R3,R4,R5,R6,R10,R11 = 150 Ω D5 = 1N4007
servo under test. The unit uses less than 15 mA, so it will not impose
R2,R7,R12,R13,R14 = 1 kΩ Q1,Q2,Q3,Q4,Q5 = 2N3904
a considerable load to the supply. The voltage can be anything from
R8,R9,R15 = 10 kΩ U2 = PIC16F1829-I/P
4.5 to 6.0 V, depending on the servo requirements.
T1 = 10 k potentiometer U3 = 4-Digit 7-segment CC LED
display 3461AH
Please note: The servo will receive the full voltage supplied by
Capacitors U4 = 3.3 V LDO LP2950-3.3
the power source. Be careful not to exceed the servo maximum
C1,C4 = 100 nF
ratings! To comply with most manufacturers specifications, the center
C2 = 1 µF/10 V radial Miscellaneous
connector is always the +V terminal, while the extremes are GND
C3 = 10 µF/10 V radial U1 = 32 MHz crystal
and SIGNAL.
C5,C6 = 18 pF X1,X2 = switch SPST

The power input only requires two lines, +V and GND, but a 3-terminal
connector has been mounted to receive any standard ESC connec-
tor. On the right side of the schematic is the servo output (J4 – OUT),
with the three lines connected (+V, GND and SIGNAL). This will be
connected to the servo under test.

The top‐mid left shows the microcontroller (U2) and the user interface,
a single potentiometer (T1) and two SPST switches (X1 and X2). The
rotation of the potentiometer will change the pulse duration, while the
switches will select the four operation modes, as shown in this chart
(the various modes will be explained in the software section):

SW1 SW2 Mode


0 0 Auto, high speed
0 1 Auto, low speed
1 0 Manual, high resolution
1 1 Manual, low resolution

Finally, the top right is U3: the 4‐digit 7‐segment display, with its
required components.

Board Layout
While this hardware can work mounted on a breadboard, a proper PCB
design will make it more durable and reliable. A possible PCB layout Figure 3: Mounted board layout; the potentiometer is J3, and
is presented in Figure 3. The design (NI Multisim) and Gerber files to the switches are J1 and J2.
order the PCB at your preferred supplier are available for download at [1].

lektor January & February 2022 75


may work, it is recommended not to go lower than 500, since the
servo might not be able to reach such extreme.
> MAX: maximum pulse width (in µs). This will be the longest value
of the pulse both in manual and auto mode. While any number
may work, it is recommended not to go higher than 2500, since
the servo might not be able to reach such extreme.

These four parameters add huge versatility to the tester, which cannot
be found in any cheap commercial unit. If you mount the microcon-
troller in a socket, you can easily remove, reprogram, and have a new
tester whenever you need it; or, if you are satisfied with one set of
parameters, just keep the same program forever.

Each digit is fully defined within a function (num) and can be selected
using a switch statement; each time this function is called with a

Figure 4: 3D-design of the enclosure.

PIC16F1829, using a 32 MHz crystal as the main


oscillator; it is written in C, using the CCS C
Compiler. The source code and the HEX-file for
programming the microcontroller are available for download at [1].
Figure 5: The PCB and connections
The program starts with the definitions of hardware and connections, inside the 3D-printed case.
as well as key reference values: The letters a to g represent the 7
segments of the numerical display, while d1 to d4 correspond to the
four digits. PWM is the output signal to control the servo and SW1 / SW2
are the switches. The potentiometer is connected to the analog input number stored in n, the number will be shown in the display. To select
AN7 (PIN_C3) and it is set in the main function. which of the four digits is active at a given time (since the display is
scanned sequentially) the function digit includes the selection, also
At the bottom, there are four very important definitions: within a switch statement. Whenever it is called, the digit stored in
z will be illuminated. If z contains “5”, then all digits will be off; this
> BRI: brightness of the LED display. This number controls the is used to have a clean transition from one digit to the next, with no
persistence of each digit (in µs), thus its apparent brightness. It is “ghosts” in the display.
set at 50 but can be changed from 1 to 200.
> SPD: speed of the servo movement in the auto mode. This The function that brings all together (digit selection and number output)
number represents the step size (in µs) when incrementing/ is display; this function takes a 4‐digit number, breaks it into the
decrementing the pulse width; the higher the number, the faster individual numbers and shows them in sequence in the display, from
the servo moves. Any number from 1 to 100 will work. right to left (units first), by calling the two previous functions. Here
> MIN: minimum pulse width (in µs). This will be the shortest value is where the display brightness is controlled, by adjusting the delay
of the pulse both in manual and auto mode. While any number before clearing a digit.

76 January & February 2022 www.elektormagazine.com


The precise timing of the period and pulse duration is achieved by
using TIMER1 interruption. Being a 16‐bit counter, it will overflow at
65536, triggering the interrupt; by preloading TIMER1 with an offset
value, a precise time can be measured by detecting this interruption. Contributors
In sequence, the first time this INT is called we load TIMER1 with the Text: Marcelo Maggi
value required for the pulse duration; next time, it will be the remaining Illustrations: Marcelo Maggi, Patrick Wielders
of the total period. This process is repeated continuously (controlled Editor: Luc Lemmens
by the variable pulse), so a precise pulse width is achieved, while Layout: Giel Dols
keeping a constant 20 ms period.

Here we also check the status of the switches to decide if we are in auto Questions or Comments?
mode (SW1 = 0). If so, SW2 will determine the speed of the automatic Do you have technical questions or comments about this article?
sweep (from MIN to MAX and back to MIN continuously): SW2 = 1 Email the editor at [email protected] or contact Elektor
means normal speed (the pulse varies 1 µs at a time) and SW2 = 0 at [email protected].
means high speed (the pulse varies SPD µs at a time). You may recall
that SPD can be any number from 1 to 100; if set to 1, then normal and
high speed will be the same (not very useful indeed).

Finally, main brings all together; besides the initialization of the Analog
to Digital Converter (ADC), TIMER1 and interrupts, the main program RELATED PRODUCTS
loop resides here. This loop will read the ADC (thus the value of the
potentiometer) and set the pulse duration accordingly.
> FeeTech Mini 360 Degree Continuous Rotation Servo
If we are in manual mode (SW1 = 1), then SW2 is evaluated; if “1”, the FS90R (SKU 19784)
low resolution mode is active, and the potentiometer will be able to www.elektor.com/19784
sweep the full range of the pulse width (MIN – MAX). This mode is
called “low resolution” for a simple reason: the ADC can only acquire
1024 different levels, but the pulse width range may be 1400 or more µs,
so it is not possible to achieve a 1 µs resolution within the full range. If
SW2 = 0, then the high resolution mode is enabled. Here the full pulse
width range is limited from 1469 to 1531 µs. The potentiometer can
easily be moved to change 1 µs at a time, which is extremely useful to:

> Put a servo in the center point (1500 µs).


> Measure the dead band, how many µs the pulse needs to change
to move the servo.
> FeeTech FS90MG Metal Geared Servo with Accessories
Making It Look Professional (SKU 19788)
With the proper case, this unit will look quite professional, and it will www.elektor.com/19788
also protect the hardware. A simple 3D-printed enclosure (Figure 4)
will do the job and also this design file is available for download at [1].
The PCB will be ”sandwiched” between four spacers (cylinders) and
the bottom case; the top case will be secured with four M2.5 x 20 mm
(#2‐56 x ¾) Phillips Pan Head screws. The assembly of the final unit
is shown in Figure 5.
200491-01

WEB LINK
[1] Software, PCB and 3D-design dowloads: http://www.elektormagazine.com/200491-01

lektor January & February 2022 77


project

Over WLAN (Part 2)


Software for the Modbus TCP WLAN Module
By Josef Bernhardt and Martin Mohr (Germany)

Built around an Espressif NodeMCU board, the module described in the first part of
this series enables you to use the Modbus protocol over a WLAN. This article covers
the software and Modbus module configuration.

In the first part [1] of this article series, we dealt with the project Preparing the Modbus WLAN Module
hardware. The module is built around a NodeMCU board fitted with In order to use the WLAN module with the Modbus protocol, you first
an ESP8266 microcontroller, with an additional baseboard providing have to load the required firmware. For this, remove the NodeMCU
industry-compatible ports. After a brief introduction to the operating board from the Modbus board and connect it to a USB port on your
principle of the Modbus protocol, here we focus on how the module is computer. Then open the Arduino IDE, configured as described in the
controlled and the software used for this purpose. The lift door control- first part of this article. You can download the firmware, which turns
ler from the first part is again used in the example. the module into a Modbus client, from the Elektor project page [3].

The Modbus Protocol Open the downloaded file OpenPLC_ESP8266_1_0_MUX_V1_1.ino in


The Modbus protocol is widely used in the automotive sector. It operates the Arduino IDE (File -> Open). The Arduino IDE will ask whether the
according to the master/slave principle, and the bus master can control project should be moved to the sketchbook. Answer this with ‘Yes’. If
up to 246 slave devices. The bus nodes can be assigned addresses the IDE creates a new folder, copy the header file (modbus.h) to the
from 1 to 247. Address 0 is reserved for broadcast data; all data sent to new folder containing the ino file, so the compiler will be able to find
this address is received by all nodes. The consistency of the individual the header.
data packets is ensured by CRC checksums. The slave devices have
internal registers with diverse functions. Table 1 provides an overview To enable access to the module over WLAN, the WLAN access data
of the Modbus functions. must be modified at the start of the source code (see Listing 1). There
you should enter the access data of your own WLAN.
There are three variants of the Modbus protocol:

> Modbus RTU: Binary transmission over RS485 (EIA485).


> Modbus ASCII: Plain text transmission over RS485 (EIA485). This Table 1: Overview of Modbus functions.
is less efficient than binary transmission, but human-readable.
Description Mode Bits
Commands can be sent using a simple terminal utility.
> Modbus TCP: In this variant the Modbus commands are trans- Individual “Coil” input/output Read/write 1
mitted using TCP/IP. This is usually over Ethernet, but with this Individual “Discrete Inputs” Read only 1
module it is over WLAN.
“Input Registers” (analog/digital) Read only 16

For more detailed information and protocol descriptions, visit the “Holding Registers” inputs/outputs
Read/write 16
Modbus website [2]. (analog/digital)

78 January & February 2022 www.elektormagazine.com


After making this modification, you can load the program into the
Modbus module as described in the first part. The module works with Listing 1: Modbus module WLAN configuration.
DHCP, which means it will be assigned an IP address automatically
by your router. You can check this in the router firmware. Alternatively, /*********NETWORK CONFIGURATION*********/
you can view the program output on the Arduino IDE serial monitor
(opened by the looking glass icon at the top right). In the dropdown const char *ssid = “<YOUR_SSID>”;
box at the bottom right, set the interface data rate to 115,200 baud. const char *password = “<YOUR_PASSWORD>”;
Listing 2 shows an example of how to output the IP address to the
serial monitor. To avoid having to repeat this procedure every time you /***************************************/
power up the Modbus module, you should assign a static IP address.
All recent routers allow this option. In any case, you should note the
module IP address output by the program so that you can access the
module over WLAN. If you do not see any output, press the Reset
button on the NodeMCU board to restart the software, since the IP
Listing 2: Modbus WLAN module IP address output.
address is only issued during the start-up process.
Connecting to Vodafone-3980
First Test .......
To check whether the Modbus WLAN module is working properly, WiFi connected
you can use the EasyModbus tool, which can be downloaded from Server started
SourceForge [4]. EasyModbus provides a server, a client, and a library. My IP: 192.168.0.85
For this test you only need the client, which can be downloaded directly
at [5]. In order to use the tool, you must have a Java version installed
on your PC. If Java is not yet installed, you can use the free OpenJDK
[6], which is very popular in the developer and maker community EasyModbus client (on the left under Linux; on the right under
and is a standard component of all Linux distributions. In Ubuntu, Windows). Here you should select Modbus TCP and enter the IP
for example, you can install it with the terminal command sudo apt address of your module. Leave the Starting Address set to 1 and change
install openjdk-11-jdk. the Number of Values to 4. If you now click Read Discrete Inputs – FC 2,
the four digital inputs of the module will be read and displayed. You
To run the EasyModbus client, enter the command java -jar should apply a signal to at least one of the inputs, so that you can see
EasyModbusJavaClient.jar . Figure 1 shows the output of the whether everything is working as expected.

Figure 1: The EasyModbus client reading data from the module. The Linux version is shown on the left, and the Windows version on the right.

lektor January & February 2022 79


get-pip.py [9] (don’t use the Linux package manager for this):
Listing 3: Example program tor.py for door control.
wget https://bootstrap.pypa.io/get-pip.py
from pyModbusTCP.client import ModbusClient python get-pip.py
client = ModbusClient(host=”192.168.0.85”, get-pip.py
port=502, auto_open=True, debug=False)
while(True): Then install the Modbus library:
inputs=client.read_discrete_inputs(0,4)
end_switch_top = inputs[0] $ python -m pip install -U pymodbusTCP
end_switch_bottom = inputs[1] C:\> py -m pip install -U pymodbusTCP
push_button_down = inputs[2]
push_button_up = inputs[3] You can find extensive documentation for the library at [10], along
motor_up = 0 with many code examples.
motor_down = 1
# request end_switch Example Program
if(end_switch_top): Let’s have a detailed look at the example program in Listing 3. The first
client.write_single_coil(motor_up,False) line imports the Modbus library. The next line creates a new connec-
print(“gate open”)
tion object in order to communicate with a specific Modbus device.
if(end_switch_bottom):
Several parameters can be passed for this. In our case we pass the IP
client.write_single_coil(motor_down,False)
address of the target device as host. Port 502 is the default port for
print(“gate closed”)
Modbus TCP communication. The parameter auto_open determines
# request push button
whether the connection should be set up automatically or manually.
if (push_button_up and not end_switch_top):
In our example we chose automatic for the sake of convenience, but if
client.write_single_coil(motor_up,True)
if (push_button_down and not
you want to have complete control over connection setup, you should
end-switch_bottom): choose False. With manual connection setup you have more options
client.write_single_coil(motor_down,True) for control and for error handling. If the parameter debug is set to True,
the software will output all transmitted data to the console. This is very
helpful when you are looking for a bug.

Using a while loop, we repeatedly run through the program as described


The EasyModbus client can only read data from Modbus; it cannot in the first part. This means the program works cyclically, just like all
write data. To test writing, you can use the example program described industrial controllers. The code inside the loop is the main part of the
below. The data actually transmitted can be seen at the bottom of the program, which first reads the inputs and then converts the input values
EasyModbus client window. This function is very helpful for debugging. into meaningful variables. We also define variables for the two digital
If the first test was successful, you can now proceed to programming outputs. This makes the following program lines easier to read.
the module with Python.
There you can see that the motor is switched off when the end points
Installing the Modbus +Library are reached. A text message is output to the console so that you can
To make the test more realistic, here we are using the lift door model see the current door position on the computer. Last but not least, the
from the first part [7]. We wrote a program for the PC that receives motor is run in the respective direction when the Up or Down button
the positions of the buttons and the limit switches over Modbus in is pressed. The logical AND between the limit switches prevents the
order to transmit corresponding motor actions (again over Modbus). relays from chattering when the door is already at an end point.

Our Python program needs a library [8] in order to access the Modbus. To run the program, enter the command line python tor.py. As usual,
This is nothing unusual; there are Modbus libraries for virtually all you can stop the program with Ctrl-C.
programming languages. If necessary, you can even generate the bit
sequences of the commands yourself and send them over the network. AdvancedHMI
However, we don’t want to go into that here. Convenient remote control with visual feedback that you can adapt
to your own purposes can be realised with a variety of PC frame-
First, you should make sure that the Python package installer pip is works. The program AdvancedHMI is open-source software for creat-
on board, which should always be the case with fairly recent Python ing human-machine interface (HMI) applications that communicate
installations. You can check this with either $ python -m pip – with your PLC or other I/O devices. This software differs from other
version under Linux or C:\> py -m pip –version under Windows. standard packages in that it allows you to create executable files
instead of just configurations that are interpreted by a runtime engine.
If the pip installer is not present, you can install it via Python with This results in very fast and efficient applications.

80 January & February 2022 www.elektormagazine.com


AdvancedHMI [11] is based on the Microsoft .NET framework.
Applications are generated in Microsoft Visual Studio Community 2019,
which is available free of charge. This allows you to create basic HMIs
by drag & drop without having to write any code. The .NET framework
is used by a large number of developers and has a wealth of support
networks. You can find much more support for AdvancedHMI than
for all other standard HMI packages combined.

The author used this platform to generate a user interface to control


the baseboard. It shows the status of the inputs and provides buttons
that can be used to switch the outputs (Figure 2).

.NET programs, such as this user interface to control the baseboard,


can also run under Linux with Mono. It has been tested successfully
on a Raspberry Pi.

Get Control
Figure 2: The AdvancedHMI software generates human-machine interface
The Modbus WLAN module makes it easy to control Modbus-compliant
applications.
devices from a PC or a smartphone. This module is also a good learn-
ing project if you want to get the hang of the Modbus protocol. The
hardware design, however, is so robust and error-tolerant that you
can also use it in your own ESP8266 projects if you want to control
and read industrial devices such as solenoid valves, motors, and other
kinds of sensors or actuators.
200507-B-01

RELATED PRODUCT
Questions or Comments?
Do you have any technical questions or comments? If so, please > NodeMCU Module (SKU 17952)
contact the author at [email protected] or the editorial staff at www.elektor.com/17952
[email protected].

Contributors
Idea, Design and Text: Josef Bernhardt, Martin Mohr
Editor: Rolf Gerstendorf
Layout: Giel Dols

WEB LINKS
[1] Modbus over WLAN (Part 1), ElektorMag 9-10/2021: http://www.elektormagazine.de/200507-01
[2] Modbus website: https://modbus.org/
[3] Elektor project page: https://www.elektormagazine.de/200507-B-01
[4] EasyModbus website: https://bit.ly/2QDIDJz
[5] EasyModbus client download: https://bit.ly/3d2zzFp
[6] OpenJDK download: https://bit.ly/2OVK4m6
[7] Lift door model on YouTube: https://youtu.be/VHIBQswdA0E
[8] Modbus library for Python: https://pypi.org/project/pyModbusTCP/#description
[9] get-pip.py: https://bootstrap.pypa.io/get-pip.py
[10] Modbus library examples: https://pymodbustcp.readthedocs.io/en/latest/
[11] AdvancedHMI: https://www.advancedhmi.com/index.php?main_page=page&id=14&chapter=0
[12] More infos by the author: https://bit.ly/3ch1PFl

lektor January & February 2022 81


background

Understanding the
Neurons in Neural
Networks (Part 3)
Practical Neurons

By Stuart Cording (Elektor)

So far, we have created a neural network and developed an


understanding of how it functions. We’ve even been able
to teach it how the XOR function works, something that
requires the classification of input patterns. In this article,
we will examine how to implement a part of an autonomous
driving system: recognizing the state of traffic lights.

There have been many predictions regar- markings, and vehicle types and people. or macOS with an integrated or external
ding self-driving cars [1], none of which Now that we have a working neural network camera.
have come to fruition. Much of the comple- in the form of our multilayer perceptron, we
xity arises from attempting to understan- will use it to detect a traffic light’s colors. Finding Your Camera
ding the intent of other road users and Before we can get started, a new library
pedestrians. However, a lot of the autono- One of the great things about the Processing needs to be added to Processing that provi-
mous driving system is about classifying environment we have used thus far is the des access to any attached webcams. From
everything the many sensors and cameras ease with which it can access webcams. The the menu, select Sketch -> Import Library…
‘see’ around the vehicle. This ranges from examples used here will run on just about -> Add Library… (Figure 1), which opens the
traffic lights and road signs, to street or road any laptop or PC running Windows, Linux window shown in Figure 2. Ensuring that

82 January & February www.elektormagazine.com


Figure 1: Adding a new library to Processing. Figure 2: Searching for and installing the Video library.

the Libraries tab is selected, enter “video” Video library but has no impact on the be a high R and G value as, together, red
into the search box. From the list that code’s functionality. and green make yellow. To get a better
appears we select Video | GStreamer-based feel for additive color mixing, the project /
video library for Processing and then click How Do Cameras See? trafficlights/addititive/additive.pde may be
on Install. As before, we will be using the Perhaps one of the most important aspects of interest (Figure 5).
code from the GitHub repository prepared of using neural networks is to develop an
for this series of articles [2]. understanding of how a computer can With this knowledge, it would seem to make
interpret the incoming data. In the case sense to determine how our camera “sees”
With the library installed, we can run the of camera input, the computer image is the colors of our traffic light and note the
project /trafficlight/findcamera/findca- displayed by mixing the three primary RGB values it reports. We can then teach
mera.pde. This code simply requests the colors, red, green, and blue. This is our neural network the three traffic light
list of available cameras connected to the commonly termed the RGB format. The colors so that it may classify them as red,
computer and allows the user to select three values vary between 0 and 255 (or amber, and green.
one by entering a number between 0 and 0x00 and 0xFF in hexadecimal). If we
9. Make sure the small findcamera window point the camera at something blue, we Determining RGB Values
has the context (click inside the window) would expect the B value to be relatively The project trafficlight/computer_vision/
before pressing a number. If the Processing high and the other values quite low. Point it computer_vision.pde is the next project
IDE window has context, you will simply at something yellow, and then there should we will need. This displays the selected
end up typing a number somewhere in the
source code.

Once a camera source has been selec-


ted, its output is shown in a low-resolu-
tion 320×240-pixel output in the window
(Figure 3). The text console will also
provide the source code needed to select
your camera for the next two projects we
will look at (Figure 4).

Finally, we need a traffic light. Since you


are unlikely to have one to hand, one has
been prepared in trafficlight/resources in
various file formats. Simply print one out
and keep it to hand.

When stopping Processing projects that


use the camera, you may see the message
“WARNING: no real random source present!”. Figure 3: Example output from findcamera.pde.
This seems to be a bug related to using the

lektor January & February 2022 83


Figure 4: The console output of findcamera.pde provides the initialization code for the other projects Figure 5: additive.pde demonstrates
to use the desired camera. additive color mixing.

camera’s output next to the RGB values it is the dashed circle), note the color seen (top) set. Finally, we could improve the incoming
reporting. Using this project, we can record and the RGB values that define it (Figure 6). data from the camera, perhaps by adding
the RGB values the camera sees. Before The RGB values are actually the average of an infrared image of the traffic light (which
starting the code, don’t forget to paste the all the pixels the camera captures in the lamps are hot) or some other clever filte-
line of code you determined in findcamera. center’s red bounding square. Despite being ring. However, don’t despair! We shall add
pde to line 22 in this project. This ensures an average, the RGB values will change up some robustness into our training data to
your chosen camera is used. and down rapidly. To capture a single value, handle some variation in the color of our
press ‘p’ on your keyboard, and the code traffic light input.
While pointing the camera at the red traffic pauses on a single set of values. Be sure to
light (keep the ‘light’ approximately within click inside this window before pressing ‘p’ The critical task at this point is to collect
to give it the context. Pressing ‘s’ restarts the RGB data for the red, amber, and green
the camera capture and RGB generation traffic lights using your camera and your
Table 1: RGB values captured for the again. lighting conditions. The data collected
three traffic light colors. using the author’s setup is shown in Table 1.
The traffic light printout used here was
laminated so there are some reflections Detecting Traffic Lights
Light color R G B in places. If you have printed your traffic Armed with our data, we can now train
Red 220 56 8 light image out using a laser printer, you the neural network the colors of our
may also have a slightly reflective surface. traffic light. For this final stage we will
Amber 216 130 11
As a result, although the camera is pointing need the project trafficlight/tlight_detect/
Green 123 150 128 at the red traffic light, the “Color seen” may tlight_detect.pde open in Processing. Start
be pinkish or even close to white. This is, by ensuring that the correct camera initi-
obviously, not much use for the neural alization code is pasted into line 30 (from
network. It needs to know the color ‘red find_camera.pde).
traffic light’ under optimal conditions, so
move the camera or change the lighting This project uses a three-input, six-hid-
until you feel you have achieved an RGB den, and four-output (3/6/4) node MLP.
value representing the color optimally. The three inputs are for the three colors,
R, G, and B. Three of the four outputs are to
Figure 6: computer_vision.pde provides us with This also raises another issue concerning classify the ‘red,’ ‘amber,’ and ‘green’ of the
the RGB values the camera ‘sees’ for each traffic- accuracy. Drivers will know how difficult traffic light. The fourth will be used later.
light color. it is to discern the active traffic light lamp The use of six hidden nodes was chosen
when the sun is shining into our eyes or arbitrarily as ‘enough’ to handle the classi-
directly into the lamps. If we humans fication task. We will see that this configu-
cannot distinguish which lamp is lit, how ration does work and, as before, readers are
can a neural network figure it out? The encouraged to experiment with fewer or
answer is, it can’t. If we need a more robust more hidden nodes.
algorithm, we need to train it with ‘poor
visibility’ data. We may also need to provide If you run the code ‘as is,’ the neural
another input, such as where the sun is network operates without any learning.
Figure 7: The response of tlight_detect.pde prior shining from, so that the neural network The results (Figure 7) show that any color
to learning any colors. knowns when there is ‘poor visibility’ and is classified as all the colors the network is
that it should use the ‘poor visibility’ data defined to detect.

84 January & February www.elektormagazine.com


Figure 8: The three traffic
light colors in RGB color
space after randomization.

Figure 9: tlight_detect.pde having learned red,


amber, and green.

The teaching of the neural network takes The decision on the color seen is then made
place around line 51. Uncomment the first starting at line 171. The output of each
three methods and add the RGB values you output node is evaluated. If classification
acquired earlier. The three methods used to certainty is above 90% (0.90), the color
define red, amber, and green are: seen is displayed in a circle along with the
classifier ‘Red,’ ‘Amber,’ or ‘Green’.
teachRed(159, 65, 37);
teachAmber(213, 141, 40); // If likelihood of ‘Red’ > 90%...
teachGreen(128, 152, 130); if (network.getOutputNode(0) >
0.90) {
Each time these functions are called, the fill(200, 200, 200);
network is trained to classify that RGB // …write “Red”…
combination as the associated color text("Red", 640+(100), 320);
(Figure 8). To allow for some variation in // … and set color to the
lighting and automatic changes in exposure color seen.
setting by the camera, a small amount of fill(r, g, b);
variation (±4) to the RGB values is applied } else {
using a randomise() function (line 336). // Otherwise, set color to
Again, you can experiment with the effec- black
tiveness of this approach and the amount fill(0, 0, 0);
of randomization applied. }
// Now draw the color seen in a
Training of the network is swift compared circle
to previous projects as we are no longer ellipse(640+(50), 300, 40, 40);
writing the error values during learning Figure 10: Misclassification of other colors as
to a file. Simply run the project and, after a You can experiment with the accuracy ‘green.’
few seconds, the neural network will start of the MLP by pointing the camera at the
evaluating the color in the red bounding different traffic light at different angles and
square of the camera window (Figure 9). under different lighting conditions. Also,
try pointing the camera at objects in your
The traffic light in the view of the camera is vicinity that, in your opinion, approximate
determined on line 156 onwards. The RGB the colors the MLP has learnt.
colors captured are applied to the inputs
of the MLP and the network’s output is One thing you may notice is the misclassifi-
calculated: cation of a wide range of colors as a known
color. In the author’s example, the ‘green’
network.setInputNode(0, (float) r classification is also given for the traffic
/ 255.0); light surround, frame, and overall image
network.setInputNode(1, (float) g background (Figure 10).
/ 255.0);
network.setInputNode(2, (float) b Tightening-Up Neural Network Figure 11: Misclassification of other colors as
/ 255.0); Classification ‘green’ resolved using ‘other’ output node.
network.calculateOutput(); From the RGB values displayed, it is clear

lektor January & February 2022 85


your RGB values:
on the system?
Table 2: RGB values captured for the
‘unwanted’ colors. teachOther(76, 72, 35); > Would a fourth input for ‘general
teachOther(175, 167, 138); brightness’ help to increase recogni-
teachOther(152, 167, 161); tion accuracy under varying lighting
conditions?
Object R G B
Rerunning the project results in a notice-
Dark able improvement. The area around the While it is great to run neural networks
traffic light 76 72 35 traffic lights (surround, frame, background) on powerful laptops and PCs, many of us
surround
is classified as ‘Other’ instead of ‘Green’ will desire to have such a capability on the
White frame 175 167 138 (Figure 11). smaller processors used on boards such as
Blue Arduino. In our final article of this series,
background 152 167 161 For Next Time we will use an RGB sensor and an Arduino
In this article, we’ve now seen a neural to implement a color-detecting neural
network resolve a real-world classification network. Perhaps it will form the basis for
that the colors passed to the MLP are reaso- problem. We’ve also learned that it can help your next brainy Arduino project!
nably close to that of the wanted classifica- to teach both the desired classification and 210160-C-01
tion for ‘Green.’ There are several ways to the undesired classification data.
tighten up the classification. The first would
be to raise the 90% bar for accurate classifi- Why not try building upon this example to Questions or Comments?
cation to a higher value. Another may be to explore the following? Do you have technical questions or
increase the number of epochs of learning. comments regarding this article? Then
The other is to rethink the classification > How ‘robust’ can you make the MLP email the author at
implementation. to camera angle and changes in [email protected].
exposure? Is it better to more heavily
So far, we have focused on what we want to randomize the learning data or raise
positively classify. However, sometimes it the bar for classification (> 90%)? Contributors
can help to teach the neural network what > Does accuracy improve if you increase Idea, Text and Images: Stuart Cording
does not belong to the patterns we are the number of ‘Other’ output nodes Editors: Jens Nickel, C. J. Abate
looking for. Essentially we can say, “these and teach each one an unwanted color? Illustrations: Patrick Wielders
are three things we are looking for, but here > What impact does reducing or increa- Layout: Harmen Heida
are some similar things we are definitely sing the number of hidden nodes have
not looking for.” This is where our fourth
output node comes into play.

Returning to the computer_vision.pde project


once more, we can capture the RGB values RELATED PRODUCTS
for colors that we want to be classified as
‘other.’ As an example, RGB values for the
dark traffic light surround, the white border, > B. van Dam, Artificial Intelligence (E-book) (SKU 18090)
and the blue background were collected, www.elektor.com/18090
with the results as shown in Table 2.
> Google AIY Vision Kit for Raspberry Pi (SKU 19365)
www.elektor.com/19365
Back in tlight_detect.pde, these values can be
taught as ‘Other’ unwanted colors using the > HuskyLens AI Camera with Silicone Case (SKU 19248)
teachOther() method. Simply uncomment www.elektor.com/19248
the code around line 60 as follows and add

WEB LINKS
[1] M. Anderson, “Surprise! 2020 Is Not the Year for Self-Driving Cars,” IEEE Spectrum, April 2020: http://bit.ly/2ZSwm5f
[2] GitHub repository - simple-neural-network: https://bit.ly/2ZHLv9p
[3] H
 . Zhang et al., “StackGAN: Text to Photo-realistic Image Synthesis with Stacked Generative Adversarial Networks,” CVF,
December 2017: https://bit.ly/3qZccCs

86 January & February www.elektormagazine.com


elektor books

Inside an Open-Source
Processor
Sample Chapter: Lattice and Xilinx FPGA Results

Alchitry FPGA development boards mentioned in this article. Left to right: Cu — Au — Au+.

By Monte Dalrymple (USA)

This instalment of Elektor Books presents material excerpted from Monte Dalrymple’s book
Inside an Open-Source Processor published by Elektor. FPGA technology in combination with
(V)HDL is hot among electronicists and RISC-V adds the open-source path to professional
applications In this article, we examine some side-by-side comparisons and results obtained
from an example application running on both Lattice and Xilinx FPGA boards of the
‘Alchitry’ series now available from Elektor. But first, a few tips!

Editor’s Note. This article is an excerpt from the book Inside an described elsewhere in the book) most of the work has already
Open-Source Processor — an Introduction to RISC-V, formatted been done.
and lightly edited to match Elektor Magazine editorial standards
and page layout. Being an extract from a larger publication, some Just be aware that large projects, or projects taking maximum
terms in this article may refer to discussions elsewhere in the origi- advantage of the capabilities of the FPGA, will inevitably be much
nal. The Author and Editor have done their best to preclude such more complex.
instances and are happy to help with queries. Contact details are in
the Questions or Comments? box. In the case of both Lattice and Xilinx, besides selecting the appropri-
ate FPGA target for the project only two or three files will need to be
In the past, setting up a project in an FPGA tool flow was a daunt- linked in the tools. All of the project files need to be in the same direc-
ing task, but as the technology has matured this setup has gotten tory in this simplified approach. As mentioned previously, readers
much simpler. In the case of the example here (a 24-hour clock are strongly encouraged to review the Alchrity tutorials for FPGA

lektor January & February 2022 87


software installation and project setup because only the essential
Table 1: FPGA Results.
details will be covered here.
100 MHz
Alchrity Cu Alchrity Au Alchrity Au+
Lattice (Alchrity Cu) Tips Divider
The FPGA used on this board requires the Lattice iCEcube2 software. Speed (at
313.9 MHz 114.1 MHz 114.2 MHz
This is a mature product without a lot of bells and whistles, but synthesis)
there are a few things to remember: Speed (at
542.3 MHz - -
placement)
1. Be sure to set up the project with the correct device options.
Speed (final) 625.4 MHz 111.9 MHz 111.9 MHz
The Alchrity Cu uses the HX8K device from the iCE40 family,
in the CB132 package. All of the I/O banks use a 3.3 V supply.
2. Only the yrv_alchrity.v file needs to be entered as a design
file, because all of the other design files will be automatically
included in the correct order. Table 2: FPGA Results.
3. For the synthesis tool, be sure to select the Lattice LSE Synthesis.
FPGA
No constraint files are necessary during logic synthesis. Alchrity Cu Alchrity Au Alchrity Au+
Attribute
4. After the synthesis completes, the yrv_alchrity.pcf pin constraint
Logic
file and timing.sdc timing constraint file need to be linked before 7,680 20,800 63,400
elements
running the remainder of the tools.
LEs Used 4,646 2,189 2,185
There will be a number of warnings in the various log files but LEs Used (%) 60.6% 10.5% 3.5 %
none of them should be important enough to require any action.
Flip-flops 1331 1377 1377

Xilinx (Alchrity Au and Au+) Tips Speed (at


11.8 MHz 28.1 MHz 27.7 MHz
The FPGAs used on these boards require the Xilinx Vivado software. synthesis)
This is a very complex product, and this project will only use a Speed (at
25.8 MHz - -
small subset of the capabilities of this software. Here are a few placement)
things to remember: Speed (final) 30.8 MHz 34.4 MHz 34.2 MHz

1. Only the yrv_alchrity.v file needs to be entered as a design file.


2. Only the yrv_alchrity.xdc constraint file is required. This file
contains the pin constraints, timing constraints as well as the logic synthesis to logic placement to the final routed result. While
programming voltage specifications. it is best to have the final performance be better than the initial
3. The correct device option is the xc7a35tftg256-1 for the Au board estimate, being off by a factor of two is not ideal because it might
and the xc7a100tftg256-1 for the Au+ board. lead to abandoning a project as unfeasible erroneously.

There are even more warnings in the log files for these devices, but The Xilinx tools do not give a separate speed estimate at logic
again, none of them should be important enough to require action. placement, but the reported speed is nearly identical between
logic synthesis and the final result. From the point of view of a
FPGA Results designer, this is preferred.
This example project has been implemented on all three target
FPGA development boards and the individual results will be covered Table 2 shows the resources required for the project as well as
in the following sections. But at this point it is interesting to do a the maximum clock frequency for the CPU itself. These results do
side-by-side comparison of some of the results. Table 1 shows the not include any of the 64-bit counters that are part of the RISC-V
reported clock speed for the 100 MHz divider. Privileged Architecture.

The 100 MHz divider was designed for maximum speed with only The second line of this table demonstrates why comparing FPGA
one level of logic between flip-flops. This means that this result results can be complicated. From the table, it appears that the Xilinx
should represent the capabilities of the technology. implementation requires less than half of the resources required
by the Lattice implementation. But a Xilinx logic element contains
The reported speed for the Lattice device, if true, is impressive. significantly more logic than a Lattice logic element. In addition,
What is most interesting is that the reported speed gets better, the Xilinx design uses the dedicated DSP blocks which the Lattice
and presumably more accurate, as the implementation goes from device does not have.

88 January & February 2022 www.elektormagazine.com


Listing 1: Lattice Report Excerpt.

Total Logic Cells: 4646/7680


Combinational Logic Cells: 3315 out of 7680 43.1641%
Sequential Logic Cells: 1331 out of 7680 17.3307%
Logic Tiles: 847 out of 960 88.2292%
Registers:
Logic Registers: 1331 out of 7680 17.3307%
IO Registers: 0 out of 1280 0
Block RAMs: 12 out of 32 37.5%
Warm Boots: 0 out of 1 0%
Pins:
Input Pins: 36 out of 95 37.8947%
Output Pins: 50 out of 95 52.6316%
InOut Pins: 0 out of 95 0%
Global Buffers: 2 out of 8 25%
PLLs: 0 out of 2 0%

Looking at the percentage of logic elements used reveals the size


disparity between the three FPGAs here. A little over half of the
Lattice device is required for the yrv_mcu design, but roughly
one-tenth of the mid-range Xilinx device is used and less than
one-twentieth of the large Xilinx is required. This usage is in line
with the cost of the different development boards.

As expected, the number of flip-flops required for the design


is similar across the three FPGAs, and the exact count is more
a function of the logic synthesis tool than anything else. Logic
synthesis tools will replicate flip-flops to increase performance
or to simplify routing.

The speed rows show that all three FPGAs provide roughly the
same performance, which is somewhat surprising given that the
Lattice FPGA does not contain the dedicated DSP blocks that are
used in the Xilinx implementation.
Figure 1: Lattice Floorplanner View (Alchitry Cu).

Alchrity Cu Details
Listing 1 is extracted directly from the Lattice implementation
report, showing the details of the resource utilization. Figure 1 is report is much larger, covering all of the dedicated hardware avail-
taken from a screenshot of the Lattice floorplanner tool, showing able in the FPGA.
the usage of logic elements as distributed across the device. This
distribution is fairly even across the entire device even though the Figure 2 is taken from a screenshot of the Xilinx floorplanner tool,
overall usage is only about 60 percent. showing the usage of logic elements as distributed across the device,
along with how the dedicated logic blocks are distributed through-
Alchrity Au Details out the device. It seems that placement tools always start in the
Listing 2 is extracted directly from the Xilinx implementation lower-left corner of a device. It is not clear why the logic seems to
report, showing details of the resource utilization. The full Xilinx be split into two pieces.

lektor January & February 2022 89


Listing 2: Xilinx XCA35T Report Excerpt.

1. Slice Logic
--------------

+-------------------------+------+-------+-----------+-------+
| Site Type | Used | Fixed | Available | Util% |
+-------------------------+------+-------+-----------+-------+
| Slice LUTs | 2189 | 0 | 20800 | 10.52 |
| LUT as Logic | 2189 | 0 | 20800 | 10.52 |
| LUT as Memory | 0 | 0 | 9600 | 0.00 |
| Slice Registers | 1377 | 0 | 41600 | 3.31 |
| Register as Flip Flop | 1377 | 0 | 41600 | 3.31 |
| Register as Latch | 0 | 0 | 41600 | 0.00 |
| F7 Muxes | 3 | 0 | 16300 | 0.02 |
| F8 Muxes | 0 | 0 | 8150 | 0.00 |
+-------------------------+------+-------+-----------+-------+

Alchrity Au+ Details


Listing 3 is also extracted directly from the Xilinx implementa-
tion report, showing details of the resource utilization. Notice that
the numbers for resources used are nearly identical between the
two Xilinx devices.

Figure 3 is also taken from a screenshot of the Xilinx floorplan-


ner tool. What is interesting here is that even though this FPGA
contains three times the number of logic elements, the overall area Figure 2: Xilinx XCA35T Floorplanner View (Alchitry Au).
required by the example here seems to be spread out over nearly
the same area as in the first Xilinx implementation.

Hardware Programming
Downloading the FPGA bitstream to an Alchrity development board
is simple when using the Alchrity Loader program. This stand- Labs software available from Alchrity. Figure 4 shows the user
alone program is automatically installed as part of the Alchrity interface for this program.

Programming the Flash memory device on the development board


that is used to load the FPGA is as simple as specifying the bitstream
file, selecting the target board, and clicking the Program button.

By default, the program looks for a bitstream file of type .bin, which
is the default used by the iCEcube2 software. The Vivado software
generates a bitstream file of type .bit, so keep that in mind when
loading the Xilinx bitstream file.
210347-01
Figure 4: Alchitry Loader View.

90 January & February 2022 www.elektormagazine.com


Listing 3: Xilinx XCA100T Report Extract.

1. Slice Logic
--------------

+-------------------------+------+-------+-----------+-------+
| Site Type | Used | Fixed | Available | Util% |
+-------------------------+------+-------+-----------+-------+
| Slice LUTs | 2185 | 0 | 63400 | 3.45 |
| LUT as Logic | 2185 | 0 | 63400 | 3.45 |
| LUT as Memory | 0 | 0 | 19000 | 0.00 |
| Slice Registers | 1377 | 0 | 126800 | 1.09 |
| Register as Flip Flop | 1377 | 0 | 126800 | 1.09 |
| Register as Latch | 0 | 0 | 126800 | 0.00 |
| F7 Muxes | 3 | 0 | 31700 | <0.01 |
| F8 Muxes | 0 | 0 | 15850 | 0.00 |
+-------------------------+------+-------+-----------+-------+

Figure 3: Xilinx XCA100T Floorplanner View (Alchitry Au+).

RELATED
PRODUCTS

Questions or Comments?
Do you have any technical questions or comments related to this > Book: M. Dalrymple, Inside
an Open-Source Processor
article? Then email the author at [email protected] or Elektor
(Elektor 2021) (SKU 19826)
at [email protected]. www.elektor.com/19826

> E-Book: M. Dalrymple,


Contributors Inside an Open-Source
Processor (Elektor 2021)
Text: Monte Dalrymple
(SKU 19827)
Editor: Jan Buiting www.elektor.com/19827
Layout: Giel Dols
> Alchitry Au FPGA Kit (SKU 19638​)
www.elektor.com/19638

lektor January & February 2022 91


basic course

Starting Out in Electronics


We Are Not Yet Done with the Coil

By Eric Bogers (Elektor)

In this installment we continue with the coil.


Unloved by hobbyists, but oh so important.

Series and Parallel Circuits Crossover Filters


Resonant circuits (Figure 1) are the frequency-determining circuits Figure 3 shows the impedance and phase characteristics of a bass
in oscillators; at the so-called resonant frequency their impedance speaker (which, incidentally, is mounted in a front-loaded horn
is at its minimum or maximum (that is, the value is at its most enclosure, but there is no need to remember that detail). Figure 4
extreme). At this resonant frequency the impedance of the capaci- shows the frequency characteristic of that system and Figure 5
tor is equal to that of the inductor; the following equation holds: gives an impression of the amount of distortion that is present.

1 We see that we can divide the entire frequency range into four
XC   X L  2   fR  L regions. The first region is below the resonance frequency — in
2   fR  C
1
 fR 
2   L C

Impedance measurement

Series circuit

Figure 1: Series and parallel


resonant circuits.

Parallel circuit
This formula is valid for both series and parallel resonant circuits.
In Figure 2 you can see the impedance characteristics as a function Inductor Capacitor
of frequency. A series circuit can be used in (among other things!)
a loudspeaker box to attenuate a small frequency range in order
to linearise the overall characteristic of the box. For this purpose,
in most cases, a resistor has to be connected in series with this
series-resonant circuit. Figure 2: Impedance characteristics of series and parallel resonant circuits.

92 January & February 2022 www.elektormagazine.com


the example of this loudspeaker this region is from 0 Hz to about
30 Hz. The efficiency of the loudspeaker could be called fairly
mediocre here, the amount of distortion is very large, while the
voltage and the current are some 60° to 90° displaced in phase
with respect to each other. This also means that the power loss
in the amplifier is at its highest. For these reasons it is pointless
to use this loudspeaker in this frequency range: in the first place,
it doesn’t sound good, in the second place, because of its poor
efficiency, it requires way too much electrical power, and in the
third place, the amplifier will overheat (with all the detrimental
consequences that entails).

For this loudspeaker, a high-pass filter with a corner frequency


Figure 3: Impedance and phase characteristics.
of at least 50 Hz should be used. For the reproduction of lower
frequencies we would need to use another type of loudspeaker
and/or another type of enclosure.

The second region is around the resonant frequency; here the


impedance (and therefore also the efficiency) increase dramati-
cally. In most cases, loudspeaker boxes work quite well in this
frequency range (as it happens, however, that is not the case in
this example...).

In the third region the impedance has a reasonably horizontal


(constant) characteristic and the efficiency is acceptable with a
small distortion factor; the phase characteristic too, gives no reason
for concern. In the example this region is from about 100 Hz to
about 1 kHz — and this is the frequency range where this loudspe- Figure 4: Frequency characteristic.
aker should be used. The distortion characteristic illustrates the
relatively large second-order distortion (even harmonics) that are
a characteristic of horn systems.

Finally, in the fourth region the impedance progressively increa-


ses as a consequence of the self-inductance of the voice coil, the
output level clearly reduces and the distortion also increases again.
This point is the upper frequency limit of the signal that may be
applied to this loudspeaker. If with passive crossover filters (see
later on) the corner frequency falls in this fourth region, then
impedance compensation has to be used (this will be a topic in
the next instalment).

Why Crossover Filters?


As we have seen in the example above, loudspeakers can only
reproduce a limited frequency range well. That is why the audio Figure 5: Distortion.
spectrum has to be split into a number of regions, each of which
is then applied to a loudspeaker that was designed specifically
for the corresponding range. This is the purpose of the crosso-
ver filter, which ensures that each loudspeaker is served with the
correct frequencies.
loudspeaker. In this case we speak of an active crossover filter.
This can, in principle, be done in two different ways: the signal
can be split after the power amplifier with the aid of a passive filter As an aside, there is also a hybrid form possible: here the low
network (that comprises inductors and capacitors), or the signal frequencies are separated from the remainder using an active filter,
can be separated earlier into the different frequency ranges, after and for this remainder a passive filter is used. This is sometimes
which each signal range then has its own power amplifier and called bi-amping.

lektor January & February 2022 93


Low pass High pass

Below we will continue with passive crossover filters; active filters


will be dealt with in a later instalment.

Passive Crossover Filters


Figure 6 shows the schematics of both a low-pass and a high-pass
Figure 6: Passive low-pass and high-pass filters with a slope of 12 dB/octave.
filter with a slope of 12 dB/octave. Slopes of 6 dB/octave, which can
be realised with a series inductor or capacitor respectively, must be
avoided in audio applications. Figure 7 illustrates the frequency
characteristics of these filters.

The corner or crossover frequency of a filter is the frequency at


which the level of the output signal has been reduced by 3 dB
compared to the input signal. Figure 8 demonstrates that at the
corner frequency the phase of the output signal is displaced +90°
(high-pass filter) or –90° (low-pass filter), compared to the phase
of the signal in the pass-band.

When the loudspeakers are connected with equal phases, their


signals in the region of the crossover frequency are displaced by
180° with respect to each other, and these signals will therefore
then cancel each other. The result would be a ‘dip’ in the characte-
ristic of the system, as can be seen in the lower curve of Figure 9.
Figure 7: Frequency characteristics of a high-pass and a low-pass
filter.
In principle it doesn’t matter which of the two speakers needs to
have its terminals reversed, but to guarantee that any two loudspea-
ker boxes that are positioned near each other have the same phase,
it is recommended that we stick to the international ‘standard’: the
low-frequency speaker is connected normally and the high-fre-
quency speaker is connected with reversed polarity.

Although having stated that, in practice we cannot blindly trust


the labelling that the manufacturer places next to the terminals
of their loudspeakers – firstly because any manufacturer can do
whatever they please, and secondly, as a consequence of a difference
in delays, the phase can actually be the opposite at the crossover
frequency. Both with active and with passive filters the polarity of
the loudspeakers must always be verified in practice.
Figure 8: Phase characteristics of a high-pass and a low-pass filter.
For the values of the components the following holds (for a Butter-
worth characteristic):

1 0.1125
C 
2 2  f  Z f Z
Z 0.2251  Z
L 
2   f f

Various characteristics are popular for the design of crossover filters,


each of which has its advantages and disadvantages with regards to
the slope at the crossover frequency and impulse behaviour; for
further details, we refer you to the relevant professional literature.
Figure 9: Correctly and incorrectly connected crossover filter.
Figure 10 shows the basic schematic of a band-pass filter, which is
really just a series connection of a low-pass and a high-pass filter.

94 January & February 2022 www.elektormagazine.com


The upper and lower corner frequencies are then also calculated
using the familiar method. L1 C2
210564-01
C1 L2 RL
The series of articles “Starting out in electronics” is based on the book,
Basic Electronics Course, by Michael Ebner, published by Elektor.

Figure 10: Band-pass filter.


Questions or Comments?
Do you have any technical questions or comments prompted by
this article? Send an email to the author or to the editor of Elektor
via [email protected].
RELATED PRODUCTS

> B. Kainka, Basic Electronics for Beginners,


Elektor 2020. (SKU 19212)
Contributors www.elektor.com/13950
Idea and illustrations: Michel Ebner
Text and editing: Eric Bogers > B. Kainka, Basic Electronics for Beginners (E-Book),
Translation: Arthur de Beun Elektor 2020. (SKU 19213)
www.elektor.com/18232
Layout: Giel Dols

(INT0)PD2 1-WIRE
4 2
VCC T1
6 3
VCC BSN20
C3 C4 C5 18 30 K2
100n 100n AVCC (RXD)PD0 RXD
100n 3
31

Post your ideas and


(TXD)PD1 TXD
20 +3V3 +3V3 2
AREF 1
10
(AIN0)PD6
12 11

electronics projects
PB0(ICP1) (AIN1)PD7
13 PB1(OC1A)
1 MOSI L1 MOD1
14 PB2(SS/OC1B) 23
(ADC0)PC0
3
15 24
FERRITE BEAD RXM-433-LR
PB3(MOSI) (ADC1)PC1 LED1
5 16 25
PB4(MISO) (ADC2)PC2 R3 R7 R1 1 16
7 SCK 17 26 NC ANT
9 MISO
all sizes / all levels / all sorts 7
PB5(SCK) (ADC3)PC3
27
2
NC GND
15
220

10k

PB6(XTAL1)
10

(ADC4/SDA)PC4 3 14
8 28 NC NC
X1 PB7(XTAL2) (ADC5/SCL)PC5 4 13
GND NC
8MHz 1 5 12
(INT1)PD3

at www.elektor-labs.com
VCC NC
9 S1 C9 6 11
(T1)PD5 PDN NC
21 7 10
RSSI NC
GND

and become famous!


19 LEARN 9
5 ADC6 22µ NC
C1 C2 GND 22
3 ADC7
22p 22p GND DATA 8
L2 DATA
FERRITE BEAD
2 +3V3 +5V
(XCK/T0)PD4 +3V3
29
(RESET)PC6 IC2
R6
LD39015M33R
Create a project now at:
10k

1 5
IN
www.elektor-labs.com 3
EN
OUT
NC
4

200136-007 KD
design > share > sell R2
100
C6
100n
C7

GND
2

lektor January & February 2022 95


interactive

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

An In-Depth Look at
Mains Transformers
Elektor 09-10/2021, P. 34
(200587)
A connection to earth is missing from the
schematic of the test rig shown on page 35
(see picture).

B4
B1 KBPC3510
F1

Single Phase 1-kW


DB107 6A

Tr1 MGND

AC Motor Drive
K4
1
K2 S1 C1 L
12V 470µ S 2
L P (N)
Elektor 1-2/2020, P. 62 (191142) N
P 50V
O
3
(N)
S2
RE1 2 1
12 V B2
A mistake was found in the DB107

schematic of the PSU board for the Single- C2


D1
T1
1N4007
phase 1-kW AC Motor Drive shown on page 470µ
50V
MGND
BC547

64 of the January/February 2020 edition. R1 VR1 C4


B3 3W IC1 V25S275P 220n
DB107 PC817X4J000F R6 630V
47k

1
The diodes in the bridge rectifier B4 are 1 3 5
R2 4 5W
560
10k

drawn the wrong way round. To make the K1

2 4 6 2 3
drawing correct, the four-diode symbol
+5V
should be rotated 180°. The ‘+’ and ‘-‘ sym- T2
STW26NM60N C3
bols on the drawing are correct and the PCB 220n
630V
IC2
is correct also. 1
4 R3 D2
1k

R4 12V R5
10k

1 3 5 ZCross
2k2

1W 2W
3
K3
2 PC817X4J000F
2 4 6
Gate
MGND

150199-11 KD

96 January & February 2022 www.elektormagazine.com


Differential Oscilloscope Current Probe 2.0
Elektor 11-12/2020, P. 68 (180665)
The INA849 from TI is a better pin-compatible alternative to
the AD8421 used in this probe design. It does not require any
frequency response compensation and has a significantly higher bandwidth.
It is only necessary to adjust the value of the resistor which sets the gain.
Alfred Rosenkränzer

Joy-IT LCR-T7 Multifunction Tester Balcony Power Plant


Elektor 11-12/2021, P. 22 (210365) Elektor 09-10/2021, P. 44 (210326)
The article gives the impression that Joy-IT devel- Want to use SmartHome sockets to measure solar
oped the described device itself. This is definitely power feed in? Our reader Jörg Trautmann wanted
not the case. The LCR-T7 is a copy of a community project to do this and wrote us about his experiences:
based on an open source project (www.mikrocontroller.net/
articles/AVR_Transistortester). The idea for an
​​ automatic tran-
In my own PV installation I was a bit disappointed that the first
sistor tester originally came from Markus Frejek, it was taken
SmartHome sockets I tested could only measure power con-
up by several other enthusiastic electronics hobbyists such as
sumed by an appliance and would not show power fed into the
Markus Reschke, Karl-Heinz Kübbeler, Pieter-Tjerk de Boer and
socket from a grid-tie inverter and PV system. After a long period
many others who improved the design using a lot of their own
of searching, I discovered the LogiSmart PA0066 SmartHome
effort and expertise. There is also a special forum for the tes-
socket from LogiLink, which can actually measure power fed into
ter (www.mikrocontroller.net/topic/transistortester-avr), where
the mains. As far as I know, the simplest method for measuring
development of the design is documented all the back to 2012.
current is to use a current clamp; the direction of current flow
No reference is made to this resource in the Elektor article.
is irrelevant for the measurement. Here the units should use a
I assume this omission was not deliberate but as a result of
different method of measurement, which is a very interesting
incomplete knowledge on your part. There is a lot of discus-
aspect of their design.
sion these days about IP ownership, plagiarism and copyright.
There is no suggestion that any law has been violated, as far Jörg Trautmann
as I know the original authors of this copied design have made
N.B. The smart socket referred to accepts standard German
no claims to copyright or sought any financial compensation
domestic mains plugs, in the UK a grid-tie inverter should only
for the commercial exploitation of their ideas. Fairness dictates
be connected to the mains wiring via its own isolator.
that honor be given where honor is due.
Marcel “Derri” Derrmann

Dear Mr Derrmann,
Thank you for your detailed information.
You are of course right that we did not
set out to reinvent the wheel. The original
developers of this project deserve great
respect for their fantastic idea and the
work they put into its design. Our com-
pany not only develops its own original
equipment, but also takes great ideas and
tries to build them into a quality finished Questions or Comments?
product for developers and makers at If you have any questions
the most attractive price possible. Our or comments, please let us know.
development department is often You can reach us by email at
responsible for adding the ‘finis- [email protected].
hing touch’ here.
Volker Bode, SiMAC/Joy-IT

210560-01

lektor January & February 2022 97


project

Color to Sound
How to Read Out a Color Sensor via I2C
By Annika Schlechter (Germany) and
Volker Ziemann (Sweden)

Electronics can be helpful for


handicapped people, as this
educational project demonstrates.
For those who cannot see colors
themselves, a color sensor can do
the job; a buzzer is used as acoustical
feedback, for color and brightness
information. Here we report on two
versions of the project, based on an
inexpensive Arduino Nano. Figure 1: Schematics of the prototype. A piezo buzzer and a TCS34725 color
sensor, mounted on a small breakout board, are connected to an Arduino
Nano.

How can a seeing-impaired person select clothes with matching colors Arduino IDE. As a second prerequisite, we need to install python [5],
in the morning? Well, by converting the color information into a sound which is likewise available for all systems. Windows and MAC OS
signal, which is the idea behind this project. The color is converted to binaries can be found on [5] and practically all Linux distributions have
the pitch of a sound and the brightness to its duration. packages in their repositories. Again, follow the instructions for your
system. But, enough of the preliminaries, let’s get started!
Figure 1 shows the schematics of a prototype, with a piezo buzzer
and an ams TCS34725 color sensor mounted on a small breakout The Color Sensor
board [1]. Both are connected to an Arduino Nano. This prototype The heart of this project is the TCS34725 color sensor [6], which
system was developed as part of the course “From Sensor to Report” comprises a 3x4 photo-diode array (Figure 2). Color-sensitive filters
at Uppsala University [2], which teaches basic data-acquisition skills mounted in front of the diodes make them sensitive to red, green, and
including interfacing of sensors and microcontrollers to the outside blue light. Moreover, a clear diode without a filter provides information
world. Therefore, we do not use ready-made libraries to interface the
sensor, but code the basic functions to read out the sensors ourselves.
Moreover, the logic to assign the sounds to the colors initially resides
in a Python script on a laptop, rather than on the microcontroller. The
PC and microcontroller are communicating via a serial interface. We
developed a communication protocol to send sensor values from the
Nano to the PC; commands are going in the other direction to activate
the buzzer with the right frequency. Later, however, we extended the
functionality to allow stand-alone operation on the Nano. Still, this is
not a production-ready system, but a prototype that shows the basic
functionality and invites the reader to experiment further.

Before starting to assemble components, we need to install the Arduino


development system (IDE) from [3] in order to develop programs for the
Nano. The IDE is available for all commonly used operating systems. Figure 2: The TCS34725 color sensor integrates a 3x4 photo-diode array.
Please follow the instructions relevant for your system. If you have not Color-sensitive filters mounted in front of the diodes make them sensitive to
used Arduinos before, please follow [4] to familiarize yourself with the red, green, and blue light. Source: Datasheet / ams [6].

98 January & February 2022 www.elektormagazine.com


RELATED PRODUCTS

> Arduino Nano (SKU 17002)


www.elektor.com/17002

> Breadboard (830 Tie Points) (SKU 17092)


www.elektor.com/17092

Figure 3: The hardware (see Figure 1) is assembled on a solder-


less breadboard (here without the button).

about the brightness. The analog signal from the diodes is converted to read out two 8-bit registers and assemble the received bytes to a
to digital form by on-board analog-to-digital converters. The color 16-bit word - following the instructions from the data sheet. This is
information is made available via an I2C interface that connects to shown in the following code snippet for the red color:
a microcontroller using only two wires for the communication, one
for the clock signal (SCL) and one for data (SDA). The color sensor b3=I2Cread(TCS34725,0x16); // raw data, red
is then controlled by writing and reading registers on the device, but b4=I2Cread(TCS34725,0x17);
more on that later on where we describe the software. red=b4*256+b3;

The hardware is assembled on a solder-less breadboard (Figure 3), Here b3 contains the least-significant byte and b4 the most-signif-
pretty much following Figure 1 with the Nano shown on the left-hand icant byte, which we multiply by 256 and add to b3 to obtain the
side and the TCS34725 color sensor on the right. The latter is connected 16-bit variable red. We treat the other colors likewise; only the register
by black and red wires to Ground and the 5 V rail at the bottom. addresses are adapted.
Likewise, the corresponding pins of the Nano are connected to the
power rails. The green and yellow wires connect the data (SDA) and Additionally, we use the brightness reported from the un-filtered diode
clock (SCL) pins to the corresponding pins on the Nano, which are and store it in the variable clea. This will determine the duration d of
situated on A4 and A5, respectively. The blue wire that connects the the sound. If the value of clea is less than 1000, we emit a 0.5 s long
digital output pin D2 to the pin labeled LED on the color sensor allows to tone; and if it is larger, we use 1.5 s.
control a white LED that is mounted on the breakout board. The buzzer
is connected to pin D8 on the Nano. The button that connects pin D3 Now we read the received command and copy the result into a charac-
to ground with the brown wires triggers a conversion when operat- ter array line, so we can use the standard C function strstr() to
ing the Nano in the standalone mode of operation, discussed below. find out which command was sent. The following code snippet illus-
trates this:
This circuit is brought to life by an Arduino sketch that first includes
the wire.h library to provide low-level functions to communicate over Serial.readStringUntil(’\n’).toCharArray(line,30);
the I2C lines. These functions are used right away in our own two if (strstr(line,"color?")==line) {
functions I2Cread() and I2Cwrite(), which encapsulate all commu- Serial.print(clea); Serial.print(" ");
nication with the sensor. Serial.print(red); Serial.print(" ");
Serial.print(green); Serial.print(" ");
I2Cread() is used to readout a sensor value or parameter, stored in
Serial.println(blue);
so-called registers. As parameters, the function gets the address of
} else if (strstr(line,"tone_red")==line) {
the sensor on the I2C bus, here 0x29, and the register address (it took
tone(buzz, 262, d);
us a while to find out that 0x80 has always to be added to the latter).
The function returns the contents of that register. ...

The function I2Cwrite() is used to send commands from the control- We see that the command color? causes the Nano to send the values
ler to the sensor, for example to set configuration values. This function of the four signals clea, red, green, and blue back across the Serial
gets the sensor and register addresses and, additionally, the new value line. If tone_red is received, the built-in tone() command is used to
that should be written to that register. No value (void) is returned activate the piezo buzzer - in that case with the frequency which is
from this function. assigned to the red color. Several equally constructed strstr() blocks
follow and trigger the appropriate actions.
The Application
Let’s return to our specific sketch. In the setup() function, we initialize Note that we use a simple protocol, based on sending character strings
the serial communication, the basic I2C functionality and the sensor back and forth; a request from the laptop is terminated with a question
(via function color_begin()). Inside the loop() function, which is mark, for example “color?”, and the Nano responds by sending the
executed indefinitely, we first check whether any command from the values back. An instruction is based on just sending the command, for
PC has arrived on the serial line. If that is the case, we read the register example, “tone_red", which causes the buzzer to sound with 262 Hz for
contents from the sensor, for all three colors. For one color, we have the duration specified by d. The communication vaguely mimics the

lektor January & February 2022 99


SCPI command language that is supported by modern About the Authors
oscilloscopes and other test and measurement equip- Volker Ziemann’s interest in
ment. This makes interfacing to external programs that electronics started with Elektor,
support accessing the serial line very simple; python, around the time of the 40W
octave, Matlab, and Labview all support this. Edwin amplifier (mid-1970s), but he got sidetracked to studying physics and
worked with particle accelerators ever since — SLAC in the US, CERN in
The PC Program Geneva, and now in Uppsala, Sweden. Since electronics plays an important
We used Python 3 on the laptop to communicate with the role for control and data acquisition in accelerators, his early interest has
Nano. The very basic code is shown in Listing 1. been useful throughout his career. He now teaches at Uppsala University
and has authored three books, one of them about data acquisition with
After importing support for the serial communication Arduino boards and the Raspberry Pi.
and basic timing functionality we open the Serial port
to which the Nano is connected at the baud rate that Annika Schlechter is studying toward an MSc in Physics at the University of
matches that chosen on the Nano. Giving the operating Heidelberg, Germany. At the moment, she is continuing her studies during
system 3 seconds to establish the connection we then her Bachelor thesis at the German Cancer Research Institut in Heidelberg.
send the command “color?”. This project began during an Erasmus semester at the University of
Uppsala, Sweden, where she attended Volker’s lecture “Sensor to Report.”
Note that Python 3 encodes character strings as Unicode,
whereas the Nano expects plain ASCII strings. We there-
fore have to prepend the letter “b” to the command
“color?” in order to send the string as plain ASCII data.
After another short wait, we receive the response from
the Nano in the variable reply, which contains the values
of the four colors that we individually retrieve with the Listing 1: Python script for laptop communicating with Arduino Nano.
.split() method and assign to mnemonic names, such
as red. # colortosound_arduino.py
import serial, time

Having the values available, we are ready to implement


ser=serial.Serial("/dev/ttyUSB0",9600,timeout=1)
the logic to assign the sounds to the colors. This assign- time.sleep(3);
ment is based on quite a bit of experimentation with
colored paper sheets until a good setup was found. We ser.write(b"color?\n") # write command to get colors
used paper with a light, medium, and dark tone for each time.sleep(2);
of the three base colors in order to calibrate the sensor.
We repeatedly measured the respective color values at reply=ser.readlines() # read answer
a fixed distance and used that information to specify the
constants in the python code shown above. For example, # process answer to get color values
the command tone_red is sent to the Nano, if the red colors = reply[0].split()
for i, entry in enumerate(colors):
component, normalized to the intensity, is larger than 0.6.
colors[i]= int(entry.decode(’utf-8’).replace(’\r\n’, ’’))
Next we test the green intensity and send tone_green if
the threshold is exceeded. Finally, the value of the blue intensity = colors [0]; red = colors [1]
component is tested. If even that does not qualify, “no_ green = colors [2]; blue = colors [3]
color” is sent to the Nano, causing it to emit the corre-
sponding tone. Certainly some experimentation with the # write command to control buzzer according to color
constants is needed in order to adapt the system to your
wardrobe. if red/intensity > 0.6:
ser.write(b"tone_red\n")
Standalone Version elif green/intensity > 0.3:
The standalone version of the code is available from this ser.write(b"tone_green\n")
elif blue/intensity > 0.24:
article’s website [7]. It closely follows the example above,
ser.write(b"tone_blue\n")
except that instead of waiting for a command arriving on
else:
the Serial line, the Nano now waits for the button to be ser.write(b"no_color\n")
pressed before reading the sensor and emitting the appro-
priate sound. Moreover, the color information is directly ser.close()
processed on the Nano as shown in the following snippet:

if (red/clea > 0.6) {


tone(buzz, 262, d); If it is desirable to always illuminate the clothes with the built-in LED on the break-
} else if (green/clea > 0.3) { out board, we can turn it on with digitalWrite(led,HIGH) just before reading
... the registers from the TCS34725 and turning it off afterwards.

100 January & February 2022 www.elektormagazine.com


I2C Communication
The communication between two integrated circuits, hence I2C, is read a register from the sensor, it transmits the bit to indicate that
based on a synchronous serial protocol that is carried by two wires. the sensor is now in charge of SDA, and reads SDA synchronously
It follows the simple rule to detect the voltage level on one of the with the clock signal that the microcontroller continues to generate.
wires, called SDA, after the voltage on the other wire, called SCL,
has changed. One such reading provides a single bit and eight con- The upper image in the figure illustrates writing to the sensor. The
secutive bits constitute one byte. One of the participants on the I2C bits that are shaded dark are controlled by the microcontroller
bus, usually a microcontroller, orchestrates the communication and and the un-shaded bits by the sensor. To initiate a transaction, the
always provides the clock signal. The other participants have a chance microcontroller creates a start condition, denoted ’S’, followed by
to enter the communication, if they are addressed and given the right the seven bits of the sensor’s address and the eighths bit set to
to put their information on SDA. Moreover, after each byte the sensor indicate that the controller wants to continue sending. One bit ’A’
is given one clock cycle to acknowledge receipt of the previous byte. is provided by the sensor to indicate that it understood. The sec-
ond byte contains the address of the register on the sensor and
In order to initiate the communication with a sensor, the micro- one byte with the value to be written to the register. Note the bit
controller sends one byte. The first seven bits of that byte contain labeled ’A’ where the sensor has to acknowledged each received
the address and the last bit indicates whether the controller or the byte. Reading from the sensor, shown by the lower image in the
sensor is in control of SDA to transmit the following byte. If the con- diagram, works pretty much the same way, only the eights bit of the
troller wants to continue sending, for example to change a register first byte now indicates that the sensor is given the right to ’speak’
on the sensor, it sends two additional bytes, the register address and SDA is subsequently controlled by the sensor, while the mi-
and the new value. If, on the other hand, the controller wants to crocontroller has to acknowledge every received byte.

Source: TCS34725 data sheet / ams [6].

In a third stage, we can make the system portable by using a bare plots were recorded just before Christmas and made us painfully aware
ATmega328, flashed with an Arduino bootloader, connected to the of how short the days can get in Uppsala. Further data acquisition
sensor. Powered from a battery as long as a button is pressed, the projects, following the same spirit, are described in [8].
system starts up and continuously converts color to sound until the 210051-01
button is released to disconnect the battery. The software is also avail-
able from the article’s web page. Building the system is left as an Questions or Comments?
exercise for enthusiastic readers. Do you have technical questions about this article? Please email
the editors at [email protected].
In the “Sensor to Report” course the color sensor was quite popular.
A second student, who wanted to monitor the color of the sky over a
longer time to later analyze the data, used essentially the same setup Contributors
with the Nano communicating with a host computer via the Serial Design and Text: Annika Schlechter, Volker Ziemann
line. She used a python script on a Raspberry Pi to store the data in Editor: Jens Nickel
a MySQL database, also running on the Pi, and later used Octave to Layout: Sylvia Sopamena
prepare plots of the colors that were recorded over about a week. The

WEB LINKS
[1] TCS34725 breakout board: https://www.adafruit.com/product/1334
[2] “Sensor to Report” course: https://ziemann.web.cern.ch/ziemann/teaching/s2r19/
[3] Arduino website: https://www.arduino.cc/
[4] Arduino tutorials: https://www.arduino.cc/en/Tutorial/HomePage
[5] Python website: https://www.python.org/
[6] TCS34725 Color Sensor datasheet: https://ams.com/tcs34725#tab/documents
[7] Software Download: http://www.elektormagazine.de/210051-01
[8] V. Ziemann, A Hands-on Course on Sensors using the Arduino and Raspberry Pi, CRC Press, 2018.

lektor January & February 2022 101


review

BattLab-One
Measure and Optimize the Battery Life of IoT Devices

By Tam Hanna (Slovakia)

When you need to choose a suitable


battery for your next battery-powered IoT
design, you could sit down with a DVM and
measure the active and sleep current to
estimate roughly how long the device will
run from a single charge. The design could
then be optimised by perhaps altering the
ratio of sleep to active mode and maybe
by choosing a different battery type and
capacity. The BattLab One is a USB-powered
device that can do all this at a click of a
mouse button. It both powers the device
under test and also shows all data relating
to expected battery life.
Figure 1: The BattLab-One and its aluminum housing.

Obtaining a consistent measurement of the energy consumed by makes accurate measurements of power consumed over defined
a device running a microcontroller is not a trivial task. As with periods of time. Professional examples of SMUs are manufactured by
any computer chip, power consumption depends heavily on the Keithley and Keysight. The BattLab-One from Bluebird Labs aims to
instantaneous processing load and operational status. It is not fulfill a similar function, but for a price of less than €100. The device
only necessary to consider normal operation and standby or deep (including metal enclosure) is available from the Elektor shop [1].
sleep states, in which the current consumption of common micro-
controllers can vary between less than 1 µA and several hundred Refer to Figure 1 to see the USB type B socket on the left together
milliamps (mA). Some peripherals in the device may also only with a BNC socket that accepts a trigger input signal. On the right
be active at certain times so that current consumption will not are the two 4-mm sockets from which the DUT can be powered.
be constant. A specialized tool like BattLab-One is very useful in Figure 2 shows the plastic collars, which can be unscrewed to allow
this respect and can take this dynamic behaviour into account to croc clips to be attached to the posts. A closer look at the case end
make a reasonably realistic estimate of the operating time of the caps shows a surface texture consistent with 3D printing.
device when powered by different battery types.
BattLab-One is powered from a computer USB port and is able to
What Is BattLab-One? supply devices with a range of supply voltages from 1.2 to 4.5 V
In the field of power consumption measurements, a source measure and currents up to a maximum of 450 mA. The discharge profiles
unit (SMU) is a useful tool to have on the workbench. This type of of frequently used battery types (such as Li-Ion, LiFePO4, alkaline,
power supply provides power to the device under test (DUT) and also NiMh and NiCd technology) are included in the software and used

102 January & February 2022 www.elektormagazine.com


to calculate expected battery life. BattLab-One does not take into
account subtleties such as load and battery age related voltage
drops. According to the manufacturer, the measuring device offers
a basic battery simulation and a current measuring range from
10 µA to 500 mA. A 16-bit ADC sampling at 1 kHz is incorporated
into the design to measure current to the DUT.

BattLab-One and Linux


Software for the device was developed by Bluebird Labs using
Python. As a first attempt, I was keen to get the system working
directly under Ubuntu 20.04 LTS. The software source code is avail-
able from GitHub [2] and can be compiled using the usual methods.
However, Bluebird Labs has taken a different approach by using
pipenv. Anyone who, like me, has only installed the usual venv
variant needs to install pipenv. For me the process went as follows: Figure 2: Croc clip power hook up.

tamhan@TAMHAN18:~/BattLabonespace/
BattLab-One$ sudo apt install pipenv

The first problems arose when setting up the Virtual


Environment, as Python version 3.7. is assumed. If,
like me, you want to use a newer version (i.e., version
3.8 preinstalled under Ubuntu 20.04 LTS), the follow-
ing statement will be required:

tamhan@TAMHAN18:~/BattLabonespace/
BattLab-One$ which python3 Figure 3: PipEnv error message.
/usr/bin/python3
tamhan@TAMHAN18:~/BattLabonespace/BattLab-One$ pipenv
install --dev --python /usr/bin/python3

Now let’s consider the process of creating a virtualenv for this project.
The software issues warnings (Figure 3) when the commands are Unfortunately, Bluebird Labs does not comply with the setup tools
entered. The virtual environment is therefore activated according specification but explicitly includes a library that is only available
to the following scheme. It will remain active like a normal venv in a few versions of the setup tools. The .py file must be edited to
environment until the terminal window is closed: remove the following statement:

tamhan@TAMHAN18:~/BattLabonespace/BattLab-One$ pipenv import pkg_resources.py2_warn


shell
. . . Now the software has a problem with the local paths:

Execution of the three .py files with the software is now possible (BattLab-One-CK7P-15V) tamhan@TAMHAN18:~/
using to the following method: BattLabonespace/BattLab-One$ python
BattLab-Release_V1.2.1.py
(BattLab-One-CK7P-15V) tamhan@TAMHAN18:~/ . . .
BattLabonespace/BattLab-One$ python3 _tkinter.TclError: error reading bitmap file "icons\
BattLab-Release_V1.2.1.py bbirdlogo.xbm"
Traceback (most recent call last):
The solution is to modify the TK-Inter-GUI by removing the line:
File "BattLab-Release_V1.2.1.py", line 59, in
<module>
root.iconbitmap(bitmap=GetIconPath())
import pkg_resources.py2_warn
ModuleNotFoundError: No module named ’pkg_resources.
to remove the program icon. On this occasion you can adjust the
py2_warn’ file path using:

lektor January & February 2022 103


Figure 4: The BattLab Linux GUI. Figure 5: BattLab-One records and displays the DUT current consumption.

provided under [3]. The ZIP archive includes, among other things,
img = PhotoImage(file=’/home/tamhan/BattLabonespace/ the SOC_profiles subfolder, which contains the various battery
BattLab-One/icons/bbirdlogo_png1.png’) profiles in tabular form. You will need to unzip the archive.

The next attempt to execute it shows that the TK-Inter environment When BattLab-Release_V1.2.3.exe file is executed, the user inter-
is looking for the bblogo.gif file in the wrong folder face display looks similar to the Linux version in Figure 4. The
Windows version behaves largely in the same way but has fewer
_tkinter.TclError: couldn’t open "/home/tamhan/. rendering errors. First, we can select the battery type up in the top
local/share/virtualenvs/BattLab-One-CK7P-15V/lib/ left area. The associated battery data is used to create the character-
python3.8/site-packages/matplotlib/mpl-data/images/ istic discharge curve shown at the bottom right. To the right of the
bblogo.gif": no such file or directory PSU Output field, On and Off buttons switch the integrated voltage
converter to power the DUT connected at the two output sockets.
You can therefore copy any GIF file into this directory and give it the
appropriate name. If you now comment out the following line, you can I have been working on my own IoT sensor project called HygroSage
start the program with a slightly limited range of functions (Figure 4): for some time now. With its colour display and powerful processor, it
would be an ideal candidate to test out BattLab-One. I connected the
#toolbar.children[’!button8’]. sensor. By clicking on the option Capture Active, the software shows a
config(command=select_range) flikering green progress bar labeled Active Event Current and then does
nothing visible for 10 seconds. During this time, the system measures
Deactivation of the measuring range button turns out to be uncrit- the information and finally displays it as shown in Figure 5.
ical in practice, because the MatPlotLib diagram is problematic in
terms of usability anyway. Many labels appear cut off and the size The value of any point of the waveform can be displayed using the
of the window cannot be adjusted. cursor. In practice, however, this does not work quite as convinc-
ingly because the value indicated in the text box below does not
As we will see, the program has fewer problems running in Windows show the measured value, but the position of the mouse pointer
10. Before changing the operating system, we can tidy up to remove the on the graph. This means you need to move the mouse pointer to
created virtual environment and thereby free up mass storage space: a point on the curve. In addition, there is no really convenient way
to zoom into the diagram (generated by MatPlotLib). Despite the
(BattLab-One-CK7P-15V) tamhan@TAMHAN18:~/ full HD resolution of my screen, I wasn’t able to expand the user
BattLabonespace/BattLab-One$ exit interface screen but it is possible to select an area of the waveform
exit using the Zoom to Rectangle option.
tamhan@TAMHAN18:~/BattLabonespace/BattLab-
For testing purposes, I connected a calibrated, high-quality multi-
One$ cd /home/tamhan/.local/share/virtualenvs/
meter in series with the DUT, which measured a current of around
BattLab-One-CK7P-15V
32 mA. BattLab-One did not agree with this; it would seem the type
tamhan@TAMHAN18:~/.local/share/virtualenvs/BattLab-
MCP1640 switching regulator in BattLab-One generates noise that
One-CK7P-15V$ rm * -rf actually interferes with BattLab-One. As a second test, I used a 1-kΩ
tamhan@TAMHAN18:~/.local/share/virtualenvs/BattLab- resistor as a load for BattLab One and specified output voltage of 3 V.
One-CK7P-15V$ ls The result is the trace showing measurement quantisation noise
in Figure 6. Connecting a 100-µF electrolytic capacitor in parallel
BattLab-One Running in Windows 10 to the HygroSage did not result in any significant improvement of
The situation here is simpler in that ready-made .exe files are the quantised current consumption waveform.

104 January & February 2022 www.elektormagazine.com


Figure 6: Trace showing current through a 1-kΩ-resistor at 3 V with some Figure 7: Battery life can be optimised using sleep
noise evident. and active mode current values and battery capacity.

Sleep Mode Capture and Optimization gives you the opportunity to explore BattLab’s inner workings and
Once the active current consumption has been captured in Step even to adapt and improve the software as required so that BattLab-
2, we can move on to Step 3 to measure sleep current. Here we One fits your own requirements. When it comes to hardware,
need to ensure the DUT will be in sleep mode when the measure- BattLab-One does a lot of things right and very little wrong. Its
ment is taken. We now enter parameters as we did in Step 2 for the low price and high performance makes it a good addition to the
active mode capture. Unless things went badly wrong with your test bench for those developing IoT devices.
design the device will always consume significantly less power 210473-01
in sleep mode. BattLab-One gives you the option to switch the
current range in sleep mode between 10 uA – 800 µA or 800 µA Questions or Comments?
– 500 mA to improve measurement resolution. Be aware that the Do you have any technical questions or comments about this article?
device shouldn’t draw too much current in the lower measuring Contact the author at [email protected] or Elektor at
range. According to the documentation, a load current exceeding [email protected].
250 mA can damage the hardware. With the DUT running in sleep
mode we can now press Capture to record the current.
Contributors
The results after a test with Hygrosage are shown in Figure 7. In Text and illustrations: Tam Hanna
Step 4, the system displays the calculated values. Using this data Editors: Dr. Thomas Scherer, C. J. Abate
we can play around with the battery characteristics and capacity Translation: Martin Cooke
together with the active/sleep times and then click on Optimize Layout: Giel Dols
to easily see what sort of battery life we can expect for the device
when it is deployed in the field.

The battery life prediction will be reasonably accurate for devices


which operate with a defined active and sleep period. Some devices
rely on an external event interrupt to wake from a sleep mode; in
this case, we can only work out the battery life by using an estimate
of how often we can expect the interrupts to occur.
RELATED PRODUCTS

To Sum Up
The BattLab-One hardware is quite usable. This software however > BattLab-One – Battery Life Optimizer, with Enclosure
(SKU 19757)
has scope for improvement. The design is open-source so we can www.elektor.com/19757
expect its evolution to benefit from community support. This also

WEB LINKS
[1] BattLab-One: www.elektor.com/battlab-one-battery-life-optimizer-with-enclosure
[2] Software at Github: http://github.com/petersdw1/BattLab-One.git
[3] Software for Windows 10: https://github.com/petersdw1/BattLab-One/releases/tag/V1.2.3

lektor January & February 2022 105


project

Simple Earth-Leakage Tracer


Testing Isolation of
Mains Supply

By Elbert Jan van Veldhuizen (The Netherlands)

Residual-current circuit breakers are


essential safety devices in our domestic
mains supply installation, but sometimes
they can switch off (trip) for no apparent
reason. A professional earth-resistance
tester (or megohmmeter) will help to locate
the leak, but the easy-to-build earth-leakage
tracer presented in this article proves to be a
safe, affordable and useful alternative, using
standard CR2032 lithium batteries for the
high-voltage power supply.

WARNING. Working with mains voltage can be fatal. The circuit described here is
not for beginners. Do not build or use it unless you are experienced in dealing with
mains voltages!

106 January & February 2022 www.elektormagazine.com


Residual-current circuit breakers have saved many lives from fatal
electric shocks. Where the older generation knows examples of people S2 R2a
100Ω
who were electrocuted because of — for example — a broken lamp S1 S3 R1

socket, this is unlikely to happen with more modern electrical instal- R2b
2k2
R4
lations. A residual-current device (RCD) detects current differences 10Ω

100k
between the Live (L) and Neutral (N) leads (i.e., if current leaks via Bt1 96V M1 R3
the earth). If this difference is more than 30 mA, the residual-current 11k

circuit breaker will switch off. An alternating current of around 30 mA D2 60µA


Rm=2k4 D1

through the human body is potentially sufficient to cause cardiac arrest


1N4148
or serious harm if it persists for more than a fraction of a second. RCDs
are designed to disconnect the conduction wires quickly enough to 200576-006

prevent serious injury [1].

Figure 1: The schematic diagram of the earth-leakage tracer.


An earth-leakage circuit breaker does not only switch off when a person
touches the live wire; moisture for example can also cause leakage
currents, like moisture in an outdoor wall socket or lamp. The source
of such a problem is often difficult to locate. A “simple” way is to first
switch off the mains power, then disconnect the various wires at the
junction boxes, switch the power back on to see if the earth-leakage also — even more important — in a safe way. In the latter respect, a
switch still trips and thus locate the problem by trial and error, but this lower voltage may be advisable and with the solution chosen for the
method does have its disadvantages. First of all, the power has to be power supply it also cuts the costs: the lower the voltage, the less
switched off and on again every time wires are (dis-)connected, which batteries we need to power this earth-leakage tracer.
increases the risk of errors and of accidentally working on a live circuit.
In addition, some earth-leakage problems occur only sporadically, not Why Batteries?
all faults are easily reproducible. The CR2032 is a 3 V lithium battery that, as the name implies, has a
diameter of 20 mm and is 3.2 mm thick. This makes this battery about
Why Design This Circuit? the same diameter as a standard C-battery, which is approximately
The designer of this project had problems with the electrical system in 50 mm long. With 16 CR2032 batteries stacked on top of each other,
the sunroom at his parents’ house: the RCD of this circuit occasionally we have about the same form factor as a C-battery, with a voltage of
tripped for no apparent reason. When he came to check the circuit 48 V. With two such “C-batteries” connected in series, we get 96 V
during the weekend, the earth-leakage switch remained switched and a standard, dual C-cell battery holder can be used. CR2032s
on during testing, but a few days later, it tripped again. Rather than are widely used in portable electrical appliances, toys, and gadgets,
simply testing if and when the RCD switches off, it is much better making them almost everywhere available at very reasonable prices.
to actually measure the leakage current. If we can measure leakage Other options, for about the same price, would be to use 64 LR44s,
current below RCD trip level, it is much more convenient to tackle or eight A23 batteries, but there are no standard battery holders for
(potential) problems. sale that can accommodate these stacks of batteries.

How to Measure At first, another consideration for the use of these batteries in this
In case of isolation issues in mains circuits, measuring resistance design was that, according to some sources (although it is difficult to
with a standard multimeter simply does not work. Anyone who has find conclusive data on this!), CR2032s can deliver only a relatively
measured the resistance of their skin with a multimeter will know the low current, on the order of 10 mA. A voltage of 96 VDC is potentially
paradox: it shows a resistance of around 1 MΩ (depending on how dangerous, for direct current (DC) the lethal current for humans is
wet or sweaty your hands are). That would mean that if you touch about 100 mA. But, according to the datasheets, the batteries cannot
230 V mains voltage, the current would be well below 1 mA, which deliver such a high current; so in theory, the batteries would make a
is far from lethal; you cannot even feel a current of this magnitude. safe power supply for the earth-leakage tracer. In practice, however,
However, the resistance is very much dependent on the voltage that the author measured (peak) currents of a few hundred milli-amps
is applied to perform the resistance measurement, with most multi- that could be sustained long enough to be potentially dangerous (see
meters this will not exceed 9 V. At 230 V, however, the resistance of textbox about the CR2032s). Therefore, for safety reasons, this design
the human body is in the order of kilo-ohms, which leads to currents includes a current limiting resistor.
of a few hundred milli-amps, which can certainly be harmful or even
lethal. This voltage dependency of the resistance is caused, among The Hardware
other things, by electrochemical reactions in the human body. For the measurement of the leakage current, the author used an
old-fashioned panel current meter that he still had lying around. The
So in order to make an accurate measurement of the leakage current, advantage of an analog meter is that it reacts faster than a (standard)
we must not measure at a low voltage — as a multimeter does — digital meter, so peak currents when switching on are also visible. The
but ideally with 230 V, which is the mains voltage in most European resistance of this meter (Rm) is 2.4 kΩ and the full-scale current (IFS) is
countries. The challenge for the author was to do this in a cheap, but 60 µA. With resistors, we must ensure that the meter has the correct

lektor January & February 2022 107


HOW MANY CR2032s ARE THERE?
The popularity of this type
of battery has the less
favorable side-effect that
there are numerous
manufacturers
producing CR2032s.
Apart from the
renowned brands, there
is an unknown number of
manufacturers making lithium batteries with a voltage of 3 V
with the same dimensions (20 mm diameter, 3.2 mm thick)
from which this button cell takes its type number. When it
comes to data like capacity, internal resistance and maximum
current, the “CR2032 standard” turns out to be much less of
a standard. And when it comes to the cheaper ones — the
ones you would prefer to buy when you need 32 batteries
— it is impossible to find out from which production line
they originate, and the packaging usually provides no more
electrical data than “3 V”. In retrospect, the general data found
by the author indicating that the short-circuit current of these
batteries would remain on the order of a few tens of milli-amps
turned out to be very optimistic in practice, from a safety point
of view. In practice, the CR2032s that he bought turned out to
have a short-circuit current of about 300 mA, which gradually
dropped to 80 mA after ten seconds. For this reason, it would
be a bad idea to omit resistor R1 that limits the current from
the earth-leakage tracer. Better safe than sorry!

Figure 2: How the author’s prototype is constructed.

range. But it is also wise to protect the meter against high currents > R3 is 11 kΩ (10 kΩ and 1 kΩ in series). This limits the meter to
with a diode. A diode will limit the voltage across the meter and its value ‘7’ on a full-scale of ‘8’: the diode limits the voltage across
series resistor R3 to 0.7 V. R3 and the meter to 0.7 V, resulting in a maximum current of
approximately 53 µA, while the full-scale value is 60 µA. The
Figure 1 shows the schematic of this earth-leakage tracer. R1 is the author therefore uses two diodes in series with a total voltage of
current limiting safety resistor; to be on the safe side, a resistor of 2.2 kΩ 1.4 V, so that full-scale range can be obtained, while the current
is used, which limits the current to around 45 mA. If this maximum through the meter stays within limits.
current flows, 4 W will be dissipated in resistor R2. So, either use a > R2a is 100 Ω (for 8 mA range)
power resistor or let the current only flow for a short time. > R2b is 10 Ω (for 80 mA range)

With the shunt resistor R2, the resistor R3, and the internal resistance Given the simplicity of the circuit and the small number of components,
Rm of the meter we can, under the condition that R2 is much smaller no circuit board is required to build this project, Figure 2 shows the
than R3 + Rm, use Ohm’s law to calculate the correct range of the meter: inside of the earth-leakage tracer built by the author. At the bottom
of this picture, you see the two stacks of CR2032 batteries wrapped
Vdiode  Rm  R3  I FS in tape, in a standard dual C-cell battery holder. The plus and minus
R3   Rm R2 
I FS terminals of these home-made 46 V batteries are marked with red
I scale
and black tape, respectively.

Measuring Earth-Leakage Current


where Iscale is the actual maximum output current of the circuit. Using this earth-leakage tracer is simple. When the device is switched
on with S1, the power LED D2 lights up. When button S2 is pressed, the
We can then tweak the resistor values so that standard (E12 range) measuring current flows to the terminals, crocodile clips are preferred
resistors can be used. The author used the following parts for his meter: to connect the test leads to the wires of the circuit that’s being tested.

108 January & February 2022 www.elektormagazine.com


The current can be read from the meter. In this way, we can check all
Contributors
wires in the junction boxes on leakage currents.
Design and text: Elbert Jan van Veldhuizen
Editing: Luc Lemmens
With the 96 V test voltage from the batteries, the current measured
Illustrations: Elbert Jan van Veldhuizen, Patrick Wielders
is of course lower than the current that would actually flow through
Layout: Giel Dols
the earth-leakage at 230 V mains voltage. That is, if we assume
that the resistance of the leakage only marginally changes between
96 and 230 V, a proportionally higher current will flow at a higher
voltage. In addition, the internal resistance of the battery, the shunt
and the safety resistor Rint will also reduce the current. The internal
Questions or Comments?
resistance can easily be determined by measuring the short-circuit
Do you have technical questions or comments about his
current of the earth-leakage tracer with a multimeter. In the case
article? Email the editor at [email protected] or
of the author’s prototype with 10 Ω shunt (R2b) selected, this was
contact Elektor at [email protected].
38 mA and thus an internal resistance of 2526 Ω. From the current
measured Im , the actual leakage current Iactual at mains voltage can
then be calculated with:

Vmains
I actual 
Vbatt
 Rint
Im related products

Plotted in a table this is: > PeakTech 2710 Digital RCD Tester (SKU 19318)
www.elektor.com/peaktech-2710-digital-rcd-tester

Im [mA] Iactual [mA] > PeakTech 2715 Digital Loop / PSC Tester (SKU 19078)
0 0 www.elektor.com/peaktech-2715-digital-loop-psc-tester

1 2
2 5
3 8
4 11
5 14
6 17
7 20
8 24
10 31
20 100
30 >200

And what the issue was with the electrical installation of my parents’
sunroom? A cable to an outdoor lamp had a isolation leakage that
indicated 4 mA during the troubleshooting with this earth-leakage
tracer, which would in practice be about 11 mA with the mains voltage
switched on. Probably the leakage became worse during the rain. The
best way to solve the problem was to replace the cable.
200576-01 CAUTION! HIGH VOLTAGE!
There are always safety risks associated with working on
circuits or systems that are (potentially) connected to mains
power. Elektor and the designer of this project accept no
WEB LINK liability for any damage (in whatever form) caused by using
this earth leakage tracer. As with all projects involving mains
[1] Residual-Current Device: power, we offer the following sincere advice: If you don’t know
https://en.wikipedia.org/wiki/residual-current_device what you are doing, don’t do it!

lektor January & February 2022 109


ethics

Poverty
and Electronics
Sustainable Development Goal 1
By Priscilla Haring-Kuipers (The Netherlands)

Electronics touch poverty in many ways. Technologies can be a


resource to help people out of poverty, or they can be the cause of it.

“To end poverty in all its forms everywhere”


is the first of the Sustainable Development
Goals (SDGs) defined by the United Nation.
Electronics often have a supportive role in
fighting poverty by providing communication,
content or measurements in various projects
such as micro-financing, enhancing farming
methodology and basic health care. [1]

Poverty Targets
The first target is to end extreme poverty,
which is determined as people living on less
than $1.25 a day. If you want to know what
that looks like, go to Dollar Street [2] and
take a look at families with an income up to
$38 per month. Sadly, because of Covid-19,
for the first time in our generation poverty
has risen. Effects of the global pandemic
have pushed around 120 million people back
into this bottom category during 2020.

Other targets include halving the amount


The Chowdhury family lives in India on $30 per month. Their favorite household item
of people living below the national poverty
is this mobile phone. (Source: Zoriah Miller, Dollar Street 2015 [2], CC BY 4.0)
line, making sure poor people have access
to basic services, can own property and to
reduce exposure to climate change related
extreme weather.

110 January & February 2022 www.elektormagazine.com


Deeper Issues
The worst way our electronics are inter-
twined with poverty is in the mining of raw
materials. Cobalt mining in the Congo is
mostly done under very harsh conditions
while paying the workers — often children —
a fee that keeps them living in (extreme)
poverty. Gold and copper mines all over the
world have “unhealthy working conditions”
while providing very low wages. Mining is
booming, but this economic benefit is not
passed down to the hands that do the work.
Several large manufacturers (Samsung,
BASF, Tesla, etc.) have started initiatives to
promote ethical mining, but these projects
seem to be at the stage of good intentions. The Jacques family lives in Haiti on $39 a month. These are the spices they use for
cooking. (Source: Zoriah Miller, Dollar Street 2015 [2], CC BY 4.0)
We Decide
Many of the decisions made in High Income
Countries determine the economic oppor-
tunities for people living in Low Income
Countries. What sorts of regulations do we decide on for materials is one of the most effective solutions to poverty.” [3] The mobile revolu-
used in electronics? Do we design for repair? How do we process tion has allowed people living in poverty to access mobile banking and
our e-waste? People in Low Income Countries can make use of the receive vital health information. Farmers can cooperate on crop prices
electronics we discard by repairing them and selling them as refur- and receive weather predictions. Mobiles also function as warning
bished electronics within their own economies, creating value for systems in case of natural disasters, which is especially important for
themselves. But only if our people living in remote areas.
designs allow. Or they can Pump and filtering installations
make a very unhealthy and with solar power provide clean
underpaid living sorting our water and reliable energy.
electronics as waste. Our These technologies, as well
design decisions determine as tech used in education
their options. The mobile revolution has allowed people and political collaboration,
can support people to increase
Tech to the Rescue living in poverty to access mobile banking their resources and opportu-
Some believe that technol- and receive vital health information. nities and find their way out of
ogy provides the way out of (extreme) poverty.
poverty: “Modern technology 210561-01

WEB LINKS
[1] UN Department of Economic and Social Affairs, “SDG Good Practices - A Compilation of Success Stories and Lessons Learned in
SDG Implementation,” First Edition, 2020.: https://sdgs.un.org/publications/sdg-good-practices-2020
[2] Dollar Street: https://www.gapminder.org/dollar-street
[3] The Borgen Project, “10 Technological Solutions to Poverty,” 2014.: https://borgenproject.org/10-technological-solutions-poverty/

lektor January & February 2022 111


store
www.elektor.com

The Elektor Store


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

Creality HALOT-SKY
Resin 3D Printer

Price: €849.00
Member Price: €764.10

www.elektor.com/19745

Elektor Dual DC LISN 150 kHz – 200 MHz

Price: €109.95
Member Price: €98.96

www.elektor.com/19869

112 January & February 2022 www.elektormagazine.com


Cytron Maker Pi RP2040 –
Robotics with Raspberry Pi RP2040 Pimoroni Raspberry Pi Pico
Wireless Pack

Price: €16.95 Price: €17.95


Member Price: €15.26 Member Price: €16.16

www.elektor.com/19926 www.elektor.com/19916

MonkMakes Air Quality Kit WIZnet W5100S-EVB-Pico


for Raspberry Pi RP2040-based Evaluation Board

Price: €14.95
Member Price: €13.46
Price: €29.95
Member Price: €26.96 www.elektor.com/19971

www.elektor.com/19913

lektor January & February 2022 113


Hexadoku
Puzzles with an Electronic Touch

Traditionally, the last page of Elektor The Hexadoku puzzle employs numbers in the hexadecimal range 0
through F. In the diagram composed of 16 × 16 boxes, enter numbers
magazine is reserved for our puzzle with an such that all hexadecimal numbers 0 through F (that’s 0-9 and A-F)
electronics slant: welcome to Hexadoku! occur once only in each row, once in each column and in each of the
Find the solution in the gray boxes, submit it 4×4 boxes (marked by the thicker black lines). A number of clues
are given in the puzzle and these determine the start 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 numbers in the gray boxes.

SOLVE HEXADOKU AND WIN! PARTICIPATE!


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

PRIZE WINNERS
The solution of Hexadoku in edition 11-12/2021 (November & December) is: 53974.
Solutions submitted to us before December 17th were entered in a prize draw for 5 Elektor Store Vouchers.
The winners are posted at www.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 January & February 2022 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
Join the
Elektor C mmunity
Take out a G O LD
membership
membership!

The Elektor web archive from 1974! An online Elektor LABs account, with
6x Elektor magazine (Print) access to more than 1000 Gerber files
9x Digital (PDF) including and a direct line of communication with
Elektor Industry (EN) magazine our experts!
A 10% discount in our web shop and Bring a project to publication or even sell
exclusive offers it in our shop
Elektor’s annual DVD-ROM

Also available Access to Elektor’s web archive


10% discount in our web shop
The Digital G R E E N membership
6x Elektor magazine (PDF)
Exclusive offers
membership! Access to more than 1000 Gerber files

www.elektor.com/member

You might also like