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

Lektor: 6-Channel Temperature Monitor & Logger

Uploaded by

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

Lektor: 6-Channel Temperature Monitor & Logger

Uploaded by

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

Edition 4/2019 | July & August 2019 | www.elektormagazine.

com

lektorlabs
DESIGN BUILD SELL ELECTRONICS magazine

6-Channel Temperature
Monitor
& Logger

with –240 °C to 850 °C industrial range


Snips Speech
Recognition
With an example
for the
Raspberry Pi

AS-Interface Essentials
Industrial automation bus system explained

6-Channel Temperature Monitor & Logger AC-in, DC-out Baristors An Elektor BoBs Catalog AS-Interface Essentials Bright
Flashing LED Create a 100% Private Vocal Assistant with Snips Creating a New Component (Symbol) in KiCad Differential
Probe Power Supply Display Serial Data on a Web Page ESP32 as a Time Server ESP32 Battery Monitor Fair Algorithms
From Tubes to Silicon Hexadoku IOTA Crypto Currency (and an FPGA for the RPi) MIDI I/O Breakout Board and more...
DISCOVER OUR
NEW PRODUCTS!
IP 67 Multimeter from 79,- €
Graphic Multimeter from 189,- €
Bluetooth Multimeter from 109,- €
from
79,- €

All prices are RSP excl. VAT

Basic Oscilloscope from 299,-


Professional Oscilloscope from 599,-
Touchscreen Oscilloscope from 699,-
from
299,- €

Whether you are looking for professional digital multimeters with data logger
and Bluetooth interface, 4-channel oscilloscopes with integrated generator,
multimeter and CAN bus decoder or simply a low-cost basic oscilloscope
– PeakTech® offers extensive new products at the best price!
www.peaktech.de Our value is measurable.
Elektorlabs Magazine
Edition 4/2019
Volume 45, No. 496
July & August 2019

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

www.elektor.com
www.elektormagazine.com

Wide, Wider, Wideband


Scope for Electronics
Elektorlabs Magazine, English edition
is published 6 times a year by

Elektor International Media


78 York Street For every edition of Elektor Labs magazine the editorial team makes a concerted
London W1H 1DP attempt at balancing what effectively goes in print and online. In the process, vari-
United Kingdom
ous ‘ranges’ contend as we want to keep as many readers happy as possible without
Phone: (+44) (0)20 7692 8344
being sycophants to fans of just one field in electronics.
Head Office: A weighting quadrant already arises by declaring the ranges hobbyist – professional as
Elektor International Media b.v.
one “scale” (say x) and 100% hands-on – nice to know as the other (y). But there are
PO Box 11
confounding ‘z’ ranges as well, meaning more aspects to complicate our final compila-
NL-6114-ZG Susteren
The Netherlands tion: old school versus programming only, microcontroller versus analogue, sponsored
Phone: (+31) 46 4389444 versus journalistic, technology versus ethics, and Homelab versus Elektor Labs, just
Fax: (+31) 46 4370161
to mention a few. And I mean versus in the sense of: contrasting with; not: opposing.
The pages you are about to read, skip, flip, scan or browse, are sure to reveal some
Memberships: of the extremes of the ranges I just mentioned and should help to define the middle
Please use London address
ground. For example, for a truly ambitious project I would point at ‘IOTA Crypto
E-mail: [email protected]
www.elektor.com/memberships Currency (and an FPGA for the RPi)’ on page 64, where cutting edge electronics —
mostly microcontroller of course — is presented at a terrific pace. This project not
just taps into the world of ‘new trading’ willy-nilly, but also explains how it all works
Advertising & Sponsoring:
without losing grip of the hardware. Compare that to the delightfully old-school
Margriet Debeij
Phone: +49 170 5505 396
‘Bright Flashing LED’ on page 48 or the slightly more challenging ‘AC-in, DC-out
E-mail: [email protected] Baristors’ on page 84 and you have a rough idea of the scope of 21st century elec-
tronics as well as that of the project proposals we receive through our Elektor Labs
www.elektor.com/advertising website and our editorial email accounts. Thanks all and keep ‘m coming!
Advertising rates and terms available on
It’s a vast scope and somehow terms like wideband, trigger slope, focus, intensity,
request.
overshoot, and sensitivity seem to apply to Elektor’s dreaded selection criteria for
article proposals. A tip: the authors in publication here got the trigger setting right.
Which is another way of saying we work painstakingly, like a ’scope, to present crisp
Copyright Notice
images on your screen.
The circuits described in this magazine are for domes-
tic and educational use only. All drawings, photographs,
Jan Buiting, Editor-in-Chief
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
Elektor International Media b.v. and may not be repro-
duced or transmitted in any form or by any means,
including photocopying, scanning and recording, in
The Circuit
whole or in part without prior written permission from Editor-in-Chief: Jan Buiting
the Publisher. Such written permission must also be
Translators: David Ashton, Jan Buiting, Martin Cooke,
obtained before any part of this publication is stored
in a retrieval system of any nature. Patent protection Ken Cox, Arthur deBeun, Andrew Emmerson,
may exist in respect of circuits, devices, components Mark Owen, Julian Rivers
etc. described in this magazine. The Publisher does
Membership Manager: Denise Bodrone
not accept responsibility for failing to identify such
patent(s) or other protection. The Publisher disclaims
International Editorial Staff: Eric Bogers, Mariline Thiebaut-Brodier,
any responsibility for the safe and proper function Denis Meyer, Jens Nickel
of reader-assembled projects based upon or from
Laboratory Staff: Clemens Valens, Ton Giesberts, Luc Lemmens,
schematics, descriptions or information published in or
in relation with Elektor magazine.
Jan Visser
Graphic Design & Prepress: Giel Dols, Jack Jamar
© Elektor International Media b.v. 2019 Publisher: Don Akkermans
www.eimworld.com
Printed in the Netherlands

www.elektormagazine.com July & August 2019 3


This Edition
6-Channel
Volume 46 – Edition 4/2019
Temperature
& Logger
No. 496 July & August 2019

Regulars
63 Peculiar Parts, the series
TL431 Precision Programmable Reference
76 Questions & Answers
(Almost) everything you always wanted to
know about...Analogue Design and Circuitry with –240 °C to 850 °C
80 Err-lectronics
Corrections, Feedback and Updates to
published articles industrial range
82 Elektor Store Highlights
Equipping Your Maker Lab
90 HomeLab Helicopter
Wondrous Things Electronic Snips Speech Recognition
Spotted From Above with an example for the Raspberry Pi
104 Retronics
Language assistants like Alexa, Google Home or
From Tubes to Silicon
Siri are now commonplace. However, the actual
110 Elektor Ethics recognition of the spoken words is not done
Fair Algorithms locally, but in the Cloud of the provider –
112 Elektor Store which raises questions about data privacy.
what’s available @ www.elektor.com There are other solutions such as Snips – a
speech recognition system that runs entirely
114 Hexadoku on local hardware like the RPi. We took a
The original Elektorized Sudoku look at a speech recognition kit and show
how you can use it to develop your own
applications...


Features
14 Create a 100% Private Vocal Assistant
with Snips
Everyone’s entry ticket to the world of
22
Artificial Intelligence, with a Raspberry Pi
72 AS-Interface Essentials
22 Snips Speech Recognition How the industrial automation bus system
with an example for the Raspberry Pi works

104
34 Revolutionary Battery Pack Design 78 An Elektor BoBs Catalog
from TUE/InMotion It’s the little things...
(it’s) Student Demonstration Time!
49 Heading Towards a Tsunami of Light
News from Chalmers University Retronics
52 Elektor Start-up Challenge - Paris 2019 Projects From Tubes
An international launchpad for start-ups
to Silicon
64 IOTA Crypto Currency
(and an FPGA for the RPi) 6 6-Channel Temperature Monitor
Part 2: PiDiver — FPGA board for fast & Logger
calculations Measures from −240 °C to +850 °C

4 July & August 2019 www.elektormagazine.com


Monitor 6 lektor magazine

48 Bright Flashing LED


Traditional analogue...
50 Qt for the Raspberry Pi
A step by step guide to set up the GUI
framework
54 New CPLD Board with MAX 10
More logic with the MAX 10 family
58 Waterflow Monitor with ESP32
With text/SMS alert of leaks
84 AC-in, DC-out Baristors
Buildings block for application in power
supplies
94 ESP32 as a Time Server
ESP32 plus RTC plus GPS plus display
equals an NTP server on your own LAN
100 Creating a New Component (Symbol)
AS-Interface Essentials
in KiCad
and preparing to associate an existing
How the industrial automation bus system works footprint

In the olden days everything was controlled using hand-made custom cabling
and proprietary data formats. In the industrial world at least, however, this
kind of thing is long gone: now entire systems are based instead around
fully-featured bus architectures. As well as the obvious advantages of easier
maintainability and expandability there are other reasons to prefer such an
approach. For example, a widespread
Next Editions
industry standard ensures the long-
term availability of hardware and
software components, at least to ElektorLabs Magazine Edition 5/2019
some degree. In this article we Horticulture Box • Build Your Own RFID reader Writer •
will take a look at AS-Interface. 8 Channel Timer with OLED Display • Sound Blink DIY
Portable Speaker • Flicker Free LED Dimmer • WSPR

72
SDR • Q&A on Sensors • Littlevgl GUI library with ESP32
and a Raspberry Pi Touchscreen • USB-RS232 converter
(FT231X BoB) • Remote Control for Hover-Catamaran •
A Time-Corrected Woofer Concept • Universal battery
Charger • Wireless In-Car Voltmeter.

ElektorLabs Magazine edition edition 5/2019 covering September &


October 2019 is published on 22 August 2019. Delivery of printed copies
to Elektor Gold Members is subject to transport.
Contents and article titles subject to change.

26 MIDI I/O Breakout Board Elektor Industry Edition 3/2019


Supports DIN and TRS connectors
Elektor Industry issue 3/2019 is a special edition for the
29 The SCCC Project (3) Productronica 2019 trade show in Munich, Germany
Homebrew soft-core processor (November 12-15, 2019), and will focus on a range of
and C compiler
innovative technologies, research, hardware and software,
38 ESP32 Battery Monitor including IoT, 5G, sensors, CAD, SMT, PCB manufacturing,
Measures three channels via Wi-Fi and and more. Plus, you’ll find fresh instalments of the maga-
Thingspeak zine’s regulars like Infographics and Industry Store.
42 Differential Probe Power Supply
Elektor Industry issue 3/2019 will be published early November 2019
An ultra-simple power solution using USB
to Elektor Gold members in print and to Elektor Green members as a
43 Display Serial Data on a Web Page PDF download. The edition will be available for purchase at
Using PHP or Python scripts www.elektormagazine.com.

www.elektormagazine.com July & August 2019 5


LABS PROJECT

6-Channel
Temperature Monitor
& Logger
Measures from
−240 °C to +850 °C
By Clemens Valens (Elektor Labs) and Sunil Malekar
(India)

Temperature is an important parameter to


control in many industrial processes. At
home, too, the fridge, freezer, heater,
kitchen oven, and air conditioner all
measure and adjust the temperature
to get their job done. Weather
stations, cars, computers, tablets
and smartphones keep an eye on
temperature too. Come to think of it,
temperature may well be the world’s
most surveyed physical quantity.

Even my low-cost Bluetooth speaker up to +850 °C. Note that these are soft-
sounds an alarm when it gets too hot (as ware limits; the real-world limits greatly nickel. Sensor preci-
I discovered after placing it on a heater). depend on the sensors being used. sion depends on the purity of the metal.
Because humankind likes to measure Platinum has the most stable resistance/
temperature so much, we decided to Resistance thermometers temperature relationship over the largest
design a device capable of measuring To measure temperature, we will use temperature range.
up to six of them. Usually, thermometers so-called RTDs in the shape of Pt100 A Pt100 probe is an RTD made from plat-
only measure one temperature — some probes. RTD is short for Resistance inum wire (‘Pt’ in the Periodic Table). The
can do two, often labelled ‘inside’ and Temperature Detector, a device con- value ‘100’ indicates that its resistance
‘outside’ — but for process control more sisting of a length of metal wire with a is 100 Ω at 0 °C. Other val-
channels may be required. Range is also known resistance/temperature relation- ues can be
important, which is why the device pre- ship spiralled on a suitable supporting
sented here can measure temperatures material. The metal typically
across the massive range from −240 °C used is platinum, copper or

6 July & August 2019 www.elektormagazine.com


project decoder
8051
temperature monitoring

entry level
Æ intermediate level
expert level

4 hours approx.

soldering iron,
C2 programmer (see text)

£45 / €50 / $55 approx.

had too, like 500, 1000 or even


2000. Pt100 sensors are widely
used and easy to find. They come
in different quality grades — classes — Quick Features
that determine their price, • 6 channels for Pt100 RTDs
range, • Range: −240 °C to +850 °C
• 8051 MCU
• 2-line alphanumerical display
accuracy • Serial data output in CSV format
and precision. They also
come with a variable number of con-
necting wires: 2, 3 or 4. The extra wires
are used to measure the resistance of

www.elektormagazine.com July & August 2019 7


R1 R2

Pt100 V–

400
350
R4
300
R3
250 V+ V
R [Ω]

200 Rw

150
RTD
100
I RTD
50 Rw
VRW
0 Rw
-200 -100 0 100 200 300 400 500 600 700 800
T [°C] 190118-010

Figure 1: The relationship (in blue) between resistance and temperature of a platinum (Pt) wire is Figure 2: The Howland current source has a
nonlinear. It may be approximated using a lookup table of short “straight” segments of the curve. very high output impedance. It is used here to
excite a 3-wire RTD.

the RTD’s connecting wires (more on that


later). As these wires — that can be rather +5V
R7 R8 R6
long — behave like inaccurate RTDs, it is

10K
10K
10K
important to compensate the sensor for
13 11
Y0 A
them to ensure reliable and repeatable 14
Y1 B
10
IC5
results. To avoid complicating our sys- 15
Y2 C
9
12
Y3
tem too much, we opted for 3-wire RTDs. 1
Y4 R13 IC6
3 5 3 3
Y5 4051 Z 1k R11
K7 2 2 6
Y6 OP07 1k
An RTD is not a thermocouple RTD2 1 4
Y7 INH
6 2

This is important to understand. A ther- R16


3
12k
mocouple is a junction of two different K6 2
C27
R15
C21
RTD3 1
metals that produces a temperature-de-
1k
100n 100n
pendent voltage as a result of the ther- 3
K5 2 13 11
moelectric (Seebeck) effect. Therefore, RTD4 1 14
Y0 A
10
Y1 B
a thermocouple does not need a power 15
Y2
IC7
C
9
3 12
source to operate whereas an RTD K8 2 1
Y3
Y4 R17 IC8
requires some form of excitation. Ther- RTD1 1 5
Y5 4051 Z
3
1k
3
R12
2 6
mocouples tend to be less precise than 3 4
Y6
6 2
OP07 1k
Y7 INH
RTDs, but they are very cheap. K4 2
R19
RTD5 1
12k
R18
C31 C22
Linearity 3
1k

K3 2
One last but important thing to mention RTD6 1
100n 100n

about RTDs is their slightly non-linear 13


Y0 A
11
14 10
resistance/temperature relationship (see 15
Y1
IC9
B
9
Y2 C
Figure 1). This implies that some calcu- 12
Y3
-5V
1 R23
Y4
lations must be done to obtain the correct 5 4051 3
C40
C37
1k

Y5 Z IC11
1n
temperature from the measured resis- 2
Y6
8 1 100n R20
4 6 7 2
Y7 INH 10k
tance. The Callendar–Van Dusen equation R3 6 3
R22 IC10
has long been used for platinum RTDs, 5 4
10k
2
470

6
LM336M-2.5 OP07
but in 1990 the Comité International des 0.01% 3
R21
Poids et Mesures replaced it by a 12th-or- C38 R1
10k

+5V 10k
der polynomial valid over the tempera- 100n

ture range from -259.35 °C to 0 °C and C20 C30 C35 C34 C29 C41

a second, 9th-order polynomial for tem- 100n


16
100n
16
100n
16
100n
7
100n
7
100n
7

peratures from 0 °C up to 961.78 °C. 8 IC5 8 IC7 8 IC9 IC8 IC6 IC10
C24 C33 C36 C32 C25 C39
Because evaluating such polynomials 7 7 7 4 4 4

calls for heaps of computing power (and 100n 100n 100n 100n 100n 100n -5V
190118-006
debugging), most applications simply use
lookup tables. We did so too.

8 July & August 2019 www.elektormagazine.com


Howland current source to make it work as intended, resistors  
As briefly mentioned above, an RTD R1 to R4 surrounding the opamp should VRTD = V − 2 VRW [V]
must be excited in some way to make have a tolerance of 1% or better.  
it usable. Either a constant voltage or When the ratio R1/R2 is equal to the This completes our theoretical introduc-
a constant current source can be used ratio R3/R4, then the output current is tion, and we can move on to studying the
for this. We preferred a constant current given by: actual schematic.
source since it poses fewer problems  
with long sensor wires. In this case the IRTD = (V+ − V−) / R3 [A] The input multiplexer
voltage across the sensor depends on Looking at the left of Figure 3, we find
the current only and, of course, the tem- Compensating connectors K3—K8 for the six RTD chan-
perature, and not on the resistance of for connecting wires nels. One wire of each RTD is connected
the connecting wires in addition. Figure 2 also shows how the RTD is to GND, the two others to a Type 4051
Constant current source designs are connected to the current source with CMOS multiplexer IC. IC7 forwards the
plentiful but a popular one for use with its three wires. Assuming that the three signal ‘V’ from Figure 2 to the rest of
RTDs is the Howland current source or wires are identical and that we can mea- the system; IC5 does the same for sig-
current pump (Figure 2). This kind of sure the voltages ‘V’ and ‘VRW’ at a very nal ‘VRW’. The third multiplexer, IC9,
source has the advantage of having a high input impedance (meaning that works the other way around and con-
very high output impedance compared to there is no current flowing in the direc- nects the output of the current source
other current source designs and it can tions of V and VRW (properly: VRW), then — constructed around IC10 — to the
sink as well as source current. However, the voltage across the RTD is given as: selected RTD.

Figure 3: Schematic of the multi-


node temperature logger. The
analogue input stage is on the
R14 +5V
10 +3V3 left, the digital part on the right.
C23 C26 C28 -5V
8
V+
1n 100n 10
10V 2 1
C+ NC
C14 C13 IC3
7 5
OSC VOUT
10 100 4
TC7660COA 6 C15
16V 16V C– LV

GND 100
+3V3 K2 16V
3
R9 1 2
3 4 8 7 6 5 4 3 2 1
1k

C1 C11
5 6
AIN0.7
AIN0.6
AIN0.5
AIN0.4
AIN0.3
AIN0.2
AIN0.1
AIN0.0

R10
7 8
1k 9 32 1 100n
9 10 AGND VREF-
C19 10 31
AV+ VREF+
11 30
FRC10 PIN
PC2.0/C2D P1.7/IDA1 RN1
1 12 IC4 29 2
/RST/C2CK P1.6/IDA0
13 28 3
+5V P0.0 P1.5
14
P0.1 C8051F350 P1.4
27 4
1
+5V
15 26 5
P0.2/XTAL1 P1.3
MBR140 D1 16 25 6
USB P0.3/XTAL2 P1.2
7
RX/P0.5
TX/P0.4

DGND
VDD
P0.6
P0.7

P1.0
P1.1

6 x 10k
CBUS3 +5V
17 18 19 20 21 22 23 24
CBUS2 VCCIO C6
CBUS1 +3V3 +3V3
CBUS0 GND 100n
RESET
BOB1 CTS R2
DCD RI +5V
+5V
10

DSR BOB-FT231X RXD


DTR TXD
R5 R4
VCCIO

S4 S3 S2 S1
RXD
GND

TXD

RTS

C18 C17 C16 C3


CTS

P1
10k
10k

10k

1n 100n 10 100n
SAVE INCR DECR MENU 10V

+5V
LD1117DT50TR +5V

IC1 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1

C5 C4
VCC
GND
RS
ADJ
A

R/W
D7
D6
D5
D4
D3
D2
D1
D0
E
K

10 100n
16V LCD1
LD1117DT33TR +3V3 MC21605G6WD-BNMLW-V2
K1
D2
IC2
MBR140 C7 C8 C9 C10 C2 C12

47 100n 10 100n 10 100n


25V 25V 16V
190118-007

www.elektormagazine.com July & August 2019 9


Figure 4: The assembled main board. Note: the board shown is version 1.0 that used the legacy FT232R BoB instead of the FT231X BoB.

Each multiplexer has eight channels, two Power supply MCU used here runs internally at 49 MHz
of which are used for reference signals Theoretically, the supply voltage for the and executes most of its instructions in
Vmin (GND) and Vmax (VR3). Now you finally circuit connected to K1 can be up to one cycle, making it a pretty fast device.
understand why there are six RTD chan- 15 VDC, but this will put unnecessary The C8051F350 is part of a family of
nels and not seven or five. These refer- strain on the low-drop voltage regulators. four that differ only by package type and
ence signals follow the same paths as The minimum supply voltage is 7.5 VDC, ADC resolution. The ‘F350 is the largest
the RTD signals (R3, a 0.01% tolerance the recommended value is 9 VDC. The part with a 24-bit sigma-delta ADC, eight
resistor, is even mounted close to the total current consumption is around dedicated analogue inputs, and 17 dig-
RTD connectors to mimic an RTD as close 70 mA including the 20 mA consumed ital I/O pins. It's an analogue-oriented
as possible). Because the values of these by the backlight in LCD1. (Note that the controller with built-in digital filters and
signals are known, this allows the soft- latter has a built-in current limiting resis- two 8-bit DACs. In this project we do
ware to calibrate the digitizer stage and tor.) IC1 lowers the supply voltage to 5 V not use all its capabilities, but you may
remove errors introduced by the multi- for most of the circuit except microcon- want to study the MPU further for some
plexer and current source. troller IC4; IC2 creates a 3.3-volt supply future project.
The outputs of the input multiplexer are for this clever part. Although running from 3.3 volts, the
individually amplified by a factor of 13 The analogue input stage also requires C8051F350's digital I/O pins are 5 V tol-
by IC6 and IC8. The signal ‘V’ from Fig- a −5 V supply voltage, and this is taken erant, which is why it interfaces nicely
ure 2 then arrives at the microcontrol- care of by IC3. with the 5-volt-powered peripheral cir-
ler’s ADC input 3 (AIN0.3), while signal cuitry (note the pull-up resistors R4 to
‘VRW’ connects to AIN0.5. The microcontroller R8 and network RN1).
Over the past years, we have seen so A quartz crystal or resonator is not called
Current source, part two many Arduino-based circuits flashing for as the MCU has a calibrated oscilla-
The Howland current source in the proj- by that some have come to believe that tor on chip.
ect comprises IC10, resistors R1, R20, there exists only one type of 8-bit micro- Four pushbuttons (S1—S4) and an LCD
R21 and R22. V+ from our description controller. That this is not true is proven provide the user interface. P1 sets the
above is connected to GND and therefore by our circuit with its pimped-up, 8051- display contrast level; if you forget to
has a value of 0 V. V− is equal to −2.5 V, based brain! Now, before turning away adjust it when you power the board for
produced by voltage reference IC11. R21 in disgust, be aware that almost forty the first time, the display may not show
corresponds to R3 from the description years after its introduction the 8051 is anything.
above. The output current is: still a widely used 8-bit processor. Manu- For communication with a computer,
(0 − −2.5) / 10,000 = +250 [µA]. factured by Silicon Labs, the C8051F350 we added the option to plug a USB-to-

10 July & August 2019 www.elektormagazine.com


TTL-serial converter onto the board. We the corrections in hardware; nothing to ilar reasons the upper limit was fixed at
used our own breakout board, but it is do for us in software. +850 °C.
also possible to connect a functionally Of course, most ADC readings will be
equivalent interface. Please note that A word on sampling in between two table values, hence lin-
the photographs in this article show a The rest of the time main will spin in an ear interpolation is used to estimate the
prototype which used Elektor's (golden endless loop, scanning for key presses temperature. If more precise conversions
oldie) FT232R BoB, no. 110553. Since and updating the display when needed. are desired, it is possible to make the
then it got replaced by our new FT231X Every second a sample is taken from a lookup table’s step size smaller, as long
BoB no. 180537 which is compatible with channel, converted to a value in degrees as it fits in memory (of which there is not
the de facto standard of 'FTDI' USB-to- Celsius or Fahrenheit and printed to the a lot). If the table becomes really large
serial cables. screen. A second later the next channel and unwieldy, you might want to imple-
in line is updated. In the background ment a more efficient search algorithm
Software dealings the ADC runs at a faster rate of nearly than the linear search we used or use a
At the time of writing the kind people of 18.7 Hz. This higher speed is necessary polynomial approximation.
Silicon Labs still handed out free licenses for two reasons. First, to measure one
for Keil µVision5 so people who develop RTD two voltages (‘V’ and ‘VRW’) have Construction
software for the C8051 devices in C to be converted as the RTD value must Even though the project uses mostly SMT
can do this in a comfortable way. When be compensated for the voltage over parts, assembling the PCB should not be
you request such a license it seems to the connecting wires. Second, the ADC too difficult. Start by mounting 2-ter-
be valid for just one month, but once has a built-in low-pass filter that needs minal parts like resistors and ceramic
installed in the IDE it becomes a perma- three samples to calculate an output capacitors and then continue with the
nent license. Of course, we have explored value. Therefore, at least six samples taller parts. Respect and verify the polar-
this avenue, and everything went fine — are required for one RTD measurement, ity of polarized parts like diodes and elec-
yet you never know when they decide which corresponds to 320 ms. By reduc- trolytic capacitors.
to stop doing this and so we ported our ing the display time to 1 Hz, the system It is always a good idea to build and
software to SDCC, the open source com- has enough slack to sample and filter test the power supply (D2, IC1 and IC2
piler for 8051 and PIC devices. comfortably. and the capacitors around them) before
SDCC does not work with projects and mounting the other parts.
does not make use of any other GCC- Lookup table Make sure to use resistors with 1% toler-
based tool. Our project therefore is just Samples must be converted to tempera- ance in the input stage, except R3 which
a bunch of files in a folder together with ture values and this is done with the must have a tolerance of 0.01%. To cre-
a batch file to compile them. help of a lookup table. Pt100 conver- ate a real good current source, you might
As with every C program, the visible part sion tables can be found on the Inter- want to use 0.1% tolerance resistors for
starts in the function main. The first thing net and we compiled one from −240 °C R1, R20, R21 & R22.
to do here is to switch off the watchdog to +850 °C with a 10-degree step size. Depending on if and how you mount the
timer; you can always switch it back on Below −240 °C things become highly USB-serial interface, you may want to
later when you are ready for it. (Note inaccurate and so we limited the dis- use extra-tall connectors for the display
that the Keil compiler does this in the play to −260 °C (which actually as it is mounted over the serial BoB.
runtime (CRT) startup file so you don’t means Underflow). For sim-
notice it. We found that out the Loading the firmware
hard way.) Connector K2 is used for program-
After initializing the MCU’s ming the firmware into the MCU. This
peripherals — 1 ms sys- connector follows the official Sil-
tem tick timer, UART run- icon Labs 2-wire C2 Pro-
ning at 9600 baud, etc. gramming/Debug-
— the program per-
forms a cali-
bration
of the
ADC.
This is a
pretty neat fea-
ture of the MCU as
it allows us to calibrate
away many of the imper-
fections of our analogue front
end. After calibration, converting
Vmax — the voltage over 0.01% resis-
tor R3 — will read as 0xffffff (24-bit
maximum value) while Vmin (GND) will
produce a reading of 0. The ADC applies

www.elektormagazine.com July & August 2019 11


ging Interface Standard so connecting Connect the Arduino to the computer enter the settings “page”. On this
a C2-compatible programmer should be before powering the board and all should page you can toggle the temperature
easy. Less easy, on the other hand, is be fine. unit between Celsius and Fahrenheit
getting your hands on such a program- A Python 3 script, also included in the by pressing S1 again. With the keys
mer, which is why we rolled our own. The download, permits uploading Intel HEX ‘Decr’ (S2) and ‘Incr’ (S3) you can
free download on the support page for files to the home-brew programmer. This adjust the display refresh value from
this article [3] includes an Arduino sketch script requires pySerial. one second to one minute. When
that transforms any Arduino-Uno-com- done, you can either press ‘Save’
patible board into a C2 programmer. You Using the system (S4) to store the new settings in
can also find it on GitHub [2]. The MCU’s There are two firmwares for this project, non-volatile memory or let the page
5 V-tolerant pins allow us to do this with one with debugging options (‘d’ suffix) time out. When the page times out
impunity. and one with fewer options. The main UI the new settings will be used until
Connect Arduino pin A0 to K2 pin 7 functions are the same for both. the next change or a power cycle.
(‘C2CK’), Arduino pin A1 to K2 pin 4 • ‘Save’ (S4): press to recalibrate the
(‘C2D’), and Arduino GND to K2 pin 2. • ‘Menu’ (S1): press this button to system.

component list

12 July & August 2019 www.elektormagazine.com


The debug firmware adds to this:
Web Links
• ‘Decr’ (S2): pressing this key during [1] Project at Elektor Labs:
startup and keeping it pressed until www.elektormagazine.com/labs/6-channel-temperature-monitor-logger
the splash screens have passed will [2] C2 Programmer at GitHub: https://github.com/ElektorLabs/ElektorLabs_Tools
skip ADC calibration at startup. Use
[3] Web page for this project: www.elektormagazine.com/190118-01
‘Save’ (S4) to calibrate when you
want to.
• 'Decr’ (S2) and ‘Incr’ (S3): press-
ing these keys at the same time will
open the debug page where you
@ www.elektor.com
can see raw 16-bit ADC values for
both the signals ‘V’ (RTD) and ‘VRW’ ª6-Channel Temperature Monitor & Logger, partly assembled module
www.elektor.com/130548-91
(Wire). Pressing ‘Incr’ will select the
next channel. Press ‘Save’ (S4) to ª6-Channel Temperature Monitor & Logger, bare PCB
return to normal mode. www.elektor.com/130548-1
ªLCD 2x16 characters w. blue backlight
Data logging www.elektor.com/120061-77
Plug BOB1 on the board (or use another ªFT231X USB/Serial Bridge/BoB
USB-to-serial converter, the connections www.elektor.com/180537-91
are compatible with an 'FTDI' cable) and
connect it to a free USB port on a PC. The
latter should detect it as a serial port.
Launch a terminal program and config-
ure it for 9600 baud, eight data bits, no serial port terminal programs will allow
parity and one stop bit (9600n81). As you to record the data to a file so it can
soon as the board is powered, it will start be processed further in for instance a
sending comma-separated values (CSV) spreadsheet.
in human-readable ASCII format. Most (190118-01)

Advertisement

Post your ideas and


electronics projects
all sizes/all levels/allsorts,
at www.elektor-labs.com
and become famous!

Elektor Labs: www.elektor-labs.com


Design, Build, Share... Electronics!

www.elektormagazine.com July & August 2019 13


artificial
intelligence

Create a 100% Private


Vocal Assistant with Snips

Everyone’s entry ticket to the world of


Artificial Intelligence, with a Raspberry Pi
By Mennad Yami and Robin Guignard-Perret (France)

Snips is a platform for connected “things”. It allows developers and manufacturers of “things” to add a voice
assistant to their products Your Raspberry PI may not yet obey your finger or your eye, but thanks to Snips
it is at your command. This article explains how to add “ears” to a Raspberry Pi.

14 July & August 2019 www.elektormagazine.com


Formed in 2013, Snips wants to install an artificial intelligence
assistant in every object , making the technology so intuitive
that it will fade into the background. wake word
  Hey, Snips!
The Snips technology is unique in that it executes locally on the
actual object that the user is talking to, which implies that no
data is ever sent to the cloud. It’s a concept that guarantees
confidentiality and continued functioning, even in the case of
ASR
an Internet fault, which makes Snips one of the foremost voice
Automatic Speech Recognition
technologies to follow the general standards for data protection.
The Snips platform is free to anyone who wants to evalu-
ate our technology for non-commercial use. We have created
a community of 25,000 people - the biggest community of
voice application developerartifs outside Amazon and Google. NLU
Snips works on Linux (Raspberry Pi), Android, iOS, MacOS and Natural Language Understanding
Debian. Anyone can discover online the collection of tools and
documentation to create their own voice applications - see [1]
Snips is available in French, English, German, Japanese, Span-
ish and Italian. actions code
with snips-skill-server
Using our models in embedded systems
The principle of privacy by design (simply, taking privacy into
consideration right from the start) puts confidentiality at the
heart of the system design process. This confidentiality is even Figure 1: Overview of the building blocks needed for voice recognition.
more crucial as voice assistants are deployed in various sce-
narios in the private space of users. This choice guarantees
users against any abuse, present or future, of their data. At
Snips, “privacy by design” translates into the absence of any
communication of user data to the cloud. English, “Hello world” will be correctly returned, then sent on
During the design of the Snips voice platform, priority was given to the next block, the NLU.
to portability and good resource management. The system The NLU’s purpose is to extract the meaning of a text, A voice
works on as light a platform as the Raspberry Pi, a common assistant is designed to respond to a limited range of com-
IoT platform board popular among developers. Other Linux mands. The task of the NLU is to label a sentence with an
boards are also supported, and the Snips SDK for Android intention. These intentions often come with parameters which
works with the Android 5 and ARM environment, while the iOS should be isolated in order to correctly process the command.
SDK targets iOS version 11 or higher. For reasons of efficiency for example, if the user says “Hey, Snips! Switch on the light
and portability, the algorithms are re-implemented whenever in Paul’s room in red”, when the NLU receives the transcrip-
necessary in Rust (a compiled programming language from tion of this command, it distinguishes the intention “Switch
Mozilla Research). on the light’ with the parameters of place “Paul’s room” and
the colour “red”. It is this information which will be redirected
Vocal assistants towards the action code.
Modern voice assistants can be broken down into several build- The final building block is thus the action code, which waits,
ing blocks: the detection of a key word or wakeword, recog- via an infinite loop, for an intention to be detected so that it can
nition of the spoken word (Automatic Speech Recognition, execute it, taking the received parameters into account. This
ASR), the understanding natural language (Natural Language code is specific to each application and each device, and can
Understanding, NLU) and an action code which will execute as process any scriptable action. It can call on remote APIs, send
soon as a command is detected. commands to connected objects, speak via a voice assistant,
The wakeword is the word that lets you indicate to your assistant or all these at once. The wakeword, the ASR and the NLU are
the start of a command. A Snips assistant will start listening the cognitive senses of your assistant, the rest is thus carried
as soon as it hears “Hey, Snips!”. It then begins to transcribe out by the action code (see the overview in Figure 1)
the words of the user, this is the function of the second build- The existing voice assistants on the market (Google Home,
ing block: the ASR. Alexa, Siri) have their wakeword detector, their ASR and their
The ASR block tries to transform the sound signal captured by NLU in the cloud. Their models, being very large, need far
the micro into text intelligible to humans. If the user says “Hello greater processing power than is available in embedded tech-
world” the sound signal is first processed by a deep learning nology. This is not the case with Snips. The models are created
model, an acoustic model, which converts it into phonemes, on a case-by-case basis, for each assistant and each user, and
the sound representation units used by linguists. “Hello world” are specific to the tasks for which they are designed. This is
is first perceived in the form “hɛˈləʊ wɜːld”. Following this, a how, thanks to Snips, ultra light voice assistants can be cre-
specific model for the language of the assistant is applied to ated, capable of running on a Raspberry Pi Zero or 3, or more
transpose these phonetics into the vocabulary that we use, that 100% offline assistants. All this is accomplished without any
is the model of the language. If the assistant is configured for sacrifice in respect of voice recognition performance.

www.elektormagazine.com July & August 2019 15


The SNIPS platform
The Snips platform is an environment which comprises all the
necessary parts of a working voice assistant. It is the installa-
tion of this which allows anyone to take advantage of his own
voice assistant, respecting privacy, on Linux, MacOS, iOS and
Android. Alongside the Wakeword detector, the ASR and the
NLU, we find the Dialog Manager handles the coordination and
succession of tasks presented to it. The TTS, or Text To Speech,
handles voice synthesis for eventual responses. It receives text
and reads it aloud, adapting its accent to the language of the
assistant. Finally, the snips-skill-server is the component
which handles the execution of the action code.

The internal communication of the platform uses the Hermes


protocol, created by Snips around the MQTT protocol, light and
quick. Thanks to Hermes, it is easy to customise the working
of the platform to, for example, communicate with peripherals
of your main equipment, make it say a sentence through the
TTS, or command one of the platform components separately.
Once the Snips platform is installed on a device, is ready for
Figure 2: Creation of an assistant on the Snips online console.
an assistant to be loaded. It is on the Snips web console [1]
where this assistant is created (Figure 2). From the console the
user can define the language of the voice assistant, its range
of understanding and the functionalities (or apps).
For example, the platform, installed on your Raspberry Pi, can
accommodate a French assistant with an App for control of
lights, as well as a weather App.

Create and install the assistant


Let’s pass now to the creation of your personal assistant, to
deploy on an RPi. Your RPi must first of all accommodate the
Snips platform. To ease the installation process and the man-
agement of assistants, we have created SAM (Snips Assistant
Manager), and easy-to-use deployment tool run from the com-
mand line. Sam is a program for your computer, which con-
nects to your RPi via SSH. The two devices must of course be
on the same network, so think about connecting your RPi to
a wireless network or direct to your computer by Ethernet. In
addition, your main computer must support Node.js (JavaScript
execution environment) and npm (packet controller of Node.
js) to be able to run SAM. The command sudo npm install
Figure 3: Examples of apps available on the console. -g snips-sam is all that’s needed to install the tool. Then the
command sam devices which lists all the RPi present on your
network will allow you to detect yours. Once you have obtained
the IP address or the hostname of your device. connect it to
SAM with the command sam connect <adresseIP/hostname>.
Finally, sam init starts the installation of the Snips platform.
To connect your microphone and your audio output, use sam
setup audio.

Snips Console
Then go to [1] to create an account, then a new assistant.
This assistant may have one or many function(s), you can
choose from the Apps available in the App Store (Weather,
recipe book, control of Philips Hue lamps... See Figure 3)
or construct your own. You can also personalise an App from
the App Store to produce a unique version thanks to the fork
function (Figure 4).

Figure 4: The fork function allows the creation of a copy of an existing An App captures intentions, or intents, thanks to the training
App to modify it (this message appears automatically on clicking Edit). of the NLU model. It also captures the parameters, or slots, if

16 July & August 2019 www.elektormagazine.com


there are any. In the case of a calendar
App, when the user says “Add an event
anniversary for the 13th November”
the request is transformed by the NLU
into the intent “addEvent” with slots
for the name of the event “anniver-
sary” and a date “13th November”.
The Snips team have already created
certain standard slots, such as dates,
to enable their detection.
Listing 1 shows what the data sent
by the NLU to the action code looks
like, in the JSON format.

Your assistant needs trial data to train


its neural network. You can create your
own examples with the aid of the con-
sole. To improve the performance of
the NLU, you can identify the posi-
tion and nature of the slots in a sen-
tence by highlighting them with the
mouse. Moreover, the more numerous
Listing 1. Data Sent by the NLU to the Action Code
and varied your examples are, the better will be the perfor- (JSON Format).
mance of your assistant. The Snips console also offers you a
paid service for producing training data. “input": "add an anniversary for the thirteenth of
november",
Don’t forget to save, the console also updates your assistant. "intent": {
You can use the test interface at the right of the console to "intentName": "userName:addEvent",
observe the responses of your assistant to oral or written com- “probability": 0.9662896
mands. You can now install your assistant on your RPi, using },
SAM. The command sam login lets you connect to your account “slots": [
used in the console. You can then run sam install assistant {
and select your assistant to install it.
“rawValue": "anniversary",
“value": {
Action
“kind": "Custom",
The action code is composed of callbacks which are executed
when the intent which corresponds to them is detected. You “value": "anniversary"
can program in any language, however Python and Javascript },
have a Hermes library available, which simplifies the internal “range": {
communications with the Snips platform. These two languages “start": 10,
are recommended (but not obligatory). You can run your code “end": 22
manually, but the snips-skill-server can do it automatically when },
the RPi starts. For that, create a directory with your choice of “entity": "common names",
name in /var/lib/snips/skills/, and put your script in that “slotName": "summary"
directory. Your script must have a name beginning with action- },
and be executable. its role is to listen for intents, via an infinite
{
loop. It is possible to link an App to a Github directory, and let
“rawValue": "for the thirteenth of november",
SAM copy your files to a proper place during the installation
“value": {
of the assistant. It must be public, you can also add it to the
Actions tab in the console. You can also, in addition to your “kind": "InstantTime",
action file, put in a setup.sh file which will be executed on “value": "2019-11-13 00:00:00 +00:00",
installation, for example to compile your project. “grain": "Day",
“precision": "Exact"
Example of an assistant },
Let’s look at the construction of a practical assistant. This “range": {
assistant will get you to revise your multiplication tables via “start": 23,
a game of questions-replies. From the console, create a new “end": 46
assistant in English called “FirstAssistant”which has an App },
called “TimesTables”. [Note the editing: you will fnd in the App
“entity": "snips/datetime",
Store the App “TimesTablesEN” which is a bit more advanced
“slotName": "start_datetime"
than the one described here, Figure 5]. The player must be

www.elektormagazine.com July & August 2019 17


able to start the game, then respond to questions or pass if he
doesn’t have a reply. We have there our three intents named
start_quiz, gives_answer and doesnt_know. Note: the action
code receives the intent in the formatuserName:intentName
(for example snips:gives_answer).
 
• intent start_quiz: is limited to starting the game, and
thus does not need a slot to adjust the behaviour of your
assistant. It must include phrases of the type “let’s start
the game” or “I want to play”. It is important to add
numerous and varied examples of phrases to make the
intent robust, so let’s add “I feel like playing the game” or
“let’s play” to the examples before saving (Figure 6).

• intent gives_answer: must allow understanding of a reply


which is variable. A slot is thus required, we can call it
answer and give it the predefined type number. In the
example phrases, don’t forget to highlight the numbers if
they are not included automatically (Figure 7). For this,
select the number with the mouse, then click on Select
a slot then on answer. Responses like “forty-nine” or “I
think it’s twelve” are expected. Data in the JSON format
received by your action code will carry the value of the
number spoken by the user in its slots.

• intent doesnt_know: follows the same logic as start_quiz


Figure 5: The TimesTables app is available online. Select it and then click in that it does not need a parameter. You only need to
on Add 1 App at the bottom right of the window to add it. give sufficient examples to train the models of your assis-

Figure 6: Possible phrases registered in the intent start_quiz to start a game. This can of course be done in any of the available languages.

18 July & August 2019 www.elektormagazine.com


tant. “I don’t know”, “I have no idea” or “I can’t get the MQTT_URL = "{}:{}".format(MQTT_HOST, MQTT_PORT) # ==>
answer” are pertinent examples. "localhost:1883"
   
The assistant is ready to install with SAM, but before this, we SNIPS_USER_NAME = "snips"
need to write the action code in the Actions tab. INTENT_STARTS_QUIZ = "{}:start_quiz".format(SNIPS_
Here we have chosen a script written in Python, called action-
USER_NAME) # ==> "snips:start_quiz"
timestable.py (downloadable at [2]), and we put it in the
INTENT_GIVES_ANSWER = "{}:gives_answer".format(SNIPS_
directory /var/lib/snips/skills/timestables/.
USER_NAME) # ==> "snips:gives_answer"
INTENT_DOESNT_KNOW = "{}:doesnt_know".format(SNIPS_
Action code
To run the action code, we use the library hermes_python. The USER_NAME) # ==> "snips:doesnt_know"
first step is to import it, as well as the library random (to pro-  
duce the numbers for the questions). sessions_states = {}
   
Definitions The three MQTT_... variables define the access point to our
#!usr/bin/env python2 MQTT server, in our case we connect to localhost, because the
# coding: utf-8 code is run on the RPi which is running Snips.
  The three INTENT_...variables define the names of your intents
from hermes_python.hermes import Hermes prefixed by the name of the user who created the assistant
at [1]. These should be replaced by your user name.
import random
  The sessions_states lets the assistant remember the ques-
tion posed to the user.
The combination “#!” (1st line) is needed so that the snips-  
skill-server can execute the code of your assistant. Start the game
Now we define the global variables for our action. Now we define the function to call when the user asks the
  voice assistant to make him revise the multiplication tables.
MQTT_HOST = "localhost" def starts_quiz(hermes, intent_message):
MQTT_PORT = "1883" # Standard MQTT port session_id = intent_message.session_id

Figure 7: For the intent gives_answer, the numbers are highlighted for the Answer type slot.

www.elektormagazine.com July & August 2019 19


# Generating question tts = tts_no_answer
a = random.random() * 10 + 1 elif answer == sessions_states[session_id][0] *
b = random.random() * 10 + 1 sessions_states[session_id][1]:
tts = "What's {} times {} ?".format(a, b) tts = tts_good
sessions_states[session_id] = [a, b] else:
tts = tts_bad
# Define what the assistant is able to understand
intent_filter = [INTENT_DOESNT_KNOW, hermes.publish_end_session(session_id, tts)
INTENT_GIVES_ANSWER]
The two initialisation lines for the variable answer allow us to
recover the value (in the form of a complete number) of the
hermes.publish_continue_session(session_id, tts, user’s response. the second line verifies that the user has given
intent_filter) a good response before providing the value.
The lines tts_... = define the phrases with which the voice
Each function associated with an intent receives two objects assistant will reply in the three different cases:
as parameters: hermes and intent_message.
1. the user gives a good response;
The first step in constructing a dialogue with Snips is to recover 2. the user gives a bad response;
the “dialogue session identifier (session_id). This identifier 3. the response from the user was not understood by the
allows us to identify the dialogue that is running in a unique assistant.
manner; This is important, because several people can use
your assistant at the same time (using satellites). A dialogue The if lets us determine which of the three cases is correct.
session starts when the user says the wakeword and ends Finally we publish the end_session event with the session_id
when your code sends an end_session. as the parameter as well as the phrase that the assistant will
Then we create a random question in the tables from  1 to 10 say before closing this dialogue session.
and save the question in our sessions_states dictionary. This
allows us to verify the user’s response.. The function called when the user says he does not know the
Finally we need to publish an event to continue the dialogue by answer is equally simple. We just publish an end_session to
responding to the user and listening for his response. For this, we close the dialogue, with a predefined TTS.
run hermes.publish_continue_session(...) with the first param-
eter identifying the session to continue. The second parameter is def doesnt_know(hermes, intent_message):
the phrase/question which the assistant is going to pose to the session_id = intent_message.session_id
user (tts = text to speech). The last parameter is the intent filter tts = "Ok, at least try next time !"
which allows the assistant to know if the user will respond with a
phrase contained in one of the two selected intents.
hermes.publish_end_session(session_id, tts)

Reply to the question


Here the two intents are INTENT_DOESNT_KNOW and INTENT_GIVES_ We’re done
ANSWER which means that the user can only give a response or The following function is called once a session has closed after
say that he doesn’t know. a call to hermes.publish_end_session(...).
Now we have to define the function to call when the user gives
a response. def session_ended(hermes, session_ended_message):
del sessions_states[session_ended_message.session_id]
def gives_answer(hermes, intent_message):
session_id = intent_message.session_id Here we suppress the dictionary element which was associated
with the session which has just closed.
# get answer from user
answer = intent_message.slot.get("answer")
The arrival of Hermes
answer = None if answer is None else answer.first().
The last step is to connect all this together.
value

with Hermes(MQTT_URL) as h:
# defines TTS
tts_good = "Good answer !"
# Subscribe to intents
tts_bad = "Wrong answer ..."
h.subscribe_intent(INTENT_STARTS_QUIZ, starts_quiz)\
tts_no_answer = "I'm sorry I didn't get your answer"
.subscribe_intent(INTENT_GIVES_ANSWER, gives_answer)\
tts = ""
.subscribe_intent(INTENT_DOESNT_KNOW, doesnt_know)

# Check user's answer


# Subscribe endSession
if answer is None:
h.subscribe_session_ended(session_ended)

20 July & August 2019 www.elektormagazine.com


# Start Listening
h.loop_forever()
 
@ www.elektor.com
The first line creates an instance of the object Hermes in a ªSnips Voice Interaction for Raspberry Pi, base kit
context manager. Note that its argument MQTT_URL is the url www.elektor.com/snips-voice-interaction-base-kit
See also online review [3]
defined at the start of the file.
The three lines after # Subscribe to intents define that for a ªRaspberry Pi 3B+
www.elektor.com/rpi-3b-plus
given intent (defined by our global variables), a given function
is associated. It is thanks to these three lines that Snips knows
which function to call for each of the three intents received.
Then in the same manner we define that the function session_
ended will be called when a dialogue session finishes.
Finally we execute the function which listens for the different
Snips events and calls the functions associated with each intent.
To summarise, the action code has the following structure:

• importing the libraries;


• definition of variables;
• definition of actions for each intent;
• initialisation of a context (Hermes).

We hope that this first article about the Snips voice assistant
will get you on the way to using it. You are now ready to add
voice commands to any of your Raspberry Pi projects. To make
this easier, don’t forget to check in the App Store in case some-
one has already designed an App close to your needs.
(180733-02)

Web Links
[1] Snips console, tools and documentation : https://console.snips.ai
[2] Python Code of the App on the Article Page: www.elektormagazine.com/180733-01
[3] Review: Snips — Speech Recognition for the Raspberry Pi:
www.elektormagazine.com/news/review-snips-speech-recognition-for-the-raspberry-pi

Advertisement

Plastic enclosures
standard and miniature
More than 5000 different enclosure styles:
hammfg.com/electronics/small-case

01256 812812
[email protected]

www.elektormagazine.com July & August 2019 21


Snips
Speech Recognition
with an example for the Raspberry Pi
By Mathias Claußen (Elektor Labs)

Language assistants like Alexa, Google Home or Siri are now commonplace. However, the actual recognition
of the spoken words is not done locally, but in the Cloud of the provider – which raises questions about data
privacy. There are other solutions such as Snips – a speech recognition system that runs entirely on local
hardware like the RPi. We took a look at a speech recognition kit and show how you can use it to develop
your own applications...

”Tea, Earl Grey – hot” – 10 years ago it


would have been pure science fiction to
expect a computer to respond appropri-
ately to that sort of spoken request. That
was before the arrival of Alexa, Google
Home and Siri. The language assistants
of Amazon, Google or Apple can listen
to everything we say and respond (not
always as expected). Anyone who wants
to write their own application using
speech recognition will quickly realize
that the home assistant is not quite what
it seems to be. All of these systems are
continually looking for a match between
incoming sound samples and a limited
list of keyword templates. After we have
enabled the wizard with the keyword,
everything that it collects from audio
signals is sent directly to the respec-
tive vendor’s servers. The spoken-word
recognition process does not take place
locally but somewhere in the provider’s
cloud. In this context a cloud is nothing
more than a collection of computer sys-
tem resources that exists somewhere
in a data centre. What eventually hap-
pens to that data, we as the user and
app developer cannot see. We can only
trust that the provider deals with it in accordance
with the applicable data protection regulations. A judge
in the US recently ordered Amazon’s Alexa to be summoned
as a “witness” in a murder case.

22 July & August 2019 www.elektormagazine.com


Figure 1: The kit after unpacking.

Anyone with a fear of Big Brother will be happy to know there The sensors and actuators
are alternatives available such as Snips — this is speech rec- The temperature and humidity sensor is a Sensirion type SHT31
ognition software that works completely offline and ensures mounted on a Grove module. The temperature can be measured
your data does not go any further than your home network. to ±0.3 °C and the humidity with ±2% accuracy.
It doesn’t need a permanent Internet connection or a bank of The relay is also a Grove module from Seeed Studio. Its contacts
computers to perform speech recognition. To explore the sys- can switch 250 VAC / 30 VDC with a current rating of 5 A and
tem further we will use the Snips Voice Interaction Kit which should be good for 100,000 switching cycles. Although the relay
uses a Raspberry Pi 3B+ as the base unit. can switch mains voltages the board has not been designed to
operate with them because there is no insulation provided and
In addition to the RPi we need a few more components for this it would be easy to accidentally touch live conductors. As long
speech recognition application. Let’s take a look what’s in the as the load voltage is below the extra-low voltage safety level
kit (Figure 1). (<25 VAC / <30 VDC) and within the relay parameters, you
can safely use this relay module for experimentation.
The kit A small speaker is included so you can hear what the language
The kit arrives packed in a plain blue cardboard box. Inside assistant is saying. As you would expect from a small speaker
are all the components including the Raspberry Pi 3B+, a 5-V the sound quality is quite poor but adequate for the purpose.
3-A mains power adapter, a relay, a temperature and humid-
ity sensor, a speaker, a ReSpeaker 2-Mics Pi HAT, a mounting ReSpeaker 2-Mics Pi HAT
plate and an SD card with pre-installed system along with a The heart of the system — apart from the RPi itself — is the
quick start guide. ReSpeaker 2-Mics Pi HAT [1]. This is built around a WM8960
This gives us all the ingredientsto build our own small language audio codec. Unfortunately, this one is not yet supported directly
assistant. When assembling the kit, use the appropriate spacers by Raspbian, and the driver also has a few bugs. Therefore its
and screws. Unfortunately the manual skips over some details necessary to when using the shield with a naked Raspbian-im-
here so we are left wondering which screws go where.  After age, the driver itself has to be translated for the RPi. Here are
some trial and error we finally get it sorted. The RPi board is the instructions to manually configure the driver. The WM8960
not ideally positioned to easily access the SD card slot. integrates a Class D power amplifier which can supply 1 W into
8 Ω per channel and also includes wiring for microphones. Two
The perforated acrylic mounting board microphones are installed on the board; the connections for a
An acrylic mounting board is supplied onto which you can fix speaker or headphones are also available.
the various modules using self-tapping screws. The matrix of On the board there are also three RGB LEDs (APA102), which
fixing holes allows a certain degree of freedom as to where connect via SPI to the Raspberry Pi. These can signal when
the modules can be fixed. the voice assistant starts to listen (or has not understood).

www.elektormagazine.com July & August 2019 23


After booting, the system is ready for its first test. Try saying
“Hey Snips - What’s the temperature?” The system should
reply with the current temperature, then “Hey Snips — Turn
the relay on” to switch the relay on. These commands should
work straight out of the box without the need to make any
configuration changes. Now we get to the more interesting part
when we begin to implement our own applications/commands
using speech recognition.

Setup
The Raspberry Pi now needs access to our network, the eas-
iest way to do this is by using a cable. If you want to do the
whole thing via Wi-Fi, the SD card must be taken out of the
RPi and the file wpa_supplicant.conf  placed  in the drive with
the name boot. The file contains:
 
ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev
update_config=1
country=<your_country_id>
network={
Figure 2: Creating an Intent (speech command).
ssid=”<your_ssid>”
psk=”<your_password>”
}
 
A pushbutton is also provided to provide interaction with the The corresponding country, SSID and password entries must
system. Finally, there are the connections for the relay, the match your own Wi-Fi credentials.
temperature and humidity sensor. Using snips-base.local you can connect to the Raspberry Pi
A micro-USB port on one side provides convenient power sup- via SSH and explore the system. The snips software is already
ply connection to the RPi. Unfortunately, the header connector preinstalled on the system.
strip is not feedthrough so we can’t stack another HAT on top After the basic setup of the RPi, which is quite straightforward,
and it’s not possible to use a SPI-TFT display as a GUI. we install Sam. Sam is a command-line interface that lets you
Make sure you connect the cables to the correct ports when monitor and manage the Snips software on the Raspberry Pi.
hooking up the relay, humidity and temperature sensor. After To install Sam we need to open a terminal and enter sudo
everything has been assembled and the SD card inserted we npm install -g snips-sam. We can now link to the Snips soft-
can begin. An HDMI monitor and a USB keyboard are useful ware on the Raspberry Pi with sam connect snips-base.local.
now so that we can track the RPi’s first boot process. With sam status we can then output the state and the version
numbers of the individual components. The output should look
like Listing 1.
Listing 1. State output and version number Since the software is still subject to updates, it can occur that
of the individual Snips components. one or other of the versions will sometimes not work properly.
To get the latest version, we now run sam update. The RPi now
Connected to device snips-base.local downloads and installs the latest version. Finally we need to
OS version ........... Raspbian GNU/Linux 9 (stretch) run the sam update-assistant. This will then also update the
Installed assistant .. MakerKitBundle_EN applications and all Snips components should be online again.
Language ............. en If we now enter sam status, all components (except snips-
Hotword .............. hey_snips analytics) now run and the RPi should respond to the example
ASR engine ........... snips commands from the tutorial.
Status ............... Live
Build your own application
Service status:
After creating an account [2] you can use the web interface to
create your own application, and even better, train the assis-
tant on your own voice commands. As a small demo, we will
snips-analytics ...... 0.60.8 (running)
get the language assistant to give us the current time.
snips-asr ............ 0.60.8 (running)
We first create a new wizard, in this case we call it WhatTi-
snips-audio-server ... 0.60.8 (running) meItIs. Within a wizard, apps can now be created. We create
snips-dialogue ....... 0.60.8 (running) an app called “currentTime”. This app is then responsible for
snips-hotword ........ 0.60.8 (running) issuing the current time on command.
snips-nlu ............ 0.60.8 (running) In order for the app to understand a voice command, we have
snips-skill-server ... 0.60.8 (running) to train it as an “intent” (short for intention), see Figure 2.
snips-tts ............ 0.60.8 (running) There are a couple of built-in modules that can make things
easier for us if we Talking numbers or a date. Since our key-

24 July & August 2019 www.elektormagazine.com


word questions are not available as a finished module, we
need to create them. We want to listen to “Time”, as well as
a few synonyms.
Now that we have finished learning, we can take care of the
action that our voice command should trigger. For this we go
to the point Actions and choose for our demo Code snippets.
Currently we can write Python3 and Python2 code via the web
interface and have it executed as an “action”. (Figure 3).
For more detail consult the snips documentation [3].
To output the time, we use the Python3 code in Listing 2.
This code will be executed when the word “Time” or one of its
synonyms is detected. In response, we build a string, which is
then sent to the text-to-speech software module which reads
out the time for us.
With this we have created our first application and can test
it. For this we still have to transfer them to the Raspberry Pi.
In our attached Linux, we enter sam install assistant and
install the newly created wizard. Then we can ask for the time
with “Hey Snips, what’s the time”.

Figure 3: Entering code for command execution.


To sum up
The kit contains everything you need to start experimenting
with voice control including speakers, microphones, sensors
and relays. Unfortunately, the output signals from the two
built-in microphones is poor quality and quite noisy. This does Once you get used to using the Snips.ai web interface, it’s fun
not affect the speech recognition but anyone following the to work with the system and explore the possibilities the sys-
instructions to record a new keyword to activate the speech tem offers. Above all, it’s reassuring to know that at the end
assistant will unfortunately need a better quality microphone. of the day, I am the only one with access to all my data.
When assembling the hardware you need to pay attention, one (180208-02)
or two additional pages in the manual with illustrations show-
ing the spacer placing would have been helpful.
It is not ideal that the wm8960 codec is not currently sup-
ported by the current Pi kernal builds making it necessary to
manual build to run the sound card in the official Raspbian. If
@ www.elektor.com
you want to create your own image based on Raspbian, then
you will need to compile and patch the driver yourself. If a ªSnips Voice Interaction Base Kit
www.elektor.com/snips-voice-interaction-base-kit
new version of Snips is installed the assistant will need to be
updated again or reinstalled.

Listing 2. Python code for our application.

import time
now = time.localtime()
if len(intentMessage.slots.DateTime_Req) > 0:
date_or_time = intentMessage.slots.DateTime_Req.first().value # We extract the value from the slot
result_sentence = "Current time is : {} {} ".format(str(now.tm_hour), str(now.tm_min))
# The response that will be said out loud by the TTS engine.
else:
result_sentence = "Time is running out"
current_session_id = intentMessage.session_id
hermes.publish_end_session(current_session_id, result_sentence)

Web Links
[1] Embedding an audio driver: http://wiki.seeedstudio.com/ReSpeaker_2_Mics_Pi_HAT/
[2] Snips homepage: https://snips.ai/
[3] Snips documentation: https://docs.snips.ai/articles/console/actions/actions/snippets

www.elektormagazine.com July & August 2019 25


LABS PROJECT

MIDI I/O Breakout Board


supports DIN and TRS connectors
By Clemens Valens (Elektor Labs)

At the start of 2019, some 35 years after its introduction, version 2.0 of the Musical Instrument Digital
Interface, better known as MIDI, was announced. MIDI 2.0 introduces many new features, two of them being
two new connectors. A new universal MIDI interface breakout board is due and here it is.

know is that the new standard will remain 3.5 mm and 2.5 mm, where the latter
Quick Features 100% compatible with MIDI 1.0. is the recommended type. The motiva-
• One PCB for MIDI In, MIDI Out tion for this addition to the standard is
and MIDI Thru TRS? Like "jack"? simple and size related: the venerable
• Configurable for 5-V and 3.3-V To be honest, the new MIDI connec- DIN plug is too bulky to fit in modern,
systems tor specification was released in the flat smartphone-like equipment.
• Supports DIN, 3.5-mm TRS and summer of 2018, and therefore is pre-
2.5-mm TRS connectors MIDI 2.0. In a Letter of Agreement for New, new, all new!
• Compliant with latest MIDI Recommended Practice the Tip-Ring- The new MIDI breakout board (BoB) we
standard Sleeve (TRS) socket/plug combination present here can be equipped with either
got accepted as the MIDI connector/plug, one of the three connector types: DIN,
and the way to wire it to the traditional TRS-3.5 or TRS-2.5. Furthermore, the
5-way DIN connector/plug is standard- BoB supports RF grounding and 3.3-volt
At the time of writing this article (April ized. Most people will know the TRS con- signalling, and the same PCB can be con-
2019) the MIDI 2.0 specification has nectors as 'audio jack' plugs and sock- figured as either a MIDI In or MIDI Out
not been released yet. We will therefore ets. Actually, the new connectors are just (or MIDI Thru, which is the same thing
not go into any detail here. What we do one but with two different diameters: as Out).

26 July & August 2019 www.elektormagazine.com


K3
L1 +VCC
project decoder
MIDI
BLM21AG102SN1D
C3
R1 R3 R2 TRS DIN
* *

1k
2.5mm

220
100n Breakout Board

IC1
4 1 1 6 3
Æ entry level
K4
* *
C2 C1 D1
2
K1 & 4 intermediate level
2
100n 5 100n BAT54 expert level
3 DIN5 2 5 1
H11L1MS

K2 R4 1 hour approx.
R5
*
L2

3.5mm * BLM21AG102SN1D 190070-003

soldering iron

Figure 1: This slightly muddled schematic of the MIDI I/O BoB is what you get when you combine
multiple circuits into one configurable circuit.

£12 / €15 / $17 approx.


The schematic of the MIDI I/O BoB is ing shield connector on the MIDI jacks
shown in Figure 1. Due to configuration should not be connected to any circuit
options and EMI/EMC and RF measures, or chassis ground.” However, in 2014
there are a few more components than this was relaxed and an optional con-
in a typical MIDI interface design. nection between the shields of MIDI Out fore allows for these grounding options
and MIDI Thru connectors to Ground was using C1 and C2. When the board is used
Ground loops versus EMC allowed to improve EMI/EMC perfor- as a MIDI In, C1 and C2 are either left
The original MIDI 1.0 specification mance. MIDI In connector shields may be off, or mounted as 100-nF (US: .1 µF)
stated that in order to avoid ground grounded through a small capacitor, but capacitors; in the case of a MIDI Out (or
loops between devices “The ground- never directly. Our MIDI I/O BoB there- Thru) C1 and C2 can be 0-Ω resistors.

component list

www.elektormagazine.com July & August 2019 27


Avoid RF interference sure that the LED would light well. Mod-
Ferrite beads L1 and L2 attenuate RF ern optocouplers usually don’t need that
interference but may be replaced by much current (ours only needs 1.6 mA),
0-Ω resistors for simplicity (depending but since a modern MIDI Out must still
on what you have in stock, for instance). be capable of driving an vintage MIDI In,
R3 and R4 are configuration resistors 5 mA is what is needed.
and are only required for MIDI Out (and A MIDI input presents itself as a 220-Ω
Thru) applications. To prevent anyone resistor in series with an LED; the MIDI
from accidentally mounting them on a standard assumes that this LED can have
MIDI In module, they are placed in the a forward voltage as high as 1.9 V. This
same position as optocoupler IC1. means that the output signal level VTX
must be at least:
MIDI In calls for an optocoupler  
The optocoupler is a fast device ensur- VTX ≥ 0.005 × 220 + 1.9 = 3.0 V
ing good signal quality and low latency  
between In and Thru in the case of Short-circuit current limiting is required,
chaining multiple MIDI devices. Diode which is the function of R4. R1 and R4
D1 protects it against reverse-polarity together (remember that R3 = 0 Ω) will
signals. introduce a voltage drop that has to be this 100 mA current, R1 must be rated
R2 is the output resistor for the open-col- overcome by VTX as well. Therefore for 0.5 W.
lector output on IC1. You can lower its   Similar reasoning holds for R4 (a 1.2-W
value to improve speed slightly, but at VTX – 3.0 ≥ 0.005 × (R1+R4) type would be required), except that for
the expense of a higher current con-   this resistor it is assumed to be driven
sumption. IC1’s minimum supply volt- With VTX = 3.3 V, we can calculate by an open-collector or open-drain out-
age is 3 V, which sets the lower bound-   put with a pull-up resistor. This resistor
ary for VCC for the MIDI In configuration R1 + R4 = 0.3 / 0.005 = 60 Ω with a value of a few hundred ohms (typ-
(the upper extreme for IC1 is no less   ically) would limit the current, allowing
than 16 V). The MIDI Manufacturers Association pro- the power rating of R4 to be relaxed to
C3 provides supply bypassing and is poses R1 = 33 Ω and R4 = 10 Ω, a total 0.25 W. Therefore, be careful when driv-
probably more of a good practice thing of 43 Ω, to allow for all sorts of toler- ing the 3.3-volt MIDI Out from a digital
than really necessary, but hey, you never ances on resistor values and supply and driver. This limitation does not apply to
know what lengths of wires or traces output voltages. the 5-V MIDI Out.
people connect to K4 (keeping them as
short as possible is also good practice). Beware of short-circuits Finally...
Resistor R5, a 0-Ω resistor, has no func- An easy to overlook detail is the cur- The above description shows that even
tion other than to provide a way to share rent through R1 and R4 when the remote for simple circuits there are a good many
a shield pin of K2 with a shield pin of K1 MIDI input is faulty and for some reason things to e-worry about, especially when
without unintendedly connecting every- shorted to GND: trying to interconnect equipment from
thing to GND. It must only be mounted   different origins and eras.
when K2 is mounted also. VCC / R1 = 3.3 / 33 = 0.1 A Final note: a complete set of nine com-
PR1 = (0.1)2 × 33 = 330 mW ponent stuffing tables for the MIDI I/O
Configuring for MIDI Out   BoB can be found at [1].
and MIDI Thru Because R1 is connected to the trans- 190070-01
A MIDI Out or MIDI Thru module con- mitter’s power supply which we can only
sumes fewer parts since IC1, D1 and R2 assume to be powerful enough to deliver
are not needed. For these configurations
R3 is a 0 Ω resistor that connects R1 to
VCC. R4 is the MIDI output current lim-
Web Link
iting resistor.
The values of R1 and R4 depend on VCC. [1] MIDI I/O BoB at Elektor Labs:
For a 5-V supply voltage, both take a www.elektormagazine.com/labs/midi-io-break-out-board
value of 220 Ω; this is the traditional
MIDI Out port for 5-V systems. However,
for 3.3-V systems their values must be
adapted as follows. @ www.elektor.com
ªMIDI IO Breakout Board, configured as input – Partly Assembled Module
Calculations for www.elektor.com/190070-91
low-voltage signalling ªMIDI IO Breakout Board - Bare PCB
At its introduction the MIDI standard www.elektor.com/190070-1
specified a current of 5 mA through the
MIDI input’s optocoupler LED to make

28 July & August 2019 www.elektormagazine.com


LABS PROJECT

The SCCC Project (3)


Homebrew soft-core processor and C compiler
By Martin Oßmann (Germany)

In the previous installment of this series we limited


ourselves to running our DIY CPU in simulation. In
this part we will return to the MAX1000 board. We
will connect this small development board to a PC using
a couple of serial interfaces, which will allow us to upload
programs and monitor serial input and output. We will also read
data from the acceleration sensor that is included on the board.

We already made use of the MAX1000 board in the first part which defines the CPU, achieve this.
of this series [1]. We will now briefly describe how to get a  
compiled program into the FPGA. The process of compiling the parameter sCcodeMemAddressWidth=12 ;
C program itself is relatively quick, and results in two files, parameter sCdataMemAddressWidth=10 ;
codemem.txt and datamem.txt. The content of these files must reg [40-1:0] sCcodeMem [0:(1 <<
be loaded, in effect, into the CPU’s memory space, which is sCcodeMemAddressWidth)-1] ;
physically located inside the FPGA.
reg [32-1:0] sCdataMem [0:(1 <<
 
sCdataMemAddressWidth)-1] ;
The following lines of the Verilog source file sCCCPcpu1v01.v,
 
initial begin
  $readmemh(“CodeMem.txt”,sCcodeMem) ;
  $readmemh(“DataMem.txt”,sCdataMem) ;
sC Sourcecode end
experiment1.c Verilog-Code
 
TopLevel.v
sCCCPcpu1v01.v The first four lines above specify the word size and the number
SFRs.v of words of storage for the code and data memories.
SC Compiler
The lines after ‘initial begin’ specify that the code and data
memories are to be initialized with the contents of the named
files. That means that these files must be available at the time
Quartus
Mem1.java
Synthesis Tool the FPGA code is synthesized. We therefore synthesize the
FPGA design after compiling the C program to generate the
bitstream that is to be loaded into the FPGA. This step is rela-
CPU
Processing sketch
SFRs
tively time-consuming (on the author’s machine it takes about
UploadCode...pde
Memory five minutes) and the synthesis process must be repeated from
scratch after each change to the C source code.
This resynthesis process becomes somewhat tedious after a
Uploader while, and we might wonder if it is possible to load the program
FPGA
and data memory after synthesis has been done. One way to
achieve this is to build an ‘uploader’ into the FPGA design.
Let us look at how this is done. In the working directory of
Figure 1. The uploader can be used to send compiled application experiment5 (available for download at [3]) there is a Quar-
programs to the CPU after the synthesis step: this makes the tus project file (.qpf extension). In order to use the uploader
development cycle much quicker. we need to synthesize this project and load it into the FPGA.

www.elektormagazine.com July & August 2019 29


To test whether the service interface is working,
K2 send the string
GND  
R4
1k PWMa
R5 1234x
1k PWMb
C2 C3  
K3
to the port, for example using a terminal emu-
2n2 2n2 1
lator program. The response should be a row of
J6 6
MAX1000 R1
2 hexadecimal characters
1k
1
7  
R2 R3
3
2 1k 1k 000000001234 000000000000 1234
8
3 D1 D2  
4
4
9 including an echo of the hexadecimal data that
5 BAT43 BAT43
6
5 were sent.
IC1a
C1 In the directory Processing\UploadCodeViaSeri-
1 2
1 DSUB to PC al1v01 you should find a further file Mem1.java,
100n
assuming you have started the SCCCP develop-
JP1 K4
IC1b ment environment supplying the output option
RXD
2 1
1 TXD -p (for ‘Processing’). This file will later hold the
IC1 = 74HC04 GND object code for our application program and will
180394-036
TTL USB
be used by the Processing environment in order
to carry out the upload operation.

Figure 2. Hardware extension to allow uploading programs over the service interface. For
the time being we will not be using the PWM interface. Connecting peripherals
The CPU that we will use for experiment 5 is
equipped with other functional blocks alongside
the UART used for the service interface. These
The workflow that we will be able to use as a result is illus- include a real-time counter (RTC), a pulsewidth modulator
trated in Figure 1. (PWM), an analog to digital converter, a GPIO port, and, last
A serial interface will be used to send data and program code to but not least, a user UART. The user UART can be connected
the FPGA. So first a few remarks on how that is implemented. to the PMOD2 connector on the MAX1000 board (J6) using the
hardware shown in Figure 3.
Our first hardware extension
The serial interface uses the standard 8N1 protocol at We will now look at how the CPU in the FPGA can be expanded
115200 baud. The hardware shown in Figure 2 is used to using simple peripheral modules. First we will use three pins as
connect the PC’s serial port to the MAX1000 board. If on the general-purpose I/O (GPIOs). In Verilog we do this as follows.
PC side you are lucky enough to have a real serial port, this  
hardware can be connected to the 9-pin connector. In that case parameter GPIOINPWIDTH = 3 ;
IC1 is not required (and jumper JP1 can be removed). This wire[GPIOINPWIDTH-1:0] GPIOinp ;
is the setup used by the author with his serial port. Although parameter GPIOOUTPWIDTH = 3 ;
the circuit does not strictly meet the interface standards, it reg[GPIOOUTPWIDTH-1:0] GPIOoutp ;
nevertheless works well.  
Many readers may have a USB-to-TTL serial cable, with the To read data from the expansion module the CPU needs to
signal levels inverted with respect to the RS-232 levels. Such execute an INPA c instruction, where c (for ‘channel’) is the
a cable can be connected at K4. To make things even simpler number of the port to which the GPIO peripheral is connected
it is possible to connect the USB-to-TTL cable directly to the in the CPU implementation in the FPGA.
FPGA, but in that case the inversion of the signals must addi-
tionally be implemented inside the FPGA. In Verilog the mechanism is modeled using the variable inpA,
which holds the value that will eventually end up in register R0
Serial service interface as a result of executing the above instruction. The source of
To upload an application program over the ‘service interface’ the data for this variable is selected using a large multiplexer,
requires a small program running on the development PC. The which is implemented as follows.
author implemented this program using Processing [4]. The  
program can be downloaded as Processing\UploadCodeViaSe- assign inpA=
rial1v01 at [3], and it can be launched directly from the Pro-   (inpAchannel==0) ?  { 32’h12341234   } :
cessing development environment. Before running it, however,   (inpAchannel==1) ? sCuartRXdata :
it is necessary to modify the line   (inpAchannel==2) ? sCTXuartBitsLeft :
 
  (inpAchannel==3) ?{ 20’h12300 , ADCval[12-1:0] } :
String serialPort=”COM3”;
  (inpAchannel==4) ? RTCtimer :
 
  (inpAchannel==5) ? debugReg1 :
to suit the COM port that you will be using for communication
  (inpAchannel==6) ? aDacSignal :
with the hardware.

30 July & August 2019 www.elektormagazine.com


  (inpAchannel==7) ? bDacSignal :
  (inpAchannel==18) ? GPIOinp : K2
  32’h12341111 ; GND
IOa
 
IOb
For example, if channel 0 is selected then the
K3
value ‘12341234’ will always be returned, which
1
can be used for testing; channel 1 returns the
J6 6
data received by the user UART; and channel 18 MAX1000 R1
2
1k
reads the signals on the GPIO pins, which we will 7
7
R2 R3
make use of in experiment 5. 8 1k 1k
3
8
9 D1 D2
4
10
Operation in the other direction is similar. If data 9
11 BAT43 BAT43
are output to channel c using the instruction 12
5

OUTA c, the signal outAstrobe is activated and IC1a


C1
1 2
the data are routed to the correct destination 1 DSUB to PC
100n
using a large if-then-else construct. The Verilog
JP1 K4
code to implement this is as follows. IC1b
RXD
2 1
  1 TXD
IC1 = 74HC04 GND
always @(posedge sCclk) begin
180394-038
TTL USB
  if(outAstrobe) begin
    if( outAchannel==0) begin
      ... Figure 3. This extension lets us carry out simple I/O experiments.
      else if( outAchannel==5) begin
        LEDs<=outA[8-1:0] ;
        end
        ... assign GPIOinp[0] = LISsenINT1 ;
      else if( outAchannel==18) begin assign GPIOinp[1] = LISsenINT2 ;
        GPIOoutp<=outA[GPIOOUTPWIDTH-1:0] ; assign GPIOinp[2] = LISsenSDO ;
        end  
      ... assign LISsenCS = GPIOoutp[0] ;
    end assign LISsenSDI = GPIOoutp[1] ;
  end assign LISsenSPC = GPIOoutp[2] ;
   
From this code we can see, for example, that the LEDs that we These two modifications to the Verilog code are sufficient to
used in experiment 1 are connected to channel 5. And again, enable the soft-core CPU to read and write data using INPA
channel 18 is used to control our GPIO pins. Now we just need and OUTA instructions respectively. This illustrates how we can
to connect these virtual pins to real pins in hardware. extend the peripherals already available in the CPU to create
our own peripheral functions. We will now see how to write
Experiment 5: GPIO and software SPI a C program that lets the CPU talk to the peripheral device.
The MAX1000 board sports a type LIS3DH acceleration sen-
sor made by ST. It would be desirable if the CPU could talk to Do it all in C
this device, and for that purpose we will use the CPU’s gen- We have already seen how it is possible to include assem-
eral-purpose I/O pins as mentioned above. These pins will be bler code in our C programs, and this facility makes talking
connected to the LIS3DH’s interface pins. First we arrange for to the CPU’s peripherals (and thence to external hardware)
the physical pins to be configured as inputs or outputs in the very easy. The example in Listing 1 originates from the file
top-level module of the Verilog code as follows. experiment5/IOlib5.c.
  To understand this code we need to know a bit about how the
  ... compiler works. When an arithmetic expression is evaluated
  input LISsenINT1, the result is placed in R0. Also, R0 is used to hold the return
  input LISsenINT2, value from a function call. Armed with this knowledge, and
  input LISsenSDO, looking at the comments in the code, we can see how it all fits
together. We are now in a position to write a function in C that
  output LISsenCS,
can be used to access the LIS3DH acceleration sensor: we will
  output LISsenSPC,
write code to implement the SPI interface by ‘bit banging’ the
  output LISsenSDI
GPIO pins. Listing 2 shows some example C code to achieve
  ... this. So now to the experiment proper.
 
Now we can connect up the LIS3DH pins to the GPIO signals Action stations
on channel 18 of our DIY CPU inside the FPGA using a series The SCCCP development environment is launched by execut-
of assign statements as follows. ing the file c.bat in experiment5/experiment. Then clicking on

www.elektormagazine.com July & August 2019 31


Listing 1. Reading from and writing to a peripheral.

GPIOchannel       EQU  18
 
GPIOout(int p){
  p ;                 // ‘calculate’ the value of p and leave it in R0
#asm                  // now a bit of assembler code
  OUTA  GPIOchannel   // write value in R0 to GPIO channel
#endasm
}
 
GPIOin(){
#asm                   // switch to assembler code
  INPA  GPIOchannel    // read value from GPIO channel into R0
#endasm                // switch back to C
}

the ‘MAKE’ button will compile the C code. the FPGA: the example here reads values from the three chan-
  nels of the LIS3DH acceleration sensor and outputs them over
c.bat: the user serial port at 115200 baud. The results might appear
Java as follows.
-jar c:\SCCCP\CompilerAsJar\sCCCP.jar  
-s experiment5.c   x= -00000032 y= -00000128 z= +00016576

-p ..\..\Processing\UploadCodeViaSerial1v01\   x= -00000048 y= -00000224 z= +00016688


    x= -00000064 y= -00000240 z= +00016544
The effect of the -p option is that when the ‘MAKE’ button   x= -00000032 y= -00000224 z= +00016640
is clicked on, the resulting object code will be written to the
  x= +00000016 y= -00000256 z= +00016704
upload directory with file name mem1.java.  
  If you now move and turn the MAX1000 board you should see
The next step is to synthesize the Quartus project experiment5. the acceleration readings change.
qpf in the working directory, and load the resulting bitstream Should you now wish to make changes to the programming
file into the FPGA. The uploader will now be sitting in the FPGA, running in our CPU, you simply need to compile the new ver-
ready to receive data and program memory contents over the sion of the code and send it to the MAX1000 using the uploader
service interface. To test this, use a terminal emulator program sketch. This process is considerably quicker than resynthesiz-
to send an ‘x’ character and verify that you receive a string of ing the whole CPU from scratch every time. When your pro-
hexadecimal characters in response. gram is finally running as it should, the upload facility can be
To upload the memory contents we launch the sketch Upload- disabled in the CPU Verilog project by replacing the lines of
CodeViaSerial1v01.pde, which runs in the Processing program- MainInclude.txt that read
ming environment. This will load the application program into  
`define bootload
//`define standalone
 
by the following lines.
@ www.elektor.com  
//`define bootload
ªMAX1000 FPGA development board
www.elektor.com/max1000 `define standalone
 
ªE-book: ‘Microprocessor Design Using Verilog HDL’
www.elektor.com/verilog
The result of this change is that the data and program mem-
ory contents will be incorporated into the CPU design at syn-
thesis time.

Web Links
[1] The SCCC Project (1), ElektorLabs magazine 2/2019: www.elektormagazine.com/180394-01
[2] The SCCC Project (2), ElektorLabs magazine 3/2019: www.elektormagazine.com/180394-B-01
[3] Project page for this article: www.elektormagazine.com/180394-C-01
[4] Processing: http://www.processing.org

32 July & August 2019 www.elektormagazine.com


Listing 2. SPI communication using bit-banging.

int GPIOoutShadow ;
#define bitMaskLISsenINT1 1
#define bitMaskLISsenINT2 2
#define bitMaskLISsenSDO  4

#define bitMaskLISsenCS   1
#define bitMaskLISsenSDI  2
#define bitMaskLISsenSPC  4
 
LISinit(){
  GPIOoutShadow= bitMaskLISsenCS | bitMaskLISsenSPC | bitMaskLISsenSDI ;
  GPIOout(GPIOoutShadow) ;
}
 
LSIclockPulse(){
  GPIOoutShadow = GPIOoutShadow & (~bitMaskLISsenSPC) ;
  GPIOout(GPIOoutShadow) ;
  GPIOoutShadow = GPIOoutShadow | bitMaskLISsenSPC ;
  GPIOout(GPIOoutShadow) ;
  }
 
SPItxrxByteMSBfirst(int vTX){
  int vRX ;
  int k ;
  int GPIOinp ;
  vRX=0 ;
  for( k=0 ; k<8 ; k++){
    if(vTX & 0x80) {
         GPIOoutShadow =GPIOoutShadow | bitMaskLISsenSDI ;
       }
   ​   ​  ​else {
   ​
     ​
 ​ ​
GPIOoutShadow =GPIOoutShadow &( ~ bitMaskLISsenSDI );
     }
    LSIclockPulse() ;
      vRX = vRX << 1 ;
      GPIOinp=GPIOin() ;
      if( GPIOinp & bitMaskLISsenSDO ) { vRX = vRX |1 ; }
      vTX=vTX<<1 ;
  }
  return vRX ;
}

Experiment 5 is one of our more complicated endeavours, as SPI functionality directly in the FPGA, but for our simple and
it involves a disparate range of files, programs and compo- non-time-critical application the bit-banging approach is much
nents. If something fails to work as it should, then the first more straightforward.
things to check are the following: are all the paths specified  
in the batch files correctly set to reflect the installation? And In the next installment of this series we will take a look at how
are the COM port numbers and baud rates correctly set for to generate analog signals, with the help of sigma-delta DACs
the serial interfaces? and interrupts. Stay tuned!
When you do have everything up and running you can then (180394-C-02)
take a look at the code in experiment5.c in order to learn how
it goes about outputting data using the user UART.
The code drives the acceleration sensor using a bit-bang-
ing technique. It would also be possible to implement the

www.elektormagazine.com July & August 2019 33


Student
Demonstration
Time!

TUE/InMotion:
Revolutionary Battery Pack Design

Photo credit: Johan van Uden.

Kjeld Teunissen (The Netherlands)

The InMotion student team from the Technical University Eindhoven (TUE) in The Netherlands
is grabbing this space to publicize they’re working on ‘Electric Refuelling’, a concept which aims
to offer a solution to recharge electric cars as fast as you would refuel those with a combustion.
Interesting, right? Let’s see what they’re up to...

The InMotion student team, which I am industry, permitting work at the very tric refuelling by joining the Garage 56
a member of, consists of more than 50 edge of technology. We are working on Class during the 24 Hours of Le Mans
young and ambitious students from the a concept called ‘Electric Refuelling’, race with a fully electric endurance race
Eindhoven University of Technology and which is the ability to charge your car in car in 2023. For this, we need to develop
the Fontys University of Applied Scien- the same amount of time as you would our own custom-made battery pack and
ces. Student teams offer a unique col- refuel a car with a combustion engine. We this is my responsibility for this year. So,
laboration between universities and the intend to showcase the potential of elec- in case you have ever wondered

34 July & August 2019 www.elektormagazine.com


Is your team working on something cool?
Are you on a student team with a cool or amazing achievement to report on in the
field of electronics?
Then email [email protected], subject “Student Demonstration Time”.

• how electric vehicles are powered force us into a dilemma. For one, we
• how it’s possible to power a vehicle can aim for a high-capacity battery pack
with cells so small they fit in the that allows you to take more energy with
palm of your hand you and therefore cover longer distances.
  Alternatively, we can build a high-po-
then this article is just for you. wer battery pack that’s more suitable
to high-power applications and faster
First things first charging. Since the focus of InMotion is
If ever you wanted to design a battery on developing fast-charging technology,
pack no matter its application, you our battery pack of choice is the latter.
should always clearly define what you So, we are now developing a battery
want in a set of requirements. The four pack with a lower capacity than offered
main requirements are the (minimum, by some commercial vehicles. Still, this
nominal and maximum) voltage, capa- allows us to develop technology that can
city, weight, and power. Furthermore, be used when battery technology has
you should always take safety features improved to a level where high-power
and regulations into account. battery packs provide enough capacity
Current battery technology seems to for commercial applications.

The InMotion team (photo credit: Bram Naus).

www.elektormagazine.com July & August 2019 35


ger surface area which makes it easier
to cool the cells.

Module
The design variables of a single module
are determined by the free space requi-
red around each cell. With pouch cells the
space above, below and on the sides of
the cells are all parameters that need to
be determined or acquired. These usually
depend on the placement of the tabs and
the type of cooling used.
 
Pack
With the dimensions of the modules
determined, they’re ready for stacking to
make a pack. This will determine where
Figure 1. An example of a battery cooling pack made by Kokam [1]. cooling lines need to be run, as well as
how the modules need to be connected
electrically inside the pack.
Structure ant decision in the process. It is the defi-  
As mentioned before, a battery pack is ning factor in the battery pack’s per-
made up of lots of smaller battery cells. formance. InMotion uses pouch cells Fancy software
Several cells are bundled in a module, because they’re better suited for fast At InMotion the development stage is
and these modules are then configured charging than cylindrical cells. very dynamic. It allows us to change
in a battery pack (see also Figure 1). things on-the-fly. It also means that not
  They can take more abuse, usually have all our requirements are set in stone,
Cell a lower internal resistance which in turn and we’re trying to find a set that fits
The cell type is probably the most import- generates less heat, and they have a lar- our goals. The battery pack is a good

Figure 2. A specially written program helps to design the battery pack.

36 July & August 2019 www.elektormagazine.com


Advertisement
example of this as it can be configured in literally a million

Get your
ways. But how to find out which configuration works best?
To avoid having to generate a model for every single con-
figuration, I have made a battery pack configurator that
optimizes the pack for different input parameters. To ensure

TI Chips
ease-of-use and to allow the user to try out different con-
figurations without having to understand the underlying
code, I created a GUI (see Figure 2). It basically takes

at Mouser
all the design variables as input and then tries to fit as
many modules in a given space, stacking them in the same
direction. In the space that’s left, it will once again try to
fit as many modules as possible, even if that means the
orientation of some modules is different than that of others.
The script uses a heuristic method rather than an analytic
approach to this space optimization problem. This is done
because it is easier to write and still reaches local minima.
It is also extremely efficient and fast. On an average PC
the script creates 190 optimal configurations, selects the
best for a given set of preferences, and plots it within
5 seconds. Within this time it also saves all created opti-
mal configurations, allowing them to be filtered for diffe-
rent preferences. If a different configuration turns out to
be better, it’s easily plotted using the GUI.

The GUI calculates the expected performance of the bat-


tery pack. It tells you:

• the expected capacity;


• the number of modules connected in series and in
parallel;
• the expected cells weight;
• the voltage difference between a full pack and an
empty one.
 
Additionally it calculates the charging currents while indica-
ting the heat generation as well as the charging power range
that will be necessary to charge the pack in 7.5 minutes.

Achievements
With Electric Refueling we aim to be able to charge an elec-
tric car in just a few minutes. If successful, it will undoub-
tedly accelerate the energy transition from petrol to elec-
tric in the automotive industry. To show the world how
fast electric racing can be, we have created the “Fusion”,
an electric formula car that currently holds the electric lap
records at Circuit Zandvoort, TT Circuit Assen (both in The
Netherlands) and Circuit Zolder (Belgium). Our concept car
“Vision” is the true embodiment of future electric mobility.
It is designed to be 10 times more aerodynamically effi-
cient than a Formula 1 car. It is truly the endurance racer
of our dreams.
180732
Mouser is an authorised distributor with the largest
selection of Texas Instruments’ chips in stock
mouser.co.uk/ti

Web links
[1] Website for Kokam: http://kokam.com/modulepack
[2] InMotion website: www.inmotion.tue.nl/

www.elektormagazine.com July & August 2019 37


LABS PROJECT

ESP32 Battery Monitor


Measures three channels via Wi-Fi and Thingspeak

By Laurent Labbe (Hong Kong) and Luc Lemmens (Elektor Labs)

This project shows the simplicity and ease of measuring analogue values with an ESP32 board and to send
the values via Wi-Fi to a router, and from there, to the ThingSpeak website where the data are saved and
displayed.

At the moment, Laurent is working on available, the author used two exter- The analogue/digital converted of the
several projects powered with solar nal batteries (powerbanks), one small ESP32 is equipped with an internal atten-
energy. He was looking, amongst other (1000 mAh) and one large (10,000 mAh). uator which may be set by the Arduino
things, to develop a solar power source The smaller is connected permanently to sketch with the function analogSetAt-
for his Nixie watch [1]. By its nature, power the ESP32 board. It is recharged tenuation to one of the following val-
solar radiation is not dependable, so it by the larger one which is replaced ues: 0 dB, −2.5 dB, −6 dB or −11 dB;
may take some hours or even days to almost every day so that the system is corresponding to factors of 1 ; 0.75 ;
test a power supply model. He developed always working. If only a single battery 0.5 or 0.28.
three different modules, each charging was used, measurements would be lost By default, the full scale voltage of the
three identical small batteries (130 mAh) during the recharge of the battery pow- ADC is 1.1 V. This voltage is the max-
with a resistor to simulate the power ering the ESP32. imum that can be read (as a function
drawn by the watch. Then he read the of the number of bits configured for
battery voltage on the three modules and Three I/O pins of the ESP32 (Figure 1) ADC1: 4095 for 12 bits, 2047 for 11 bits,
sent them to the free ThingSpeak plat- are used to take the measurement sof 1023 for 10 bits, 511 for 9 bits). To
form [2] for the Internet of Things (IoT). the three channels/batteries. Each pin read higher voltages (up to the max-
has its own voltage divider and a 100 nF imum voltage for the pin, generally
Measurements filter capacitor. In the sketch, this attenu- 3.3 V = Vdd), an attenuation greater
The measurements are taken by an ation is represented by the variable Coef_ than 0 dB must be set for the ADC chan-
ESP32-PICO-KIT-V4 development board Vx and its value may be adjusted to com- nel in use. Table 1 sets out the the
powered by USB (5 V). As the device pensate for tolerances in the external settings and the ranges which can be
is used outside, with no mains power voltage divider. used. For an attenuation of −11 dB, the

38 July & August 2019 www.elektormagazine.com


R1 1% project decoder
V1 1M1 FCS FSD1
FSD0 FSD3
ESP32
R2 C1

576k
FSD2 FCLK ESP32-PICO-KIT
1% 100n FSVP IO21
ThingSpeak Wi-Fi
FSVN IO22
MOD1
IO25 IO19
R3 1%
IO26 IO23 Æ entry level
V2 1M1
intermediate level
IO32 IO18
R4 C2
IO33 IO5 expert level
576k

IO27 EN IO10
1% 100n
IO14 IO9
IO12 RXD0
IO13 TXD0
2 hours approx.
R6 1% LED1
BOOT
V3 1M1 IO15 IO35

C3 IO2 IO34
R7
576k

IO4 ESP32 IO38 R5


1% 100n IO0 Pico-Kit V4 IO37
PC with Arduino IDE

1k
3V3 EN
GND GND
5V 3V3
USB
170500-013
€15 / £12 / S18 approx.

Figure 1. Circuit diagram: the ESP32 board takes care of most of the work.

maximum voltage is limited by VDD_A, Speak for a weather station project. So then create an account (Figure 2). Then
and not by the full scale voltage. he naturally opened a page there to store click on Connexion to access your account
The circuit was designed to monitor the measurements taken for his watch and fill in your ID information. Then cre-
LiPo batteries at 4.2 V and the analogue batteries (see [3]).. ate an account where the Battery Moni-
inputs are calculated to support a maxi- ThingSpeak is a free web service with tor data will be collected (New Channel),
mum input voltage of 5 V. with a voltage open source code, which allows you to give your channel a logical name which
divider using resistors of 1.1 MΩ and gather and store in the cloud data from will be easily recognised as your battery
576 kΩ, the inputs of the ESP32 board sensors, and develop applications for monitor data. In the Channel Settings,
are specified for a voltage of ±1720 mV the Internet of Things. Sensor data can add three fields to sort the data which
for a voltage input of 5 V, which is the be sent to ThingSpeak from Arduino, the Arduino sketch will send in the form
maximum input voltage recommended Raspberry Pi, BeagleBone Black and of strings and label them (in our case V1,
for and attenuation of −6 dB.Of course, similar boards. V2 and V3 as in Figure 3). Now choose
you can modify the input circuit if you Also, it is possible to use functions from the API keys tab, here you will find the
need a different input voltage range, and/ various MATLAB (from MathWorks) tool- Write API key which you must copy into
or change the internal attenuation of the boxes on a ThingSpeak connection. For the sketch of the ESP32 board to iden-
ADC of the ESP32 board. that it is necessary to be connected with tify the ThingSpeak channel(Figure 4).
  a MathWorks account with an active
Note: you can only apply DC voltages licence in order to use these toolboxes. Battery Monitor Sketch
to the inputs which are within the range If you’re starting this project and you The Battery_monitor_elektor_3.ino
defined by the settings of the ADC. In don’t yet have a ThingSpeak or Math- sketch written in C is not very compli-
addition, there is no protection against Works account, Go to www.thingspeak. cated, but before compiling it and upload-
reverse polarity or overvoltages! com and click Get Started For Free, ing it to the ESP32 board, you need to
Pin GPIO17 of the ESP32 board drives a
LED which lights during voltage measure-
ments and data transmission. Then the
LED goes off and the ESP32 board goes Table 1. Theoretical full scale of the ADC and actual full scale available, as
into sleep mode until it automatically a function of attenuation settings if VDD_A = 3.3 V
wakes up for the next measurements. Theoretical Actual range for the most
ADC Attenuation
This minimises energy consumption from full scale accurate results
the external batteries. 0 dB (ADC_ATTEN_DB_0) 1.1 V 100 - 950 mV
You can easily wire up the circuit on a 2.5 dB (ADC_ATTEN_DB_2_5) 1.5 V 100 - 1250 mV
breadboard or a piece of stripboard.
6 dB (ADC_ATTEN_DB_6) 2.2 V 150 - 1750 mV
11 dB (ADC_ATTEN_DB_11) 3.9 V 150 - 2450 mV
Create a ThingSpeak account
Laurent uses the online platform Thing- (Source : https://docs.espressif.com/projects/esp-idf/en/latest/api-reference/peripherals/adc.html#adc-calibration)

www.elektormagazine.com July & August 2019 39


Figure 2. Creation of a ThingSpeak account.

modify it so that the board connects to in the Tools menu. Make sure that the until now).
you Wi-Fi network and sends the data transmission speed of the monitor is set Then the ESP32 board (re)connects to
to your ThingSpeak channel. to 115200 and you should receive a mes- you Wi-Fi network and shows that the
On line 68 of the sketch, enter the Write sage from the ESP32: Battery monitor connection is successful with the IP
API key that you got from the Thing- V1.0 Start followed by the first three address of the ESP32, or sends the mes-
Speak site to identify your channel. voltage measurements. sage WiFi cannot connect if the attempt
Then enter the SSID and the password After each measurement cycle the ESP32 fails.
for your local area network in lines 70 passes into sleep mode. Boot number: x You can set the measurement interval
and 71 respectively. Then upload the indicates how many cycles have run since by modifying TIME_TO_SLEEP on line 45.
sketch to the ESP32 board and open the beginning of the session (i.e. how Note that only the setup function is
the serial monitor of the Arduino IDE many measurements have been made executed, it performs all the process-

Figure 3. Channel settings on ThingSpeak. Figure 4. API key to recopy into the sketch.

40 July & August 2019 www.elektormagazine.com


ing (measurements and data transmis-
sions) and puts the ESP32 into sleep @ www.elektor.com
mode until an internal timer wakes it
ªESP32-PICO-KIT V4 development board, ref. 18423
up for the next cycle of measurements.
www.elektor.com/esp32-pico-kit-v4
The setup function is then executed
again. The loop function is empty, and
it is never executed.

If this is your first project with the ESP32


board in the Arduino IDE, don’t forget to in the menu Tools -> Port and choose door to all sorts of other measurements
install the ESP32 boards in this environ- ESP32 Pico Kit in Tools -> Board. and lets you get a foot in the cloud.
ment. You will find numerous tutorials   170500-02
on the Internet (See for example [4]). This project is simple and quick to get
Note: select the right COM port for the working as there is no printed circuit
connection to the ESP32-PICO-KIT-V4 board to get and wire up. It opens the

Web links
[1] Elektor Labs Nixie watch page: www.elektormagazine.com/labs/nixie-watch-1
[2] ThingSpeak Platform: www.thingspeak.com
[3] ThingSpeak battery monitor public page: http://thingspeak.com/channels/329068
[4] Installation of ESP32 boards in Arduino IDE:
http://randomnerdtutorials.com/installing-the-esp32-board-in-arduino-ide-windows-instructions
[5] Elektor Labs Battery monitor page: www.elektormagazine.com/labs/simple-wifi-multimeter
[6] Article support page: www.elektormagazine.com/170500-02

Advertisement

Join the Elektor Community GOLD


MEMBERSH
Take out a GOLD Membership now! ✔ 6x ElektorLabs
IP
Magazine (Print)
✔ 6x ElektorLabs
Magazine (PDF)
✔ 3x Elektor Indu
stry Magazine
(PDF)
✔ Access to Elekt
or Archive
✔ Access to over
1,000 Gerber fil
es
✔ Elektor Annual
DVD
✔ 10% Discount
in Elektor Store
✔ Exclusive Offer
s

GREEN
MEMBERSHIP
✔ 6x ElektorLabs
Magazine (PDF)
✔ 3x Elektor Indu
stry Magazine
(PDF)

Also available: ✔ Access to Elekt


✔ Access to over
or Archive
1,000 Gerber fil
The all-paperless GREEN Membership! ✔ 10% Discount
in Elektor Store
es

✔ Exclusive Offer
www.elektor.com/member
s

www.elektormagazine.com July & August 2019 41


Differential Probe
Power Supply
An ultra-simple power solution using USB
By Dr. Martin Oppermann working at the AD8479’s maximum measurement frequency
of 130 kHz or replaced by 0-Ω resistors or wire straps.
In our July & August 2016 issue [1], Elektor author Alfred Rosen- To connect Rosenkränzer-type probes, I used 3.5-mm stereo
kränzer presented a wonderfully simple differential probe for jack sockets. These connectors are nice and compact, although
oscilloscopes, based around the AD8479 precision differential they do have the disadvantage that their contacts are short-cir-
amplifier. I built one of them immediately and found it particu- cuited momentarily when the jack plugs are inserted. In order
larly suitable for measurements in the audio range, for example. to prevent damage, 100-Ω resistors are provided in each out-
But one small detail was not covered in this article: the power put circuit. Since the total current consumption of a probe is in
supply used for the probe (or for several of them). Practically the range of a few milliamperes (the AD8479 datasheet indi-
all modern oscilloscopes have a USB port on the front panel for cates about 850 µA; the only additional current drawn is by
data output. Since the power consumption of a probe is very low, the operating voltage indicator LEDs D5 and D6), the voltage
it makes sense to use this socket to power the probe. Figure 1 drop arising across these resistors is not a problem.
shows the schematic of the circuit I decided upon. The circuit was built on a small piece of double-sided board,
A standard USB cable is used to connect the probe power sup- mainly with SMDs, with the underside used only as a ground
ply to the USB outlet on the oscilloscope; the type is unim- plane. The smallest SMD package used is 1206, which is still
portant, as even a charging cable is adequate. C1 and C2 filter perfectly easy to solder by hand. Figure 2 shows the layout
the DC voltage from the USB port and LED1 indicates that the that I created in Autodesk Eagle, which can be downloaded
power is on. The heart of the circuit is the DC-DC converter from the project page [3].
IH0512S from XP Power [2]. It generates symmetrical ±12 V The PCB fits inside a small, translucent blue plastic enclosure
from +5 V with a maximum output current of ±84 mA, and it from Hammond Manufacturing (type 1551RTBU).
is galvanically isolated (with an electrical barrier between the Lastly a tip. In my own setup I used 78L09 and 79L09 (i.e.
input and output to improve safety)! The isolation voltage is ±9 V) voltage regulators for IC2 and IC3 of the probes, to
1,000 V, meaning there should be no ground problems when increase their measuring range to ±8.7 V.
making measurements. The output voltage is filtered using (180177-02)
various capacitors and ferrites, which can be omitted when

L1 R2
100
JP2
C3 C5 C7
+12V
100n 47 100n
16V
GND
LED1
C8
–12V
JP1 1
IN+
6
100n
OUT+ R3
+5V C1 C2 DC1 100
5
COM R4
GND 47 100n IH0512S 100
16V R1 2 4 JP3
IN– OUT– C9
1k

+12V
100n

GND
C4 C6 C10
LED1 = HSMR-C150
–12V
L1,L2 = Ferrit 1.000 @ 100MHz 100n 47 100n
R5
L2 16V
100
180177-010

Figure 1. Schematic of the power supply circuit, equipped for two probes. Figure 2. PCB layout and component placement.

Web Links
[1] Rosenkränzer, Alfred: A Simple Current Sensor Probe, Elektor July/August 2016: www.elektormagazine.com/150182
[2] 2W DC-DC Converter IH0512S: www.xppower.com/Portals/0/pdfs/SF_IH.pdf
[3] Project page: www.elektormagazine.com/180177-02

42 July & August 2019 www.elektormagazine.com


Display Serial Data
on a Web Page
using PHP or Python scripts

By Clemens Valens (Elektor Labs)

Occasionally it may be useful to visualize a continuous stream of data arriving through a serial connection as
a web page in a browser. But how do you go about? May we suggest a bit of scripting?

Basically, the problem boils down to periodically creating a it every ten seconds (the timeout can, of course, be another
webpage containing the latest serial data. A web browser then value). If we rewrite the page every ten seconds and put fresh
can display the page, be it on the same computer or over a serial data into it, then the browser will show it too.
network. Therefore, what is needed is a small program that
continuously converts the serial data into for instance HTML or Split the task in two
PHP files. Aha! Isn’t PHP a programming language for Inter- It is also possible to put the refresh tag in a PHP file instead of
net related applications? Yes, it is. So, can we use PHP to get an HTML file and the browser will do the same thing. The PHP
the job done? Yes, we can. But there are other ways too, as file then could also contain a script to read the data from the
we will see. serial port. This is the point where things become complicated
because PHP doesn’t natively support serial ports. And even
Use automatic page refresh if it did, it would mean that every time the browser requests
It all starts by remembering that HTML allows the use of a meta the (latest version of the) page, the script would have to open
tag that instructs the browser to reload a page periodically: the serial port, get some data and close the port again. Data
  received outside this window is lost. Furthermore, some Ardu-
<meta http-equiv="refresh" content="10"> ino-like systems may reset when the serial port is opened,
  making the setup useless. A solution to this is to split the pro-
This tag tells the browser to reload the page containing the cess in two subprocesses:
tag every ten seconds. (In case your browser does not sup-
port this tag, it can be replaced by a piece of JavaScript. See • Process 1: A script to continuously read the serial port and
download at [1]) If we create a web page that includes this update a data file that is imported by the PHP webpage
tag and point the browser to it, the latter will keep reloading (Listing 1);

www.elektormagazine.com July & August 2019 43


Listing 1: A PHP script that reads data from the serial port and writes it to a file named “data.txt”.
<?php

// Linux $comPort = “/dev/ttyACM0”;


$comPort = “COM15”;

include “php_serial.class2.php”;
$serial = new phpSerial;
$serial->deviceSet($comPort);

// On Windows (10 only?) all mode settings must be done in one go.
$cmd = “mode “ . $comPort . “ baud=115200 parity=n data=8 stop=1 to=off xon=off”;
$serial->_exec($cmd);
$serial->deviceOpen();

echo “Waiting for data...\n”;


sleep(2); // Wait for Arduino to finish booting.
$serial->serialflush();

while(1)
{
$read = $serial->readPort();

if (strlen($read)!=0)
{
$fp = fopen(“data.txt”,”w”);
if ($fp!=false)
{
fwrite($fp,trim($read));
fclose($fp);
}
}
}

?>

• Process 2: A browser that periodically reloads the PHP


webpage so that it can refresh the data (Listing 2, Figure 1: The dynamic PHP file generated by the PHP script is served by
Figure 1). a WAMP web server to our browser (see its address bar). It presents the
comma-separated values read from the serial port data in a basic table.
Values below 500 are printed in red, the others are green. The title of the
Oops, web server needed…
Command Prompt window shows the command to execute the script.
Doing this solves the serial port opening and closing problem
and the data loss resulting from it, but it requires a script to
run in the background. If this is a PHP script, then the com-
puter must be able to execute PHP scripts. Also, you need a group. To get serial communications to work with PHP, we
web server to feed the PHP webpage to a browser. If not, the first had to open and immediately close the port with a serial
browser will simply show the PHP code making up the page terminal program (Tera Term for instance); impossible to get
instead of the page itself. The traditional way of getting this it going otherwise. We therefore ditched the PHP method and
done is by installing a so-called “AMP” or “WAMP” package. went for Python instead.
AMP stands for Apache-MySQL-PHP, the ‘W’ is for Windows,
and together they form an all-singing, all-dancing web server. … use Python instead
Python 3 with pySerial [3] turned out to work perfectly fine on
Don’t use PHP… our Windows 10 test computer so we wrote a script to read data
We have tried this method and managed to get it to work, but from the serial port and write the webpage containing the data.
not without problems. Besides difficulties in setting up the Now that there is no longer a need for PHP, the Python script
web server, the main problem we encountered was getting might as well produce a plain HTML file (Listing 3, Figure 2).
PHP to reliably open a serial port to receive the data. Search- All the data formatting done by the PHP web page can be done
ing the Internet, there seems to be only one PHP library for directly in Python. Everything is now in one place. The web
serial communications, PHP Serial. All others appear to have page may still be served up by a web server (pun intended),
been derived from it. As the author mentions on the GitHub but a browser can also display and refresh the page without
page [2] “Windows: it seems to be working for some people, one. Therefore, there is no longer a need for a (W)AMP pack-
not working for some others.” We clearly were in the second age either, making everything much simpler.

44 July & August 2019 www.elektormagazine.com


Listing 2: This PHP webpage formats the contents of a file named “data.txt” as a table.

<?php

$page_title = “Arduino on PHP”;

// Start of HTML page.


echo “<!DOCTYPE HTML PUBLIC ‘-//W3C//DTD HTML 4.01//EN’ ‘http://www.w3.org/TR/html4/strict.dtd’>”;
echo “<html>”; // Page begin.
echo “<head><title>”,$page_title,”</title>”; // Head begin.
echo “<meta http-equiv=’refresh’ content=’1’>”;
echo “<meta http-equiv=’Content-Type’ content=’text/html; charset=UTF-8’>”;
echo “<link rel=’shortcut icon’ href=’favicon.ico’ />”;
echo “<link rel=’icon’ type=’image/x-icon’ href=’favicon.ico’ />”;
echo “<link rel=’icon’ type=’image/png’ href=’favicon.png’ />”;
echo “</head>”; // Head end.
echo “<body><center>”; // Body begin.

echo “<p>”,$page_title,”</p>”; // Page title.

// Create a table from data file.


$handle = fopen(“data.txt”,”r”);
if ($handle!=NULL)
{
// Read one line from the file, then close it.
$data = fgets($handle);
fclose($handle);

// Synchronise to the data.


if ($data[0]==’$’)
{
// Remove whitespace.
str_replace(‘ ‘,’’,$data);
// Split data in fields separated by ‘,’.
// Expected format: “$,id1,value1,id2,value2,CRLF”
list($startchar,$id1,$value1,$id2,$value2,$newline) = explode(“,”,$data);
// Create array from list.
$numbers = array($id1=>$value1,$id2=>$value2);
// Sort array in ascending key order.
ksort($numbers);

// Table begin.
echo “<table border=’1’ border-spacing=’5’ style=’text-align:center;’>”;
echo “<tr><th>ID</th><th>Value</th></tr>”;
foreach ($numbers as $x => $x_value)
{
echo “<tr>”; // Table row begin.
echo “<td>”, $x, “</td>”; // Table column 1.
echo “<td>”; // Table column 2 begin.
if ($x_value>=500) echo “<font color=’green’>”;
else echo “<font color=’red’>”;
echo $x_value;
echo “</font></td>”; // Table column 2 end.
echo “</tr>”; // Table row end.
}
// Table end.
echo “</table>”;
}
}
echo “</body>”; // Body end.
echo “</html>”; // Page end.
?>

www.elektormagazine.com July & August 2019 45


Figure 2: This time a Python script produces a dynamic HTML file (as can be seen from the browser’s address bar).

Sounding off
In this article we presented a method of displaying serial data
in a web browser. The method is neither new, exclusive, or
"the best". If you know of another way — simpler, more ele-
gant, whatever — please share it with us [1]. And, of course,
you don’t need Python to write the script, feel free to use any
programming language capable of doing serial communications
and writing files. The advantage of using Python with pySerial
is that it will run on Windows, macOS, and Linux machines
(and more).
The code developed for this article in the shape of PHP and
Python scripts, and an Arduino sketch can be downloaded
from [1].
(170111-01)

Web Links
[1] Downloads for this article:
www.elektormagazine.com/170111-01
[2] PHP Serial: https://github.com/Xowap/PHP-Serial
[3] pySerial: https://pypi.org/project/pyserial/

Figure 3: This Arduino sketch generates a serial data stream that can be
used for script development, debugging, and testing.

46 July & August 2019 www.elektormagazine.com


Listing 3: A Python script that reads data from the serial port and generates an HTML file for it.
import serial
import time

file_name = “serial.html” # Once created, open this file in a browser.

# Adapt serial port nr. & baud rate to your system.


serial_port = ‘COM15’
baudrate = 115200

page_title = “Arduino on Python”;

def write_page(data_list):
    fo = open(file_name,”w+”)
    # Start of HTML page.
    fo.write(“<!DOCTYPE HTML PUBLIC ‘-//W3C//DTD HTML 4.01//EN’ ‘http://www.w3.org/TR/html4/strict.dtd’>”)
    fo.write(“<html><head><title>”+page_title+”</title>”) # Page & Head begin.
    fo.write(“<meta http-equiv=’refresh’ content=’1’>”)
    fo.write(“<meta http-equiv=’Content-Type’ content=’text/html; charset=UTF-8’>”)
    fo.write(“<link rel=’shortcut icon’ href=’favicon.ico’ />”)
    fo.write(“<link rel=’icon’ type=’image/x-icon’ href=’favicon.ico’ />”)
    fo.write(“<link rel=’icon’ type=’image/png’ href=’favicon.png’ />”)
    fo.write(“</head><body><center><p>”+page_title+”</p>”) # Head end, body begin.

    # Table begin.
    fo.write(“<table border=’1’ border-spacing=’5’ style=’text-align:center;’>”)
    fo.write(“<tr><th>ID</th><th>Value</th></tr>”)
    for i in range(0,len(data_list),2):
        fo.write(“<tr>”) # Table row begin.
        fo.write(“<td>”+data_list[i]+”</td>”) # Table column 1.
        fo.write(“<td>”) # Table column 2 begin.
        fo.write(“<font color=’”)
        # Values >= 500 will be printed in green, smaller values will be red.
        if (int(data_list[i+1])>=500): fo.write(“green”)
        else: fo.write(“red”)
        fo.write(“’>”)
        fo.write(data_list[i+1])
        fo.write(“</font></td>”) # Table column 2 end.
        fo.write(“</tr>”) # Table row end.
    fo.write(“</table>”) # Table end.
    fo.write(“</body>”) # Body end.
    fo.write(“</html>”) # Page end.
    # Done, close file.
    fo.close()

s = serial.Serial(serial_port,baudrate) # Open serial port.


s.dtr = 0 # Reset Arduino.
s.dtr = 1
print(“Waiting for data...”);
time.sleep(2) # Wait for Arduino to finish booting.
s.reset_input_buffer() # Delete any stale data.

while 1:
    data_str = s.readline().decode() # Read data & convert bytes to string type.
    # Clean up input data.
    # Expected format: “$,id1,value1,id2,value2,...,CRLF”
    data_str = data_str.replace(‘ ‘,’’) # Remove whitespace.
    data_str = data_str.replace(‘\r’,’’) # Remove return.
    data_str = data_str.replace(‘\n’,’’) # Remove new line.
    data_str += ‘123,65,1,999,cpv,236’ # Add some more data
    print(data_str)
    # Split data in fields separated by ‘,’.
    data_list = data_str.split(“,”)
    del data_list[0] # Remove ‘$’
    # Write HTML page.
    write_page(data_list)

www.elektormagazine.com July & August 2019 47


HOMELAB PROJECT

Bright Flashing LED


traditional analogue...
R1 R4

9k09

3k3
By Bram Melse, MSc. (The Netherlands) 1

T2
2
A flashing LED? What is so special about that, you
may well ask yourself. A microcontroller plus a BC177 R3
+

5k6
handful of discrete parts, and Bob’s your uncle – C1
15 VDC T1

isn’t it? In harmony with the emphasis on analogue 100u

electronics in this edition we present here a variant


3
BC109C

R2 R5
that is built entirely from discrete parts and hopefully
LED

47R
330R
triggers your own experimentation! D1

The author has kept himself busy professionally with the design Figure 1: The schematic counts only a few parts. The transistors are not
of (mainly) analogue chips. But to prove that you don’t always critical; just about any TUP and TUN should suffice.
have to use an IC, and also because it is sometimes just fun to
figure out an analogue circuit, he presents here a flashing LED
that needs no more than a couple of transistors and a handful
of small parts. The result is drawn in Figure 1. Audio variant
The operation of the circuit is best described as follows. For If you have an appetite for that, you can also build an audio
convenience we start with the situation where the voltage at variant of this circuit. The circuit remains practically the same;
node 1 is relatively low. A current flows towards node 3 via R3 only the component values need to be changed as follows:
and R4 (and therefore also R2), but the current is not large • Resistors: R1 = 3k9; R2 = 180 Ω; R3 = 2k7; R4 = 1k8;
enough to turn T1 on. R5 = 15 Ω.
Capacitor C1 is continually being charged through resistor R1; • Capacitor: C1 = 0.2 µF.
once R1 (via T2) also starts to supply current towards node 3, • Transistors: T1 = BC109C; T2 = BC240B (not critical, any
the sum of the currents becomes large enough for T1 to turn TUP and TUN will do).
on. The voltage at node 2 will be pulled low and the circuit • The loudspeaker (8 Ω) is connected between C1 and
locks itself in this state (functions as a latch). ground; the LED is omitted.
The current towards node 3, via resistor R3, now stops, but  
instead capacitor C1 is discharged (via T2) and the LED lights This variant generates a (somewhat objectionable) sound with
up brightly. As C1 discharges, the current through T2 towards a frequency of about 1 kHz. However that would be perfectly
node 3 diminishes until it is no more than what is supplied via suitable for alarm applications.
R1, and that is not enough to keep T1 turned on. Node 2 will The construction of the circuit is not very critical; a small piece
now be pulled high by R4, which turns T2 off. At this instant of prototyping board is more than sufficient.
the entire cycle begins again. (180542-02)
Resistor R5 has an important function as a bypass: without this
resistor, the LED would cause a threshold voltage that is too
high for T1 to turn on, with the consequence that the latching
action doesn’t happen. The bypass current amounts to about
10% of the LED current.

Note that the LED flashes very brightly (with the component @ www.elektor.com
values indicated, at a rate of about 0.8 Hz); a simulation (in
ªBook, Electronic Circuits for All
LTspice XVII) indicated a value of about 600 mA. Of course www.elektor.com/electronic-circuits-for-all
it is not ideal when the capacitor is discharged only through
ªBook, The Art of Electronics, part 1 (analoue electronics)
the transistors and the LED; you can experiment here with a www.elektor.com/the-art-of-electronics-3rd-edition
current-limiting resistor (which, by the way, will also increase
the duration of the flash).

48 July & August 2019 www.elektormagazine.com


Heading Towards a

Tsunami of Light
Researchers at Chalmers University of Technology and the
University of Gothenburg, Sweden, have proposed a way to
create a completely new source of radiation. Ultra-intense
light pulses consist of the motion of a single wave and can be
described as a tsunami of light. The strong wave can be used
to study interactions between matter and light in a unique
way. Their research is now published in the scientific journal
Physical Review Letters.
“This source of radiation lets us look at reality through a new tific landscape of light sources.” says Tünde Fülöp.
angle — it is like twisting a mirror and discovering something Read the scientific paper Electron beam driven generation of
completely different,” says Illia Thiele, a theoretical physicist frequency-tunable isolated relativistic sub-cycle pulses in Phy-
at Chalmers University of Technology. sical Review Letters [1].
Together with Dr Evangelos Siminos at the University of Gothen-
burg, and Tünde Fülöp, Professor of Physics at Chalmers, Illia A more detailed description of the new method
Thiele now presents a theoretical method for creating the fastest for creating ultra-intense light pulses
possible single wave motion. This kind of radiation has never The researchers propose a method for the generation of ult-
yet been observed in the universe or even the lab. ra-intense light pulses containing less than a single oscillation
The radiation source is interesting for understanding the pro- of the electromagnetic field. These so-called sub-cycle pulses
perties of different materials. Since it offers an ultra-fast swit- can be used to probe and control matter in unique ways. Con-
ching of light matter interactions, it can be useful in material ventional methods can only produce sub-cycle pulses of limited
science, or sensor related research, for example. Moreover, field strength: above a certain threshold the amplifying medium
it can be used as a driver for other types of radiation, and to would be ionized by the intense fields. The researchers propose
push the limits of how short a light pulse could be. to use an electron beam in a plasma, which is not subject to a
“An ultra-intense pulse is like a great tsunami of light. The wave damage threshold, as an amplifying medium for a seed electro-
can pull an electron out of an atom, accelerating it to almost magnetic pulse. To ensure that energy is transferred from the
the speed of light, creating exotic quantum states. This is the electron beam to the pulse in such a way that a sub-cycle pulse
fastest and strongest switch possible, and it paves the way is produced, the beam needs to be introduced at an appropriate
for advances in fundamental research,” says Dr Illia Thiele. phase of the oscillation of the electromagnetic field. This can
The new pulses can be used to probe and control matter in unique be achieved by using a mirror to reflect the seed pulse while
ways. While other light pulses, with multiple wave periods, impose the electron beam is being injected. This scenario leads to sig-
changes in the material properties gradually, pulses with a single nificant amplification of the seed pulse and the formation of an
strong wave period cause sudden and unexpected reactions.  intense, isolated, sub-cycle pulse. Readily available terahertz
Researchers worldwide have tried to create this source of radi- seed pulses and electron bunches from laser-plasma accelera-
ation, since it is of high interest for the scientific communities tors could generate mid-infrared sub-cycle pulses with millijou-
within physics and material science.  le-level energies, which are highly desirable as probes of matter
“Now, we hope to be able to bring our theoretical setup to the but not possible to produce with conventional sources.
lab. Our method could help close the existing gaps in the scien- 190252-01

Illia Thiele, postdoctoral Tünde Fülöp, Professor of Physics


researcher, Department of at Chalmers University of
Physics, Chalmers University of Technology.
Technology. Photo: Johan Bodell/Chalmers
Photo: Mia Halleröd Palmgren/ University of Technology.
Chalmers University of
Technology.

Weblink
[1] Electron Beam Driven Generation of Frequency-Tunable Isolated Relativistic Subcycle Pulses :
https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.122.104803

www.elektormagazine.com July & August 2019 49


Qt for the Raspberry Pi
A step by step guide
to set up the GUI framework

By Mathias Claußen (Elektor Labs)

Elektor software developer and lab


worker Mathias Claußen was tasked
to develop a control for the FM radio
on the Raspberry Pi [1] using a touch
screen. The platform-independent
(GUI) framework Qt has almost
become the go-to industry standard
to build such interfaces, so the
choice was clear. For any developers
out there facing similar challenges,
Mathias has put together a manual
that shows how set up a cross-
compiler environment on a PC to allow
you to compile Qt applications for
the Raspberry Pi from a PC — he also
includes a simple demo of course.

The Qt framework logo (www.qt.io).

In software development, the client usually supplies a spec- version, you can even build applications that don’t use open
ification sheet — listing what functions the software should source code — it is advisable to study the terms of the license
perform in the finished product. In this case, the instructions agreement for Qt more closely. The commercial Qt license
from the editorial board here at Elektor was pretty basic — includes additional tools useful for embedded applications.
“Make it so…”
Fair enough but before any work can begin it’s always helpful Qt
to get a basic specification of what expected from the software. Qt [2] is a cross-platform framework that can be used to create
It turned out that what was needed was a Linux application applications in C ++/QML that ideally run on multiple platforms
running on a Raspberry Pi to provide control for some FM radio based on common code. This includes the usual suspects such
hardware and also to display RDS information if it is available as Windows, Linux, Android, iOS, QNX and some embedded
in the received signal. It goes without saying that it needs to Linux variants. Using this framework saves work in a number
be finished by… yesterday. of places since you don’t have to bother about the peculiar-
At this point, I chose to implement the project using the Qt ities of different operating systems. In addition to the many
framework [2]. Qt is available under a dual-licensing model, as other libraries available in the framework, those designed for
the source code will be open source, I did not need to decide GUI use are especially helpful for speedy code development.
between GPL and commercial versions of Qt. Using the GPL What is generally true of the framework is also applicable to

50 July & August 2019 www.elektormagazine.com


the Raspberry Pi; my own experience based on the use of Qt Instructions (to code Nirvana)
for some previous projects (from a console application up to a Online tutorials and You Tube ‘how-to’s are where many people
small GUI tool) has demonstrated its usefulness. The elegant start when considering installing a new programming envi-
thing about Qt is that the experience gained in developing ronment. This path can often be frustrating if you get stuck
various projects say for the RPi is transferrable to any of the somewhere, because a step has been glossed over or maybe
other supported platforms. you’ve missed one setting or suddenly realise that the tutorial
was written for an earlier version of RPi’s operating system
A fresher Framework and gives problems with the latest version. To make things
Whole books could be devoted to describing the Qt framework. a whole lot easier I’ve written a manual [3] describing the
This applies to many aspects of the system such as opera- steps necessary to set up Qt for the Raspberry Pi running in a
tion of the tools, development of applications and the design cross-compiler development environment on a PC.
of graphical user interfaces. You could begin by installing a Since the latter is easier running under Linux, the Ubuntu PC
ready-made version of Qt directly on the RPi environment. Operating system is used. Don’t worry: you won’t need to buy
This may seem like the obvious path to take but this version an extra PC just for RPi development (the problem here is often
of Qt is now over two years old. In the world of software that not a question of the additional expense but more about desk
time span roughly equates to two millennia. The alternative space availability). All you need is to run a virtual machine
is the classic CIY (Compile It Yourself). With the benefits of (VirtualBox) on your PC which will use up about 60 GB of space
all the latest security updates and patches it is always prefer- on your hard drive.
able, where possible, to In addition to setting up the environment, a small demo pro-
use the most up to date gram is also described as an example to test the setup. You can
version available. also load the FM radio project into Qt and see how the different
The Qt framework also parts work together. This guide should be a starting point and
includes Qt creator. This show how to work with all the various tools — without need-
useful tool just gets bet- ing to worry about and the setup of important details.
ter with each new ver- 180477-02

The Raspberry Pi Foundation logo


(www.raspberrypi.org).

sion. Earlier versions have proved


to be a little buggy. Qt Creator
also runs on the RPi, but RAM and
access to the display is limited and the version is now quite
old. You can build a Qt environment yourself using the latest
PC version. This will allow you to develop RPi applications that
do not use specialities of the RPi hardware to directly compile @ www.elektor.com
on a PC and test it there. With just one click and the right set- ªFM Radio HAT PCB for the RPi (160520-1 V2.0)
tings, you can then copy the software that you developed and www.elektor.com/rpi-receiver-160520-1
tested on a PC to the RPi and run it there. This works well and ªRaspberry Pi 3 B+
allows remote code debugging, breakpoint setting and display www.elektor.com/rpi-3b-plus
of program variables.

Web Links
[1] FM Radio with RDS, Elektor 1 / 2019: www.elektormagazine.com/magazine/elektor-70/42360
[2] Qt framework: www.qt.io
[3] Qt manual (PDF, 41 pages): https://github.com/ElektorLabs/160520-QT-compile-and-install-manual

www.elektormagazine.com July & August 2019 51


Elektor
Start-up Challenge
Paris 2019
An international launch pad
for start-ups
By Denis Meyer Who can enter? Before, during and after the show you
and Mariline Thiebaut-Brodier Anyone who has developed a product, a will achieve a high visibility:
software or a service in the electronics
field. The Elektor Start-up Challenge • You and your start-up will have all
gives you the opportunity to come and the support of the Forum de l’Élec-
Don’t wait for present your project to professionals in tronique: show catalogue, list of
Elon Musk to invite the industry. exhibitors, official site...
you aboard SpaceX! Previous contests organised by Elektor, • You and your start-up will be pre-
notably those at electronica in Munich, sented to all Elektor magazine’s
the largest electronic show in the world, readers via all our media (print,
After Germany and Holland, have rewarded some remarkable projects Internet, social media, YouTube
this year Elektor makes a in various areas of electronics. channel...) in France, French-speak-
stop in Paris with a new ing countries and all over the world
contest for young companies Why get aboard this rocket? • You and your start-up will be intro-
who are active in the field If you enter the Elektor Start-up Chal- duced to the members of the
of embedded electronics. lenge in Paris in 2019 and your applica- Cap’tronic program
This will take place at the tion is successful, you will be welcomed  
new Forum de l’Électronique with the other entrants to the Elektor For you and your start-up, the ultimate
(Electronics Forum) exhibition Start-up Challenge, a large central goal is to win the jackpot. The winner
in September 2019. stand at the Forum de l’Électronique of the Elektor Start-up Challenge in
This contest, called the Elektor (Paris Expo - Porte de Versailles, from Paris will receive an entry ticket to the
Start-up Challenge, aims to the 24th to the 26th September 2019). next electronica show in Munich: you
stimulate the advancement of will be automatically selected to enter in
young entrepreneurs after their You will be able to: the international Fast Forward Award
promising debuts. • Present your project there in your contest, in the course of which you will
The winners will be chosen on own space present your project on the stand and
the industrial viability of their • Compete alongside other finalists benefit from the huge publicity given to
projects, their usefulness and of • Attract the attention of potential this event.
course their originality. partners
the Elektor Start-up Challenge
is the result of our close
cooperation with Cap’tronic, The Elektor Start-up Challenge is organised in collaboration with:
the support program for SMEs
in hardware electronic systems
and embedded software, and
GL Events Exhibitions, the
organiser of the exhibition.

52 July & August 2019 www.elektormagazine.com


Making your application
• To participate in the Elektor Start-up Challenge at the
Forum de l’Électronique, entrants can contact us directly at
email [email protected]. They can also create a (free) account at our
website: www.elektormagazine.fr. WE
• You should provide the most complete documentation that you can,
so that the jury can clearly appreciate the objective of your start-up,
WANT
the technology used, get an idea of the product, and, if applicable, YOU!
the services provided. All entries will be evaluated by the jury of the
Elektor Start-up Challenge. To be considered a start-up, your
business must have been created at most five years ago.
• If your start-up is selected to enter the
Elektor Start-up Challenge, the representative of the business
accepts to be personally present in Paris during the
Forum de l’Électronique 2019.
• All the general conditions of entry to the
Elektor Start-up Challenge in Paris are available online.

This is where
your start-up
meets the future
Where? Paris Expo Porte de Versailles

When? From the 24th tot the 26th September 2019

How? Enter by Wednesday 31st July at the latest

Go to:
Participants and winners of the Fast Forward electronica 2018 contest. www.elektormagazine.fr/escparis2019

The winner will automatically participate in the electronica contest in The Jury at work, headed by Clemens Valens from Elektor Labs.
Munich next year.

Note:
The final date of entry is fixed at
Wednesday 31st July 2019.
In case of a high number of applications, it is possible that
the limited number of places will cause us to bring forward
the closing date for entries. So don’t wait to go to
www.elektormagazine.fr/escparis2019 to enter.

The general conditions of entry to the


Elektor Start-up Challenge in Paris are available online.

The initial meeting between Elektor and its partners.

190232-02

www.elektormagazine.com July & August 2019 53


HOMELAB PROJECT

New CPLD Board


with MAX 10
By Alfred Rosenkränzer (Germany)
4 VCC
IC1 = LT1117CST3.3
+5V D1
IC1
3 2
+VCC
R1 R2
10MQ040

10k
1
Upgrading the CPLD board: With XO1

270
4
VCC OE 1
C15 C16 C17 C18 C19
an MAX10M08 CPLD as the core C1 C2 C3 C4
3
22 22 22 22 22
10u 100n 22 100n FO 10V 10V 10V 10V 10V
component, the board not only 25V 10V LED2
R4 R3

GND

100
50
provides more logic elements XO91SMD 2
CLK disable

than the previous version but


26
also supports typical FPGA 27
CLK0N
CLK0P
PLL_L_CLKOUTN
32
R5

functions such as PLLs, ADCs and

10k
28
CLK1N
29 33
implementable microcontrollers. CLK1P PLL_L_CLKOUTP

+VCC
30 10M08SAE144 31
+VCC VREFB2N0 VCCIO2
BANK 2
R10
R11
R7
R8
R9

+VCC JTAG
1k
10k
10k
10k
10k
2

15
JTAGEN 21
DIFFIO_RX_L14N
4

C22 16
TMS 22
DIFFIO_RX_L14P
6

18
TCK 24
100n DIFFIO_RX_L16N
8

19
TDI 25 RX_L16P
DIFFIO_RX_L16P
10

20
TDO
In the May & June 2018 issue of Elektor
RX_L1N 6 11 RX_L5N
magazine the author presented a board RX_L1P 7
DIFFIO_RX_L1N/ADC1IN1 DIFFIO_RX_L5N/ADC1IN5
DIFFIO_RX_L1P/ADC1IN2 DIFFIO_RX_L5P/ADC1IN6
12 RX_L5P

with a CPLD from the Altera (now Intel) RX_L3N 8


DIFFIO_RX_L3N/ADC1IN3 DIFFIO_RX_L7N/ADC1IN7
13
RX_L3P 10 14
DIFFIO_RX_L3P/ADC1IN4 DIFFIO_RX_L7P/ADC1IN8
MAX II family [1]. The EPM570 used in
23 +VCC
that project is a CPLD with 570 logic ele- +VCC
17
VREFB1N0
10M08SAE144 VCCIO1B
9
BANK 1 VCCIO1A
ments (LEs) in a TQFP100 package. The
73
smaller but pin-compatible EPM240 can VCC_ONE@1
72
VCC_ONE@2
also be fitted on the CPLD board. Thanks +VCC
VCC_ONE@3
51 TX_RX_B1N 38
DIFFIO_TX_RX_B1N DIFFIO_TX_RX_B9N
50 TX_RX_B9N
37 TX_RX_B1P 39 52 TX_RX_B9P
to the relatively small device package, it 35
VCC_ONE@4
36
DIFFIO_TX_RX_B1P
IC2
DIFFIO_TX_RX_B9P
VCCA@1 VCC_ONE@5 54 TX_RX_B10N
was possible to design a prototype board 34
VCCA@2 VCC_ONE@6
144 TX_RX_B3N 41
DIFFIO_TX_RX_B3N
DIFFIO_TX_RX_B10N
107 115 TX_RX_B3P 43 55 TX_RX_B12N
VCCA@3 VCC_ONE@7 DIFFIO_TX_RX_B3P DIFFIO_TX_RX_B12N
that allows the IC to be used in more or 143
VCCA@4 VCC_ONE@8
109
DIFFIO_TX_RX_B12P
56 TX_RX_B12P

less the same way as a DIL component. 71


VCCA@5 VCC_ONE@9
108 TX_RX_B5N 44
DIFFIO_TX_RX_B5N
DIFFIO_TX_RX_B14N
57 TX_RX_B14N
2 1 TX_RX_B5P 45
VCCA@6 VCC_ONE@10 DIFFIO_TX_RX_B5P
Although a considerable amount of logic +VCC DIFFIO_TX_RX_B14P
58 TX_RX_B14P

42 TX_RX_B7N 46 59 TX_RX_B16N
can be built with 570 LEs, you have to MC1525TT
2V5
GND@1
53 TX_RX_B7P 47
DIFFIO_TX_RX_B7N DIFFIO_TX_RX_B16N
60 TX_RX_B16P
GND@2 DIFFIO_TX_RX_B7P DIFFIO_TX_RX_B16P
switch to a different CPLD family if that 1 IC3 2 5
ADC_VREF GND@3
63
40 +VCC
68 48 10M08SAE144 VCCIO3_1
is not enough. As the MAX V family only 3
GND@4
83
VREFB3N0
BANK 3 VCCIO3_2
49
3 ANA_IN1 GND@5
offers a few extra features compared to C20 C21
R6
GND@6
95
104
10k

the MAX II family, the author decided to 100n 100n


GND@7
116
GND@8
go directly to Intel’s newest CPLD family: 4
REF GND GND@9
125 TX_RX_B25N 66
DIFFIO_TX_RX_B25N DIFFIO_TX_RX_B20P
62 TX_RX_B20P
133
GND@10
137 TX_RX_B27N 69 64 TX_RX_B23N
GND@11 DIFFIO_TX_RX_B27N DIFFIO_TX_RX_B23N
EP 142 TX_RX_B27P 70 65 TX_RX_B23P
PAD GND@12 DIFFIO_TX_RX_B27P DIFFIO_TX_RX_B23P
+VCC
10M08SAE144 61 10M08SAE144 67
VREFB4N0 VCCIO4
POWER BANK 4
Figure 1: For ease of understanding, the MAX-
10M08SAE144 is divided into many sections in 180673-018

the schematic diagram.

54 July & August 2019 www.elektormagazine.com


More logic with the
MAX 10 family

MAX 10. This family [2] consists of seven


+VCC +5V
CPLD product groups, each with several
versions. You can choose from 2 K to
+VCC R12 R13
50 K logic elements, single or dual power
0

0
JP1
supply with an integrated 3.3-V LDO vol-
1 2
C5 C6 C7 C8 C9 C10 C11 C12 C13 C14 RX_L5P
?
R14 3 4 tage regulator (only single power sup-
100n 100n 100n 100n 100n 100n 100n 100n 100n 100n
RX_L5N
?
R15 5 6
ply is possible with the selected device),
RX_L3P R16 7 8 R28 RX_L3N
? ?
9 10 RX_L1P several flash memory block sizes, ana-
RX_L1N R17 11 12 RX_T26N
RX_T26P
?
R18 13 14
log to digital converters (ADCs), tempe-
?
RX_T23N
?
R19 15 16 RX_T22N rature sensors, dual configuration flash
17 18 RX_T22P
RX_T20N R20 19 20
(two dynamically usable images on the
RX_R1P 75 85 RX_R10P ?
RX_R1N 77
DIFFIO_RX_R1P DIFFIO_RX_R10P
87 RX_R10N
RX_T19N 21 22 RX_T20P same device), and much more.
DIFFIO_RX_R1N DIFFIO_RX_R10N RX_T19P R21 23 24 BOOT_SEL
?
RX_R2P 74 25 26 RX_T18P
DIFFIO_RX_R2P 84 RX_R11P
RX_R2N 76
DIFFIO_RX_R2N
DIFFIO_RX_R11P
DIFFIO_RX_R11N
86 RX_R11N
RX_T10N
?
R22 27 28 R29
?
RX_T16P
From CPLD to FPGA
RX_T10P R23 29 30
?
RX_R7N 79
DIFFIO_RX_R7P RX_T6P
?
R24 31 32 RX_T4N In addition to pure CPLD functions, the
RX_R7N 81 78
DIFFIO_RX_R7N IO_78 RX_T1N
?
R25 33 34
MAX 10 family has fully operable FPGA
+VCC RX_R33N R26 35 36 RX_T1P
80 10M08SAE144 82 ?
VREFB5N0
BANK 5
VCCIO5 RX_R33P
?
R27 37 38 RX_R28N functions such as up to four internal
39 40 RX_R27N
PLLs for generation of higher clock fre-
+VCC +5V
RX_R14P 88
DIFFIO_RX_R14P/CLK2P R30 R31
quencies, implementable (NIOS) micro-
RX_R14N 89
DIFFIO_RX_R14N/CLK2N
DIFFIO_RX_R27P
99 RX_R27P controllers, digital signal processing
0

101 RX_R27N JP2


RX_R16P 90
DIFFIO_RX_R16P/CLK3P
DIFFIO_RX_R27N
1 2 (DSP) blocks, and soft DDR3 memory
RX_R16N 91
DIFFIO_RX_R16N/CLK3N
DIFFIO_RX_R28P
100 RX_R28P RX_L16P
?
R32 3 4 controllers.
102 RX_R28N TX_RX_B1N R33 5 6
DIFFIO_RX_R28N ?
RX_R18P 92
DIFFIO_RX_R18P TX_RX_B1P
?
R34 7 8 R40
?
TX_RX_B3N All these different versions are availa-
RX_R18N 93
DIFFIO_RX_R18N
DIFFIO_RX_R33P
105 RX_R33P 9 10 R41
?
TX_RX_B3P
ble in a variety of package types, ran-
106 RX_R33N TX_RX_B5P 11 12 R42 TX_RX_B5N
DIFFIO_RX_R33N ?
RX_R26P
RX_R26N
96
98
DIFFIO_RX_R26P/DPCLK3 TX_RX_B7N
?
R35 13 14 ging from small wafer packages to large
DIFFIO_RX_R26N/DPCLK2 TX_RX_B9N 15 16 R43 TX_RX_B7P
94 +VCC 17 18 R44
?
TX_RX_B9P
packages with hundreds of I/O pins. This
97 10M08SAE144 VCCIO6_1 ?
VREFB6N0
BANK 6 VCCIO6_2
103 TX_RX_B10N 19 20 is also the first selection criterion: the
TX_RX_B12N R36 21 22 R45 TX_RX_B12P
TX_RX_B14N
?
23 24 R46
?
TX_RX_B14P
only package suitable for soldering by
?
25 26 R47
?
TX_RX_B16N hobbyists (which means with a solde-
TX_RX_B20P R37 27 28 R48 TX_RX_B16P
RX_T1P 110
DIFFIO_RX_T1P DIFFIO_RX_T6P
114 RX_T6P
TX_RX_B23N
?
29 30
?
ring iron) is the EQFP package with 144
RX_T1N 111
IC2
DIFFIO_RX_T1N
DIFFIO_RX_T10P
118 RX_T10P
TX_RX_B25N
?
R38 31 32 R49
?
TX_RX_B23P
pins. Although the size of this package
TX_RX_B27N 33 34
RX_T4N 113
DIFFIO_RX_T4N DIFFIO_RX_T10N
119 RX_T10N
RX_R2P 35 36 R50
?
TX_RX_B27P (22 × 22 mm) makes the board some-
112
VREFB7N0
10M08SAE144 VCCIO7
117
+VCC RX_R2N 37 38 R51
?
RX_R1P
what larger than the previous version, it
39 40 R52 RX_R1N
BANK 7 ?
offers 101 usable I/O pins with all device
JP3 options. For more detailed information,
RX_T16P 120 RX_R7N 1 2 RX_R7P
RX_T16N 121
DIFFIO_RX_T16P
135 RX_T23N RX_R10P 3 4 RX_R11P
see the user guides for the MAX 10 family
DIFFIO_RX_T16N/DEV_CLRN DIFFIO_RX_T23N
DIFFIO_RX_T22N/CRC_ERROR
134 RX_T22N RX_R10N 5 6 RX_R11N [3].
RX_T18P 122 132 RX_T22P RX_R14N 7 8 RX_R14P
DIFFIO_RX_T18P/DEV_OE DIFFIO_RX_T22P
BOOT_SEL 126 9 10
BOOT_SEL 140 RX_T26P
DIFFIO_RX_T26P
DIFFIO_RX_T26N
141 RX_T26N +VCC
11 12
+VCC Peripherals
RX_T19N 124 13 14
DIFFIO_RX_T19P
RX_T19N 127
DIFFIO_RX_T19N DIFFIO_RX_T24P/NSTATUS
136
R53
3k3
15 16 Like its smaller predecessor, this board
DIFFIO_RX_T24N/CONF_DONE
138
3k3 +5V
17 18
+5V has several peripherals in addition to the
RX_T20P 130 RX_R16P 19 20 RX_R16N
DIFFIO_RX_T20P R54 R39
RX_T20N 131
DIFFIO_RX_T20N NCONFIG
129
1k
RX_R18P 21 22 RX_R18N new CPLD (see the schematic diagram
RX_R26P 23 24 RX_R26N
123 10M08SAE144 VCCIO8_1
139
RX_R27P 25 26 RX_R28P
in Figure 1): a voltage regulator with
VREFB8N0 128
BANK 8 VCCIO8_2 decoupling capacitors, a clock oscillator,
+VCC
and a JTAG connector for programming.
There is also an onboard voltage refe-

www.elektormagazine.com July & August 2019 55


Pin JP2 JP1 Rpi GPIO Pin Pin JP3 Pin

1 +3.3 V +5 V +3.3 V +5 V +3.3 V +5 V 2 1 P81 P79 2


3 P25 +5 V P12 +5 V GPIO 2 +5 V 4 3 P85 P84 4
5 P38 GND P11 GND GPIO 3 GND 6 5 P87 P86 6
7 P39 P41 P10 P8 GPIO 4 GPIO 14 8 7 P89 P88 8
9 GND P43 GND P7 GND GPIO 15 10 9 +3.3 V +3.3 V 10
11 P45 P44 P6 P141 GPIO 17 GPIO 18 12 11 +3.3 V +3.3 V 12
13 P46 GND P140 GND GPIO 27 GND 14 13 GND GND 14
15 P50 P47 P135 P134 GPIO 22 GPIO 23 16 15 GND GND 16
17 +3.3 V P52 +3.3 V P132 +3.3 V GPIO 24 18 17 +5 V +5 V 18
19 P54 GND P131 GND GPIO 10 GND 20 19 P90 P91 20
21 P55 P56 P127 P130 GPIO 9 GPIO 25 22 21 P92 P93 22
23 P57 P58 P124 P126 GPIO 11 GPIO 8 24 23 P96 P98 24
25 GND P59 GND P122 GND GPIO 7 26 25 P99 P100 26
27 P62 P60 P119 P120 GPIO 0 GPIO 1 28
29 P64 GND P118 GND GPIO 5 GND 30
31 P66 P65 P114 P113 GPIO 6 GPIO 12 32
33 P69 GND P111 GND GPIO 13 GND 34
35 P74 P70 P106 P110 GPIO 19 GPIO 16 36
37 P76 P75 P105 P102 GPIO 26 GPIO 20 38
39 GND P77 GND P101 GND GPIO 21 40

Figure 2: Pin assignments of the three connectors on the CPLD board and the Raspberry Pi GPIO connector.

rence for the A/D converter integrated can be plugged into a breadboard or for comparison. Adjacent pairs of pins,
in the CPLD (bank 1A). used with a stripboard like a large DIL each marked with the same background
The prototype is fitted with a type 10M08 IC, the key consideration is that both colour, form differential inputs or out-
device, which has 8 K logic elements of the long pin/socket headers have the puts. They can also be used in single-en-
(LEs), one PLL and one A/D conver- same pin assignments as the 2×20- ded mode, just like the pins without a
ter. However, the board is suitable for way GPIO connector of the Raspberry background colour.
all members of the MAX 10 family with Pi (type 2 or later), so that they can be
2 K to 50 K LEs, as long as they are plugged directly onto the Raspberry Pi. Combinations
housed in an EQFP-144 package. The This way the processing power and PC This creates a variety of options. As
board layout has four layers to ensure interfaces of the Raspberry Pi can be shown in Figure 3, the board can be fit-
reliable operation even at relatively high combined with the hardware capabili- ted directly on a Raspberry Pi (the moun-
clock frequencies. ties of an advanced CPLD. The pinouts ting holes also match). Connector JP1
As with the previous version, not all pos- of the three connectors (with the CPLD is mounted on the bottom of the board
sible I/Os are fed out to the connectors, pins) are shown in Figure 2, along with as a socket header and mates with the
and for good reason. Although the board the Raspberry Pi GPIO connector pinout GPIO connector of the Raspberry Pi. The

Figure 3: The CPLD board mounted on top of a Raspberry Pi 3 Model B+. The mounting holes also match.

56 July & August 2019 www.elektormagazine.com


Figure 4: The Raspberry Pi controls the CPLD, which in turn controls the circuitry on the application board.

other two connectors are freely acces-


sible, top-mounted pin headers.
Figure 4 shows how the Raspberry Pi
controls the CPLD through JP2 and the
CPLD in turn controls circuitry (such as
a power driver) on a stripboard through
connector JP1. The power supplies of the
two boards can be linked or kept sepa-
rate. Zero-ohm resistors (R12, R13, R30
and R31) are provided for this purpose.
Connection through a ribbon cable is
also possible (see Figure 5) if you want
to put the boards in different places.
Finally, you can also use the board with
the 10M08SAE144 entirely on its own,
without any Raspberry Pi support.
180673-02

Figure 5: Distributed layout with ribbon cables.

Get it while you can in the elektor store


A few blank or partially populated boards (only the CPLD
ªCPLD Breakout Board in DIL Format
fitted) are available from the author.
(project from May/June 2018)
www.elektor.de/cpld-bob
[email protected]

Web links
[1] CPLD Breakout Board in DIL Format, Elektor May & June 2018: www.elektormagazine.com/160425
[2] MAX 10 family overview: www.intel.com/content/www/us/en/products/programmable/fpga/max-10.html
[3] Resources for the MAX 10 family:
www.intel.com/content/www/us/en/programmable/products/fpga/max-series/max-10/support.html

www.elektormagazine.com July & August 2019 57


HOMELAB PROJECT

Waterflow
Monitor
with ESP32
with text/SMS alert
of leaks
By Denis Lafourcade (France)

There are two kinds of people: those who have


already had a big water leak, and those who
haven’t yet had one... Insurance companies
will cover this risk, but wouldn’t it be better to
anticipate and warn of a possible leak? The device
offered here consists of a board which combines
an ESP32 microcontroller for WiFi Connection and
an OLED screen for local information.

Prevention is better than cure! which include an alert if a water leak is tions to oversee my water consumption.
Everything that happens downstream of suspected. But the deployment of these By chance many water meters, mine in
your water meter is your responsibility. systems is slow, and most communities particular, are equipped with counter
In case of leaks, the extra consumption have not got them yet. But some water wheels. The units wheel has a magnet
is for your account, and it can cost you meters are equipped with a pulse trans- attached on the zero digit, allowing you
dearly: mitter which sends a pulse for each litre to detect each revolution, which generally
  used, and some meters can be retro- corresponds to a litre of use. There are
• a dripping tap: 4 l/h, that’s 35 m3 fitted with the transmitter. The system on the market pulse transmitters (Fig-
per year, over €100; presented here uses this possibility and ure 1) which clip onto the meter and
• a leaking toilet flush: 25 l/h, that’s allows you to keep a permanent monitor produce a signal over radio or wires for
220 m3 per year, nearly €1000; on your water consumption. each passing of the magnet past a Hall
• a leak in the buried pipes between Over a few months, three of my neigh- effect detector. These transmitters are
the meter and your house: sev- bours here in France discovered, after powered by a Lithium battery with a life
eral m3 per hour, several thousand a receipt of their water bill, that they had of around 15 years, so they don’t need
week! a leak between their meter and their an external power source.
  house. The leak was undetectable for
These figures will obviously depend on several weeks, entailing a huge over- Wired or wireless?
the country you live in and your cost of consumption and a bill of several thou- I first looked at the transmission of infor-
water. sand euros! mation between the transmitter and the
The water companies have started to Wishing to avoid such a disagreeable intelligent part of the system. The wire-
install remote meter reading systems, situation myself, I set out to find solu- less pulse transmitter seemed attractive,

58 July & August 2019 www.elektormagazine.com


IC1
WeMos Lolin

GPIO36 GPIO39
GPIO25 GPIO16
GPIO26 GPIO4
GPIO8 GPIO0
GPIO11 GPIO2
GPIO7 GPIO14
GPIO6 GPIO12
GPIO13
R1 GPIO15
3V3 GPIO3
GPIO1 Li-ion battery pack 3,7 V
2k2
C1
3V3
1 µF
GND
GND
Pulse generator
at water meter 5 V GND
Battery charger
V in

USB supply

Figure 1. Example of a pulse transmitter in situ. Figure 2. Circuit diagram.

but unfortunately the protocol used is • web server for remote viewing and WROOM-32 System-on-Chip (SoC) and
not published, and in spite of consider- control; a 128 × 64 pixels OLED screen (connec-
able research, I was not able to find any • Text (SMS) alerting system. tions in Figure 3). This board is avail-
useful information on the subject. If you able in several version on the Internet,
have any better knowledge, please let Electronic construction for a few dollars, and also in the Elektor
me know. As my water meter and my These specifications led to the archi- Store. The ESP32 has WiFi and sufficient
telephone line entry are in close prox- tecture illustrated in Figure 2. The memory capacity for practical applica-
imity, I was able to pull a 1-pair cable heart of the circuit is a Lolin module tions. As well as this, it is compatible with
between the transmitter and the inte- made by WeMos, consisting of an ESP- the Arduino IDE, which makes it partic-
rior of my house through the telephone
cable conduit. For other installations, if
the provider has left the telephone cable
in place after the installation of an optical
fibre, I used one pair of that cable and
avoided having to run a new one.

General principles
Before designing the system, it’s nec-
essary to set down the specifications:

• sensing and processing of the


metered impulses;
• display of the hourly, daily and total
consumption;
• algorithm for detection of suspected
leaks;
• power supply with backup;
• data storage in non-volatile
memory;
• network access via WiFi and time
synchronisation by NTP; Figure 3. Connections of the WeMos Lolin module.

www.elektormagazine.com July & August 2019 59


Figure 4. Power supply — battery charger module. Figure 5. Interface board (connected between
the GND and GPIO25 pins of the Lolin module).

ularly simple to use. Power is secured The pulses from the transmitter are of setup() and a main loop loop() . The
with a Li-Ion battery with a 5 V charger open-collector type, with a ground pulse IRAM_ATTR handleInterrupt() handles
from a micro-USB socket. This charger for every litre consumed. Acquiring these the interrupt triggered by the grounding
(Figure 4) is designed for Li-Ion batter- pulses is very simple: a pullup resistor of the data line connected to GPIO 25,
ies and maintains the charge level and between the data line and the 3.3 V pin and its only task is to increment the value
protects against excessive discharge and on the board, and a 1-µF capacitor to fil- of the counter for litres consumed. Soft-
overcharging. It is available from several ter out any interference on the line. The ware filtering takes care of any “bounce”
Internet sites (Search “3.7V Li-ion Bat- data line is connected to pin GPIO 25 of on the line.
tery Mini USB To USB A Power Supply the ESP32, and the earth line to the GND
Module”). In the case of mains power pin. The connection of these two wires, The main loop takes care of the follow-
failure, the battery can power the sys- the resistor and the capacitor, is made ing operations.
tem for at least 36 hours. on a piece of stripboard soldered on the  
male pins of the module (Figure 5). • Display on the OLED screen
The OLEDDisplayUi library allows us to
Software implement simply a very elegant display:
The heart of the system is of course the three pages are defined and they cycle
software (available on the article page every five seconds (Figure 6). The first
[2]). Here again, it is not necessary to page displays the date (the time is dis-
reinvent the wheel, because many exam- played at the top right of all three pages),
ples already exist and are made available today’s consumption and the leak detec-
by the community of “makers”. tion status. The second page shows the
The following libraries provide most of value of the counter, the value of the last
the services that we need: reading and the consumption since then.
• Wifi, ESPmDNS, WiFiUdp and Arduino The third page gives the status of the
OTA for Wi-Fi access and wireless WiFi connection and the IP address used. 
software updating;  
• TimeLib for time setting by NTP • Web Server
(Network Time Protocol); The server listens on a port defined
• ESP32WebServer and WiFiClient for during the initialisation, and you must
the web server; thus ensure redirection on your router.
• Wire, SSD1306 and OLEDDisplayUi to When a user connects through a browser,
drive the OLED display; the server presents one page with three
• and of course the power and func- tabs (Figure 7). The Visualisation
tionality of the ESP32 Arduino Core. (Overview) tab, refreshed every 5 sec-
  onds, shows, in addition to the informa-
After the inclusion of all these libraries tion shown on the OLED display, an hour-
and the definition of the structures and by-hour table of consumption over the
constants of the program, we find the last 24 hours. The Saisie (Setup) tab
classic Arduino program architecture, allows the user to define various parame-
Figure 6. the three pages of the OLED screen. that is to say an initialisation routine ters: the initial value of the counter, offi-

60 July & August 2019 www.elektormagazine.com


cial value of the last reading, and value of
the alert threshold for daily consumption
(see below). Access to this tab is pro-
tected by a username and password. The
À propos (About) tab is a reminder of
the functions of the system and shows
the software version.
 
• Leak detection
Every hour, the software looks at the
hourly consumption and establishes a
leak diagnosis on the basis of the fol-
lowing criteria:
- the consumption for the past 24 hours
is above a threshold;
- there is not a baseline of two consecu-
tive hours without consumption.
 
In the absence of a leak, there should
be, notably at night, at least two con-
Figure 7. Web server.
secutive hours without any consumption.
If that’s not the case, there’s a strong
possibility of a leak.
In the case of presumption of a leak,
the type of leak is shown on the first Shortcuts to access the web page
page of the LED screen as well as on Users may save shortcuts on their smartphones to access this Web page. For
the web page, and an SMS is sent to those whose access provider offers a router with ‘loopback’, a single shortcut
a predetermined number thanks to the will suffice, with the external address of their router followed by the chosen port
IFTTT service.
number. For others, they will need a second shortcut with the address of the
 
server on their Local Area Network (192.168.1.234:4321 for example). Some
• IFTTT
operators offer, by default or on demand, a fixed IP address. In that case, the
(If This Then That): is a free service
external shortcut is still valid. Other operators change this address periodically,
which combines actions triggered by
which means updating the shortcut or resorting to a Dynamic Domain Name
events, the combination being labelled
Server (DynDNS) which are sometimes free. How to do this is outside the scope of
an “applet”. Here the event will be the
this article, but you will find all you need for this on the internet.
sending by our software of a specific
“Post” request to the site maker.ifttt.
com which then sends an SMS to the
number defined during the creation of
the “applet”. In case of a leak, the soft- motif in the form of a wave, as well as of double-sided tape.
ware will send an SMS every hour, but adding an aesthetic aspect, allows ven- All that is needed is to connect the
as IFTTT limits the number of SMS per tilation of the case should the battery cable from the pulse transmitter, then a
month, the software will not send more generate any heat while charging. On the micro-USB cable with a standard char-
requests once this limit is reached. inside, the case provides fixing supports ger. A USB to micro USB cable of 10 cm
  for the Lolin module and the battery. The connects between the Lolin module and
• Time setting and backup charger is simply attached with a strip the charger.
Setting the correct time is done every
hour by NTP (Network Time Protocol) and
the time is maintained by the real time
clock (RTC) of the ESP32. Changes for
Daylight Saving Time are also automatic.
@ www.elektor.com
Every hour, the software saves the cur- ªWemos Lolin ESP32 Module with OLED screen
rent consumption values in non-volatile www.elektor.com/wemos-lolin
memory (EPROM).

Assembly
A 3D printed case was specifically
designed for containing the system
(Figures 8 and 9). Openings have been
placed for the OLED screen, cooling the
SOC, and for the WiFi antenna. A cut-out

www.elektormagazine.com July & August 2019 61


Commissioning and use
Programming of the system is done with
the Arduino IDE, having first configured
it for ESP32-based boards and selected
WeMos Lolin32 as the board type. In
addition it is necessary to load all the
libraries shown above. The first upload
is done with the module connected to a
PC, following which they may be done
over WiFi thanks to the OTA (Over The
Air) functionality.
The system starts up after power is
applied, looks for the programmed WiFi
network, sets the time and waits for a
user connection while monitoring the
pulses from the meter. It should then
be accessed from the web page using the
address on the third page of the screen,
to set the actual value of the meter, that
of the last reading and the consumption
Figure 8. Photo of the complete system, installed in its case.
alert threshold.

Conclusion
The manual reading of our meters every
six months shows a difference with this
system of only a few litres, for consump-
tion of 50 m3 (= 50 000 litres) which is
perfectly satisfactory. several alerts were
triggered and allowed early detection of
leaks before they became serious.
I have installed several of these sys-
tems for my neighbours, and all of them
reported that they used them profitably
to monitor their consumption and even
optimise it by noting the consumption
for a shower, washing machine, dish-
washer, refilling the pool, etc. This is
another interesting application not orig-
inally foreseen! Please share your own
experiences!
(180694-02)

Figure 9. Finished operational unit in its 3D printed case.

Web Links
[1] The Project at Elektor Labs:
www.elektormagazine.com/labs/waterflow-monitor
[2] Article page: www.elektormagazine.com/180694-02

62 July & August 2019 www.elektormagazine.com


TL431 Precision
Programmable Reference
Peculiar parts, the series
By Neil Gruending (Canada)

There’s a good chance that you’ve used a TL431 programma-


ble reference recently without even knowing it. These small
3-terminal devices blend in with their surrounding circuitry
which makes them difficult to spot but they are the voltage
reference used in many power supplies. Let’s see what makes
them so popular.
The Texas Instruments TL431 was originally released in 1978 as
an improved version of the TL430 shunt regulator. The TL431
had better voltage accuracy and stability so it was called a
‘precision adjustable shunt regulator’. It was also designed to
have sharper turn-on characteristics compared to temperature
compensated Zener diodes.
A Texas Instruments TL431 incorporates a bandgap voltage
reference, opamp and output drive transistor like in Figure 1 Six examples of power supplies using the TL431. Top row: cheap 5-volt
even though its schematic symbol is usually drawn as Figure 2. power supply, cheap phone charger, Apple iPhone charger (also ‘GB9’
The opamp is wired with the internal 2.5-V reference on the variant in lower left). Bottom row: MagSafe power adapter, KMS USB
negative input and the positive input is brought out to the Ref- charger, Dell ATX power supply (with optoisolators in front). Source: Ken
Shirriff, www.righto.com/2014/05/
erence pin so that the amplifier can be configured externally.
The transistor on the amplifier output increases the current
sink capability to 100 mA. This configuration makes the TL431
a very versatile device.
For example, if you apply a voltage to the Reference input the
TL431 will act like a comparator with a nice temperature com-
pensated internal voltage reference. Or you can connect the
reference input to the cathode like in Figure 2 to get a 2.5-V
Cathode Input V KA
output on the cathode. Add two resistors to set the amplifier
gain and you can set the output voltage to any value you want. I KA
You will find that the TL431 is used a lot in various power sup- Ref
plies. For example, a PC ATX power supply can use up to three
of them with one used for the standby power, main power and
the 3.3-V regulator. They are so common in ATX power supplies
V ref V ref
that many of the PWM controller ICs include TL431’s internally
to reduce the part count. Other applications include battery
chargers and even a crystal radio amplifier [3].
Anode
I hope that I’ve inspired you to try a TL431 the next time you 180575-007 180575-005
need a precision reference voltage source. There are plenty of
great circuits available and make sure to check out Ken Shirr-
iff’s site where he reverse-engineers the TL431 [2] for some
great photos of the die. Figure 1: TL431 equivalent circuit Figure 2: TL431 schematic symbol
180575-D-01 [1]. [1].

Web Links
[1] TL431 / TL432 datasheets: www.ti.com/lit/ds/symlink/tl431.pdf
[2] TL431 reverse engineered: www.righto.com/2014/05
[3] TL431 as an amplifier: www.techlib.com/electronics/crystal.html#AudioAmp

www.elektormagazine.com July & August 2019 63


HOMELAB PROJECT

IOTA Crypto Currency


(and an FPGA for the RPi)
Part 2: PiDiver — FPGA board for fast calculations

By Thomas Pototschnig and Julia Orlitzky (Germany)

In the last issue we presented the ‘IOTA’ crypto currency which


permits IoT nodes to pay other subscribers — for example for
storing data [1]. In order to perform IOTA transactions, a proof-
of-work calculation task must first be solved; this protects the
transaction database (“tangle”) from spam. Even x86 computers
sweat during the arithmetic task, but IOTA provides for smaller IoT
nodes to outsource this work to specialized devices. The second part
of the series introduces such a platform based on an FPGA add-on
board for the Raspberry Pi.

This installment of the article describes a fast and energy-ef-


ficient solution to the IOTA proof-of-work (PoW) problem; the
MVXMX9CZFMLNMMETLWMJYMEIJDBJLZHNUD9RCNNEYCSCKZYWCXSUVEGUVHOISYDVQKEDMUXZFPGTNBPPYYQZEPM9SM9PMGZNTCG
necessary calculations are performed by an FPGA. This achieves YHHVKZOHPYFRATZOBBSHKECZUTFYQUWYOPNPWJRJZLA9EGDWCQNIQGSHRQILFZXEULD9HUWDLZPEAPRVWIZYFED9JPYJDRLFXUO
JFPYG9XFAMKYXSLIXTR9TZVTMKDPZUMLTWTF9BXSEVHY9DKUICWMYTVTVXGFPIDVIFWNUKPWDIZZSADDRFASVMZMQNOTGOZQQHY

an average PoW time of 300 ms, which is not only faster than an VMCCCSBYYXNDEBHJYNEZAM9IXRYFWNYKWFDJCOOYPNAZQMEUJBPZFMPUKOAQK9QIRGFDWYXSTXMNRXOBNM9IJLH9YH9VSN99PVN
O9IZRRGFBGTWXMFEAOMDSHCSNHPVDQNAEQZIBSRDBMEOOKXMUDGDYDYZJOBTQZIGUMWNMKHVAU99CKKOJSOFLTORJ9PBS9VIIJM
UXTOIJPDAPJGMSLLQWLOLNQHUUURFGXIMKOIKBJFCFNLYIHMHVA9SFEOFUNIICXFLSNFURJAFXREJSXVRCNKJCTYQFSKTALTKUG
SSE-optimized multi-threaded library on a Core i5 (about 1.7 s). TMUY9QP9DQAKDPZPJEYRBKZZKNKE9STVFBTCF9SBLVZVJFI9KPKIRXMONS9BIJCQOKHNJQ9OMYMZIPKCXNCJMOIESKAHKSGTYOY
OZSABMHTKGGQTOOQXVRSXLVAQJZDH9TXMMB9PYASKKCYLGLDJXJPKTOTEIOTZKKCFNVTN9LYTNSOOJDFYFSZBSGWTYIHUWJKIWD

The power consumption of 2 watts is also significantly lower. IYK9MCSLEU9KAHQGZABLSQIBMXUNFULMJBOIJOAITNOEIRMAYR9ORSNUOVTVWSXVKYEVVABZTZ9QWMIDFDMQWCLGKX9CUCSKCYY


WSOAAYGWVTHWGGXWMDPJXNMEFJLRB9QRWRLFYNLFPASQIZAWTBESKZSKKKFYLKPSHWYQMMYSAAPGBXLYYAGXXISHPWUFZFAPYRR
ITQRATB9YMDXVDLPJCQ9PDAJEHZEMUJXTECCJDCKVUREDYRHYIPTNHEPNRAOJMZSGCEWXJUCMNMXKBDGPSII9WYIQRGOAMOASUC
AGCMMSQEIDCJVL9YHWUJEVRSULAGCPPIQVZNRHFZUBYT9LNN9CQNYBCXKDTKWQOKNWOBIAJTUGLBXGCSISPMRCK9POJXOLRYDPG
OKNJD9QD9GNVYKEV9GOGNIAWXSWKGKREO9NSDLA9LFNNQKNIJRV9QMIWUKL9NGZCOORHUZOFD9FWZNINVFAFKSAKTVLBWFGENTG

IOTA’s proof of work Transaction


UQSNTUNRD9AMWF9ZXYOHNNWVPQQWATELFIYJIEDGEGDRKVAZCI9TOQBZMMUDETGYUAHGNMRCTOYUHPZODFIUAAEVKATM9HLGHWJ
BDLBPDWDPAMVMRZDTBENZYTXNPBJWPIFDKHYCUGGPVWHUQVRSYLSJPKJMMZBLUJAQBKV9JJ9QKHEEEXJAUUOLRSSHIAVAOXENPF
GSRAFOCMEXHKIANH9ZBYSCKECOB9JKZB9CIOQYPOUDOZ9NZZFAO9BAWVXJ9HVVQHJUFUVMHSQCBYPMEBU9OFZORLPHJUBWCMBN9
For a transaction to be accepted by the tangle, the last 14 GEBSLDALMXLUFUHOHYWZZRXZOWDPZIEYSUTBZVANRXXPJXHVCBFJDXQCKXDKXKHRCCQOW9YF9KJBORKOKSZBQCGEJGDXLXMKEAZ
MMMWCPOJBNXI9EU9SCMJLLBXEBOAQOBIGYIXKJPVHGBKNOOYGMVHOYECDPLECGLLIZAXEVHMGFBAAXKLGHAVHWRYLEAQLO9FABD

steps [1] of the transaction hash must be zero. If a hash does OBTQGOBUHJHWVRZBPXDFBRDOJTMRBIKMVVUDQJMSBSYAKJYUGGR9EADDHOPT9ZCGNATIFKEEBVLVWEBMZKYPKLIMTQRDUQUSYLE
SUUJSUZO9VYUCPWALPQAJERBO9HMYLHRMIXJX9PCCREF9TQNMAFKLURLFQWPDIBPWZARXAWWE9SETHHCEJHVOMSJJEHOQEUNGTC
DV9RFXXJ9DMBNMAPAXRCVCCXQ9SFDNNYEGHGTY9AOTLPWJOOAD9MFTCZ9BCRSIDFQUQOEXBGIXYQUC9NA9ZFTCEHHTZIXEGBNCR
not fulfil this condition, a counter (Nonce, see Figure 1) is SAPYNFGJLE9RDCCRJ99PQHVTLPXVIBEBPCLT9WAJSKLROLIWEGNEA9HTSRXCDZODLHOMNDXCSSVYXJADMUFKNMJMLOQHBDV9IZM
CDIFZIKYCGOLCXJZYDCVFFUZODIUAOBWOP9UPIOYTNRKNYZVMXDOISNZCHGIWMFCIZABQE9BYL9GVZCMBHRTMNYNZWZNPPHVKLW

incremented in the transaction and the transaction hash is 999999999999999999999POWSRVIO9SIDETANG99999ANCRXIQHBMEA99999999A99999999DJ99FJYTXFEGLISHQWRMAR9PNIE


H9LNUGRALYPFQFGTIDMIJAVRFXLWDINCZPLZFLVNMVOFDAHWULRLB9LTSEOM9RAZHBUMJJJPULKLB9MZKFRUUZUJ9LYOUHDEFAC
QQGFGXKWDTMDTDPWHEEWJLXRYOCCBAX99999RCEFQMJMWYDIMXQRJLDZZPH9ZEGMD9V9ISBZLOENCRCPDCSXMUTGAUBTYBTHLZB
recalculated. This is repeated until a valid hash is found. On PIDIVER999999999LNNNVKGMMMM
YPXXSBFGCXRI9A9999999POWSRVIO9SIDETANG99999ANWSXIQHBME999999999K99999999PIDIVER999999999LNNNVKGMMMM

average, it takes 314 / hps seconds to solve the calculation


Nonce
problem, where hps is the number of hashes that can be cal- CURL-P81 Hashing
culated per second. This results in an average of 4.78 million
iterations until the problem is solved. Transaktions-Hash in Trytes

The idea behind this is that the tangle can be protected from SRXDJTHWBXESFLSXOKSYRSLDETVULSRINQIEUZYBYILTQNSN9OWCKUODFXQOUVAGOVEYPVAFKUJQZ9999

spam, since the maximum achievable transaction speed is 1 1 -1 1 0 0 0 -1 1 -1 1 1 0 1 -1 1 0 1 -1 0 -1 -1 0 0 0 0 0 0 0 0 0 0 0 0 0 0


greatly reduced by the computing effort. Verification, on the Transaktions-Hash in Trits

other hand, takes hardly any time because only the hash of 14 Trits = '0'

the transaction must be checked. A valid transaction hash is


therefore called a proof of work because it is proof that the
calculations have been performed. Figure 1: Transaction hash.

64 July & August 2019 www.elektormagazine.com


The hashing algorithm CURL-P81 is used, which — similar to
SHA3 — is designed as a sponge construction. New blocks -Transaction (33 blocks @ 81 Trytes)
... +1
B1 B2 B32 B33 Nonce

with a fixed block size (rate) are absorbed into the internal no

state, which has three times the size (capacity) of a block. last

Hash
B33
B2
B1

B32
14 Trits
The entire state is then transformed into the subsequent state zero?

CURL-P81
CURL-P81

CURL-P81

CURL-P81
using a sponge function (Figure 2). Once all blocks have been yes

Mid-State
State 31
State 1

0 ...
absorbed, the hash can be squeezed out. Found!
An IOTA transaction consists of 33 blocks of 81 trytes each
(B1–B33 in the diagram). The last block contains the counter absorb absorbing squeezing squeeze

that is incremented if the transaction hash does not fulfill


the condition of the main net (there are other tangle nets for
Figure 2: The sponge construction of the hash calculation (source:
development and test).
Wikipedia).
Since the counter is only in the last of the 33 blocks, the state
after absorbing the 32nd block (“mid-state”) can be used as the
start state for the 33rd block. After incrementing the counter
in the last block, only a single block needs to be hashed in
order to calculate the hash of the entire transaction, which
saves a lot of time.

Overview of PiDiver
The PiDiver — the name consists of Raspberry Pi and the ref-
Raspberry Pi GPIO
erence PoW algorithm “Pearl-Diver” [1]) — is a HAT (Hardware
5V Pi

Attached on Top) for Raspberry Pis, which can perform IOTA’s SPI
FPGA Confi g

proof-of-work quickly and energy efficiently. CORE 1,2V/1A

Figure 3 shows the block connection of the PiDiver. In the cen-


PLL 2,5V 5V
I/O 3,3V

tre is an FPGA Cyclone 10 LP from Intel. This is a member of 5V USB

USB
the relatively new Cyclone family (released 2018), with which FPGA SPI
STM32

Intel is targeting low-cost and low-power IoT applications in

BOOT
particular. The FPGAs, which offer a lot of logic resources, are SPI
Flash
not only very inexpensive and power-saving, but also available 10

in (relatively) DIY friendly housing variants (EQFP), making 14

them the perfect choice for this project.


Extension-Header Extension-Header
The FPGA is clocked at 200 MHz and can calculate a complete
hashing lap per clock cycle (CURL-P81 uses 81 laps). Further-
more, it calculates seven hashes with different counters (non-
cents) simultaneously. In addition to the 81 clock cycles, two
more clock cycles are required to check the result, restore the Figure 3: Block diagram  of  the PiDiver with the central FPGA.
old state (mid-state in Figure 2) and set the new counter val-
ues. You get about 16.8 MHash/s. In the case of the IOTA Main
Net, the average proof-of-work time is approximately 300 ms
or 3.33 PoW/s, including data transfer.
Furthermore, there is an STM32 microcontroller (STM32F302) (LDOs) connected in series for 3.3 V and 2.5 V, the third is a
in the circuit which makes it possible to operate the FPGA via switching regulator set to 1.2 V which can supply up to 3 A
USB. The proof-of-work can thus be performed either via the current (1 A is required). The board can be supplied with 5 V
SPI interface of a Raspberry Pi or on the PC via USB (without either via the Raspberry GPIO connector or via USB. Accord-
Raspberry Pi). ing to the manufacturer, two “ideal diodes” (type MAX40200)
You may notice that there is no flash memory for configuring combine both 5-V voltages so that the two potential voltage
the FPGA. Consequently, the configuration is reloaded into sources are not directly connected to each other. The MAX40200
the FPGA after each power cycle. This can also be done via is in fact not a diode, but a logic MOSFET with a voltage drop
the Raspberry Pi or via USB. The configuration is automati- of just 85 mV at 1 A. Whether this minimal power dissipation
cally detected and executed by the PiDiver library. For future makes every Schottky diode green with envy!
expansion, an SPI flash memory was provided on the STM32 The circuit shows some extension possibilities for other pro-
that is large enough to store the complete FPGA bitstream. jects. There are two extension headers for this, on which 14 I/
This would allow an automatic configuration after the pow- Os of the FPGA and ten port pins of the STM32 microcontroller
er-up, which could be interesting for embedded applications for your own applications are located. There are also LEDs and
(for example with an ESP32 microcontroller), because the bit- buttons on the FPGA as well as on the STM32. The circuit was
stream of about 800 kB is too large for the flash memory of designed so that the STM32 internal DFU boot loader can be
many microcontrollers. used. A separate BOOT button must be pressed during pow-
The circuit diagram in Figure 4 does not offer much more than er-up so that the controller starts in bootloader mode. The total
this. There are three supply voltages, each with its own voltage current consumption of 350 mA is so low that operation on a
regulator. Two of these are low-drop fixed voltage regulators standard USB port is possible without any problems.

www.elektormagazine.com July & August 2019 65


Figure 4: Schematic of the PiDiver.

+5V +5V
1 +5V
VDD 8 L1 R8 +1V2
VIN 6
SW 0 C10 C11
POWER_PI 3 U10 5 C12 U3
2.2 H R10
EN OUT 1 C14
MAX40200 EN +3V3

12k7
10 10
100n BD9D321EFJ
GND
100n
2 3 7 0.1% R7
VREG BOOT C5 C6
+5V

270
4 EXP 2
1 SS FB 47 47
GND R11
VDD D1
C3 C4 C71 C78 C79
5 9
U11

22k
POWER_USB 3 5
EN OUT
1 3n3 47 47 47
MAX40200 0.1%
GND
2
+3V3 +3V3

J2 4
1 2 24 36 48 9
+3V3 +3V3 R22 U7 C70
3 4 RESET 7 5 3

VDDA
VDD
VDD
VDD
NRST PF0/RCC_OSCIN 22
5 6 BOOT0 44 6
+1V2 +1V2 BOOT0 PF1/RCC_OSCOUT 8MHz 100n
7 8 +3V3
+2V5 +2V5 2
PC13 R31 2
3 1
PC14/RCC_OSC32IN VBAT

10K
4
J1 PC15/RCC_OSC32OUT
1 2 USER5 18 10 LED_ARM
PB0 PA0 +3V3
CONF_NCONF 3 4 POWER_PI USER6 19 11 ARM_BUTTON
PB1 PA1
CONF_DATA0 5 6 DISC 20 U5 12 CONF_DONE
PB2 PA2
CONF_DCK 7 8 USER4 39 13 SPI2_SS
PB3 STM32F302CCT6 PA3 C75 C76
9 10 CONF_NSTAT 40 14 USER1
JP1 PB4 PA4
CONF_NSTAT 11 12 FPGA_SEL0 USER3 41 15 SPI2_SCK
PB5 PA5/SPI1_SCK R6 22 100n 100n
13 14 USER2 42 16 SPI2_MISO
JP2 PB6 PA6/SPI1_MISO
15 16 FPGA_SEL1 CONF_DCK 43 17 SPI2_MOSI
PB7 PA7/SPI1_MOSI
17 18 FPGA_SEL2 CONF_DATA0 45 29 USER10
PB8 PA8
PI_MOSI 19 20 CONF_NCONF 46 30 USER9
JP3 PB9 PA9 R27 +3V3
PI_MISO 21 22 USER7 21 31
PB10 PA10 10K
PI_SCK 23 24 USER8 22 32 USB_D–
22 PB11 PA11/USB_DM
25 26 CONF_DONE 25 33 USB_D+
R9 PB12/SPI2_NSS PA12/USB_DP +3V3
27 28 26 34 ARM_SWDIO
R5 +3V3 PB13/SPI2_SCK PA13/SWDIO
PI_SS 29 30 27 37 ARM_SWCLK
10k PB14/SPI2_MISO PA14/SWCLK
R30 31 32 28 38 PI_DETECT
PB15/SPI2_MOSI PA15 C73 C74
33 34 PI_DETECT R16
10k

VSSA
VSS
VSS
VSS

35 36 ARM_NRST
10k

100n 100n
37 38 23 35 47 8
JP4
39 40 ARM_SWDIO +3V3
+3V3
JP7
R29 +3V3
ARM_SWCLK
22
JP5 +3V3
U9 8
P2
J5 VCC 7 R15
5 HOLD 1
MISO MOSI

USER1 1 2 USER2
10k

2 2 ARM_NRST
USER3 3 4 USER4 C7
EEPROM

3 ARM_SWDIO
Array

USER5 5 6 USER6 NRST


6 4 ARM_SWCLK
USER7 7 8 USER8 SCK 100n
1 5 C72 SW1
USER9 9 10 USER10 CS 3
WP
11 12 GND 100n
SWD
SST25VF080B 4 RESET
+3V3
J3 +3V3
GPIO0 1 2 GPIO1
GPIO2 3 4 GPIO3
GPIO4 5 6 GPIO5
D3
R23 +3V3
R17 SW4
GPIO6 7 8 GPIO7 OVERFLOW
10k

270 ARM
GPIO8 9 10 GPIO9 D4 SW3
R18
GPIO10 11 12 GPIO11 LED_FOUND ARM_BUTTON
270
GPIO12 13 14 GPIO13 FPGA_BUT
R19 D5 BOOT0 BOOT
15 16 LED_RUN R28
270 SW2 R24
JP6 JP8 JP9
+3V3
10k

R20 D6 FPGA
10k

LED_ARM
270

66 July & August 2019 www.elektormagazine.com


+3V3 R14
DISC
100
R26 Q1 BC817 FL1 U8
R12
POWER_USB R3

1k5
10k
1
R1 R25 VBUS
R13

33
2

36k
1k5 D–
USB_D– 3
D+

33
USBLC6-2SC6 5
GND
USB_D+
+5V +3V3 +2V5 C85 C86
LD1117S33TR LD1117S25R L8 4 6

U2 U4 47p 47p R2 L7
C84 C83 C81

100k
C1 C2 C19 C20
4 7 100n 10n
POWER_USB X5R
100n 10 100n 4 7
X5R

+3V3 L1 = 2 2 (SPM4012)
SPI2_MISO 76 L3, L4, L5, L6, L7, L8= ferrite bead 0805
R4 6 IO
+2V5 IO SPI2_MOSI 77 (Würth 74279220181)
7 IO
10K

IO/VREFB1N0 80 IC1F FL = DLP11SA900HL2L/DLP11SN900HL2L


8 IO
C48 C50 C52 C54 IO SPI2_SS 83 (Common Mode Noise Filter)
9 IO
nSTATUS SPI2_SCK 85
100n 100n 100n 100n
CONF_NSTAT10
IO
IO +1V2
86 5 110
11 IC1B IO VCCINT GND
IO 87 29 104
CONF_DCK 12 IO VCCINT GND
IO/DCK BANK 5 34 64
CONF_DATA0 13 88 VCCINT GND
+1V2 IODATA0 IO 38 30
CONF_NCONF14 89 VCCINT GND
nCONFIG IO 45 IC1A 79
15 VCCINT GND
C66 C67 C68 C69 +2V5 TDI 61 4
16 VCCINT GND
TCK 70 140
18 BANK 1 VCCINT GND
47 47 47 47 TMS 90 78 131
20 CLK5 VCCINT GND
TDO 91 84 123
21 CLK4 VCCINT GND
nCE CONF_DONE 92 102 118
22 CONF_DONE VCCINT GND
+1V2 CLK0 94 116 95
23 MSEL0 VCCINT GND
CLK1 96 124 82
MSEL1 VCCINT GND
C63 C64 C65 97 134 63
MSEL2 VCCINT GND
138 57
PI_SCK 98 VCCINT GND
10 10 10 24 IO IC1G +3V3 48
CLK1 PI_MOSI 99 17 GND
25 IO VCCIO1 41
CLK2 PI_MISO 100 26 GND
IO VCCIO2 27
IC1C PI_SS 101 BANK 6 40 GND
+1V2 28 IO VCCIO3 19
IO 103 47 GND
31 IO/CLKUSR VCCIO3
IO/VREFB2N0 105 56
32 IO/VREFB6N0 VCCIO4
14x IO
BANK 2 106
IO
62
33 VCCIO4 145
IO 81 GND
100n 100n VCCIO5
93
VCCIO6
117
111 VCCIO7
C23, 24, 27, 28, 31, GPIO0 39
IO
IO 122
VCCIO7
112
C32, 35, 36, 39, 40 GPIO1 42 IO 130
IO 113 VCCIO8
C43, 45, 47, 49 GPIO2 43 IC1D IO IC1H 139
IO 114 VCCIO8
GPIO3 44 IO +2V5
IO 115 35
+3V3 GPIO4 46
IO/VREFB3N0
IO VCCA1
119 107
GPIO5 49 IO/VREFB7N0 VCCA2
IO 120 3
GPIO6 50 IO VCCA3
4 IO 121 75
GPIO7 51 IO VCCA4
IO 125 BANK 7
C77 U6 R21 BANK 3 IO 37 36
3 52 VCCD_PLL1 GNDA1
22 CLK15 126 109 108
53 CLK8 VCCD_PLL2 GNDA2
100n 8MHz CLK14 127 1 2
CLK9 VCCD_PLL3 GNDA3
73 74
2 VCCD_PLL4 GNDA4

54
CLK13 10CL025YE144I7G
+3V3 55 128
CLK12 CLK10 POWER
129
GPIO8 58 CLK11
C55 C62 IO
8x GPIO9 59 IC1E 132 +1V2
IO IO IC1I
10 10 GPIO10 60 133
IO IO
GPIO11 65 FPGA_SEL2 135
IO IO
OVERFLOW 66 FPGA_SEL1 136
IO/VREFB4N0 IO/VREFB8N0 L3 L4 L5 L6
+3V3 LED_FOUND 67 FPGA_SEL0 137
IO IO
LED_RUN 68 141
IO
BANK 4 IO BANK 8
GPIO12 69 142
12x IO IO
GPIO13 71 143
IO IO
100n 100n FPGA_BUT 72 144
IO IO
C46 C44 C53 C51

C21, 22, 25, 26, 29, 30, 100n 100n 100n 100n
C33, 34, 37, 38, 41, 42
180361-022

www.elektormagazine.com July & August 2019 67


Superstructure software for the STM32 microcontroller on the board. They
The PCB of the PiDiver [2] in Figure 5 has four layers and is enable a software switchable pull-up resistor for the D+ data
almost exclusively populated with SMDs. Some (U6, U7 and line of the USB. This is especially interesting for the debug-
FL1) can’t be solved with a soldering iron, because the pads ging of the STM32 software, so that the host is notified in
are hidden under the housing. Soldering paste and hot air are case of a microcontroller reset that the USB device has to be
therefore recommended for assembly. enumerated again.
You should leave R8 (a 0-Ω resistor at the output of the Unfortunately, the standard bootloader integrated in every
switching regulator U4) in its box for the moment, because STM32F302 does not support a switchable pull-up resistor,
this resistor is not populated at first. The components crossed which is why there is a fixed pull-up resistor (R26) that
out in the assembly diagram (see [2]) are not required for takes over this function. Also interesting for debugging is
operation as PoW accelerators. The components R12, R13, the pin header P2, to which the SWD debugging interface
R14, Q1 and P2 are only of interest if you want to develop was routed.

The PiDiver Development


IOTA’s proof-of-work is intended to protect the tangle May 2018 with a hashing performance of approximately 14.8
from spam, but the task is also an obstacle for many valid MHash/s. The first version of the circuit board was tested
applications that need to send data quickly to the tangle. in May 2018. In total there are four versions of the board.
The whole thing is very CPU-intensive even on full-grown The first two versions were equipped with an STM32F1
computers and even more so for smaller IoT systems. For microcontroller, which was replaced by an STM32F3 for
example, a Raspberry Pi takes 90 seconds on average to bootloader functionality from the third version onwards. In
solve the PoW problem. the second version, an optimized power supply was used
For this reason, the PiDiver project was launched. First, because the switching regulators on the first version were
a proof-of-concept was developed on a ten-year-old oversized. Version 3 has ESD protection and EMC filters
development board (Altera DE1). The Altera Quartus 13.0.1 on the USB, the two MAX40200 (“ideal diodes”) and the
development environment was used because Cyclone II DFU bootloader functionality have been added. The fourth
FPGAs are no longer supported by the newer versions. The version offers mounting holes for a heat sink as well as more
PiDiver core was written in VHDL, based on the reference compact (and therefore more) buttons and pin headers for
code “Pearl-Diver” (in Java) by Sergey Ivancheglo [12]. First your own extensions.
a hashing performance of about 4.6 MHash/s was achieved, The firmware for the STM32 microcontroller was developed in
which could be improved to about 12.9 MHash/s a short time C++ with Eclipse.
later. To be able to use the FPGA with IOTA libraries [7], the
library “dcurl” [8] was extended by a hardware SPI controller
for the Raspberry Pi and a module that implements the
command set for the FPGA.
The library dcurl is a faster alternative to the proof-of-work
library ccurl (library of the IOTA Foundation [9]), because
it supports a PoW implementation in C as well as
GPUs and CPUs with SSE or AVX instruction
sets. The then official wallet of the IOTA
Foundation [10] - an electron app -
used ccurl as an external library,
since the wallet itself was
written in Javascript,
which is relatively slow for
PoW. This library could be
replaced by dcurl. Later,
a separate PiDiver library
and a test program were
developed in GoLang, so
that dcurl was no longer
needed.
During the first optimizations at
the PoC the first PCB design of the
PiDiver was developed with KiCad. The
basic circuitry was taken from Intel
data sheets, design recommendations
were used for the layout. The first circuit
board version was successfully tested in

68 July & August 2019 www.elektormagazine.com


Most of the other components don’t need any further comment
(except that some of them are quite small), but special atten-
tion should be paid to the metal surfaces on the underside of
the FPGA (U1) and the switching regulator (U3), which also
have to be soldered. For manual assembly, therefore, large
vias were placed under these components to allow soldering
of these metal surfaces. It is recommended to heat the metal
plates with hot air from the rear through the vias until solder
melts on them. The use of a soldering iron is strongly discour-
aged here, as the heat supplied disappears very quickly in the
intermediate layers of the board and the metal surfaces will
prove difficult to heat to the required temperature. In the worst
case even the circuit board will be damaged!
Figure 5: Assignment of the (unassembled) connector J2 for checking the
supply voltages.
First commissioning
Once the circuit board has been assembled, it is advisable
to check the voltages first. First, check the 1.2-V voltage at
the output of the switching regulator. The core of the FPGA is
go get gitlab.com/microengineer18/pidiver1.3/golang/
(later) supplied with this voltage. It can quickly happen that
pidiver
the resistors of the feedback voltage divider are swapped, and
cd $GOPATH/src/gitlab.com/microengineer18/pidiver1.3/
the excessive voltage destroys the FPGA. If the voltage is okay,
R8 can be soldered in. golang/pidiver/main
go get -d ./...
Then you can check all voltages on the solder pads of the unas- go build
sembled pin header J2 (Figure 6). However, the 1.2-V supply  
can only be measured there after the R8 has been assembled. Now the actual test can begin. If you want to use the PiDiver
If the board is supplied with power, LED D1 should light up over a Raspberry Pi, you start the program there:
and thus signal that the 3.3-V operating voltage is present.
Afterwards it can be tested whether the STM32 microcontrol- $ sudo ./main -t pidiver
ler is recognized at the USB. To do this, connect a USB cable
from the PC to the board while the BOOT button is pressed, (Note: sudo is important, otherwise no direct hardware access
whereupon the microcontroller logs on to the computer as to SPI is possible).
“DFU Bootloader”. If you want to use the PiDiver via USB, enter the following on
the Linux PC:
Software
Flashing the STM32 microcontroller $ ./main -t usbdiver
To flash the microcontroller, it must first be started with the
DFU boot loader. To do this, keep the BOOT button pressed The output looks similar in both cases:
while connecting the board to the USB. Shortly afterwards the ...
controller should log on to the computer as “DFU Bootloader”. 2018/07/14 09:09:02 Found nonce: 0005e423 (mask:
Under Linux you can use the tool dfu-util [3] to flash the 00000010)
firmware: 2018/07/14 09:09:02 PoW-Time: 172ms (15.62MH/s)
2018/07/14 09:09:02 Nonce-Trytes:
dfu-util -v -d 0483:df11 -a 0 -s 0x08000000 -D
PIDIVER9V9999999OMKVVNGMMMM
usbdiver.bin
2018/07/14 09:09:02 hash: RIRQYZKVJIDQIO9RBPLCJTSRTJ
CWFVOODAMKXFHRJMFZQLR9AJPLCNYEPW9IJCEJWRBTVTRIWZY
After successful flashing and a reset, the controller should
report as USBDiver. DA9999
   
GoLang Installation 2018/07/14 09:09:03 Found nonce: 00094b5e (mask:
The libraries were written in the programming language GoL- 00000020)
ang, which has to be downloaded and installed first. GoLang 2018/07/14 09:09:03 PoW-Time: 265ms (16.03MH/s)
is available on [4] for multiple operating systems and archi- 2018/07/14 09:09:03 Nonce-Trytes:
tectures. You can also find installation instructions on the web- PIDIVER9T9999999UNGEKTVMMMM
site. After installing and setting up the environment variables, 2018/07/14 09:09:03 hash: EIW9MEACXYGVAQFCUGAKGMXKNC
restart the computer.
PGMMSPQWOLGMHZWHZKUEOLNRFKJGMNSELCSLRAEVCLYCBREBW
TZ9999
Installation of the test program
...
If GoLang has been successfully installed, the test program
can be compiled. First you get (on the Raspi or the Linux-PC) The test program calculates noncents of random transactions
the Git package: and outputs the transaction hash, which in the case of the

www.elektormagazine.com July & August 2019 69


IOTA main net always ends with “9999” (3 trits, which are 0, @ www.elektor.com
correspond to a 9 when output as a tryte).
ªRaspberry Pi 3 Modell B+
There is also a server (running on the Raspberry Pi, but also
www.elektor.de/rpi-3b-plus
on a Linux PC) that accepts the attachToTangle [5] command
of the IOTA API and calculates noncents for real transactions.
At this point, however, reference is only made to further docu-
mentation [6], as this would go beyond the scope of the article.

Power to the Pi!


For operation, it is important to use cables that can carry the
necessary power. To power the Raspberry Pis you should use a
USB cable as used for Powerbanks. The power supply must be
able to supply real 5 V at real 2 A! Operation with the PC’s USB
also requires cables that can handle at least 500 mA of current.
If you use a wrong cable or power supply that is slightly weak
on the chest, the FPGA usually loses configuration as soon as
it starts proof-of-work.
180361-B-03

Web Links
[1] First part of the series: www.elektormagazine.com/180361-02
[2] GIT Project Repository: www.gitlab.com/microengineer18/pidiver1.3
[3] DFU Tool: http://dfu-util.sourceforge.net/
[4] GoLang: https://golang.org/
[5] Attach to Tangle: https://iota.readme.io/reference#attachtotangle
[6] PiDiver Documentation: https://ecosystem.iota.org/tutorials/pidiver-usbdiver-documentation
[7] IOTA Ledger: https://github.com/iotaledger
[8] Library dcurl : https://github.com/DLTcollab/dcurl
[9] Library ccurl : https://github.com/iotaledger/ccurl
[10] IOTA Foundation Wallet: https://github.com/iotaledger/wallet
[11] Musical PiDiver: www.youtube.com/watch?v=GhgDCf9oBEo
[12] PearlDiver: https://github.com/Come-from-Beyond/PearlDiver

Musical PiDiver
The PiDiver is basically a versatile FPGA board that provides
Raspberry
unused pins for own applications via additional pin headers. SID-File
For example, a C64 hardware emulation was tested that can - SID file is being loaded
play 8-bit 80s music in stereo via an I2S digital-to-analog
- libsidplayfp generates
converter connected to the board. libsidplayfp RAM/ROM raw image

- raw image is loaded via


The library libsidplayfp was used, which provides a C64 SPI into the PiDiver
RAM/ROM Image
software emulation that can be used to play SID music on
PiDiver - C64 core is started
a PC. The library internally generates RAM and ROM images RAM/ROM
that are executed on the emulated C64. Although the images
were not intended to run on C64 hardware, it works fine. A Glue-Logic DAC Audio
big compliment to the developers of this library! A video with
the music playing PiDiver can be viewed under [11].
VIC*

CIA1

CIA2

SID1

SID2

6510
CPU
*: Mini-VIC does not generate video, but is important for timing.

70 July & August 2019 www.elektormagazine.com


The Elektor Community
82 203637 1040 546 235332
Countries Enthusiastic Members Experts & Authors Publications Monthly Visitors

Elektor breaks the constraints of a magazine. It’s a community of active e-engineers — from
novices to professionals — eager to learn, make, design, and share surprising electronics.

Elektor Web Store: 24/7 candy store for


Elektor Magazine: Six times per year a thick
every electronics engineer! Permanent 10%
publication packed with electronics projects,
discount for GREEN and GOLD Members.
news, reviews, tips and tricks.
www.elektor.com
www.elektormagazine.com

Elektor PCB Service: Order your own PCBs, Elektor Weekly & Paperless:
both one-offs and larger runs. Your digital weekly news update. Free.
www.elektorpcbservice.com www.elektor.com/newsletter

Elektor Academy: Webinars, Seminars, Elektor Books: Arduino, Raspberry Pi, ESP32,
Presentations, Workshops and DVDs ... IoT, Linux and more. Available in our online
Practice-oriented learning. store with a 10% Member discount!
www.elektor-academy.com www.elektor.com/books

Elektor Labs: Showcasing your own projects


Elektor TV: Reviews, timelapse, unboxing and
and learning from others. We develop and test
personal journals. Watching is learning.
your ideas!
www.elektor.tv
www.elektormagazine.com/labs

Become a member today!


GREEN €5.67 per month
£4.08 / US $6.25 GOLD €7.58 per month
£5.50 / US $8.42 FREE
✘ 6x Elektor Magazine (Print) ✔ 6x Elektor Magazine (Print) ✘ 6x Elektor Magazine (Print)

✔ 6x Elektor Magazine (PDF) ✔ 6x Elektor Magazine (PDF) ✘ 6x Elektor Magazine (PDF)

✔ Access to Elektor Archive ✔ Access to Elektor Archive ✘ Access to Elektor Archive


(Thousands of Articles) (Thousands of Articles)
✘ Access to over 1,000 Gerber files
✔ Access to over 1,000 Gerber files ✔ Access to over 1,000 Gerber files
✘ Elektor Annual DVD
✘ Elektor Annual DVD ✔ Elektor Annual DVD
✘ 10% Discount in Elektor Store
✔ 10% Discount in Elektor Store ✔ 10% Discount in Elektor Store
✔ weekly e-zine
✔ Exclusive Offers ✔ Exclusive Offers ✔ Exclusive Offers
www.elektor.com/green www.elektor.com/gold www.elektor.com/newsletter

facebook.com/ElektorLabs twitter.com/Elektor instagram.com/elektorlabs


AS-Interface Essentials
How the industrial automation bus system works

By Tam Hanna (Slovenia)

In the olden days everything was controlled using hand-made


custom cabling and proprietary data formats. In the industrial
world at least, however, this kind of thing is long gone: now
entire systems are based instead around fully-featured
bus architectures. As well as the obvious advantages
of easier maintainability and expandability there are
other reasons to prefer such an approach. For
example, a widespread industry standard ensures
the long-term availability of hardware and
software components, at least to some
degree. In this article we will take a
look at AS-Interface.

The approach to automating more complex manufacturing pro- ciation’ [3], a kind of special interest group. This group holds
cesses can be thought of as a series of layers as illustrated in the rights to the name ‘AS-Interface’ and sells products based
Figure 1. At the bottom level we find the sensors and actu- on the official standard. In case you might be considering join-
ators. For reasons of cost and efficiency, communicating with ing the group, you may wish to bear in mind that membership
these devices requires us to go to the trouble of using Ether- will set you back in the region of €4000 per annum.
net-style cabling: short-range connections using protocols such If you would like just to take a look at the standard there is a
as SPI or I2C are often no match for the harsh environment of more affordable path available: AS-Interface is specified via a
an industrial installation [1]. bundle of industrial standards, of which by far the most popular
  is EN 62026-2:2015. This standards document can be obtained
Two widespread techniques for connecting sensors and other through the official channels for a mere €250. Alternatively,
devices are AS-Interface (actuator-sensor interface, also known if you fancy a spot of personal research, it should be possible
as ASi) and the IO-Link protocol, standardized under the name to find the document in the library of a local technical college
SDCI, and promoted for use in PROFIBUS environments. The or university; and failing that, perhaps an inter-library loan or
most significant advantage of AS-Interface is that a master can a suitable institutional library might come to your assistance.
talk to many slaves using a single port. IO-Link, in contrast, One possible complicating factor in getting to grips with all
normally requires a separate port and cable for each slave. In these materials is that currently there are two versions of ASi
the English-speaking world at least, IO-Link is generally con- on the market. Of these, only version 3.0 has a significant level
sidered more suitable for use in systems where large quantities of availability, both in terms of specifications and in terms of
of data must be communicated. hardware. However, version 5.0 has been widely promoted
Note that ASi and IO-Link can to some extent coexist. For exam- since the ‘SPS IPC Drives 2018’ trade show: the new version
ple, the system from Bihl+Wiedemann shown in Figure 2 and improves on the old in several details.
described in detail in [2] uses IO-Link to collect information; the Although such developments are perfectly normal in themselves,
compiled datagrams are then passed to the master using ASi. a sticking point is that the exact specification for version 5.0
of the protocol is, at the time of writing, not available to all
Which version? members of the association. According to insider information
AS-Interface came into existence in 1990 from the formation of the information is only available to those directly involved in
a group of companies under the name ‘AS-International Asso- developing the protocol.

72 July & August 2019 www.elektormagazine.com


An interesting result arises from this. Transceiver ICs for ver-
sion 3.0 (on which more below) originated at the company
ZMD, which was then bought out by IDT, which was in turn
swallowed up by Renesas. Hence Renesas is the partner work- Design Level
ing on support for version 5.0, and so they can proclaim ‘we
implement all the protocols’.
Management Level
The ASi cable
A fundamental aspect of the implementation of the ‘multi-
drop’ capability of ASi lies in the construction of its cable. System Level
There are two conductors in the cable, which carry the sig-
nals AS+ and AS–. Here AS– is the ‘ground’ connection rel-
ative to which AS+ carries the positive data signal. But note Process Level (PLC; etc)
that it is under no circumstances permissible to connect the
AS– signal to earth.
In actual installations the ASi cables are almost invariably yel-
low in colour. The asymmetrical shape shown in Figure 3 is
Sensors and Actuators
typical, the form of the cross-section being reminiscent of a
nose. An optional black cable with the same construction can
be employed to deliver additional power to devices on the bus.
Figure 1: The hierarchical levels of an industrial automation system.
Most ASi devices have connectors to fit a cable of the type
shown in Figure 3, equipped with teeth that pierce the insula-
tion of the cable when the connector is fitted in order to make
electrical connection with the two conductors inside. Adding
a new device to an ASi bus is therefore reasonably easy and
‘failsafe’. Although this design is common and practical, it is
possible to use the ASi bus with other types of cable.
When sensors are connected directly to microcontroller sys-
tems using the 1-wire bus it is possible for low-power devices
to take their supply directly from the bus signal. The same goes
for AS-Interface devices: the nominal bus voltage is 24 V, and
according to the specification the bus can in theory carry up to
8 A. In practice, however, it is recommended to maintain the
current draw below 2 A in order to keep voltage drops in the
cabling and connectors within reasonable limits.
An important point is that the AS-Interface signals are not at
a fixed potential with respect to earth. Indeed, as mentioned
above, it is explicitly forbidden to earth the cable. As well as
fully-networked ASi slave devices it is also possible to have
devices that use the bus only as a power source. They can
draw up to 400 mA at 24 V, but are not allocated an address
and do not take part in communication. Since an ASi bus can
be up to 100 m long (and, with suitable termination, even up
Figure 2: From Fieldbus to sensors and actuators (source: [2]).
to 300 m long), it is also a convenient way to provide a sup-
ply to ‘alien’ systems with modest power requirements. Such
devices are simply connected to AS+ and AS– and get on with
whatever their business might be.
An ASi system is normally powered from a dedicated power
supply, whose construction is illustrated in Figure 4. Designing
2.0

and building a supply of this type yourself for a professional


application is strongly discouraged: on the website of the ASi
association [3] there are links to many companies who will be – +
happy to sell you suitably certified products.
4.0

It is interesting to note that the power supply is expected to


provide a DC output at between 29.5 V and 31.6 V. This level, 3.6

rather more than 24 V, is needed to compensate for voltage 6.5

10
drops in cables and connectors. Also, the high level of noise
immunity offered by the ASi system is not carte blanche for
sloppy or disorganized cabling. When an ASi cable is run in the Figure 3: Cross-section of an ASi cable (conductor diameter 1.8 mm). The
same duct as mains cables carrying power-line signalling, it is ‘nose’ shape prevents accidental reverse-polarity connection.
possible in some circumstances for the network to suffer inter- (Image: after Bihl+Wiedemann).

www.elektormagazine.com July & August 2019 73


ference that is hard to get rid of. A presentation by Phoenix Con-
tact [4] gives further advice on how to arrange an installation.

Balancing Data decoupling


Communication
It is clear from the cable construction shown in Figure 3 that
AS-Interface + there are no separate connections for power and data. It fol-
30 V DC
lows that before a receiver can process a message the signal
Primary
Voltage Power must be transformed or demodulated.
Supply Shield
Data are sent using APM (alternating pulse modulation). This
is a scheme based on Manchester coding, where the data clock
AS-Interface _ and the bitstream to be sent are combined. Then the Manches-
PE
ter-coded signal is used to modulate a current to transmit the
data. According to the freely-available information the ampli-
tude of this modulation is between zero and 60 mA.
Negative-going edges are represented by a rise in the trans-
mitted current and positive-going edges by a fall. Because of
Figure 4: The PELV power supply has a comparatively complex internal the inductance of the cable these changes in current are con-
construction (source: [4]). verted into voltage impulses, with excursions of around ±2V
around the nominal supply voltage. It is important to note that
the beginning of a datagram is always marked by a negative
pulse: this is relevant when it comes to triggering digital oscil-
loscopes and signal analysers.
Unfortunately the usual makers of oscilloscopes have so far
shown little interest in incorporating ready-to-use ASi protocol
UOUT +24 V decoders into their products. Only the range of devices from
ASI4U FID Pico Technology support the protocol, although even then not
DI0
DI1
natively: a third-party tool uses the API to provide analysis
UIN
DI2 functions [5].
DI3

8/16 MHz
DIO-0
If you wish to build an ASi device it is not really practical to
OSC1 DO0
DO1 DIO-1 implement the decoder hardware yourself. The company IDT
DO2 DIO-2
DO3 DIO-3 mentioned above offers the ASI4U transceiver chip, which can
OSC2
1N4001 DSR DSR & Reset
be configured to operate as a master or as a slave. Figure 5
ASI+ ASIP P0 P0
P1 P1 shows the basic circuit, taken from the data sheet.
P2 P2
ZMM 39
P3 P3 Particularly noteworthy are the two light-emitting diodes, which
ASI-
ASIN
PST PST IDT’s data sheet labels as green and red. The ASi bus specifi-
LED red
CAP

47 n
USR LED1 cation requires that these LEDs are present on slave devices,
100 n
LED green and they give information on the current operational state.
LED2
0 V IRD More information on this can be found in the device data sheet.
GND

+
The pins labelled DIx and DOx are input and outputs. If a mod-
100 n
10 µF ule using the transceiver is operating in slave mode, then this
0 V
is where data communicated over the bus will be made avail-
able. The pins labelled Px are used to configure parameters,
and are particularly important in the master mode, which we
Figure 5: The transceiver chip requires very few external components will not go into here.
(source: [6]).
The communications standard
Now that we have understood the underlying electrical prop-
erties of an ASi system, we can turn to the logic behind the
communication format. All communications are strictly under
the control of the master, which carries out a cyclic polling pro-
cess whereby it interrogates each individual slave connected
Master- Slave-
Masteraufruf pause Slaveantwort pause
to the bus in turn. Each slave will normally reply to this with a
0 SB A4 A3 A2 A1 A0 I4 I3 I2 I1 I0 PB 1 0 I3 I2 I1 I0 PB 1
four-bit payload. When a cycle is complete it starts again from
the beginning: see Figure 6.
ST EB ST EB

ST = Startbit The format of the address determines the maximum number


SB = Steuerbit
A4...A0 = Adresse des Slaves of devices on the bus. In ‘normal’ datagrams there are just
five address bits available, and address zero is reserved for a
I3...I0 = Informationsteil vom Master an den Slave (5 Bit)
und vom Slave an den Master (4 Bit)
PB
EB
=
=
Paritätsbit
Endebit
new slave. There are thus 31 available values remaining for
addressable slaves. A new slave device, which initially has
address zero, is allocated a new address from the available
Figure 6: Data format of an ASi message (source: [7]). pool by the master.

74 July & August 2019 www.elektormagazine.com


@ www.elektor.com
ªMonoDAQ-U-X (50 kSa/s) multifunctional USB data acquisition system
www.elektor.com/monodaq-u-x-multifunctional-usb-data-acquisition-system-50-ks-s
ªPicoScope 2205A
www.elektor.com/picoscope-2205a

A consequence of the cyclic polling is that the response time


of an ASi system is deterministic. In ASi 3.0 the response time
is normally around 5 ms, while the newer version 5.0 with 24
bus participants promises a cycle time of just 1.2 ms. Also,
the maximum number of slaves in ASi 5.0 is considerably
greater, at 96.
It is particularly important to realize that either data or param- the open market, but there is a big ‘however’.
eters can be transmitted. One of the information bits indicates The problem relates to intellectual property rights. If, without
which type of information is being transmitted on the bus. The explicit permission, you use the term ‘ASi’ or the ASi logo, you
control bit specifies whether an address or a command follows. will rapidly find yourself in legal hot water. And if you attempt
to sell your system on the open market, it is only a matter of
Where do we go from here? time before someone will come knocking on your door.
If you are to work on an existing ASi system, or if you would This situation is not exactly satisfactory for hobbyists inter-
like to (or have to) build a new ASi system, it is important to ested in experimenting in the lab. On the other hand, working
think rationally. Developing your own modules and sensors with ASi systems can prove very lucrative in the longer term,
may sound like fun, but in practice it is not economic. There as salaries for developers and consultants in industrial auto-
are many companies working in this field, and they offer prac- mation are in general comparatively high: that might be some
tically any sensor and actuator type you can think of with compensation for all the formalities and travails.
AS-Interface capability. It is much more efficient to assemble 190124-02
your complete system from these components and sell it, along
with consultancy support services, to customers.
If you are not put off by the above and still wish to experiment
with ASi, it will not really be possible to avoid taking up mem-
bership of the standardization organization sooner or later. The
standard includes all the necessary information, and according
to oemsecrets.com the ASI4U transceiver chip is available on

Webinar Reading the data sheet


is not optional!
A brief overview of the basics of the ASi standard can be For reasons of space this article is only able to give a broad
found at Pepperl+Fuchs’ YouTube channel. Start here: overview of the ASi standard. Before taking any practical
steps we therefore strongly suggest that you make a careful
www.youtube.com/watch?v=ytX5JOh2_bg
study the data sheet of the IDT ASI4U device [6].

Links and literature


[1] J. M. Jacob, Industrial Control Electronics, page 260 ff.
[2] ASi information: https://www.bihl-wiedemann.de/en/applications/communication/as-interface-and-io-link.htm
[3] AS-International Association: https://www.as-interface.net/en
[4] Phoenix Contact: www.phoenixcontact.com/assets/downloads_ed/global/web_dwl_technical_info/instrecomm10_e.pdf
[5] Pico Technology ASi tool: www.picotech.com/library/picoapp/as-iexpert-network-diagnosis-tool
[6] ASi data sheet from IDT: www.idt.com/document/dst/asi4u-datasheet
[7] DESY (in German): http://www-mks2.desy.de/content/e3740/e5177/e7190/e7997/e8006/e9274/e9656/index_ger.html

www.elektormagazine.com July & August 2019 75


(Almost) everything you always
Q wanted to know about...
Analogue Design
and Circuitry
With answers from Ton Giesberts (Elektor Labs)

Q How can you keep noise in an amplifier as low as


possible?
ence. It can also degrade the bandwidth. Using clamping diodes
tied to the supply voltage rails is a better option. Then you can

A Choose resistor values that are as low as possible, but


make sure that the currents are not higher than the
use a much lower series resistance. However, the diode leak-
age current can cause a large offset with a very high input
amplifier or the individual stages can supply. The feedback impedance, such as with an active probe. In that case you
circuit is also a load for the amplifier. Keep an eye on the max- must use special diodes. The diodes will only affect the band-
imum current needed by the load, and maintain a good safety width with HF circuits. You should bear in mind that the supply
margin. Too much current will also cause more noise and voltage can be lifted if the current through the clamping diodes
increase the distortion. Avoid oscillations. HF oscillation causes is too large. To prevent that, the regulator for the supply volt-
a lot of noise, and it can disturb DC settings and cause higher age must be suitably designed and protected. Another simple
distortion. If you have opamp circuits with unity gain, make solution is to connect a pair of Zener diodes in reverse series
sure you use an opamp type that is unity gain stable. Some configuration in parallel with the input (or a number of diodes
opamps are only stable with an amplification factor of 5 or 10. in series connected in anti-parallel). However, they may influ-
Another trick that’s often used with phono preamplifiers is to ence the input impedance and the linearity to a degree.
connect transistors in parallel in the input stage.  
 

Q How can you keep the distortion in a load as small as Q Why is there an analogue ground?

possible?
A In a circuit with analogue and digital parts, a separate

A Connect the grounds of the input signal, the feedback


and the load to the same point, which is called the star
ground is often used for the analogue part. It is clearly
separated on the PCB to avoid disturbances from the digital
point. The power ground connection must be tapped off from circuitry. In many cases there is also a separate supply voltage
this point. Avoid any other branches in the three connections. for the analogue circuitry. In that case it is a good idea to keep
  the supply currents and the different parts of the circuit well

Q How can you keep the DC offset in an amplifier as small


as possible?
separated from each other. With very sensitive circuits, it may
even be necessary to provide a separate ground for the input

A The simplest solution is to use decoupling capacitors at


the input and output. However, that is not possible if
portion of the analogue circuitry.
 
the amplifier has to pass very low frequencies or DC. For very
low frequencies the capacitors would be much too large. A Q How can you avoid disturbances in and from analogue
circuits?
better solution is to ensure that the DC currents at the ampli-
fier input are as small as possible. With bipolar opamps the A Proper decoupling of the supply voltage is a good start.
One example is ferrite beads in series with the supply
input currents are often in the microampere range. So it is lines of switching circuits. Depending on the bandwidth of the
better to use JFET types, which have input currents in the low disturbance signal, using SMD components may be the only
nanoampere range. The best option is to use types with MOS- solution, with increasingly smaller components necessary at
FET inputs. However, JFET types and in particular MOSFET higher frequencies. They must be placed as close as possible
types have higher input noise, especially at low frequencies. to the disturbance source. Also pay attention to common-mode
Which of the three types you use also depends on the dimen- suppression, since most of the interference generated by cir-
sioning and frequency range of the circuit (see Question 1). cuits of this sort is specifically common-mode. In practice, this
Always carefully check the information and specifications in means that the circuit, and in particular connecting leads, act
the manufacturer’s data sheet. as an antenna and can therefore pick up interference. That’s
  why you see ferrite beads on mains power cables, computer

Q How can you protect an amplifier input against over-


voltage, and what do you need to pay attention to in
cables and the like. The bandwidth and slew rate of the circuit
should also not be greater than strictly necessary. Avoid wide
this regard? loops in the PCB layout; the return current should flow as close

A A resistor in series with the input is one option, but that


increases the noise level and susceptibility to interfer-
as possible to the supply current. If this cannot be achieved
by a trace or a copper surface next to or beneath the supply

76 July & August 2019 www.elektormagazine.com


between the grounds of two different equipment items, caus-
ing currents to flow though the ground connection. A cable in
a disturbance field can also cause this sort of noise. These
problems can also occur with connections between two parts
of a circuit on a PCB. A better option is to use a symmetrical
signal, particular when transmission over a relatively large
distance is required. That is also called a balanced signal. This
actually the only option for achieving a greater dynamic range,
which means how well the circuit is able to process very small
signals. With a balanced signal, you have two identical signals
with opposite phases. Noise on both signal lines will be sup-
pressed by subtraction from the two signals. The resulting
useful signal is twice as large as each individual signal of the
balance connection. This is why high-end A/D converters with
relatively high resolution usually have balanced inputs.
trace, then designing a PCB with four (or more layers) is vir-  
tually unavoidable. Shielding is often necessary with HF cir-
cuitry. Here as well you should check if common mode sup- Q What is often overlooked when making measurements
on a circuit?
pression is necessary for the input and output signals.
  A When you use a multimeter, you should take the inter-
nal resistance into account for both voltage and current

Q hat can cause hum in an amplifier? measurements. In both cases, a measurement error can occur,
and with sensitive circuits, touching a probe to the circuit can

A This question has already been partially answered. Here


we aren’t talking about loose or unconnected cable
also cause instability or even oscillation. That often results in
a much a larger measurement error. An disturbance signal can
shields or unintentional swapping of the signal conductor and also be injected into the circuit, which is something you should
ground. The cause could be the magnetic field of a power bear in mind. In case of doubt, you should use an oscilloscope
transformer in the vicinity of the circuit. In many cases, this to view the signal. Oscilloscope probes are also not perfect;
is dealt with by using a ring core (toroidal) transformer, but they have capacitance (and resistance) that can also cause
ring core transformers also have disturbance fields and the other problems. An active probe can be helpful for very sen-
actual benefit is often less than expected. Shielding with sitive circuits and/or very high frequency signals; active probes
mu-metal may be a solution. A simpler solution is a large dis- often have a higher input impedance and lower capacitance.
tance between the transformer and the circuit, but that is often  
not possible for practical reasons. An advantage of E-core
transformers is that the metal sides where the laminated core Q What types of capacitors should be avoided in audio
circuits?
is clearly visible have a much smaller disturbance field than a
ring-core transformer. For that reason, you sometimes see this A omething that many people do not realise is that capac-
itors — depending on their construction and even more
type of transformer mounted at a 45 degree angle in a corner on their dielectric material — are far from ideal, and that they
of the enclosure, so that these two worst disturbance fields can considerably degrade the quality and performance of a
are located outside the enclosure. Another source of distur- design. Ceramic capacitors are certainly the worst. Depending
bance is bridge rectifiers, which is why four capacitors with a on the dielectric material, the capacitance is voltage and tem-
value of 10 to 47 nF are often connected over the rectifier ter- perature dependent, and they also suffer from microphonic
minals. Particularly with sensitive circuits, such as microphone effects, which means that mechanical vibration or stress can
amplifiers, this disturbance is a potential source of hum. How- generate a voltage in the capacitor. In addition, they suffer
ever, it can also cause problems with radio receivers and other from ageing. In the case of electrolytic capacitors, the capac-
HF circuits. In your PCB designs, make sure that capacitor itance is not stable, and in many cases the value is chosen
charging currents do not flow through or near signal grounds. much larger than necessary to avoid distortion at a corner
Currents through the neutral point must return to the trans- frequency, with the result that the corner frequency is much
former along the shortest possible path. Here as well, keep lower than intended. If you are interested in the subject, try
the distance to the most sensitive parts of the analogue cir- searching for the term ‘dielectric absorption’. A known phe-
cuitry as large as possible. Oscillation – in an amplifier, for nomenon is that after a capacitor has been discharged, the
example – can also cause hum. If that happens, the currents voltage on the capacitor terminals slowly rises. It is better to
can be much higher than usual, causing the supply ripple volt- use capacitors with plastic films, such as polyester, polypro-
age to rise considerably. pylene or polystyrene. The quality often increases with decreas-
  ing dielectric constant. A disadvantage with the better types,

Q What is the best way to convey small signals? such as polystyrene, is that the capacity range is small, with
a maximum of several tens of nanofarads in many cases. Con-

A The simplest way to convey a signal is to use a signal


line with an associated ground. This is called ‘asymmet-
sequently, the most suitable type is in part determined by the
specified value and/or the size of the capacitor.
ric’ or ‘unbalanced’. In the case of a cable, a coax type is often 190099-03
the preferred choice, but a pair of twisted conductors may also
be sufficient. However, there may be potential differences

www.elektormagazine.com July & August 2019 77


An Elektor BoBs Catalog
It’s the little things…

Contributed by Jelle Aarnoudse (Netherlands)

At the Elektor Lab we regularly design


small, but darn handy, Break-out-
Boards (BoBs). Although these are
frequently very popular we nevertheless
often don’t devote a complete article to
them, because there is not always that much
to say about them. That is why in this article we
provide an overview of the recently published BoBs.

SO8-to-DIP8 IoT (Internet


Adapter of Things).
(no. 150797) That is why
We start with a sim- there is an
ple and very small urgent need
Bob, partly because for simple
it was the reason for and, at the
this article. This small printed circuit board, about the size same time,
of one quarter of a postage stamp, can be used to enable secure wire-
modern, often better, chips that only come in an SMD pack- less connec-
age to be used in an older circuit board that was designed tions. This is
to accommodate a DIL8. The chip is mounted on the bottom the reason why there has been, and continues to be, a
between the header pins. A decoupling cap can be mounted rapid rate of development of chips and modules. But the
on the top between pin 4, usually ground, and pin 7 (for datasheets of these are often a complete book and the
opamps, for example) or pin 8 (many other ICs). Available application of which is not user-friendly. That is why we
in sets of five from the Elektor Store. in the Elektor Lab have developed a number of BoBs with
a 433MHz-transceiver, an ATmega328 and a UART. With
MEMS Microphone Adapter the help of the pre-programmed firmware these boards
(no. 150346) are easily employed as a wireless gateway. Command and
It can be even smaller! For the Bat data strings enter your local aether via the UART. Again
DetectorPLUS we required a MEMS-mi- available from the Elektor Store as a ready-to-go module.
crophone which is so tiny and difficult
to solder that we made a small adapter RS485 Module for ECC (no. 130155)
board for it. The module is available For less complicated communication tasks than the one
ready-made from our Elektor Store. Considering the excel- described above, it is very handy if you can quickly connect
lent specifications for this microphone, this BoB is suitable something. For this purpose there is the RS485-module
for many other applications. for ECC (Embedded Extension Connector). This can be
used to provide a microcontrol-
Wireless Gateway (no. 130023) ler board with an RS485-inter-
If something is going to characterize the developments face, which is suitable for reliable
in electronics for the next few years then it the trend of communications, also over larger
everything becoming wireless. And then not in the way that distances and for bus configura-
we have become accustomed in the HMI (Human-Machine tions. Available ready-made from
Interface), but the MMI (Machine-Machine Interface), or the Elektor Store.

78 July & August 2019 www.elektormagazine.com


FT311D BoB BME280 Arduino Shield (no. 160109)
(no. 130516) The BME280 from Bosch is a sensor which can measure
For controlling and temperature, humidity and pressure. This can therefore be
testing of boards you used to make a single-chip weather station. With this Ardu-
have built yourself ino-shield developed
you will nearly always by Elektor Labs, this
require some input chip can be compre-
and output interface. hensively evaluated,
Now nearly everyone using either SPI or
has a smartphone, I2C mode. Because
which is eminently of the built-in level
suitable for this. The FT311D-chip has been especially shifter this can used
developed to connect Android devices via USB to external in both a 3.3 as well
electronics. Now simplicity is not an obvious characteristic as a 5V environ-
of USB, but this chip has a USB-host interface and various ments. Various ver-
interface pins for connecting your own electronics; with sions are available
the FT311D that amounts to seven. In addition, the man- from the Elektor
ufacturer of this chip has already loaded the firmware that Store: the bare
provides a complete USB communications via the AOAM circuit board, the
protocol. In the Elektor Store both a bare circuit board as bare version of the
well as a completely built module are available. evaluation board, an
already fitted I2C-ver-
NFC Gateway (no. 140177) sion and an already-fitted SPI-version.
This is again a communications BoB. Many phones these
days are equipped with NFC, which can be used to exchange CC2A-eBoB Temperature/Humidity Sensor
information across a distance of a few centimeters, for (no. 140154)
example for This fantastic sensor has an accu-
(small) pay- racy of 2% and are individually cal-
ments. This, ibrated and tested. And although is
as electronics comes in an SMD package it is nev-
enthusiasts, ertheless still quite easy to solder
we find obvi- by hand. However: it doesn’t fit in
ously terribly a breadboard of course. That is why
interesting. we made this small circuit board with
How does it a standard pinheader.
work; can we
read such an Elektor Uno R4 (no. 150790)
‘NFC-tag’ or even write it? Yes, this can all be done, but it And finally, this overview cannot forget to include our own
is not all that easy. That is why we developed an NFC gate- Elektor Uno R4-board, a continued development of the now
way for our readers, containing the well-known ATmega328, well-known Arduino R3 board. The R4 has more interface
which takes care of the the protocol matters and in addi- options, is more robust and also more versatile. The ulti-
tion contains an NFC-tag and an integrated antenna. This mate platform for your own IoT developments.
NFC-tag is so difficult to solder that we supply it is a read- (150797)
made Bob, the gateway in contrast is available as a bare
circuit board.

BL600 e-BoB Bluetooth Low Energy Module


(no. 140270)
And another wireless module! The BL600 e-BoB is a bread-
board-friendly interface board for ultra-frugal radio com-
munications. Even
for long-term use a
button cell such as
a CR2032 will suf-
fice! So eminently
suitable for IoT pro-
jects up to about ten
meters, where an off-
line power supply is
not desirable. A ready-to-go module available from the
Elektor Store.

www.elektormagazine.com July & August 2019 79


Err-lectronics
Corrections, Feedback and Updates to
published articles

A Monster LED Clock


with Wi-Fi and
Temperature Display
ElektorLabs 3/2019, p. 60 (180254)
FEEDBACK. This article really sparked my
curiosity. What was interesting was the connec-
tion of sensor boards with the clock using MQTT.
In this way, the project can also be linked to other
projects, e.g. with the IoT Gateway from the March
& April 2017 edition. If you run an RPi, then you can
also install FHEM and use the sensor data there as well.
From the IoT gateway you could possibly develop a low-en-
ergy power-saving sensor for battery operation. The monster clock display could then show other information such
as when mail has arrived. A dot matrix display could be implemented so that you could then display text messages. The
clock could be a good platform for a whole series of projects. You have probably already thought of a lot more possible
applications also.
Frank Klee
 
Thanks for the feedback. In fact, there are further modifications planned for the clock and we would like to incorporate
the facility to exchange data via MQTT into several products. A link between the clock and the weather station is planned,
as well as a modification that will let the clock signal when a doorbell is rung. What is also under consideration is to use
the free IO pins to connect a light sensor or a DHT22 temperature and humidity sensor and show the readings on the
display. These new features are of course updates to the original design and will be presented in an upcoming issue.
Mathias Claußen (Elektor Labs)

9-Channel Relay Switcher Board


ElektorLabs 3/2019, p. 80 (190027)
FEEDBACK. Greetings from Austria! Will there be a
complete kit of parts for this project? It‘s exactly what
I need. However, I have one reservation — the contacts
of the relays used can handle 1200 W AC, but the maximum
voltage is not specified. Although 230 V mains looks poss-
ible the creepage separation between the relay contact pads (ie
the centre contact) are quite close to the tracks carrying low-voltage logic signals.
Manfred Tischler
 
Yes this project will soon be available as a kit of parts (we are currently awaiting its arrival).
The board is designed to switch 230V AC loads, the relay contacts are rated at 250 VAC, 7 A.
The recommended separation distance between tracks to limit the effects of creepage depends on the application and
the standards you need to comply with. In a clean and dry environment, the separation distance can be quite small; in
a dirty and damp environment it needs to be much bigger. The layout of the relay card is designed for use in clean and
dry environments.
Clemens Valens (Elektor Labs)

80 July & August 2019 www.elektormagazine.com


Dual-Anode MOSFET Thyristor
ElektorLabs 3/2019, p. 15 (190017)
UPDATE. This article is attributed solely to Michael Shustov but we should have acknowledged the work of the co-au-
thor Andrey Shustov also.

Dual-Anode MOSFET Thyristor


ElektorLabs 3/2019, p. 15 (190017)
I noticed that this article offers a high-voltage and low-voltage version of the circuit. I don’t like to be pedantic but
according to the  International Electrotechnical Commission (IEC) AC voltage <1000 VAC is classified as ‘Low voltage’
while the 40 VAC version of the circuit should carry the label ‘Extra-low voltage’.
Peter Bitzer
 
Can’t argue with that… many thanks for your observation.
Ralf Schmiedel (Technical Support)

Air Pollution Monitor


Elektor 2/2019, p. 90 (170182)
FEEDBACK. I have an improvement suggestion for this article. Although it is shown in the circuit diagram
it isn’t explained in detail in the text: With the described configuration and the associated sketch, the LEDs
cannot operate in parallel with the OLED display. There really is no need to use the same GPIOs to drive both
the three LEDs and the OLED; the ESP32 Pico Kit has enough free GPIOs to control them both independently. I rebuilt
the monitor and made a few changes so that I can run the LEDs and the display at the same time.
To make the changes it’s necessary to assign the OLED pins to some different connec-
tions of the ESP32, the wiring to the LEDs is in the form of PCB tracks so these can‘t //pin definitions
really be changed without making a mess. I chose to use IO4 for the display DAT (data) #define gasSensorPin 35
signal, IO22 for the display #define btn 9
DC and IO21 for RST on the #define alarmPin 19
display (the display clock #define dispClk 10
signal is unchanged from
#define dispDat 4
the original circuit). The
#define dispD_C 22
sketch must of course be
#define dispRst 21
changed accordingly:
#define STALed 5
 
Once done, it‘s best to go #define APLed 18
through the entire sketch #define alarmLed 23
and search for occur-
rences of STALed, APLed and
alarmLed. In these positions where the commands lines
#ifndef USEDISPLAY ... #endif and in the #else-branch
of #ifdef USEDISPLAY ... and its terminating #endif,
remove these. This is necessary in a couple of places in
tgs2600.ino and network.ino.
Once you have taken care of the changes, you should see
the display operating in parallel to the LEDs which indicate
the correct status of the network connection and the alarm.
The wires to the OLED can be easily soldered to the ESP pins.
Hans Schneider
 
Many thanks for your suggestions and improvements.
Ralf Schmiedel (Technical Support)

180573-D-02

www.elektormagazine.com July & August 2019 81


elektor store highlights
Equipping
Your Maker Lab...
...doesn’t have to cost much thanks to us!

Once you have taken your first


steps along the electronics path
you will have a need for test and
measurement equipment. And this
doesn’t need (in the beginning
at least) to be very expensive
semi-professional ‘stuff’.

OWON XDS3064E
four-channel ’scope with Touch
Screen
The XDS series oscilloscopes from the Chinese brand OWON has down to 1 mV/div (bandwidth limited). The noise of the input
a number of features that you do not (yet) find in comparable stages remains quite small with this, otherwise such a high
models from other brands, and all that for very sharp pricing. sensitivity would make no sense. With the Auto-set button
Here we take a brief look at the very affordable 4-channel you can automatically search for the appropriate settings for
XDS3064E, which has a whole lot to offer for not even € 400. a clear display of the input signal. The Math button does not
When unpacking this oscilloscope, its large display immediately only allow operations to be performed on the signals, but it is
catches the eye, with a resolution of 800x600 pixels plus touch also possible to enter equations yourself. The XDS3064E also
screen functionality. This is not a common feature in this price has an FFT function.
category. After switching on this first good impression is con- In conclusion we can state that if an input bandwidth of 60 MHz
firmed: a nice screen with a good viewing angle. is sufficient for you then this instrument will give you a great
As already mentioned, this is a 4-channel ‘scope with an input deal of measurement enjoyment.
bandwidth of 60 MHz and with a sampling rate of 1 GS/s. While
it is true that the sampling rate drops to a half or a quarter
when multiple channels are used, this is typical for this price
category. The instrument is supplied with four probes, a mains
Function Generator Kit
power cable, a USB cable and a brief getting-started manual.
A comprehensive manual is available as a PDF. from Pulsar Labs
Becoming familiar with the operation of the XDS3064E goes An oscilloscope (such as the OWON model described above) is
quite quickly. However, a few of the functions require some indispensable for seeing what an electronic circuit is doing, but
further explanation and it is then a good idea to consult the such an instrument becomes really useful when we can apply
full manual. The sensitivity of the input channels can be set a suitably defined signal at the input of a circuit. And that is
where a function generator comes in. Here we take a look at
a function generator that we have to build ourselves first: the
@ www.elektor.com open-source function generator from Pulsar Labs.
The assembly of the function generator (although it is not
ªOWON XDS3064E Four-Channel Oscilloscope explicitly described in the supplied manual) should be straight-
www.elektor.com/18829 forward, even for those who are not yet soldering experts. The
most important thing is to take your time, thoroughly check

82 July & August 2019 www.elektormagazine.com


Hand-held 3D Printer
Is it for tinkering or for learning? Don’t torment your brain any
longer: 3D Simo kit is both! When you think about 3D-printing
you may well have a reasonably complicated and noisy device
in mind and not a pen that you can use to draw in three dimen-
sions and various colours. But some time ago, a 3D-tool with
small dimensions made its entry into the world of the tinkerer.
It reminds you of the classic glue gun.
The electric tool can be compared to a 3D-printer in the same
way as a hand-held drill and a column drill press. And much
quieter! Or in other words: it is a PLA extruder that you can hold
in your hand like a pencil so that you can 3D-print manually.
It is designed as a hand tool, light and easy to use, and is
intended for use by enthusiasts of 3D-printing who would like
to take matters into their own hand, literally and figuratively.
It is both a tool for touching up and finishing as well as creat-
ing things manually. The dimensions are 138 x 25 x 21 mm,
and it does not weight more than a few tens of grams. It is
powered from 5 V via a USB cable (which has to be capable
of supplying 1.5 A).
The model described here is also a kit that you have to put
together yourself. The main circuit board is an Arduino Nano.
The 3D Simo kit is open-source: all the design data is freely
available from GitHub (the circuit board files, the 3D-printed
parts and even the software). In other words: everything can
be changed and can be personalised.

how the components have to be mounted and in the event of


doubt, attempt to fit it first and if necessary bend the legs to
the correct size. The only two SMD components are already
fitted on the board, so there is no need to worry about that.
Once the circuit board has been fully assembled and checked
(tip: in the event of doubt, let someone else also cast an eye
over it), the power supply voltage can be applied and the gen-
erator can be tried out.
The generator can generate the three most important wave
forms (sine, square and triangle) and for this price (not quite
€ 60) has a respectable frequency range of 1 Hz – 10 MHz.
Extremely practical is also a sweep mode for quickly deter-
mining the behaviour of a circuit over a wide frequency range.
The maximum output voltage amounts to about 10 V; the offset This kit not only gives you a 3D-pen for manually drawing, but
range amounts to —5 V to +5 V. The distortion of the output is also an object for learning and experimenting. It is there-
sine at 0.7 V and 1 kHz is about 0.1% — not that shabby at fore certainly also very interesting for use in education. .
all. All in all this is a very nice generator that certainly would 180689-D-02
not look silly in the lab of a beginning hobbyist.

@ www.elektor.com @ www.elektor.com
ªPulsar Labs Function Generator Kit Set ªSimo 3D Pen Kit
www.elektor.com/18653 www.elektor.com/18867

www.elektormagazine.com July & August 2019 83


LABS PROJECT

AC-in, DC-out Baristors


Buildings block for application in power supplies
By Michael A. Shustov (Germany) and Andrey M. Shustov (Russia)

In industrial and consumer electronics, the use of thyristors and triacs is known to corrupt the AC
grid voltage to a degree due to harmonics, noise, bursts and transients being superimposed on what
you thought was a clean sinewave from the power outlet. A newly developed composite electronic
device called the baristor can help to keep the line voltage clean yet offer good regulating properties.
This article describes the baristor’s functionality as well as three practical AC-in, DC-out incarnations,
on circuit boards

The barrier-resistor element (barrier + ing zero. Thyristors and triacs allow cut- user requirements;
resistor = Baristor) is a switching ele- ting off almost any part you want of the • you can easily regulate heaters and
ment for power and analogue electron- AC sinewave signal and so control the lamps with thyristor or triac based
ics, whose electrical “input-output” resis- effective power fed to the load. But they circuits;
tance changes abruptly from conducting have some disadvantages: • are suitable for use in power supply
to non-conducting and vice versa. The units to generate different output
desired “state” is obtained when a pre- • low switching performance; voltages.
determined threshold value (“barrier”) of • no turning off without interrupting  
the input signal is reached. Symbaristors current through device; As a radical thought, consider that the
are symmetric baristors intended to oper- • distortion of AC line sinewave; switching in thyristors and triacs occurs
ate on alternating current (AC). • power factor reduction; on the “horizontal” axis (i.e. with time)
• low economic efficiency. while with baristors, switching occurs on
Baristor vs. SCR   the “vertical” axis (i.e. with voltage). This
In power electronics, SCRs like thyris- The above drawbacks can be overcome feature of the baristor opens fundamen-
tors and triacs are known as commuta- to a large extent by baristors and sym- tally new opportunities for its use in com-
tion elements capable of switching from baristors which: munications equipment and power elec-
a non-conducting state to a conducting tronics. Baristors are intended to sepa-
state when their gate electrode is ener- • enable an AC-current signal to be rate signals whose amplitude is above or
gized. They are switched off when their divided into segments of adjustable below a predetermined threshold value
instantaneous anode voltage is approach- width and using them according to (barrier) set by the user.

84 July & August 2019 www.elektormagazine.com


Types of baristor, and
applications D5
K1
Baristors can be categorized as: D2 D1
1N4007
• Controlled and uncontrolled (i.e. 4x 1N4007
T4

with a controlled or an uncontrolled R2

threshold value); D3 D4 BD139

680
T1
• AC or DC (asymmetric and symmet- T3

ric baristors — symbaristors); P1 BC557


BC557 K2
• Single-channel or multi-chan-
100k T2
C1
nel (multi-level, multi-threshold
LOAD
baristors); R1 R4
470
BC547 50V

220k
• Switches of type: On/Off/switchover.

680
 
R3
Here are the names with the family

5k1
picture.
High-level baristor: the voltage at the
output occurs only in the case when the 180533-006

input voltage level exceeds a certain


threshold value.
Figure 1. Basic (‘starter’) version of a single-threshold baristor as developed out of a concept
Low-level baristor: the voltage at its
discussed in the book “Electronic Cicuits for All”.
output is present as long as the input
voltage level exceeds a certain threshold
value. After that, the baristor changes
Performance, Single-threshold Baristor
its state and turns-off the load.
Switching single-threshold baris- Reference: circuit in Figure 1. At 20 VAC input voltage the output
tor: as it rises gradually, the input volt- Some measurements results using voltage was seen to drop from 9
age is initially present at the low-level 150-Ω load and fixed setting of P1: to 6.7 V when the load resistance
signal output. After exceeding a certain   was halved to 75 Ω. At certain input
threshold value, the input signal is auto- AC in   DC out voltages and settings of P1 the output
matically switched over to the high-level 12 V 11.4 V voltage was observed to fluctuate over
output. 16 V 9.9 V time. No-load current can be under
Switching multi-threshold baristor: 20 V 9V 1 mA but also a few mA, depending
By continuously increasing/decreasing on the setting of P1, input voltage and
24 V 8.6 V
the input voltage a sequential switch- load removal.
ing-over of the baristor outputs occurs
and thus the input signal is passed on to
the baristor outputs. Thereby the input
signal being passed-through indicates • systems for multichannel remote neered by Ton Giesberts of Elektor Labs,
the corresponding voltage range. control and communication systems from a version found in the above-men-
  including a HF signal superimposed tioned book.
The use of baristors and symbaristors on a two-wire line; As long as the voltage at the output
allows distribution or redistribution of • measuring instruments and of the bridge rectifier D1–D4 (about
AC-power between consumers of elec- transducers; 16 VAC is used in this case) remains
tric energy, to suppress higher harmonics • devices for pulse technique; under the threshold set by T1/T2, “com-
of the line voltage, to increase (i.e. cor- • isolation, separation or generation of posite transistor” T3/T4 is conducting.
rect) the power factor, to use a part of signals; The actual voltage level from D1–D4
the sinewave rationally that SCRs “throw • analogue electronics for signal sepa- minus the voltage drop across T4 gets
away”. All these features should help to ration into components using a user- stored in buffer capacitor C1. If the input
increase the efficiency of electric energy set threshold value. voltage exceeds the set threshold, T4
use significantly, as well as to improve   blocks and the output voltage does not
economic effectiveness. Barrier-resistor If you are interested in knowing more increase further. This way, depending on
elements can be applied in the follow- about the origins of the baristor and its the threshold level set by T1/T2, the DC
ing areas: theory of operation, get a copy of the output voltage can be set on P1. Replac-
authors’ book “Electronic Circuits for All” ing P1 with an optocoupler or a JFET
• miniature economic power supply published by Elektor; details are given in permits the output voltage to be con-
units with low losses; the @ www.elektor.com box. trolled by another circuit. If the applied
• voltage converters and voltage AC voltage is higher than 16 V or so,
stabilizers; Baristor #1, the basic one resistors R3 and R4 should be changed
• protection of electronic components Moving on to practical incarnations of the accordingly. Depending on the values
and circuits as well as electric power baristor, Figure 1 shows the schematic of R3 and R4 and other conditions, the
equipment and communication lines. of a single-threshold baristor post-engi- current-voltage characteristic of the cir-

www.elektormagazine.com July & August 2019 85


component list

cuit around T1/T2 varies from "thyristor" A positive feedback network R7–C5 was But be careful using a TO92 packaged
to "Zener diode". The problem with this added to suppress erroneous switching device for T3 and T6 — due to the lim-
is… it’s not really a Zener diode. With T1 and to enhance switching of the output ited power dissipation of this housing it’s
and T2 not conducting, current still flows stages. This makes the base of T1 act wiser to use a larger case style. In the
through R2-P1-R1-R3. So if P1 is too low like the input of a Schmitt-trigger. Due end we used the good old BD139 in com-
in value or R3 too high, T3 may switch to the hysteresis, which depends on the bination with a standard BC547C to make
on or off, i.e. there’s no real threshold AC voltage applied to K1, the phase set a discrete Darlington replacement for the
and the output voltage will vary with the on P1 changes with the level of the input originally used BC373. The BD139 has a
AC input voltage. Also, some very low voltage. Depending on the application SOT32 (TO126) case style and allows a
frequency instability can occur at cer- and AC voltage used the values of some maximum power dissipation of 1.25 W
tain settings of P1 in combination with components are subject to tweaking, for without additional cooling (i.e. the junc-
different AC input voltages. Worse, the which simulation software like LTSpice tion will be 150 °C at room temperature,
output impedance of the transformer comes in handy. Using a voltage source 25 °C). Never operate a transistor at a
affects the operation and stability of the instead of a “real” transformer in the junction temperature of 150 °C, keep
circuit. A 10-µF capacitor from the base simulation will give false results. Every it well below 70 °C if you don’t want to
of T4 to ground can improve circuit sta- transformer has a complex output imped- reduce its lifespan. And why not use a
bility. A change in load resistance will ance consisting mainly of a combination BD679 Darlington to reduce the number
change the output voltage. of a resistance and an inductance. As a of parts, you might ask? Well, almost all
Some salient measurement results result, the moment the Baristor switches, Power Darlington’s have internal resis-
obtained with a practical construction of the input voltage changes and can cause tors in parallel with the base-emitter of
the circuit are given in the text box: Per- instability, especially when the gain of both transistors. These inevitably cause
formance, Single-threshold Baristor. T1 is high. the gain of the transistor to vary with
The original circuit found in the book the collector current, while at low cur-
Enhanced Single-threshold used high voltage Darlington transistors rents the gain is much lower than that
Baristor type BC373 which sadly proved hard to of Darlingtons without internal resistors.
The circuit in Figure 2 is again based find. The specifications are: 80 V / 1 A Back to the circuit diagram, the maxi-
on an outline found in the ‘Electronic in a TO92 case style. The parameter hFE mum voltage drop from K1 to K2 or K3
Circuits for All’ book. at 100 mA is quoted as >20000. Fortu- is about 4 V at 100 mA. This is due to
Its purpose and intent isn’t so much a nately there are quite a few replacement D1–D4 and a small voltage drop across
fully working device as a circuit that can types that are still available, including R4 and R6 and the base-emitter volt-
be modified to fit your own applications BCX38C (60 V / 0.8 A); KSP13B (30 V / ages of T2/T3 and T5/T6. Hence with-
or just give new ideas or be part of a 0.5 A); MPSA14, (30 V / 0.5 A); MPSA29 out extra cooling of T3/T6 the maximum
solution for other purposes. Sure, the (100 V / 0.5 A); ZTX603 (80 V / 1 A); output current should be limited to a few
PCB designed by Elktor Labs for this cir- ZTX605 (120 V / 1 A); ZTX614 (100 V 100 mA.
cuit does make testing and experiment- / 0.8 A); BC517-D74Z (30 V / 1.2 A but Removing D5 will increase the range of
ing easier but the circuit is simple enough with its collector and emitter connec- P1 and has more effect at low input volt-
to be tested on a breadboard. tions swapped! ages. To change the range of P1 at high

86 July & August 2019 www.elektormagazine.com


C2 C1
K1 47n 47n T6
D2 D1
R6 BD139
T3

6k8
4x 1N4007
R4 BD139 T5
P1 K2 K3

6k8
D3 D4 100k
T2
C3 C4
BC547
47n 47n D5

BZX79C3V0
BC547
R2

1M
R7 C5
1M5
T1 1n T4
R5
330k
R1 R3
BCX38C BCX38C

180k
56k

180533-008

Figure 2. This version of the baristor has enhancements and refinements compared to the basic version. It should offer many possibilities for
experimenting and adapting to your requirements.

Performance, Single-threshold Baristor, Enhanced Version

Reference: circuit in Figure 2. With equal load impedances on K2 and K3:


An example of maximum phase angles at minimum and • Input current: (Uin – 3.2 V) / Rload, measured at 300 mA
maximum setting of P1 (18 V at K1): (K1) and 75-Ω loads.
• P1 fully clockwise: 29° - 148° • Input current: (Uin – 3 V) / Rload, measured at 120 mA (K1)
• P2 fully anticlockwise: 79° - 126° and 75-Ω loads.
• No load current: 1.71 mA (12 V at K1) With two identical loads connected to K2 and K3 the input
• No load current: 3.75 mA (24 V at K1) current is virtually independent of the setting of P1 and varies
◦ only slightly, a few percent, due to component tolerances.

component list

www.elektormagazine.com July & August 2019 87


Baristor, Enhanced Version text box.
D6 Our test setup used a variable autotrans-
K1
D3 D1
1N4007
former, also known under the trademark
T4 name Variac. It’s used to vary the pri-
4x 1N4007
mary voltage of a “safety transformer”
R3
D4 D2 D5 BD440 T3
type FL30/12 from Block. This has two

1k
primary windings of 115 V and two sec-
BZX55C4V7
R1 BC547C
ondary windings of 12 V able to supply
K2
1.25 A each. This way a safe test setup

10k
T1
C1
is guaranteed. But be very careful in this
LOAD
4700 setup. The maximum output voltage of
50V
T2
the autotransformer is typically higher
2x BC547C
than the input voltage. Labs used one
R2 that is still specified for use with the old
220 V mains voltage. The output is spec-
10k

ified as 250 V / 2 A max. At the pres-


180533-010 ent time, with the mains voltage upped
to 230 V nominally, the no-load output
voltage will be even higher, like 261 V.
Figure 3. This baristor version is the result of seeking a tradeoff between component count (low)
But it’s even worse when measuring the
and stabilisation (high).
actual output voltage, a whopping 274 V
was found with the mains voltage reach-
input voltages consider changing R1 and it is less than the rated working voltage. ing 239 V at the test location. In any
R3 also, and maybe the working voltage We have again grilled this circuit in the case, never adjust the autotransformer
of D5. But due to the low current flow- Labs and the results with comments are to its maximum voltage in this test setup.
ing through D5 the voltage drop across in the Performance, Single-threshold This will most certainly destroy the safety
transformer connected to it.
In a first test a small transformer was
used and R7/C5 were enough to get rid
of the erroneous switching. But using
component list the test setup as described above this
wasn’t enough. The four diodes of the
rectifier had to be decoupled with 4 off
47 nF anti-rattle capacitors.

Parts count down,


stabilisation up
To give an idea of further enhancements
and optimizations within easy reach,
a petite baristor circuit was designed
that produces a DC output voltage less
dependent on load and AC input voltage
while using a minimum of parts. The
principle is simple. The output stage acts
as a switch and needs to be turned off as
soon as the input voltage exceeds a cer-
tain threshold. The latter is set mainly
by Zener diode D5. Here R1 limits the
current at higher input voltages while R2
makes sure some current flows through
the Zener before discrete Darlington T1/
T2 turns on. T1/T2 pulls the base of
composite transistor T3/T4 to ground,
thereby turning off the output switch.
To minimize the drop across T4 a com-
bination of an NPN small signal and a
PNP power transistor is used, saving a
few tenths of volts. To make the drop
due to the base current through R3 even
lower, the value of R3 is a mere 1 kΩ.
This latter means a .25-watt resistor

88 July & August 2019 www.elektormagazine.com


will dissipate its maximum permissible
Performance, Dressed Down Baristor
power at 21 V input voltage. Any mea-
surements with input voltages above Reference: circuit in Figure 3. At low loads most input current is due
21 V will exceed the safe specs for R3. Measurements results with T4 = to R3 being pulled to ground by T1/T2.
In that case use a .5- or .6-watt resis- BD440 and 150-Ω load: For use with very low loads consider
tor in lieu of .25 watt. There are also increasing the value of R3. The drop
types with a 1-watt specification in this Uin Iin Uout Uripple across T4 may increase but it may
package. Mount such resistors slightly [V] [mA] [V] [mV] increase overall efficiency. Something
above the PCB. Dissipation will be larg- AC AC DC ACpp to experiment with.
est with no load. 5 44 4.28 24 Another quick test with a much higher
Since the T3/T4 will be turned off per- 6 64 4.48 56 load of 10 Ω was also performed. At
manently the voltage across R3 is almost 7 74 4.46 60 12 V input voltage the input current for
all the input voltage, minus the voltage a 10-Ω load equals 0.57 A. The output
8 80 4.44 60
lost across the bridge rectifier. The fact voltage was 3.99 V. But T4 ran hot
9 85 4.43 60
that T1/T2 turns on above a certain volt- without cooling! Efficiency is not great
age doesn’t change much. With a Zener 10 89 4.42 60 but is more complex than multiplying
of 4.7 V (.5 W) the output voltage is 11 92 4.42 60 voltages and currents since currents
approximately 4.4 V with a 150-Ω load. 12 94 4.41 60 and voltage inside a baristor are far
A 10-Ω load reduces the output voltage 13 96 4.41 60 from sinusoidal.
to just under 4 V. No-load voltage is 14 98 4.40 60
about 4.67 V. Originally we used a good
15 101 4.39 60
old BD140 and at low output current
16 102 4.38 60
it worked well. But with a higher load,
such as 10-Ω resistor, it almost imme- 17 104 4.37 60
diately short circuited. Our test setup is 18 106 4.36 60
able to deliver a nominal 1.25 A AC RMS 19 109 4.36 60
current, so peak even more. A BD140 20 110 4.35 60
can handle 1.5 A peak currents which 21 110 4.34 60
especially with a large capacitor at the
22 111 4.33 60
output is not enough. It got replaced
23 112 4.33 60
with a BD440 from old stock but this
type is still available (BD440S, Mouser 24 113 4.32 60
# 512-BD440S). The BD440 is a 60 V/
4 A (7-A pulse) PNP power transistor.
There are other suitable candidates in at the bridge rectifier occur these can be Remember, they are not current limited
a TO-126 (SOT-32) package to replace reduced by inserting a diode between or protected against overloading. Also,
T4, like 2N5195 (PNP, 80 V, 4 A), BD438 D5 and R3. the case temperature of the output power
(45 V, 4 A) or BD442G (80 V, 4 A). And again we tested the circuit in the transistors should be monitored at higher
Depending on the manufacturer lead Elektor Labs, for some results see the loads and input voltages. Play it safe and
spacing can differ somewhat, instead text box: Performance, Dressed Down attach a small aluminum plate or similar
of 2.29 mm, 2.39 occurs (TO−225AA). Baristor. contraption to the power transistor(s)
Also the transistor package can be a lit- casing for cooling.
tle bigger like 14.2 x 8 mm2 instead of To your irons! (180533-01)
the original TO-126 dimensions of 11.1 x Although all three circuits were found to
7.8 mm. Fortunately all of these should be working, they are experimental and
still fit on the PCB. The footprint for not to be considered ready-engineered
(large) buffer capacitor C1 is designed projects for use in industrial applications.
for capacitors with a lead spacing of 5,
7.5 and 10 mm and a maximum can
diameter of 22 mm (no snap-in pins,
just straight leads). @ www.elektor.com
The output voltage can be made adjust- ªElectronic Circuits for All, by M.A. Shustov and A.M Shustov.
able by replacing R2 by a potentiome- www.elektor.com/electronic-circuits-for-all
ter. The output is indeed adjustable then ªSingle-threshold Baristor, bare PCB no. 160512-1 v.1
but at higher voltages it gets increas- www.elektor.com/160512-1
ingly dependent on the input voltage.
ªSingle-threshold Baristor, Enhanced Version, bare PCB 160512-2 v.2.1
The voltage across R1 will increase more www.elektor.com/160512-2
with a lower value of P1 and becomes
ªDressed-Down Baristor, bare PCB no. 160512-3 v.1.0
more dominant than the Zener voltage. www.elektor.com/160512-2
To set a different output voltage it’s best
to change the Zener voltage. If surges

www.elektormagazine.com July & August 2019 89


HomeLab Helicopter
Wondrous Things Electronic Spotted From Above
By Clemens Valens (Elektor Labs)

Blockchains,
the Universe, and Travelling Through Time

Over the past


months, the word block-
chain has become an important
buzzword that is said to help selling content. Mention block- ation. Furthermore, every new signature must be accepted
chain and you have an audience. The fact that you are reading by several verifiers. Modifying the contents of a block some-
this proves my point. where in the chain requires updating the signatures of all the
But what is a blockchain? Loosely after Wikipedia we can define blocks that follow, to prevent the blockchain from becoming
it as a chain of blocks where each block contains a signature (a invalid. If updating one signature is “complicated” — imagine
‘hash’) of the (contents of the) block preceding it, a timestamp, the effort needed to update several hundred or thousand of
and transaction data. Calculating the signature of a block is them! A blockchain is therefore quite resistant to modification
complex, making this an expensive and time-consuming oper- of the data it contains.

90 July & August 2019 www.elektormagazine.com


Soon on
a breadboard near you
Even though blockchains tend to be associated with cryptocurrencies, the Internet of Things (IoT,
buzzword 2) is another interesting domain for blockchain-based secure data communication. By
the time you read this, Egypt-based startup Elkrem should have terminated — successfully? —
their Kickstarter campaign for their Blockchain IoT Development Board.

In the real world


Some time ago it dawned on me that it is possible to transpose the concept of virtual blockchains
to the real world. Imagine that the state of the Universe at some moment, say t0, can be captured
in a block. The state of the Universe one moment later, at t1, is almost identical to the previous
state but not completely as some particles have moved. Because the particle movements were
guided by the Laws of the Universe, its new state is accept-
able — the signature is valid — and it may be
chained to the block preceding it. The

greater the distance in time


between two states, the bigger their
differences will be, yet one state always
follows naturally from the state preceding it. Also,
since each block represents a state of the Universe,
the total contains an enormous amount of information (Big
Data. Ding! Ten points for placing yet another buzzword).
After this introduction it is (hopefully) easy to make the step to time
travel (which may be the real reason why you started reading this article). Sup-
pose you want to travel back in time. How far exactly doesn’t matter, be it one
nanosecond or 1,000,000 years or more, the reasoning is the same. Let’s place block
t0 at the beginning of time, and the present, “now”, at tn. You travel back in time by
adding yourself to the state contained in block tn-m (with m<n). To make this possible,
you will have to update all the m blocks that follow. That this is not going to be easy will
be clear. Adapting the next state, tn-m+1, to make it accept the addition of a single particle will
already be difficult, doing it for the displacement or removal of the air molecules needed to insert
your body probably is impossible. Even if you could, it would require a lot of energy (but where
would that come from?). And then you must do it again for states tn-m+2, tn-m+3, and so on.
You could limit the amount of calculations needed by keeping your presence in the past very short,
a few states only, so that the disturbances you created can die out quickly, allowing later states
to remain unmodified. Your impact on the past must be as little as possible.
Even if we suppose that you can solve these problems, then you will have to face similar issues
when you return to the present. Any dust particles or memories — a state change of the brain —
you picked up during your visit in the past will have to be accounted for in the states that follow
your visit. To avoid this mountain of work, you should not bring back anything from the past to
the present. Unfortunately, this renders time travel rather pointless.

www.elektormagazine.com July & August 2019 91


Wormholes

e. Well,
rough tim
w fo r tr avelling th y
es might al
lo terminolog
eo ri es , wormhol b lo ck . In blockchain
to some th e same
According block to th forked?”
e than one iverse be
ou t w ormholes? in g m or ti on , “C an the Un e
clamour, w
hat ab rbids chai n
er the ques e alternativ
I hear you es to o as nothing fo (H om ew ork: answ n ot h av e to link to th
wormhol forward. er does the
s can have ore paths n. The latt ould create
blockchain e re su lt is two or m ck ea rl ie r in the chai te ri n g th at block w
d th to a blo e past, en
d a fork an loop back block in th
this is calle e paths could o back to a
of th es t yo u g would
ds.) One e would le s exist, we
in 500 wor , ev en if a wormhol ye t ex is ts. (If it doe ture
lock. Howev
er that not wise the fu
previous b en ti on ed above.
en te ri n g a state t n+f re ad y kn own, other
e ones m ld mean s are al t state
lems as th l, that wou l our action the presen
same prob to th e future? Wel w ou ld im ply that al th at at ta ches it to the
g alogy this h the path plies that
out travellin ckchain an gether wit ain. This im
So, what ab g th e b lo st at e to b lo ck ch
the past. Fo
llowin create this as they fo
rm a valid and less en
ergy-
be living in ill have to u, as long uch easier
g , free w ill.) You w u p to yo ld b e a m
n path is ay wou
valid. So lo ake up this reaming aw
would be in e st ates that m u r eyes and d
re th in g yo
u configu ply clos
t n. How yo ination. Sim e future.
your imag
dep en d s on elling to th
future only al te rn at ive for trav
valid
yet equally
consuming

The crystal NaSn2As2 can be both


electron-holder and hole-holder,
potentially eliminating the need for
multiple layers in semiconductors.

92 July & August 2019 www.elektormagazine.com


Must-have
Homelab Tool
Every once in a while you want to measure a voltage
or current in a place where it is difficult to look at
the multimeter’s display while holding the probes
in place. A Bluetooth multimeter like the one shown
here can help out in such situations. A connected
device like a smartphone acts as a mobile display
that you put in a place where you can actually look at
it. If even this is not possible, then the smartphone
can read out loud the captured values while you
concentrate on the probes. Even though these handy
functions alone make such a multimeter qualify as a
must-have homelab tool, there is more. Data logging
and graphing and even multiple meters displayed on
one phone. Cool, huh?

www.elektor.com/owon-ow16b-digital-multimeter-
with-bluetooth

Smoking Really
Is Dangerous

Okay, so you knew that already. Maybe you replaced your traditional tobacco-based cigarettes by a hopefully
safer e-cigarette? The long-term health risks of the e-liquids used by these devices are still unknown, but you
probably knew that too. What you may not know yet is that in the French village of Plougoulm a man got burned
when the battery of his e-cigarette went up in smoke after short-circuiting with his car keys in his trouser pocket.
According to the victim, after hearing an explosive sound, a 40-centimetre long flame shot out of his pants. When
trying to remove the burning (!) e-cigarette, the man injured his hand. (I guess he was lucky to get away with
just that.) Similar incidents involving coins have been reported too.
But there is worse. In Fort Worth, Texas, USA a man got killed when his e-cigarette exploded in his face and cut a
major artery in his neck.

www.elektormagazine.com July & August 2019 93


LABS PROJECT

ESP32 as a Time Server


ESP32 plus RTC plus GPS plus display
equals an NTP server on your own LAN
By Mathias Claußen (Elektor Labs)

Sometimes an NTP server on your own local network can come in very handy. As well as situations where
your network is cut off from the Internet but various pieces of software need a time reference, there are also
cases where you are developing a project that requires the ability to fetch time data over the Internet, but
you would ideally like to create custom NTP data. As the following guide shows, achieving all this and more is
(relatively) easy.

Figure 1. The NTP server consists of these four modules.

The executive summary is that an NTP tery-backed real-time clock (RTC). This erence (a quartz crystal). It is therefore
server is a device that sits at a given supplies the time and date information to a good idea for the computer’s operating
Internet address and, when sent a suit- the OS, which in turn provides it to soft- system to calibrate its RTC time periodi-
able request, returns the exact time ware running on the device. The informa- cally against an external reference. And
using the Network Time Protocol (NTP). tion is needed for much more than just that is where NTP comes in.
If you would like to know the details of the calendar app: many of the essen- It is of course possible to calibrate the
how the protocol works, Wikipedia and tial operations of the machine, such as time using the DCF77 or GPS signals, but
the like are your friends. ensuring that files that are created or using a bit of software to interrogate an
In order for PCs and other small com- modified are correctly time-stamped, NTP server is simpler and cheaper than
puters that have an Internet connec- rely on it. specially-designed hardware. And fur-
tion can know the exact time (and date) However, the time needs to remain accu- thermore both these time sources have
immediately that they are switched on, rate over the long term, and not depend their own disadvantages: the DCF77
they almost universally include a bat- on the accuracy of the RTC’s internal ref- transmitter near Frankfurt in Germany

94 July & August 2019 www.elektormagazine.com


has a considerable, but not infinite, range continuously, we also provide a small tor store was added. The ESP32 module
and is not easy to receive overseas. While display. Last, and by no means least, we we chose comes with an OLED display
GPS can be received around the globe, need the software to bring the server to already fitted. This display is configured
reception is often not satisfactory inside life, and we will look at that below. to respond to I2C address 0x7A rather
buildings as many are built from materi- than the more usual 0x78, which allows
als which severely attenuate the high-fre- History the possibility of connecting a second
quency satellite signals. And so NTP is Our mini NTP server was first constructed external OLED display at address 0x78.
the standard for time calibration. in 2018 for an exhibition in France, where The U8G2 library that we used allows dif-
Elektor had a stand. This first incarnation ferent display addresses to be selected,
A DIY time server? was based on an ESP8266; the other and so we arranged for the built-in dis-
The question remains: why bother mak- ingredients were just a DS3231 RTC chip play to show date and time (in GMT), the
ing your own time server when there and a small 0.96 inch OLED display. The IP address of the NTP server on the local
are plentiful public, freely-accessible NTP server allowed all the items on display network, and the status of the ESP32
servers on the Internet? on the stand to receive time data even (access point or client). On the second
As we mentioned in the introduction, when no Internet connection was avail- display we showed local time and the GPS
there are situations where the not incon- able or if the connection was too poor. position. And finally we found a spare
siderable effort of building your own NTP This prototype was also pressed into ser- DS3231 module in the lab that we could
server makes a lot of sense. There are vice at Electronica 2018 in Munich, Ger- use. With that, the hardware update was
networks that, for very good reasons, many. Subsequently in the Elektor labs it complete.
are not connected to the Internet; and
such isolated networks will still as a rule
include computers and other devices that
need to know the time. Setting the clocks
on all the network nodes manually when-
ever needed, and having to adjust them
every month or two, is no fun at all.
Also, anyone developing devices and/or
software tools that need to fetch time
data over NTP will find it extremely con-
venient to be able to control the data
sent out by the NTP server for testing
purposes. Indeed, in past issues of this
magazine we have described several pro-
jects that use NTP data. Moreover, access
to a device located on a local network is
quicker and more reliable than access
over the Internet. Another application
for a local NTP server is when operat- Figure 2. The sandwich comprising the ESP32 module with integrated OLED display, the RTC and
ing a large number of diverse connected GPS modules, is connected up with flying leads.
devices, which must operate together as
synchronously as possible.
So there are many reasons why one was used as a source of time information Modules
might want to build and operate one’s for various clock projects and Raspberry To make our new NTP server the above
own NTP server, and more will probably Pi-based designs. For this the ability to ingredients must be stirred together as
occur to you. The hardware required is manipulate the NTP data came in very shown in Figure 1. There are four com-
nowadays available at very low cost, and handy. ponent modules in total: at the heart of
the server can easily be built from ready- The first version of the server was fitted the system is the ESP32 module, and
made modules. For our purposes the with an RTC chip that showed consider- accompanying it are an OLED display with
processing power available in an ESP32 ably poorer timekeeping accuracy than SSD1306 controller, an RTC module and
module is more than enough, and this expected from the DS3231’s specifica- a GPS module. Using the ESP32 module
module also provides for a wireless con- tions. This rapidly became annoying, as with on-board OLED display saves a bit
nection to the network which allows it to the time had to be reset every month. of space in the design. Together with the
be physically placed almost anywhere While that is no problem over the dura- DS3231 RTC module and the GPS module
convenient. The actual time information tion of an exhibition, in our labs it rap- it can be assembled into a compact sand-
for our NTP server project will come from idly became impractical. And so the NTP wich, as shown in Figure 2, for which a
the GPS signal, for which low-cost ready- server hardware needed an update. suitable enclosure was 3D-printed (see
made modules are again available. We The first change was to replace the Figure 3). The result is a small and,
will add a real-time clock for backup in ESP8266 module with the more mod- most importantly, mobile NTP server that
case the GPS signal cannot be received ern ESP32 version, and, to enable auto- can be used anywhere that its built-in
or if there is interference, and, so that matic time synchronization with the WLAN can find a connection and where
we can monitor the state of the server GPS signal, a receiver from the Elek- GPS signals can be received.

www.elektormagazine.com July & August 2019 95


An important point to note is that the
pins that drive the I2C interface of the
RTC from the ESP32 are not the con-
ventional ones: instead, the SCL line to
the RTC is connected to GPIO4 and the
SDA line is connected to GPIO5. The GPS
module uses a normal serial interface,
with GPIO13 as the receive (RX) pin and
GPIO15 as the transmit (TX) pin. The RX
pin of the ESP32 should be connected to
the TX pin of the GPS module, and the
TX pin of the ESP32 should be connected
to the RX pin of the GPS module. Both
modules require a 5 V supply: the power
and ground connections come directly
from the ESP module. The one pulse per
second output of the GPS module (pin 5)
should be connected to pin 25 on the
ESP32 module. Figure 4 shows the wir-
Figure 3. The items of Figure 2 fitted into an enclosure made using a 3D printer.
ing that is required.
In order to see what kind of problems our
yet-to-be-written software will have to
address, we can first take a look at the
freely-available ESPNTPServer code [1].
For the ‘real’ code we will recycle some
components from other Elektor projects,
in particular the time correction function
in the Pinball Clock [2] as well as its abil-
ity to synchronize itself with a variety of
sources with differing priorities.
For the RTC it is possible to use a DS3231
or a DS1307. After start-up the processor
looks for an RTC device at I2C address
0x68: if a response is received then the
code assumes that a type DS3231 RTC is
connected. If you wish to use the DS1307
you will need to recompile the code with
the line in Firmware.ino that says RTC_
DS3231 rtc_clock; modified to read RTC_
DS1307 rtc_clock;.
The RTC provides time information when
no GPS signal can be received or if the
Figure 4. The electrical connections between the three modules. module is not present. The server will
also work if the ESP32 cannot find an RTC
device: in this mode the ESP32’s clock is
initialized to midnight at the beginning of
January 1, 1970, and will be updated the
The Pulse Per Second interrupt first time that any GPS data are received.
The software configures GPIO25 for the PPS (pulse per second) interrupt, with the If both RTC and GPS modules are not
internal pull-up resistor enabled in order to ensure that the pin does not take on present then the NTP server will still run,
an undefined voltage level. The interrupt is triggered by a rising edge on the pin, but in this case the time must be manu-
and the function handlePPSInterrupt is called. This function must be declared ally set and adjusted from time to time.
with the IRAM_ATTR attribute, which forces it to reside in the RAM of the ESP32. And perhaps it goes without saying that
Code not residing in RAM executes more slowly, because of the need to access the the NTP server is configured using its
external flash memory. Or even worse: if the flash is turned off then an exception own web page.
will be triggered and the ESP32 will reset itself. The use of floating-point variables
in interrupts can also be problematic, as using the floating-point unit in interrupt NTP data
code in the current version of FreeRTOS can lead to difficulties and unexpected NTP uses UDP (user datagram proto-
results after the return from the interrupt. The call to xSemaphoreGiveFromISR at col) for the transmission of data pack-
the end of the interrupt service routine triggers the update of the OLED displays. ets. The NTP server sits listening on port
123 for an incoming NTP request and

96 July & August 2019 www.elektormagazine.com


replies with a standard packet of length Time sources
56 bytes in the NTPv4 format (described As previously mentioned, the NTP server
in RFC 5905). The components of the operates with two external sources of
datagram are illustrated in Figure 5. LI, time information. One of these is the
VN and MODE are bit fields: LI indicates RTC, and the other is the GPS and its
whether a leap second is to be inserted one-pulse-per-second output. This lat-
at the end of the current minute; VN ter output, which is used to trigger an
indicates which version of the protocol interrupt, is only used when it is avail-
is being used; and MODE represents the able: under poor reception conditions it
operating mode of the system (in our can drop out. If the signal is present the
case, ‘server’). system uses the GPS seconds counter; if
Root Delay refers to the distance between it is not, an internal counter is used. The
this time server and the next. Since ours one-pulse-per-second signal is monitored
is the only time server in the (local) using the following algorithm. If no pulse
world, we set this field to 1. The Stra- is seen for 1400 ms, then the system
tum field is also set to 1 as there is no assumes that the GPS signal is lost, and
NTP server between our server and the switches over to its internal time source.
GPS reference. The Root Dispersion field That involves immediately adding one
is also set to 1. The possibility of leap extra second to the time (correspond-
seconds is ignored, and for the Reference ing to the first missing pulse), and then,
Identifier field the value ‘PPS’ (‘pulse per 600 ms later (that is, at the point where
Figure 5. Structure of an NTP datagram.
second’) is used, indicating that the serv- the next pulse would be expected), add-
er’s timekeeping is governed by a generic ing a further second.
1 Hz signal. When a GPS signal is received the module
Times are reckoned in seconds from the outputs time information. It is sufficient
beginning of January 1, 1900, which is to check the GPS time information only Inter-process communications are used
70 years or 2208988800 s before the once every ten minutes and synchronize to tell the task once per second that the
start of the ‘epoch’ used as the refer- the internal clock or external RTC: as contents of the displays needs to be
ence for time in the Unix kernel. Time- long as reception continues, the precise recomputed. The display task remains
stamps are represented by two 32-bit one-pulse-per-second output is adequate idle, consuming no processing resources,
fields, one for the number of integer to advance the ESP32’s internal clock until a semaphore is activated.
seconds and one for the fractional accurately. Also, a mutex is used to prevent the main
seconds. The Reference Timestamp is For some purposes it is desirable to dis- loop or the display task having unfettered
intended to hold the current time. Since able synchronization with absolute GPS access to the I2C bus. Mutex facilities are
our server only works in whole seconds, time, and use only the one-pulse-per- provided by the FreeRTOS real-time oper-
the Reference Timestamp Fraction field second output. This can be used to test ating system, which is normally hidden
is always zero, and the same goes for devices on your local network to ver- beneath the Arduino framework layer. A
both the Receive Timestamp and the ify that they operate correctly in special description of FreeRTOS, its capabilities and
Transmit Timestamp. The Precision field circumstances such as the changeover limitations is outside our scope here, but
contains the base 2 logarithm of the between summer time and winter time. an article on the subject is in the pipeline.
clock jitter, where the jitter is given as The code to run on the ESP32 is avail-
the execution time of the function to Software able as a free download from the Elektor
read the current time plus one second, The software takes advantage of a few web page accompanying this project [3],
which arises as a consequence of our special features of the ESP32. The updat- and any updates will also appear on this
only working in whole seconds. This is ing of the display is done in an infinite page. You can also drop by GitHub [4],
not a perfect solution, but is adequate loop in a dedicated task, which does not where you will find previews of new ver-
for our purposes. block other processes on the ESP32. sions and updates to the original code.

Web Links
[1] ESPNTPServer: https://github.com/liebman/ESPNTPServer
[2] Beat the Elektor Pinball Clock!, ElektorLabs magazine March & April 2019: www.elektormagazine.com/180307-01
[3] Project page accompanying this article: www.elektormagazine.com/180662-01
[4] Firmware on GitHub: https://github.com/ElektorLabs/180662-mini-NTP-ESP32
[5] Arduino setup for ESP32: https://github.com/espressif/arduino-esp32/blob/master/docs/arduino-ide/boards_manager.md
[6] Arduino ESP32 filesystem uploader: https://github.com/me-no-dev/arduino-esp32fs-plugin
[7] Guide to uploading files: https://techtutorialsx.com/2018/08/24/esp32-arduino-spiffs-file-upload-ide-plugin/

www.elektormagazine.com July & August 2019 97


It is a good idea to install the latest versions of the Arduino IDE
and the package for the ESP32 board on your PC (see [5]). If
you wish to compile the code yourself, you will also need to
install the following libraries:

• U8G2
• Time
• Ticker
• TinyGPS++
• RTCLib
• ArduinoJson 6.x
• CRC32
 
Figure 6. The WLAN settings configuration menu page. Note that this list might change for newer versions of the
project. Once the compiled code has been uploaded to the
ESP32 module, it is also necessary to upload the web page it
requires. How that is done is described in various places on the
Internet and in several Elektor projects that use the ESP32.
The Arduino ESP32 filesystem uploader (and documentation)
can be found on GitHub at [6], and a guide to how to upload
files (a web page is just a file) can be found at [7]. When the
device is reset the NTP server will be ready for use as soon as
the boot process is complete.

Configuring the server


Configuring the server is very straightforward. Once the code
and web page have been successfully uploaded the server starts
up as an access point. In this mode it is possible to connect
to the device and access its web page at the local IP address
192.168.4.1. There you can enter the SSID and password for
Figure 7. The menu for settings related to the time functions. your WLAN (see Figure 6). The web interface can also be used
to configure settings related to the time functions (Figure 7).
Once the WLAN settings are activated, the server attempts
to connect to the WLAN and obtain a local IP address using a
DHCP request.

Finally, the web interface can be used to adjust other config-


uration settings (see Figure 8). Under the Main Page menu
item it is possible to exchange the contents of the two dis-
plays. If only one display is connected, this option will select
what is shown on it. And that completes the configuration of
the mini NTP server. From now on it should happily serve up
time information in response to incoming NTP requests.
(180662-02)

Figure 8. The display configuration menu.

@ www.elektor.com
ªOPEN SMART GPS
www.elektor.com/open-smart-gps-serial-gps-module-for-arduino-apm2-5-flight-control
ªLolin ESP32 with OLED
www.elektor.com/wemos-lolin-esp32-oled-module-with-wifi
ªAdalogger FeatherWing: RTC + SD add-on
www.elektor.com/adalogger-featherwing-rtc-sd-add-on
ª0.96 inch I2C OLED display (optional)
www.elektor.com/blue-0-96-oled-display-i2c-4-pin

98 July & August 2019 www.elektormagazine.com


E T E T O P
C O M P TA R T U
O U R S
N C H Y
LAU
@
PRODUCTRONICA 2019

p-ffwd 2019 – Participate Now!


November 12-15, 2019
Munich

Productronica Fast Forward is brought to you by


Further information at: Platinum Sponsor:
www.elektormagazine.com/p-ffwd
INNOVATION STARTUP TRADE
Creating a New Component
(Symbol) in KiCad
and preparing to associate an existing footprint
By Dr. Peter Dalmaris (Australia)

In this “recipe” you will learn how to create a custom


component (or symbol as it is also known). You use
symbols in schematic diagrams that you can create
in Eeschema. Much of what you will learn in this
recipe you will be able to reuse for modifying existing
symbols. There is a separate recipe in the book that
explains how to do that.

Editor’s note: This article presents a sample chapter from the vention. In regard to IC symbols:
book “Kicad Like a Pro” by Dr Peter Dalmaris, reformatted to match • We arrange pins around a rectangle.
ElektorLabs magazine page layout. The book is available from the • We group pins according to function (like inputs, outputs,
Elektor Store. power etc.).
  • We place the Vcc pin on the top of the rectangle.
Most likely, you want to create a custom schematic symbol • We place the GND pin on the bottom of the rectangle.
because you have a physical component but can’t find an • We choose an appropriate name and designator for the
existing symbol to represent it. Perhaps you have searched symbol. Symbol designators are standardized; you can
through the symbols that come with KiCad, and Googled for learn more about them at [1].
suitable third-party symbols, but couldn’t find any.  
It is also likely that you will want to associate your new symbol
with a footprint. If your physical component has a standard
package, like DIP, for example, then you will be able to associ-
ate an existing footprint with your custom symbol. If not, you
will also need to create a custom footprint. You can learn how
to do this in the relevant recipe, also available in this book.
In this recipe, you will learn how to create a custom symbol by
creating a symbol for the 555 timer integrated circuit. There
are plenty of libraries for KiCad that contain this symbol, but
for the sake of learning, let’s pretend that we can’t find it.
What we want to create is a symbol like the one in Figure 35.1.
Our objective is to create a symbol that complies with the con-

Figure 35.1: A custom-made Figure 35.2: The physical Figure 35.3: Pin configuration and functions from the IC’s datasheet.
symbol for the 555 IC. component is a type 555 timer in
a DIP package with 8 pins.

100 July & August 2019 www.elektormagazine.com


the symbol. The library you
just created should be listed.
Click on it to select it and click
‘OK’ to continue. The Symbol
Properties window will show
up. The most important values
that you need to complete are
Figure 35.4: Start the Symbol Editor.
the symbol name and desig- Figure 35.5b: A section of the
nator. The name typically con- reference designators standard
sists of the physical compo- IEEE 200-1975/ANSI Y32.16-1975.
nent’s model name and any
other information that helps
to identify it. When you use it
later, you have to search for it
in the symbol library and hav-
ing a good name will help you
find it quickly. In my example,
because I want to differentiate
my 555 symbol to those that
exist in other libraries, I add
my initials ‘PD’ at the end of
the name.
Figure 35.5a: I have placed mine in a directory named ‘Custom libraries’.
For the designator, you should
not guess. Visit Wikipedia to
The physical component that we are working with is in Fig- see the Reference Designators Figure 35.6: The properties for the
new symbol.
ure 35.2. This component comes in a standard DIP package table. You can see a section
with 8 pins. of this table in Figure 35.5b.
Because we are working to create a symbol, we don’t need to The designator for integrated
know anything about the physical characteristics of the phys- circuits is ‘U,’ so type this in
ical component other than the total number of pins that its the Default Reference Desig-
package contains. You need to know details about the phys- nator field.
ical characteristics of the component when you are working
on its footprint. Figure 35.6 shows the values
However, it is beneficial if you have access to the components I have entered in the Sym-
data sheet. The data sheet contains information that you need: bol Properties window. Other
The names, numbers, and roles of each pin, whether they are than the symbol name and the
input, output, bidirectional, power, signals, etc. All this is use- designator, everything else
ful information, and the more you have on hand, the better. remains as per the default.
The datasheet for the example component is available from Click ‘OK’ to commit and con-
its manufacturer. The information you need is on page 6 in tinue. KiCad will place the
the book, and I have included it in Figure 35.3 for your designator and symbol name
Figure 35.7: An empty new
convenience. in the middle of the sheet, on
symbol.
top of the other. Use the ‘M’
Let’s start the process of creating a new symbol. In the main hotkey to relocate the two
KiCad window, click on the Symbol Library Editor button blocks of text. You should
(Figure 35.4). have something similar to
You must store each symbol inside a library file, so before you the example in Figure 35.7.
start creating the symbol create a new library. Create a new Continue by drawing the out-
library by clicking on the ‘New library’ button, or through the line of the symbol. You can
File menu (Figure 35.5a). either use the polygon tool or
the rectangle tool to do this.
KiCad will ask you if you would like this library to be available Your outline should like the
to all projects (‘Global’) or only to the current project (‘Proj- example in Figure 35.8.
ect’). Choose the most appropriate one for your circumstances
(I chose ‘Global’). You are now working in the new library, Add the background colour
and you will store the new symbol in it. You can confirm this that is consistent with other
by looking at the header of the Editor window. The path and IC symbols by opening the
name of the library you just created must be showing there. drawing properties window
Next, click on the ‘Create new symbol’ button in the top toolbar. for the rectangle (place your Figure 35.8: The outline of the
A prompt will ask you to select the library in which you will store mouse pointer on the rectan- footprint.

www.elektormagazine.com July & August 2019 101


In the orientation drop-down, select the option that matches
the side of the rectangle to which you are attaching the pin.
The Vcc pin should go on the top of the rectangle and should
have its circular connector pointing away from the rectangle.
The horizontal line of the pin orientation icon represents the
rectangle. If you wanted to place the pin on the left of the rect-
angle, you would choose the icon with the circular connector
pointing towards the left.
Finally, because the Vcc pin is a power pin, I have selected
the ‘Power input’ electrical type. You should choose the same
type for the GND pin.
Figure 35.9: Fill the rectangle background.
Click ‘OK’ to commit the changes. Place the pin in the middle of
the top side of the rectangle, as you can see in Figure 35.11.

gle line and type ‘E’). Under ‘Fill Style’, check the ‘Fill back-
ground’ radio button (Figure 35.9).

Next, work on the pins. Keep the datasheet open because


you need the information in it. For your convenience, refer to
the excerpt in Figure 35.3. Click on the pin button in the right
toolbar. Place the 8 pins around the perimeter of the sym-
bol outline, as in the example of Figure 35.1. Important to
remember here is that the convention is to group similar pins
Figure 35.11: The Vcc pin, in place. Figure 35.12: Input pins are
together and place the two power pins to the top and bottom placed on the left side.
of the rectangle. Let’s start with the Vcc pin. According to the
datasheet, the Vcc pin is number 8, and according to the con-
vention, it should go to the top edge of the rectangle. Click I have moved the text block so that it doesn’t overlap with
on the pin tool, and then click in the middle of the top edge. the pin.
The Pin Properties window will come up. Fill it as shown in the Follow the same process to add the GND pin (pin 1) in the
example in Figure 35.10. bottom edge of the rectangle. Copy the pin name and number
from the datasheet and mark it also as a Power Input.
The fields inside the box are the ones that you need to focus Continue with the left side of the rectangle where you should
on. The pin name is arbitrary, but of course, you should use place the input pins. According to the datasheet, the input
a name that is appropriate. I usually use the same name that pins are RESET, THRES, TRIG. There is one bidirectional pin,
I see in the documentation for this pin. The Pin number, on ‘CONT,’ which you can place either on the left or the right of
the other hand, is very important. The Pin number is how the rectangle. I have placed it on the left. Your symbol should
schematic symbols and footprints can associate physical and look like the example in Figure 35.12.
symbolic pins. When you design the custom footprint for this
physical component in the ‘Creating new footprint’ recipe, it is The pin attributes for the input pins on the left of the symbol
the number that you put in the Pin number field that dictates look like the example in Figure 35.13. Remember that pin 5
which net in the schematic diagram connects to the correct is bidirectional so its electrical type should be ‘bidirectional’.
pad in the footprint. Take the pin number for the Vcc pin from Continue in the same way to create the last two pins. Those
the documentation (‘8’) and type it in this field. are output pins, as per the datasheet. Use the pin names and

Figure 35.10: The Vcc pin properties. Figure 35.13: The input pin attributes.

102 July & August 2019 www.elektormagazine.com


numbers as they appear in library (read the relevant rec-
Figure 35.3 for pins 7 and 3. ipe if you don’t know how to
When completed, you should do this). Place your cursor
have a symbol that looks like on the Sheet and type ‘A’ to
the example in Figure 35.14. add a new symbol. Search for
the name of your library by
The last thing to do is to add typing part of its name in the
the URL for the real-world filter field (Figure 35.16).
component datasheet to the The library should appear.
symbol properties. This will be Double-click on the symbol
useful to you for future refer- to drop it on the sheet.
Figure 35.14: The completed ence. It will be surely useful The custom 555 symbol Figure 35.17: Your new custom
custom symbol. when you go ahead to create should now be in place inside symbol in Eeschema.
a custom footprint to match Eeschema, and you can go
the symbol. To add the data- ahead to use it as you do with
sheet URL, click on the Symbol, ‘Fields…’ to bring up the Field any other symbol (Figure 35.17).
Properties window. Click on the Datasheet row to select it and In this recipe, you learnt how to create a brand-new symbol.
then copy/paste the URL in the Field Value field (Figure 35.15). What if you have found a symbol that is close to what you want,
Click OK to commit the changes. but could be perfect with a bit of tweaking? In other words,
Your work is complete. Save the symbol to the selected library what if you want to modify an existing symbol? You can learn
by clicking on the Save Current Symbol button. Then, test how to do this in the ‘36. Modifying an existing component
that you can use it in Eeschema. Open Eeschema. Go into (symbol)’ recipe.
Symbol Libraries from the Preferences menu and add the new (190041-01)

@ www.elektor.com
ªKicad Like a Pro book (hard copy)
www.elektor.com/18822
ªKicad Like a Pro book (e-book)
Figure 35.15: The datasheet is very useful to have readily available. www.elektor.com/18830

Web Link
[1] Symbol designators:
https://en.wikipedia.org/wiki/Reference_designator
Figure 35.16: Find your new library and symbol.

www.elektormagazine.com July & August 2019 103


RETRONICS

From Tubes
to Silicon
With an interesting
intermezzo
By Dr Martin Beusekamp, MSc

We have been living in the electronic age for well over a


century now, since the invention of the triode by Lee de
Forest in 1907. Roughly speaking, in the first half of this
period electronics was based solely on electron tubes,
and in the second half almost entirely on silicon
semiconductors in discrete or integrated
form. In a relatively short transition period,
electronic equipment was designed and built
with neither tubes nor silicon semiconductors, but
instead with selenium rectifiers and germanium diodes
and transistors. Let’s have a closer look at these components.

Selenium rectifiers area of the metal plates, and in practice


Figure 1 shows a typical selenium rec- it is approximately 25 to 30 mA/cm2 [1].
tifier, consisting of a number of small This means you don’t need to look for a
metal plates made of steel or aluminium part number to determine the properties
and coated with a thin layer (approxi- of a selenium rectifier — just count the
mately 1 μm) of bismuth (Bi) or nickel number of plates for the blocking volt-
(Ni), with a thicker layer (approximately age and measure the size of the plates
60 μm) of selenium (Se) on top. This for the forward current.
sandwich structure acts as a diode Due to the relatively high forward current
because electrons can cross the barrier capacity of selenium rectifiers with large
between the selenium and the steel or dimensions, for a short while they were
aluminium more easily in the one direc- used to rectify currents up to several
tion than in the other direction. amperes. However, users often said that
Each of these diodes has a reverse block- with selenium rectifiers the question was
ing voltage of approximately 30 to 50 V, not how long they would last, but instead
but to be on the safe side the generally when they would fail. Their reliability and
accepted rule was a maximum of 20 V lifetime were in fact fairly limited, cer-
per diode. The overall rectifier in Figure 1 tainly compared to the indestructible sil-
consists of eight plates, so it has a max- icon diodes we use now (provided that
imum reverse blocking voltage of 160 V. the voltage, current and power remain
Figure 1. A typical example of a selenium
The maximum current through the recti- within the specified limits). rectifier. (Creative Commons Attribution-
fier is linearly proportional to the surface Selenium rectifiers generally fail due to Share Alike 3.0 Unported)

104 July & August 2019 www.elektormagazine.com


Retronics is a regular section covering vintage electronics
including legendary Elektor designs.
Contributions, suggestions and requests are welcome;
www.elektor.tv please telegraph [email protected]

overheating as a result of increased resis- Hold your nose, open the window, and get out.
tance in the forward conduction direc-
As mentioned in this article, selenium rectifiers can sometimes be dangerous. The
tion. This is accompanied by a pene-
internal resistance of selenium rectifiers rises as they get older, which increases
trating odour and the release of a gas
the voltage drop over the rectifier. This in turn increases the power dissipation,
that can certainly be hazardous in rela-
so the rectifier gets warmer. At some point it will be so hot that the selenium
tively high concentrations (see the inset
spontaneously starts to oxidise and turn into selenium dioxide (SeO2).
‘Hold your nose, open the window,
Selenium dioxide is a solid substance at room temperature, but it escapes from an
and get out’). If you encounter a sele-
overheated selenium rectifier as a greenish gas. This gas is toxic – in fact, highly
nium rectifier that is still working, you
toxic. It’s bad enough that it can make you dizzy, nauseous and tired, but what
are well advised to replace it by a silicon
even worse is that it can cause permanent damage to your liver and spleen.
diode with a series resistor to obtain the
Fortunately, people have a natural defence mechanism against selenium dioxide.
same voltage drop as the original sele-
Most people can smell it at concentrations as low as 200 ng/m³, so they are
nium rectifier.
alerted before the situation becomes truly dangerous. The smell of selenium
dioxide is also so disgusting that everyone wants to get away from the source.
Germanium diodes and
Selenium is located directly below sulphur (S) in the periodic system. This
transistors
means that selenium and sulphur have comparable properties, the same way
The first semiconductor devices that
as germanium and silicon, which are also vertically adjacent as described in this
became available on a large scale were
article. That’s why the odour of selenium dioxide resembles the odour of sulphur
germanium diodes and transistors (see
dioxide. It’s like rotten onions with garlic.
the inset ‘Tube codes for diodes and
See also Barry L. Ornitz, Selenium Rectifier Replacement [7], and ‘Sleepless
transistors’). Germanium (Ge) is an
nights from a pile of onions’ [8].
element that is located directly below sili-

www.elektormagazine.com July & August 2019 105


ment having one electron less in the out-
ermost shell, such as boron (B), results
in p-type germanium with a shortage of
free electrons. Germanium diodes and
transistors have the same structure and
operating principle as their silicon cous-
ins, and they look approximately the
same (see the lead photo). However,
they have different electrical charac-
teristics due to the differences in the
material properties.
For example, the voltage drop over a
conducting germanium diode or a con-
ducting base-emitter junction of a ger-
manium transistor is only 0.1 to 0.2 V,
compared to 0.6 to 0.7 V with silicon
types. This advantage is offset by a vari-
Figure 2. Schematic diagram of the Nucleon construction kit from Amroh, with two tubes and two
ety of disadvantages, such as the higher
batteries for power supply.
internal resistance of a germanium diode
and the higher leakage current in the
blocking direction – on the order of 1 μA
con (Si) in the periodic table. This means with germanium, compared to 1 pA with
that germanium also has four valence silicon. It’s also not possible to fully cut
electrons, resulting in an orderly spatial off a germanium transistor. Even with-
crystal structure with the pure form of out a base current, there is a collector
the substance. current ICEO of several microamps with
Like silicon, germanium can be doped small-signal germanium transistors or
with an element having one more elec- several milliamps with germanium power
tron in the outermost shell, such as transistors.
phosphorus (P) or arsenic (As), to pro- A wide variety of other problems, such
duce n-type germanium with an excess as temperature dependence, changing
of free electrons. Doping with an ele- characteristics with ageing and the tol-
erance range in mass production, were
also significantly greater with germanium
semiconductors than with their silicon
replacements later on (yet another prob-
lem is described in the inset  ‘Just a
Figure 3. Cover page of the July 1960 issue of whisker away’). Once the technology
the Dutch youth magazine Radio Blan. Note the for the production of silicon semiconduc-
price (in cents of a Dutch guilder, of course). tors was sufficiently advanced, germa-
nium semiconductors disappeared fairly
quickly with the exception of a few appli-
cations where their low forward voltage
Tube codes for diodes and transistors was essential.
The first germanium diodes, with type numbers such as OA79 and OA81, came
onto the market in the mid-1950s. A few years later they were joined by the first Construction kits for youngsters
germanium transistors, with type numbers OC3, OC4, OC13 and OC14. Even before the invention of germa-
These type numbers were based on the usual European codes for electron tubes nium semiconductors there were many
at that time. The ‘O’ stands for a cold cathode (no filament present), the ‘A’ DIY kits with electron tubes, such as the
stands for a single diode, and the ‘C’ stands for a triode (the simplest type of gain Philips ‘Senior’ kits for a variety of medi-
element). um-wave receivers and amplifiers. These
Specific European codes for semiconductor devices were agreed and introduced DIY projects were only suitable for adults,
only later, with the first letter ‘A’ for all materials with a band gap of 0.6 to 1.0 eV due to the high voltages in the circuits
(which in practice is always germanium), ‘B’ for all materials with a band gap of and the need for soldering.
1.0 to 1.3 eV (in practice always silicon), and ‘C’ for all materials with a larger The manufacturer Amroh tried to do
band gap (such as gallium arsenide). They form the basis for type numbers such something about this by launching some
as CQY37 for a particular infrared LED or CQY80 for a particular optocoupler. kits with electron tubes designed for
If you have a diode with an OA type number or a transistor with an OC type use with batteries. The Amroh Nucleon
number, it was probably made using a glass tube coated with black paint. If you medium-wave receiver (Figure 2) with
scratch off the paint, you have a photodiode or phototransistor. loudspeaker output, for example, used
two tubes: a DK91 (1R5) and a DL92

106 July & August 2019 www.elektormagazine.com


(3S4), with filament currents of 50 mA
and 100 mA, respectively, at 1.4 V. A
good-quality LR20 battery (also known as
a D cell) could keep the filaments glow-
ing for several hours, until the terminal
voltage dropped to 1.2 V or less and
operation of the radio was reduced to
a minimum. The anode voltage of the
Nucleon was provided by a 45 V anode
battery (B battery). Until the end of the
1950s, B batteries with high voltages (up
to 90 V) were readily available for any-
one who could afford them.
And then came the germanium diodes,
with which even relatively young kids
could build a crystal receiver such as
the Pioneer I from Philips or the ‘jam jar
Figure 4. Schematic diagram from the Philips Pionier II construction kit, with a type OA79
receiver’ from the magazine Radio Blan
germanium diode and two type OC13 germanium transistors.
for young hobbyists (Figure 3). Note
the price of the magazine: 15 cents (of
a Dutch guilder). Ignoring correction for
inflation, that’s equivalent to a bit less nium transistors could have replaced all
than €0.07, ₤0.06 or $0.08. This was electron tubes.
low cost even at that time (1960), but The Philips PM3230 oscilloscope shown
the magazine was sponsored by dozens in Figure 5 is a typical example of what
of component dealers who sensed a new could be called ‘the best of three worlds’
market. at that time. Along with the cathode ray
Germanium diodes were soon followed tube, this instrument contains seven
by germanium transistors, which could other electron tubes (five ECC88 and
be used to build more selective medi- two E180F). In addition, this oscilloscope
um-wave receivers with crystal head- contains 81 semiconductor components,
phones, such as the Philips Pionier II of which 17 are germanium (primarily
with two OC13 transistors (Figure 4),
or even loudspeaker output, such as the
Philips Pionier III with an additional OC14
as an output amplifier.
Figure 5. The Philips PM3230 oscilloscope with
A short time later, Philips came out with electron tubes, germanium transistors, silicon
the EE8 and EE20 experimenter kits (EE diodes and silicon transistors in its circuitry.
stands for ‘electronic engineer’, and the Photo: Gerrit Busscher.
number stands for how many different
devices could be made with the kit in
question). The germanium transistors
in these kits were a bit more advanced: Boiled or baked?
AF116 and AC126. A wide range of Semiconductor devices are sensitive to overly high temperatures. This means
devices could be built, including a phono they need to be soldered quickly. Germanium semiconductors are distinctly more
preamplifier, electronic organ, intercom, sensitive to overheating during soldering than silicon semiconductors.
Morse code trainer, flashing light, acous- Accordingly, there were various means commonly used to avoid damage to
tic relay, moisture indicator, timer switch, germanium components during PCB assembly. A loose crocodile clip attached to
Wheatstone bridge, and of course vari- the lead to be soldered was usually sufficient to dissipate the heat.
ous small medium-wave radio receivers
(when there was still something worth The magazine Radio Blan (see Figure 3) realised that youngsters might not have
listening to on that band). much soldering experience and also had to save all their pennies for a single
diode or transistor. Corrected for inflation and converted to euros, the price of a
Best of three worlds germanium diode in 1960 was approximately three euros (₤2.50, $3.35), and a
Of course, selenium and germanium germanium transistor cost around twenty euros (₤17.25, $25.00).
components were also used in industrial The tip from ‘Uncle Blan’, the magazine’s guru for everything to do with
applications where they could make an electronics, to avoid overheating was accordingly: “Ask your mother for a slice of
instrument better, smaller, cheaper, and/ raw potato. Cut it halfway through, and then place it on the lead of the diode or
or more reliable. However, silicon com- transistor to be soldered. After soldering, carefully remove the potato slice.”
ponents became available before germa-

www.elektormagazine.com July & August 2019 107


cathode ray tube is many kilovolts. The
power supply generates DC voltages,
while the input signals can have frequen-
cies up to 10 MHz with the PM3230, or
an order of magnitude higher with more
sophisticated (and more expensive) oscil-
loscopes available then. At that time,
some of these functions could still be
best implemented with electron tubes,
while germanium transistors or even sil-
icon transistors were a better choice for
other functions. If you’re interested, you
can find many more details in the service
manual for the PM3230 [2].
In some cases, marketing considerations
were behind the use of several sorts of
active components. At the IFA in Berlin in
1967, Philips presented a medium-wave
receiver with a futuristic appearance, the
IC2000 (see Figure 6 for an example in
remarkably good condition).
Approximately three-quarters of the
round enclosure of this radio, with a
Figure 6. The Philips IC2000 medium-wave radio (1976). The compact round radio fits in the case;
diameter of 7 cm and a height of 3 cm,
the device on its right is the mains power supply and charger.
is taken up by the loudspeaker. A round
PCB with two ICs, among other compo-
nents, is mounted on the loudspeaker
AV11x high-frequency transistors) and answer is that an analog oscilloscope magnet. One of these ICs (a TAA263)
64 are silicon (mainly diodes and bridge operates with a wide variety of electronic contains no less than three transistors.
rectifiers). circuits. The input amplifiers must pro- The radio also uses one discrete silicon
Why did the Philips designers and devel- cess signal voltages in the millivolt range, transistor, one silicon diode, and two
opers choose these components? The while the post-acceleration voltage of the germanium transistors in the output
stage.
The use of ICs in this relatively simple
small receiver is certainly not necessary,
but it fits with the external appearance
and the chosen model number IC2000.
At that time, ‘IC’ was a sort of magic
word, and in the latter decades of the
previous century the number 2000 was
always associated with the technological
future wherever it appeared. At that time
there were also other manufacturers who
tried to boost their sales figures by using
‘IC’ and ‘2000’ in their model numbers.
If you would like to know more details
about this radio, the best place to look
for the service manual [3] is the archives
of the Dutch association for the history
of radio, NVHR (Nederlandse Vereniging
voor de Historie van de Radio).

Best of one world


The situation with a relatively simple
device such as an industrial DC power
supply (non-switching) is completely dif-
ferent. No high frequencies, no very low
or very high voltages, a straightforward
design, and no need to attract the gen-
eral public. That’s why only selenium and
Figure 7. Internals of a Philips type PE4804 power supply, with exclusively selenium rectifiers and
germanium components were used in
germanium semiconductors. Gift from E.G. Pleiter (Hengelo). Photo: Rob Quentemeijer.

108 July & August 2019 www.elektormagazine.com


Just a whisker away
The first car and the first train were with antimony, cadmium, indium and transistor was embedded in a blob of
far from being as reliable as the best zinc) that is prone to the formation of silicone grease, there was usually an air
horse-drawn carriages at the time. The whiskers on the surface of the material space in the package. Spontaneously
car pioneer and industrialist Henry Ford (see Figure 8 and the Wikipedia growing metal whiskers, a few
is credited with saying, “If I had asked description [9]). micrometres thick and protruding into
my customers what they wanted, they the air space, could in time cause short
would have said faster horses.” The tin packages of early germanium circuits between the transistor package
At the end of the tube era, there was transistors were hollow. Although the and the electrodes of the transistor
a similar situation with transistors (in (collector, base, and/or emitter).
particular germanium transistors). They This problem occupied the attention of
were a lot smaller and more energy all manufacturers of electronic devices
efficient than electron tubes, but during the 1950s and 1960s, and it
certainly not as reliable. was even the subject of a specific
Although the manufacturers of early investigation by NASA. The problem
germanium transistors (OC170– was fully resolved with the advent of
OC171, AF114–AF117, etc.) made transistors in plastic packages or in
good products, they were not in a metal packages made of an alloy that
position to know what the lifetime of is not prone to the formation of metal
their new marvels would be in practice. whiskers.
It turned out that the lifetime was See also ‘The OC171 Mystery’ [10] and
limited by the spontaneous growth of the article by Mark Hennessy [11].
metal whiskers on the inside of the
tin packages of these transistors. As it Figure 8. Formation of metal whiskers on a
happens, tin is one of the metals (along zinc bracket (source: Wikipedia).

the Philips DC power supplies PE4802 sides in the photo you can clearly see [5],[6] on the NVHR website.
(0–15 V / 6 A) and PE4804 (2 × 0–30 V that this is a dual power supply. These Philips PE4802 and PE 4804 power
/ 2 × 2 A) produced in the early 1960s. The black heat sinks of the germanium supplies are collector’s items — not
Figure 7 shows the internals of a PE4804 power transistors are clearly visible below because they are especially high-tech,
from the Historical Study collection of the the light green blades of the fan. By the but from the historical perspective: no
faculty of Electrical Engineering, Math- way, the motor that drives the fan blades tubes, no silicon.
ematics and Informatics of the Univer- is a standard synchronous motor oper- (180574-D-03)
sity of Twente [4], which also includes ating from the AC power line, which was
a PE4802. The large blue components used in all Philips record players at that
are of course the selenium rectifiers, and time. More details about this device can
from the symmetry of the left and right also be found in the service manuals

Links and literature


[1] Source: E.A. Harty – Characteristics and applications of Selenium-Rectifier Cells – Transactions on Electrical Engineering,
volume 62, October 1943.
[2] Philips PM3230 oscilloscope (Dutch): www.radiodatabase.nl/meetapparatuur/philips/PM3230/PM3230.pdf
[3] Philips IC2000 radio : https://nvhrbiblio.nl/schema/Philips_22IC2000.pdf
[4] Historical Study collection of the faculty of Electrical Engineering, Mathematics and Informatics of the University of Twente:
http://studieverzameling.utwente.nl/
[5] Philips PE4804 documentation (Dutch): https://nvhrbiblio.nl/schema/Philips_PE4804.pdf
[6] Philips PE4804-05 documentation (Dutch): https://nvhrbiblio.nl/schema/Philips_PE4804-05.pdf
[7] Replacing selenium bridge rectifiers: https://yarchive.net/electr/selenium_rectifiers.html
[8] Sleepless nights from a pile of onions (Dutch): www.telegraaf.nl/nieuws/1228796/slapeloze-nachten-door-berg-uien
[9] Metal whiskers (Wikipedia): https://en.wikipedia.org/wiki/Whisker_(metallurgy)
[10] The OC171 Mystery: www.elektormagazine.com/magazine/elektor-200807/18873
[11] The AF11x problem: www.markhennessy.co.uk/articles/vintage_transistors.htm#the_af11x_problem

www.elektormagazine.com July & August 2019 109


Fair
Algorithms
By Tessel Renzenbrink (Elektor Ethics)

More and more attention is being paid to the responsible use of algorithms. How do we ensure
that algorithms do not reproduce prejudices? And how can we guarantee that algorithms reflect
our ethical values?

Cathy O’Neil, data analyst and author of Automating nepotism complaints about, for example, gar-
the book Weapons of Math Destruction However, O’Neil is not only negative bage in the street are automatically
[1], welcomes the increasing attention about the applications of Big Data. On forwarded to the cleaning department.
paid to these issues. “This is an awk- the contrary, they can make a positive But the municipality wants to pre-
ward slow frustrating conversation that contribution to the way in which we make vent that the automation has unin-
we absolutely must have”, O’Neil said decisions if we deal with them in the tended negative consequences. One
in an interview. In mid-April she was in right way. The challenge is to ensure that risk is that it creates inequality [2].
Amsterdam to advise the Municipality on mathematical models reflect our ethical In richer neighbourhoods, citizens
the use of a self-learning algorithm for values. Also, they should no longer be are often more vocal and are more
handling complaints. opaque. People must be held account- likely to complain. If the algorithm
  able for any negative consequences. To is not adjusted, it will send sweep-
With her book, O’Neil has made an enor- achieve this, algorithmic applications ers to those neighbourhoods more
mous contribution to raising awareness must be carefully tested. often on the basis of that data. As
about algorithms. Using true exam-   a result, areas where there is less
ples, she explains in an understandable “Scrutiny is exactly what people are try- complaining are served less well.
and convincing way how mathematical ing to avoid when they introduced the  
models can cause damage. The weap- algorithm”, O’Neil said during the inter- In order to prevent such unintended
ons of math destruction (WMDs) in the view. “ The algorithm was to good to be effects, Amsterdam has decided to trial
title have three characteristics: they are true in a certain sense for a lot of com- the algorithm. Together with the con-
harmful, operate on a large scale and are panies and governments and organisa- sultancy firm KPMG, the municipality is
opaque. She writes about the latter prop- tions because it made things more effi- working on the development of audits for
erty in her book: “verdicts from wmds cient and it made accountability much algorithms [3]. This was the reason for
land like dictates from the algorithmic less. I think of the use of algorithms as O’Neil’s visit to Amsterdam. She advises
gods”. The results are in no way open an automated decision making process.  both parties on what such an audit could
to discussion and no one has to account You already had decision making pro- look like. Her company ORCAA is spe-
for any harmful consequences. cesses. And they are made by humans cialised in performing audits on algo-
  and they had all kinds of biases, all kinds rithms. They are checked for characteris-
One of the WMD’s in O’Neil’s book is the of unwritten rules, all kinds of secrets tics such as bias, transparency, accuracy
use of solvency for determining the car and like ways of favouring their friends and honesty.
insurance premium. In the mathemat- and stuff like that. Once it’s automated  
ical models used by American insurers they thought: ‘Oh, it is like what we did O’Neil emphasises that developing hon-
to determine the price, solvency out- but better because we also don’t have est algorithms is not an easy task. There
weighs driving behaviour. In Florida, to answer for it’.” is no silver bullet solution that can jus-
people with a good score for credit and tify all mathematical models in one fell
a conviction for drink-driving paid more Algorithms scrutinised swoop. To ensure quality, each algo-
than $1,500 less a year than people with But the tide is turning. More and more rithm must be tested within the context
a poor score for credit and impeccable parties are thinking about how we can in which it is applied. If the Amsterdam
driving behaviour. O’Neil shows time and make algorithms fair. One of these par- algorithm works well, it cannot simply be
again that it is mainly the poor and weak ties is the Municipality of Amsterdam. It used in New York because the situation
groups in society who are the victims is in the process of developing an algo- there is different.
of WMDs. rithm to deal with complaints. Citizens’ “That is the biggest gap in people’s

110 July & August 2019 www.elektormagazine.com


Cathy O’Neil: There is still a lot of work to
be done, but we will succeed

understanding”, says O’Neil. “They think been. Once we scrutinise decision making is sexist, we are going to improve it. And
they can evaluate an algorithm. They processes, it is going to be much more we are going to use it. Because it will be
can’t. They can only evaluate an algo- transparent, much more value-laden.” less sexist than the human process it is
rithm in a context.”   replacing. But we haven’t gotten to that
O’Neil illustrates her point with an exam- step yet. But ideally we will. Than you
Clean up human errors ple. “Amazon’s algorithm for hiring, they are actually going to clean up, rather
There is still a lot of work to be done, figured out it was sexist. So they decided than just propagate, the mistakes we
but O’Neil is positive because there is a not to use it. I am glad they checked, humans make.”
movement of people who focus on this okay, that’s progress. But what does it 180572-D-02
issue. “What this movement is going to mean when you codify a human process
eventually create is a way of maintaining and discover that it is sexist? It means
accountability in algorithmic processes. that your human process is sexist. What
In fact, it may even be that accountabil- I would’ve liked to see them do is for
ity will be much stronger than it has ever them to say: we have this algorithm, it (Graphics: https://weaponsofmathdestruction.com )

Web Links
[1] Weapons of Math Destruction: https://weaponsofmathdestructionbook.com
[2] https://fd.nl/ondernemen/1291305/amsterdam-wil-eerlijke-computers-in-de-stad
[3] https://home.kpmg/nl/nl/home/media/press-releases/2018/12/kpmg-ontwikkelt-ai-in-control-om-gebruik-van-algoritmen-
te-toets.html

www.elektormagazine.com July & August 2019 111


welcome in your
ONLINE STORE Elektor Bestsellers
1. SDR Hands-on Book
www.elektor.com/sdr-hands-on-book
EDITOR’S CHOICE

LabNation WiFi Bridge


for SmartScope
The SmartScope is an exceptionally handy and versatile two-
channel USB oscilloscope that works with all computer systems,
tablets and smartphones that operate on Windows, OS X, iOS,
Android and Linux. A handy expansion module is now available
that enables the SmartScope to operate wirelessly via WiFi:
the WiFi Bridge.
The WiFi Bridge from LabNation is a great peripheral for the SmartScope and is very
2. Raspberry Pi 3 B+
interesting for anyone who would like to measure wirelessly across
www.elektor.com/rpi-3-plus
some distance. Very recommended to any
owners of a SmartScope! 3. Elektor SDR Shield 2.0
www.elektor.com/170515-91

Harry Baggen 4. Bakeey UM25C USB Multimeter


(Elektor Labs) Logger
www.elektor.com/bakeey-um25c

5. Miniware TS100 Soldering Iron


www.elektor.com/miniware-ts100

6. PCBite Kit
www.elektor.com/pcbite-kit
www.elektor.com/wifi-bridge-smartscope

Embedded in Embedded KiCad Like a Pro HiFiBerry DAC+ DSP

This book is a case study in embedded design including This book will teach you to use KiCad. Whether you are a hobbyist The HiFiBerry DAC+ DSP is a high-resolution digital-to-analog
discussion of the hardware, processor initialization, low‑level or an electronics engineer, this book will help you become converter for the Raspberry Pi. It combines a Burr-Brown DAC
driver development, and application interface design for a productive quickly, and start designing your own boards. This with digital input and output and a powerful Digital Signal
product. Though the author describes this through a specific book takes a practical approach to learning. It consists of four Processor.
application of a Cortex-M3 development board, his mission is projects of incremental difficulty and recipes.
to help the reader build foundational skills critical to being an
excellent product developer.

Member Price: £38.95 • €44.96 • $49.95 Member Price: £30.95 • €35.96 • $39.95 Member Price: £61.95 • €71.96 • $80.95

www.elektor.com/embedded-in-embedded www.elektor.com/kicad-like-a-pro www.elektor.com/hifiberry-dac-dsp

112 July & August 2019 www.elektormagazine.com


shopping books cd/dvd diy projects development tools sale

NEW

SDR Hands-on Book


Elektor’s SDR-Shield (SKU 18515) is a versatile shortwave
receiver up to 30 MHz. Using an Arduino and the appropriate
software, radio stations, morse signals, SSB stations, and digital
signals can be received.
In this book, successful author and enthusiastic radio amateur,
Burkhard Kainka describes the modern practice of software
defined radio using the Elektor SDR Shield. He not only imparts a
theoretical background but also explains numerous open source
software tools.

Member Price: £22.95 • €26.96 • $30.95


www.elektor.com/sdr-hands-on-book

OWON SDS1022 The Complete ESP32 Projects Guide PCBite Kit incl. 4 PCBite
2-ch Oscilloscope (20 MHz) Probes and Test Wires

The OWON SDS1022 is a competitively priced oscilloscope The main aim of this book is to teach the Arduino IDE and PCBite is the perfect tool for handling your PCB during
with a sample rate of 1 GSa/s and a bandwidth of 20 MHz. MicroPython programming languages in ESP32 based projects, the design process. Powerful magnets combined with a
Furthermore, with this oscilloscope you have 2  channels using the highly popular ESP32 DevKitC development board. stainless-steel base plate provide flexibility, mobility and
at your disposal and it is possible to store 10 K points per Many simple, basic, and intermediate level projects are user-friendliness. The holder can easily be relocated to deal
measurement. There is a USB connector on the back for provided in the book using the Arduino IDE with ESP32 with printed circuit boards of different shapes and sizes. The
exporting measurement results to the PC, and a USB port on DevKitC. All projects have been tested and work. Block probe is sturdy yet flexible and can be used for immediate
the front for exporting to a USB memory stick. diagrams, circuit diagrams, and complete program listings measurements or totally hands-free operations with your
of all projects are given with explanations. multimeter or another preferred tool.

Member Price: £147.95 • €170.96 • $191.95 Member Price: £30.95 • €35.96 • $39.95 Member Price: £103.95 • €121.46 • $135.95

www.elektor.com/owon-sds1022 www.elektor.com/esp32-projects-guide www.elektor.com/pcbite-kit

www.elektormagazine.com July & August 2019 113


play & win

Hexadoku The Original Elektorized Sudoku


Traditionally, the last page of Elektor Magazine is reserved for our puzzle with an electronics slant: welcome
to Hexadoku! Find the solution in the gray boxes, submit it to us by email, and you automatically enter the
prize draw for one of five Elektor book vouchers.

The Hexadoku puzzle employs numbers in the hexadecimal thicker black lines). A number of clues are given in the puzzle
range 0 through F. In the diagram composed of 16 × 16 boxes, and these determine the start situation.
enter numbers such that all hexadecimal numbers 0 through
F (that’s 0-9 and A-F) occur once only in each row, once in Correct entries received enter a prize draw. All you need to do
each column and in each of the 4×4 boxes (marked by the is send us the numbers in the gray boxes.

Solve Hexadoku and win!


Correct solutions received from the entire Elektor readership automatically
enter a prize draw for five Elektor Book Vouchers worth $70.00 / £40.00
/ €50.00 each, which should encourage all Elektor readers to participate.

Participate!
Ultimately July 1, 2019, supply your name, street address
and the solution (the numbers in the gray boxes) by email to:
[email protected]

Prize Winners
The solution of Hexadoku in edition 3/2019 (May & June) is: 46F7C.
The €50 / £40 / $70 book vouchers have been awarded to: Demierbe Guillaume (Belgium); Alexandr Papazyan (Russia);
Fostiropoulos Michalis (Greece); Sune Johansson (Sweden); Ruth Hanselmann (Germany).
Congratulations everyone!

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

114 July & August 2019 www.elektormagazine.com


Differentiate Your Application
Customise Your Embedded Design with Flexible,
Integrated Building Blocks

Microchip understands that your design needs are unique. That’s why our products
offer a robust set of integrated peripherals for a wide variety of applications:

• Add impactful displays and touch for intuitive user interaction


• Connect your application to the world—with and without wires
• Control your motor or power conversion
• Protect the data in your application

Customise your product with built-in peripherals and save on design costs and time.

Customise your design at www.microchip.com/FlexibleFunctions

The Microchip name and logo and the Microchip logo are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. All
other trademarks are the property of their registered owners.
© 2019 Microchip Technology Inc. All rights reserved. DS30010187A. MEC2287Eng04/19

You might also like